xref: /sqlite-3.40.0/src/vdbe.c (revision aeb4e6ee)
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 P3 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 ** If P3 is positive, then reg[P3] is modified slightly so that it
3926 ** can be used as zero-length data for OP_Insert.  This is an optimization
3927 ** that avoids an extra OP_Blob opcode to initialize that register.
3928 */
3929 /* Opcode: OpenAutoindex P1 P2 * P4 *
3930 ** Synopsis: nColumn=P2
3931 **
3932 ** This opcode works the same as OP_OpenEphemeral.  It has a
3933 ** different name to distinguish its use.  Tables created using
3934 ** by this opcode will be used for automatically created transient
3935 ** indices in joins.
3936 */
3937 case OP_OpenAutoindex:
3938 case OP_OpenEphemeral: {
3939   VdbeCursor *pCx;
3940   KeyInfo *pKeyInfo;
3941 
3942   static const int vfsFlags =
3943       SQLITE_OPEN_READWRITE |
3944       SQLITE_OPEN_CREATE |
3945       SQLITE_OPEN_EXCLUSIVE |
3946       SQLITE_OPEN_DELETEONCLOSE |
3947       SQLITE_OPEN_TRANSIENT_DB;
3948   assert( pOp->p1>=0 );
3949   assert( pOp->p2>=0 );
3950   if( pOp->p3>0 ){
3951     /* Make register reg[P3] into a value that can be used as the data
3952     ** form sqlite3BtreeInsert() where the length of the data is zero. */
3953     assert( pOp->p2==0 ); /* Only used when number of columns is zero */
3954     assert( pOp->opcode==OP_OpenEphemeral );
3955     assert( aMem[pOp->p3].flags & MEM_Null );
3956     aMem[pOp->p3].n = 0;
3957     aMem[pOp->p3].z = "";
3958   }
3959   pCx = p->apCsr[pOp->p1];
3960   if( pCx && pCx->pBtx ){
3961     /* If the ephermeral table is already open, erase all existing content
3962     ** so that the table is empty again, rather than creating a new table. */
3963     assert( pCx->isEphemeral );
3964     pCx->seqCount = 0;
3965     pCx->cacheStatus = CACHE_STALE;
3966     rc = sqlite3BtreeClearTable(pCx->pBtx, pCx->pgnoRoot, 0);
3967   }else{
3968     pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
3969     if( pCx==0 ) goto no_mem;
3970     pCx->isEphemeral = 1;
3971     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
3972                           BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5,
3973                           vfsFlags);
3974     if( rc==SQLITE_OK ){
3975       rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1, 0);
3976     }
3977     if( rc==SQLITE_OK ){
3978       /* If a transient index is required, create it by calling
3979       ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
3980       ** opening it. If a transient table is required, just use the
3981       ** automatically created table with root-page 1 (an BLOB_INTKEY table).
3982       */
3983       if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
3984         assert( pOp->p4type==P4_KEYINFO );
3985         rc = sqlite3BtreeCreateTable(pCx->pBtx, &pCx->pgnoRoot,
3986                                      BTREE_BLOBKEY | pOp->p5);
3987         if( rc==SQLITE_OK ){
3988           assert( pCx->pgnoRoot==SCHEMA_ROOT+1 );
3989           assert( pKeyInfo->db==db );
3990           assert( pKeyInfo->enc==ENC(db) );
3991           rc = sqlite3BtreeCursor(pCx->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
3992                                   pKeyInfo, pCx->uc.pCursor);
3993         }
3994         pCx->isTable = 0;
3995       }else{
3996         pCx->pgnoRoot = SCHEMA_ROOT;
3997         rc = sqlite3BtreeCursor(pCx->pBtx, SCHEMA_ROOT, BTREE_WRCSR,
3998                                 0, pCx->uc.pCursor);
3999         pCx->isTable = 1;
4000       }
4001     }
4002     pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
4003   }
4004   if( rc ) goto abort_due_to_error;
4005   pCx->nullRow = 1;
4006   break;
4007 }
4008 
4009 /* Opcode: SorterOpen P1 P2 P3 P4 *
4010 **
4011 ** This opcode works like OP_OpenEphemeral except that it opens
4012 ** a transient index that is specifically designed to sort large
4013 ** tables using an external merge-sort algorithm.
4014 **
4015 ** If argument P3 is non-zero, then it indicates that the sorter may
4016 ** assume that a stable sort considering the first P3 fields of each
4017 ** key is sufficient to produce the required results.
4018 */
4019 case OP_SorterOpen: {
4020   VdbeCursor *pCx;
4021 
4022   assert( pOp->p1>=0 );
4023   assert( pOp->p2>=0 );
4024   pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
4025   if( pCx==0 ) goto no_mem;
4026   pCx->pKeyInfo = pOp->p4.pKeyInfo;
4027   assert( pCx->pKeyInfo->db==db );
4028   assert( pCx->pKeyInfo->enc==ENC(db) );
4029   rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
4030   if( rc ) goto abort_due_to_error;
4031   break;
4032 }
4033 
4034 /* Opcode: SequenceTest P1 P2 * * *
4035 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
4036 **
4037 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
4038 ** to P2. Regardless of whether or not the jump is taken, increment the
4039 ** the sequence value.
4040 */
4041 case OP_SequenceTest: {
4042   VdbeCursor *pC;
4043   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4044   pC = p->apCsr[pOp->p1];
4045   assert( isSorter(pC) );
4046   if( (pC->seqCount++)==0 ){
4047     goto jump_to_p2;
4048   }
4049   break;
4050 }
4051 
4052 /* Opcode: OpenPseudo P1 P2 P3 * *
4053 ** Synopsis: P3 columns in r[P2]
4054 **
4055 ** Open a new cursor that points to a fake table that contains a single
4056 ** row of data.  The content of that one row is the content of memory
4057 ** register P2.  In other words, cursor P1 becomes an alias for the
4058 ** MEM_Blob content contained in register P2.
4059 **
4060 ** A pseudo-table created by this opcode is used to hold a single
4061 ** row output from the sorter so that the row can be decomposed into
4062 ** individual columns using the OP_Column opcode.  The OP_Column opcode
4063 ** is the only cursor opcode that works with a pseudo-table.
4064 **
4065 ** P3 is the number of fields in the records that will be stored by
4066 ** the pseudo-table.
4067 */
4068 case OP_OpenPseudo: {
4069   VdbeCursor *pCx;
4070 
4071   assert( pOp->p1>=0 );
4072   assert( pOp->p3>=0 );
4073   pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
4074   if( pCx==0 ) goto no_mem;
4075   pCx->nullRow = 1;
4076   pCx->seekResult = pOp->p2;
4077   pCx->isTable = 1;
4078   /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
4079   ** can be safely passed to sqlite3VdbeCursorMoveto().  This avoids a test
4080   ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
4081   ** which is a performance optimization */
4082   pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
4083   assert( pOp->p5==0 );
4084   break;
4085 }
4086 
4087 /* Opcode: Close P1 * * * *
4088 **
4089 ** Close a cursor previously opened as P1.  If P1 is not
4090 ** currently open, this instruction is a no-op.
4091 */
4092 case OP_Close: {
4093   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4094   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
4095   p->apCsr[pOp->p1] = 0;
4096   break;
4097 }
4098 
4099 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
4100 /* Opcode: ColumnsUsed P1 * * P4 *
4101 **
4102 ** This opcode (which only exists if SQLite was compiled with
4103 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
4104 ** table or index for cursor P1 are used.  P4 is a 64-bit integer
4105 ** (P4_INT64) in which the first 63 bits are one for each of the
4106 ** first 63 columns of the table or index that are actually used
4107 ** by the cursor.  The high-order bit is set if any column after
4108 ** the 64th is used.
4109 */
4110 case OP_ColumnsUsed: {
4111   VdbeCursor *pC;
4112   pC = p->apCsr[pOp->p1];
4113   assert( pC->eCurType==CURTYPE_BTREE );
4114   pC->maskUsed = *(u64*)pOp->p4.pI64;
4115   break;
4116 }
4117 #endif
4118 
4119 /* Opcode: SeekGE P1 P2 P3 P4 *
4120 ** Synopsis: key=r[P3@P4]
4121 **
4122 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4123 ** use the value in register P3 as the key.  If cursor P1 refers
4124 ** to an SQL index, then P3 is the first in an array of P4 registers
4125 ** that are used as an unpacked index key.
4126 **
4127 ** Reposition cursor P1 so that  it points to the smallest entry that
4128 ** is greater than or equal to the key value. If there are no records
4129 ** greater than or equal to the key and P2 is not zero, then jump to P2.
4130 **
4131 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
4132 ** opcode will either land on a record that exactly matches the key, or
4133 ** else it will cause a jump to P2.  When the cursor is OPFLAG_SEEKEQ,
4134 ** this opcode must be followed by an IdxLE opcode with the same arguments.
4135 ** The IdxGT opcode will be skipped if this opcode succeeds, but the
4136 ** IdxGT opcode will be used on subsequent loop iterations.  The
4137 ** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
4138 ** is an equality search.
4139 **
4140 ** This opcode leaves the cursor configured to move in forward order,
4141 ** from the beginning toward the end.  In other words, the cursor is
4142 ** configured to use Next, not Prev.
4143 **
4144 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
4145 */
4146 /* Opcode: SeekGT P1 P2 P3 P4 *
4147 ** Synopsis: key=r[P3@P4]
4148 **
4149 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4150 ** use the value in register P3 as a key. If cursor P1 refers
4151 ** to an SQL index, then P3 is the first in an array of P4 registers
4152 ** that are used as an unpacked index key.
4153 **
4154 ** Reposition cursor P1 so that it points to the smallest entry that
4155 ** is greater than the key value. If there are no records greater than
4156 ** the key and P2 is not zero, then jump to P2.
4157 **
4158 ** This opcode leaves the cursor configured to move in forward order,
4159 ** from the beginning toward the end.  In other words, the cursor is
4160 ** configured to use Next, not Prev.
4161 **
4162 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
4163 */
4164 /* Opcode: SeekLT P1 P2 P3 P4 *
4165 ** Synopsis: key=r[P3@P4]
4166 **
4167 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4168 ** use the value in register P3 as a key. If cursor P1 refers
4169 ** to an SQL index, then P3 is the first in an array of P4 registers
4170 ** that are used as an unpacked index key.
4171 **
4172 ** Reposition cursor P1 so that  it points to the largest entry that
4173 ** is less than the key value. If there are no records less than
4174 ** the key and P2 is not zero, then jump to P2.
4175 **
4176 ** This opcode leaves the cursor configured to move in reverse order,
4177 ** from the end toward the beginning.  In other words, the cursor is
4178 ** configured to use Prev, not Next.
4179 **
4180 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
4181 */
4182 /* Opcode: SeekLE P1 P2 P3 P4 *
4183 ** Synopsis: key=r[P3@P4]
4184 **
4185 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4186 ** use the value in register P3 as a key. If cursor P1 refers
4187 ** to an SQL index, then P3 is the first in an array of P4 registers
4188 ** that are used as an unpacked index key.
4189 **
4190 ** Reposition cursor P1 so that it points to the largest entry that
4191 ** is less than or equal to the key value. If there are no records
4192 ** less than or equal to the key and P2 is not zero, then jump to P2.
4193 **
4194 ** This opcode leaves the cursor configured to move in reverse order,
4195 ** from the end toward the beginning.  In other words, the cursor is
4196 ** configured to use Prev, not Next.
4197 **
4198 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
4199 ** opcode will either land on a record that exactly matches the key, or
4200 ** else it will cause a jump to P2.  When the cursor is OPFLAG_SEEKEQ,
4201 ** this opcode must be followed by an IdxLE opcode with the same arguments.
4202 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
4203 ** IdxGE opcode will be used on subsequent loop iterations.  The
4204 ** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
4205 ** is an equality search.
4206 **
4207 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
4208 */
4209 case OP_SeekLT:         /* jump, in3, group */
4210 case OP_SeekLE:         /* jump, in3, group */
4211 case OP_SeekGE:         /* jump, in3, group */
4212 case OP_SeekGT: {       /* jump, in3, group */
4213   int res;           /* Comparison result */
4214   int oc;            /* Opcode */
4215   VdbeCursor *pC;    /* The cursor to seek */
4216   UnpackedRecord r;  /* The key to seek for */
4217   int nField;        /* Number of columns or fields in the key */
4218   i64 iKey;          /* The rowid we are to seek to */
4219   int eqOnly;        /* Only interested in == results */
4220 
4221   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4222   assert( pOp->p2!=0 );
4223   pC = p->apCsr[pOp->p1];
4224   assert( pC!=0 );
4225   assert( pC->eCurType==CURTYPE_BTREE );
4226   assert( OP_SeekLE == OP_SeekLT+1 );
4227   assert( OP_SeekGE == OP_SeekLT+2 );
4228   assert( OP_SeekGT == OP_SeekLT+3 );
4229   assert( pC->isOrdered );
4230   assert( pC->uc.pCursor!=0 );
4231   oc = pOp->opcode;
4232   eqOnly = 0;
4233   pC->nullRow = 0;
4234 #ifdef SQLITE_DEBUG
4235   pC->seekOp = pOp->opcode;
4236 #endif
4237 
4238   pC->deferredMoveto = 0;
4239   pC->cacheStatus = CACHE_STALE;
4240   if( pC->isTable ){
4241     u16 flags3, newType;
4242     /* The OPFLAG_SEEKEQ/BTREE_SEEK_EQ flag is only set on index cursors */
4243     assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
4244               || CORRUPT_DB );
4245 
4246     /* The input value in P3 might be of any type: integer, real, string,
4247     ** blob, or NULL.  But it needs to be an integer before we can do
4248     ** the seek, so convert it. */
4249     pIn3 = &aMem[pOp->p3];
4250     flags3 = pIn3->flags;
4251     if( (flags3 & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Str))==MEM_Str ){
4252       applyNumericAffinity(pIn3, 0);
4253     }
4254     iKey = sqlite3VdbeIntValue(pIn3); /* Get the integer key value */
4255     newType = pIn3->flags; /* Record the type after applying numeric affinity */
4256     pIn3->flags = flags3;  /* But convert the type back to its original */
4257 
4258     /* If the P3 value could not be converted into an integer without
4259     ** loss of information, then special processing is required... */
4260     if( (newType & (MEM_Int|MEM_IntReal))==0 ){
4261       if( (newType & MEM_Real)==0 ){
4262         if( (newType & MEM_Null) || oc>=OP_SeekGE ){
4263           VdbeBranchTaken(1,2);
4264           goto jump_to_p2;
4265         }else{
4266           rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
4267           if( rc!=SQLITE_OK ) goto abort_due_to_error;
4268           goto seek_not_found;
4269         }
4270       }else
4271 
4272       /* If the approximation iKey is larger than the actual real search
4273       ** term, substitute >= for > and < for <=. e.g. if the search term
4274       ** is 4.9 and the integer approximation 5:
4275       **
4276       **        (x >  4.9)    ->     (x >= 5)
4277       **        (x <= 4.9)    ->     (x <  5)
4278       */
4279       if( pIn3->u.r<(double)iKey ){
4280         assert( OP_SeekGE==(OP_SeekGT-1) );
4281         assert( OP_SeekLT==(OP_SeekLE-1) );
4282         assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
4283         if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
4284       }
4285 
4286       /* If the approximation iKey is smaller than the actual real search
4287       ** term, substitute <= for < and > for >=.  */
4288       else if( pIn3->u.r>(double)iKey ){
4289         assert( OP_SeekLE==(OP_SeekLT+1) );
4290         assert( OP_SeekGT==(OP_SeekGE+1) );
4291         assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
4292         if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
4293       }
4294     }
4295     rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
4296     pC->movetoTarget = iKey;  /* Used by OP_Delete */
4297     if( rc!=SQLITE_OK ){
4298       goto abort_due_to_error;
4299     }
4300   }else{
4301     /* For a cursor with the OPFLAG_SEEKEQ/BTREE_SEEK_EQ hint, only the
4302     ** OP_SeekGE and OP_SeekLE opcodes are allowed, and these must be
4303     ** immediately followed by an OP_IdxGT or OP_IdxLT opcode, respectively,
4304     ** with the same key.
4305     */
4306     if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
4307       eqOnly = 1;
4308       assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
4309       assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
4310       assert( pOp->opcode==OP_SeekGE || pOp[1].opcode==OP_IdxLT );
4311       assert( pOp->opcode==OP_SeekLE || pOp[1].opcode==OP_IdxGT );
4312       assert( pOp[1].p1==pOp[0].p1 );
4313       assert( pOp[1].p2==pOp[0].p2 );
4314       assert( pOp[1].p3==pOp[0].p3 );
4315       assert( pOp[1].p4.i==pOp[0].p4.i );
4316     }
4317 
4318     nField = pOp->p4.i;
4319     assert( pOp->p4type==P4_INT32 );
4320     assert( nField>0 );
4321     r.pKeyInfo = pC->pKeyInfo;
4322     r.nField = (u16)nField;
4323 
4324     /* The next line of code computes as follows, only faster:
4325     **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
4326     **     r.default_rc = -1;
4327     **   }else{
4328     **     r.default_rc = +1;
4329     **   }
4330     */
4331     r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
4332     assert( oc!=OP_SeekGT || r.default_rc==-1 );
4333     assert( oc!=OP_SeekLE || r.default_rc==-1 );
4334     assert( oc!=OP_SeekGE || r.default_rc==+1 );
4335     assert( oc!=OP_SeekLT || r.default_rc==+1 );
4336 
4337     r.aMem = &aMem[pOp->p3];
4338 #ifdef SQLITE_DEBUG
4339     { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
4340 #endif
4341     r.eqSeen = 0;
4342     rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
4343     if( rc!=SQLITE_OK ){
4344       goto abort_due_to_error;
4345     }
4346     if( eqOnly && r.eqSeen==0 ){
4347       assert( res!=0 );
4348       goto seek_not_found;
4349     }
4350   }
4351 #ifdef SQLITE_TEST
4352   sqlite3_search_count++;
4353 #endif
4354   if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
4355     if( res<0 || (res==0 && oc==OP_SeekGT) ){
4356       res = 0;
4357       rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
4358       if( rc!=SQLITE_OK ){
4359         if( rc==SQLITE_DONE ){
4360           rc = SQLITE_OK;
4361           res = 1;
4362         }else{
4363           goto abort_due_to_error;
4364         }
4365       }
4366     }else{
4367       res = 0;
4368     }
4369   }else{
4370     assert( oc==OP_SeekLT || oc==OP_SeekLE );
4371     if( res>0 || (res==0 && oc==OP_SeekLT) ){
4372       res = 0;
4373       rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
4374       if( rc!=SQLITE_OK ){
4375         if( rc==SQLITE_DONE ){
4376           rc = SQLITE_OK;
4377           res = 1;
4378         }else{
4379           goto abort_due_to_error;
4380         }
4381       }
4382     }else{
4383       /* res might be negative because the table is empty.  Check to
4384       ** see if this is the case.
4385       */
4386       res = sqlite3BtreeEof(pC->uc.pCursor);
4387     }
4388   }
4389 seek_not_found:
4390   assert( pOp->p2>0 );
4391   VdbeBranchTaken(res!=0,2);
4392   if( res ){
4393     goto jump_to_p2;
4394   }else if( eqOnly ){
4395     assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
4396     pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
4397   }
4398   break;
4399 }
4400 
4401 
4402 /* Opcode: SeekScan  P1 P2 * * *
4403 ** Synopsis: Scan-ahead up to P1 rows
4404 **
4405 ** This opcode is a prefix opcode to OP_SeekGE.  In other words, this
4406 ** opcode must be immediately followed by OP_SeekGE. This constraint is
4407 ** checked by assert() statements.
4408 **
4409 ** This opcode uses the P1 through P4 operands of the subsequent
4410 ** OP_SeekGE.  In the text that follows, the operands of the subsequent
4411 ** OP_SeekGE opcode are denoted as SeekOP.P1 through SeekOP.P4.   Only
4412 ** the P1 and P2 operands of this opcode are also used, and  are called
4413 ** This.P1 and This.P2.
4414 **
4415 ** This opcode helps to optimize IN operators on a multi-column index
4416 ** where the IN operator is on the later terms of the index by avoiding
4417 ** unnecessary seeks on the btree, substituting steps to the next row
4418 ** of the b-tree instead.  A correct answer is obtained if this opcode
4419 ** is omitted or is a no-op.
4420 **
4421 ** The SeekGE.P3 and SeekGE.P4 operands identify an unpacked key which
4422 ** is the desired entry that we want the cursor SeekGE.P1 to be pointing
4423 ** to.  Call this SeekGE.P4/P5 row the "target".
4424 **
4425 ** If the SeekGE.P1 cursor is not currently pointing to a valid row,
4426 ** then this opcode is a no-op and control passes through into the OP_SeekGE.
4427 **
4428 ** If the SeekGE.P1 cursor is pointing to a valid row, then that row
4429 ** might be the target row, or it might be near and slightly before the
4430 ** target row.  This opcode attempts to position the cursor on the target
4431 ** row by, perhaps by invoking sqlite3BtreeStep() on the cursor
4432 ** between 0 and This.P1 times.
4433 **
4434 ** There are three possible outcomes from this opcode:<ol>
4435 **
4436 ** <li> If after This.P1 steps, the cursor is still point to a place that
4437 **      is earlier in the btree than the target row,
4438 **      then fall through into the subsquence OP_SeekGE opcode.
4439 **
4440 ** <li> If the cursor is successfully moved to the target row by 0 or more
4441 **      sqlite3BtreeNext() calls, then jump to This.P2, which will land just
4442 **      past the OP_IdxGT opcode that follows the OP_SeekGE.
4443 **
4444 ** <li> If the cursor ends up past the target row (indicating the the target
4445 **      row does not exist in the btree) then jump to SeekOP.P2.
4446 ** </ol>
4447 */
4448 case OP_SeekScan: {
4449   VdbeCursor *pC;
4450   int res;
4451   int nStep;
4452   UnpackedRecord r;
4453 
4454   assert( pOp[1].opcode==OP_SeekGE );
4455 
4456   /* pOp->p2 points to the first instruction past the OP_IdxGT that
4457   ** follows the OP_SeekGE.  */
4458   assert( pOp->p2>=(int)(pOp-aOp)+2 );
4459   assert( aOp[pOp->p2-1].opcode==OP_IdxGT );
4460   assert( pOp[1].p1==aOp[pOp->p2-1].p1 );
4461   assert( pOp[1].p2==aOp[pOp->p2-1].p2 );
4462   assert( pOp[1].p3==aOp[pOp->p2-1].p3 );
4463 
4464   assert( pOp->p1>0 );
4465   pC = p->apCsr[pOp[1].p1];
4466   assert( pC!=0 );
4467   assert( pC->eCurType==CURTYPE_BTREE );
4468   assert( !pC->isTable );
4469   if( !sqlite3BtreeCursorIsValidNN(pC->uc.pCursor) ){
4470 #ifdef SQLITE_DEBUG
4471      if( db->flags&SQLITE_VdbeTrace ){
4472        printf("... cursor not valid - fall through\n");
4473      }
4474 #endif
4475     break;
4476   }
4477   nStep = pOp->p1;
4478   assert( nStep>=1 );
4479   r.pKeyInfo = pC->pKeyInfo;
4480   r.nField = (u16)pOp[1].p4.i;
4481   r.default_rc = 0;
4482   r.aMem = &aMem[pOp[1].p3];
4483 #ifdef SQLITE_DEBUG
4484   {
4485     int i;
4486     for(i=0; i<r.nField; i++){
4487       assert( memIsValid(&r.aMem[i]) );
4488       REGISTER_TRACE(pOp[1].p3+i, &aMem[pOp[1].p3+i]);
4489     }
4490   }
4491 #endif
4492   res = 0;  /* Not needed.  Only used to silence a warning. */
4493   while(1){
4494     rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
4495     if( rc ) goto abort_due_to_error;
4496     if( res>0 ){
4497       seekscan_search_fail:
4498 #ifdef SQLITE_DEBUG
4499       if( db->flags&SQLITE_VdbeTrace ){
4500         printf("... %d steps and then skip\n", pOp->p1 - nStep);
4501       }
4502 #endif
4503       VdbeBranchTaken(1,3);
4504       pOp++;
4505       goto jump_to_p2;
4506     }
4507     if( res==0 ){
4508 #ifdef SQLITE_DEBUG
4509       if( db->flags&SQLITE_VdbeTrace ){
4510         printf("... %d steps and then success\n", pOp->p1 - nStep);
4511       }
4512 #endif
4513       VdbeBranchTaken(2,3);
4514       goto jump_to_p2;
4515       break;
4516     }
4517     if( nStep<=0 ){
4518 #ifdef SQLITE_DEBUG
4519       if( db->flags&SQLITE_VdbeTrace ){
4520         printf("... fall through after %d steps\n", pOp->p1);
4521       }
4522 #endif
4523       VdbeBranchTaken(0,3);
4524       break;
4525     }
4526     nStep--;
4527     rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
4528     if( rc ){
4529       if( rc==SQLITE_DONE ){
4530         rc = SQLITE_OK;
4531         goto seekscan_search_fail;
4532       }else{
4533         goto abort_due_to_error;
4534       }
4535     }
4536   }
4537 
4538   break;
4539 }
4540 
4541 
4542 /* Opcode: SeekHit P1 P2 P3 * *
4543 ** Synopsis: set P2<=seekHit<=P3
4544 **
4545 ** Increase or decrease the seekHit value for cursor P1, if necessary,
4546 ** so that it is no less than P2 and no greater than P3.
4547 **
4548 ** The seekHit integer represents the maximum of terms in an index for which
4549 ** there is known to be at least one match.  If the seekHit value is smaller
4550 ** than the total number of equality terms in an index lookup, then the
4551 ** OP_IfNoHope opcode might run to see if the IN loop can be abandoned
4552 ** early, thus saving work.  This is part of the IN-early-out optimization.
4553 **
4554 ** P1 must be a valid b-tree cursor.
4555 */
4556 case OP_SeekHit: {
4557   VdbeCursor *pC;
4558   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4559   pC = p->apCsr[pOp->p1];
4560   assert( pC!=0 );
4561   assert( pOp->p3>=pOp->p2 );
4562   if( pC->seekHit<pOp->p2 ){
4563     pC->seekHit = pOp->p2;
4564   }else if( pC->seekHit>pOp->p3 ){
4565     pC->seekHit = pOp->p3;
4566   }
4567   break;
4568 }
4569 
4570 /* Opcode: IfNotOpen P1 P2 * * *
4571 ** Synopsis: if( !csr[P1] ) goto P2
4572 **
4573 ** If cursor P1 is not open, jump to instruction P2. Otherwise, fall through.
4574 */
4575 case OP_IfNotOpen: {        /* jump */
4576   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4577   VdbeBranchTaken(p->apCsr[pOp->p1]==0, 2);
4578   if( !p->apCsr[pOp->p1] ){
4579     goto jump_to_p2_and_check_for_interrupt;
4580   }
4581   break;
4582 }
4583 
4584 /* Opcode: Found P1 P2 P3 P4 *
4585 ** Synopsis: key=r[P3@P4]
4586 **
4587 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
4588 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4589 ** record.
4590 **
4591 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
4592 ** is a prefix of any entry in P1 then a jump is made to P2 and
4593 ** P1 is left pointing at the matching entry.
4594 **
4595 ** This operation leaves the cursor in a state where it can be
4596 ** advanced in the forward direction.  The Next instruction will work,
4597 ** but not the Prev instruction.
4598 **
4599 ** See also: NotFound, NoConflict, NotExists. SeekGe
4600 */
4601 /* Opcode: NotFound P1 P2 P3 P4 *
4602 ** Synopsis: key=r[P3@P4]
4603 **
4604 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
4605 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4606 ** record.
4607 **
4608 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
4609 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
4610 ** does contain an entry whose prefix matches the P3/P4 record then control
4611 ** falls through to the next instruction and P1 is left pointing at the
4612 ** matching entry.
4613 **
4614 ** This operation leaves the cursor in a state where it cannot be
4615 ** advanced in either direction.  In other words, the Next and Prev
4616 ** opcodes do not work after this operation.
4617 **
4618 ** See also: Found, NotExists, NoConflict, IfNoHope
4619 */
4620 /* Opcode: IfNoHope P1 P2 P3 P4 *
4621 ** Synopsis: key=r[P3@P4]
4622 **
4623 ** Register P3 is the first of P4 registers that form an unpacked
4624 ** record.  Cursor P1 is an index btree.  P2 is a jump destination.
4625 ** In other words, the operands to this opcode are the same as the
4626 ** operands to OP_NotFound and OP_IdxGT.
4627 **
4628 ** This opcode is an optimization attempt only.  If this opcode always
4629 ** falls through, the correct answer is still obtained, but extra works
4630 ** is performed.
4631 **
4632 ** A value of N in the seekHit flag of cursor P1 means that there exists
4633 ** a key P3:N that will match some record in the index.  We want to know
4634 ** if it is possible for a record P3:P4 to match some record in the
4635 ** index.  If it is not possible, we can skips some work.  So if seekHit
4636 ** is less than P4, attempt to find out if a match is possible by running
4637 ** OP_NotFound.
4638 **
4639 ** This opcode is used in IN clause processing for a multi-column key.
4640 ** If an IN clause is attached to an element of the key other than the
4641 ** left-most element, and if there are no matches on the most recent
4642 ** seek over the whole key, then it might be that one of the key element
4643 ** to the left is prohibiting a match, and hence there is "no hope" of
4644 ** any match regardless of how many IN clause elements are checked.
4645 ** In such a case, we abandon the IN clause search early, using this
4646 ** opcode.  The opcode name comes from the fact that the
4647 ** jump is taken if there is "no hope" of achieving a match.
4648 **
4649 ** See also: NotFound, SeekHit
4650 */
4651 /* Opcode: NoConflict P1 P2 P3 P4 *
4652 ** Synopsis: key=r[P3@P4]
4653 **
4654 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
4655 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4656 ** record.
4657 **
4658 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
4659 ** contains any NULL value, jump immediately to P2.  If all terms of the
4660 ** record are not-NULL then a check is done to determine if any row in the
4661 ** P1 index btree has a matching key prefix.  If there are no matches, jump
4662 ** immediately to P2.  If there is a match, fall through and leave the P1
4663 ** cursor pointing to the matching row.
4664 **
4665 ** This opcode is similar to OP_NotFound with the exceptions that the
4666 ** branch is always taken if any part of the search key input is NULL.
4667 **
4668 ** This operation leaves the cursor in a state where it cannot be
4669 ** advanced in either direction.  In other words, the Next and Prev
4670 ** opcodes do not work after this operation.
4671 **
4672 ** See also: NotFound, Found, NotExists
4673 */
4674 case OP_IfNoHope: {     /* jump, in3 */
4675   VdbeCursor *pC;
4676   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4677   pC = p->apCsr[pOp->p1];
4678   assert( pC!=0 );
4679   if( pC->seekHit>=pOp->p4.i ) break;
4680   /* Fall through into OP_NotFound */
4681   /* no break */ deliberate_fall_through
4682 }
4683 case OP_NoConflict:     /* jump, in3 */
4684 case OP_NotFound:       /* jump, in3 */
4685 case OP_Found: {        /* jump, in3 */
4686   int alreadyExists;
4687   int takeJump;
4688   int ii;
4689   VdbeCursor *pC;
4690   int res;
4691   UnpackedRecord *pFree;
4692   UnpackedRecord *pIdxKey;
4693   UnpackedRecord r;
4694 
4695 #ifdef SQLITE_TEST
4696   if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
4697 #endif
4698 
4699   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4700   assert( pOp->p4type==P4_INT32 );
4701   pC = p->apCsr[pOp->p1];
4702   assert( pC!=0 );
4703 #ifdef SQLITE_DEBUG
4704   pC->seekOp = pOp->opcode;
4705 #endif
4706   pIn3 = &aMem[pOp->p3];
4707   assert( pC->eCurType==CURTYPE_BTREE );
4708   assert( pC->uc.pCursor!=0 );
4709   assert( pC->isTable==0 );
4710   if( pOp->p4.i>0 ){
4711     r.pKeyInfo = pC->pKeyInfo;
4712     r.nField = (u16)pOp->p4.i;
4713     r.aMem = pIn3;
4714 #ifdef SQLITE_DEBUG
4715     for(ii=0; ii<r.nField; ii++){
4716       assert( memIsValid(&r.aMem[ii]) );
4717       assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
4718       if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
4719     }
4720 #endif
4721     pIdxKey = &r;
4722     pFree = 0;
4723   }else{
4724     assert( pIn3->flags & MEM_Blob );
4725     rc = ExpandBlob(pIn3);
4726     assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
4727     if( rc ) goto no_mem;
4728     pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
4729     if( pIdxKey==0 ) goto no_mem;
4730     sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
4731   }
4732   pIdxKey->default_rc = 0;
4733   takeJump = 0;
4734   if( pOp->opcode==OP_NoConflict ){
4735     /* For the OP_NoConflict opcode, take the jump if any of the
4736     ** input fields are NULL, since any key with a NULL will not
4737     ** conflict */
4738     for(ii=0; ii<pIdxKey->nField; ii++){
4739       if( pIdxKey->aMem[ii].flags & MEM_Null ){
4740         takeJump = 1;
4741         break;
4742       }
4743     }
4744   }
4745   rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
4746   if( pFree ) sqlite3DbFreeNN(db, pFree);
4747   if( rc!=SQLITE_OK ){
4748     goto abort_due_to_error;
4749   }
4750   pC->seekResult = res;
4751   alreadyExists = (res==0);
4752   pC->nullRow = 1-alreadyExists;
4753   pC->deferredMoveto = 0;
4754   pC->cacheStatus = CACHE_STALE;
4755   if( pOp->opcode==OP_Found ){
4756     VdbeBranchTaken(alreadyExists!=0,2);
4757     if( alreadyExists ) goto jump_to_p2;
4758   }else{
4759     VdbeBranchTaken(takeJump||alreadyExists==0,2);
4760     if( takeJump || !alreadyExists ) goto jump_to_p2;
4761     if( pOp->opcode==OP_IfNoHope ) pC->seekHit = pOp->p4.i;
4762   }
4763   break;
4764 }
4765 
4766 /* Opcode: SeekRowid P1 P2 P3 * *
4767 ** Synopsis: intkey=r[P3]
4768 **
4769 ** P1 is the index of a cursor open on an SQL table btree (with integer
4770 ** keys).  If register P3 does not contain an integer or if P1 does not
4771 ** contain a record with rowid P3 then jump immediately to P2.
4772 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
4773 ** a record with rowid P3 then
4774 ** leave the cursor pointing at that record and fall through to the next
4775 ** instruction.
4776 **
4777 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
4778 ** the P3 register must be guaranteed to contain an integer value.  With this
4779 ** opcode, register P3 might not contain an integer.
4780 **
4781 ** The OP_NotFound opcode performs the same operation on index btrees
4782 ** (with arbitrary multi-value keys).
4783 **
4784 ** This opcode leaves the cursor in a state where it cannot be advanced
4785 ** in either direction.  In other words, the Next and Prev opcodes will
4786 ** not work following this opcode.
4787 **
4788 ** See also: Found, NotFound, NoConflict, SeekRowid
4789 */
4790 /* Opcode: NotExists P1 P2 P3 * *
4791 ** Synopsis: intkey=r[P3]
4792 **
4793 ** P1 is the index of a cursor open on an SQL table btree (with integer
4794 ** keys).  P3 is an integer rowid.  If P1 does not contain a record with
4795 ** rowid P3 then jump immediately to P2.  Or, if P2 is 0, raise an
4796 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
4797 ** leave the cursor pointing at that record and fall through to the next
4798 ** instruction.
4799 **
4800 ** The OP_SeekRowid opcode performs the same operation but also allows the
4801 ** P3 register to contain a non-integer value, in which case the jump is
4802 ** always taken.  This opcode requires that P3 always contain an integer.
4803 **
4804 ** The OP_NotFound opcode performs the same operation on index btrees
4805 ** (with arbitrary multi-value keys).
4806 **
4807 ** This opcode leaves the cursor in a state where it cannot be advanced
4808 ** in either direction.  In other words, the Next and Prev opcodes will
4809 ** not work following this opcode.
4810 **
4811 ** See also: Found, NotFound, NoConflict, SeekRowid
4812 */
4813 case OP_SeekRowid: {        /* jump, in3 */
4814   VdbeCursor *pC;
4815   BtCursor *pCrsr;
4816   int res;
4817   u64 iKey;
4818 
4819   pIn3 = &aMem[pOp->p3];
4820   testcase( pIn3->flags & MEM_Int );
4821   testcase( pIn3->flags & MEM_IntReal );
4822   testcase( pIn3->flags & MEM_Real );
4823   testcase( (pIn3->flags & (MEM_Str|MEM_Int))==MEM_Str );
4824   if( (pIn3->flags & (MEM_Int|MEM_IntReal))==0 ){
4825     /* If pIn3->u.i does not contain an integer, compute iKey as the
4826     ** integer value of pIn3.  Jump to P2 if pIn3 cannot be converted
4827     ** into an integer without loss of information.  Take care to avoid
4828     ** changing the datatype of pIn3, however, as it is used by other
4829     ** parts of the prepared statement. */
4830     Mem x = pIn3[0];
4831     applyAffinity(&x, SQLITE_AFF_NUMERIC, encoding);
4832     if( (x.flags & MEM_Int)==0 ) goto jump_to_p2;
4833     iKey = x.u.i;
4834     goto notExistsWithKey;
4835   }
4836   /* Fall through into OP_NotExists */
4837   /* no break */ deliberate_fall_through
4838 case OP_NotExists:          /* jump, in3 */
4839   pIn3 = &aMem[pOp->p3];
4840   assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid );
4841   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4842   iKey = pIn3->u.i;
4843 notExistsWithKey:
4844   pC = p->apCsr[pOp->p1];
4845   assert( pC!=0 );
4846 #ifdef SQLITE_DEBUG
4847   if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid;
4848 #endif
4849   assert( pC->isTable );
4850   assert( pC->eCurType==CURTYPE_BTREE );
4851   pCrsr = pC->uc.pCursor;
4852   assert( pCrsr!=0 );
4853   res = 0;
4854   rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
4855   assert( rc==SQLITE_OK || res==0 );
4856   pC->movetoTarget = iKey;  /* Used by OP_Delete */
4857   pC->nullRow = 0;
4858   pC->cacheStatus = CACHE_STALE;
4859   pC->deferredMoveto = 0;
4860   VdbeBranchTaken(res!=0,2);
4861   pC->seekResult = res;
4862   if( res!=0 ){
4863     assert( rc==SQLITE_OK );
4864     if( pOp->p2==0 ){
4865       rc = SQLITE_CORRUPT_BKPT;
4866     }else{
4867       goto jump_to_p2;
4868     }
4869   }
4870   if( rc ) goto abort_due_to_error;
4871   break;
4872 }
4873 
4874 /* Opcode: Sequence P1 P2 * * *
4875 ** Synopsis: r[P2]=cursor[P1].ctr++
4876 **
4877 ** Find the next available sequence number for cursor P1.
4878 ** Write the sequence number into register P2.
4879 ** The sequence number on the cursor is incremented after this
4880 ** instruction.
4881 */
4882 case OP_Sequence: {           /* out2 */
4883   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4884   assert( p->apCsr[pOp->p1]!=0 );
4885   assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
4886   pOut = out2Prerelease(p, pOp);
4887   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
4888   break;
4889 }
4890 
4891 
4892 /* Opcode: NewRowid P1 P2 P3 * *
4893 ** Synopsis: r[P2]=rowid
4894 **
4895 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
4896 ** The record number is not previously used as a key in the database
4897 ** table that cursor P1 points to.  The new record number is written
4898 ** written to register P2.
4899 **
4900 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
4901 ** the largest previously generated record number. No new record numbers are
4902 ** allowed to be less than this value. When this value reaches its maximum,
4903 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
4904 ** generated record number. This P3 mechanism is used to help implement the
4905 ** AUTOINCREMENT feature.
4906 */
4907 case OP_NewRowid: {           /* out2 */
4908   i64 v;                 /* The new rowid */
4909   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
4910   int res;               /* Result of an sqlite3BtreeLast() */
4911   int cnt;               /* Counter to limit the number of searches */
4912   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
4913   VdbeFrame *pFrame;     /* Root frame of VDBE */
4914 
4915   v = 0;
4916   res = 0;
4917   pOut = out2Prerelease(p, pOp);
4918   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4919   pC = p->apCsr[pOp->p1];
4920   assert( pC!=0 );
4921   assert( pC->isTable );
4922   assert( pC->eCurType==CURTYPE_BTREE );
4923   assert( pC->uc.pCursor!=0 );
4924   {
4925     /* The next rowid or record number (different terms for the same
4926     ** thing) is obtained in a two-step algorithm.
4927     **
4928     ** First we attempt to find the largest existing rowid and add one
4929     ** to that.  But if the largest existing rowid is already the maximum
4930     ** positive integer, we have to fall through to the second
4931     ** probabilistic algorithm
4932     **
4933     ** The second algorithm is to select a rowid at random and see if
4934     ** it already exists in the table.  If it does not exist, we have
4935     ** succeeded.  If the random rowid does exist, we select a new one
4936     ** and try again, up to 100 times.
4937     */
4938     assert( pC->isTable );
4939 
4940 #ifdef SQLITE_32BIT_ROWID
4941 #   define MAX_ROWID 0x7fffffff
4942 #else
4943     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
4944     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
4945     ** to provide the constant while making all compilers happy.
4946     */
4947 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
4948 #endif
4949 
4950     if( !pC->useRandomRowid ){
4951       rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
4952       if( rc!=SQLITE_OK ){
4953         goto abort_due_to_error;
4954       }
4955       if( res ){
4956         v = 1;   /* IMP: R-61914-48074 */
4957       }else{
4958         assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
4959         v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4960         if( v>=MAX_ROWID ){
4961           pC->useRandomRowid = 1;
4962         }else{
4963           v++;   /* IMP: R-29538-34987 */
4964         }
4965       }
4966     }
4967 
4968 #ifndef SQLITE_OMIT_AUTOINCREMENT
4969     if( pOp->p3 ){
4970       /* Assert that P3 is a valid memory cell. */
4971       assert( pOp->p3>0 );
4972       if( p->pFrame ){
4973         for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
4974         /* Assert that P3 is a valid memory cell. */
4975         assert( pOp->p3<=pFrame->nMem );
4976         pMem = &pFrame->aMem[pOp->p3];
4977       }else{
4978         /* Assert that P3 is a valid memory cell. */
4979         assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
4980         pMem = &aMem[pOp->p3];
4981         memAboutToChange(p, pMem);
4982       }
4983       assert( memIsValid(pMem) );
4984 
4985       REGISTER_TRACE(pOp->p3, pMem);
4986       sqlite3VdbeMemIntegerify(pMem);
4987       assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
4988       if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
4989         rc = SQLITE_FULL;   /* IMP: R-17817-00630 */
4990         goto abort_due_to_error;
4991       }
4992       if( v<pMem->u.i+1 ){
4993         v = pMem->u.i + 1;
4994       }
4995       pMem->u.i = v;
4996     }
4997 #endif
4998     if( pC->useRandomRowid ){
4999       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
5000       ** largest possible integer (9223372036854775807) then the database
5001       ** engine starts picking positive candidate ROWIDs at random until
5002       ** it finds one that is not previously used. */
5003       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
5004                              ** an AUTOINCREMENT table. */
5005       cnt = 0;
5006       do{
5007         sqlite3_randomness(sizeof(v), &v);
5008         v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */
5009       }while(  ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
5010                                                  0, &res))==SQLITE_OK)
5011             && (res==0)
5012             && (++cnt<100));
5013       if( rc ) goto abort_due_to_error;
5014       if( res==0 ){
5015         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
5016         goto abort_due_to_error;
5017       }
5018       assert( v>0 );  /* EV: R-40812-03570 */
5019     }
5020     pC->deferredMoveto = 0;
5021     pC->cacheStatus = CACHE_STALE;
5022   }
5023   pOut->u.i = v;
5024   break;
5025 }
5026 
5027 /* Opcode: Insert P1 P2 P3 P4 P5
5028 ** Synopsis: intkey=r[P3] data=r[P2]
5029 **
5030 ** Write an entry into the table of cursor P1.  A new entry is
5031 ** created if it doesn't already exist or the data for an existing
5032 ** entry is overwritten.  The data is the value MEM_Blob stored in register
5033 ** number P2. The key is stored in register P3. The key must
5034 ** be a MEM_Int.
5035 **
5036 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
5037 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
5038 ** then rowid is stored for subsequent return by the
5039 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
5040 **
5041 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
5042 ** run faster by avoiding an unnecessary seek on cursor P1.  However,
5043 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
5044 ** seeks on the cursor or if the most recent seek used a key equal to P3.
5045 **
5046 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
5047 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
5048 ** is part of an INSERT operation.  The difference is only important to
5049 ** the update hook.
5050 **
5051 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
5052 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
5053 ** following a successful insert.
5054 **
5055 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
5056 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
5057 ** and register P2 becomes ephemeral.  If the cursor is changed, the
5058 ** value of register P2 will then change.  Make sure this does not
5059 ** cause any problems.)
5060 **
5061 ** This instruction only works on tables.  The equivalent instruction
5062 ** for indices is OP_IdxInsert.
5063 */
5064 case OP_Insert: {
5065   Mem *pData;       /* MEM cell holding data for the record to be inserted */
5066   Mem *pKey;        /* MEM cell holding key  for the record */
5067   VdbeCursor *pC;   /* Cursor to table into which insert is written */
5068   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
5069   const char *zDb;  /* database name - used by the update hook */
5070   Table *pTab;      /* Table structure - used by update and pre-update hooks */
5071   BtreePayload x;   /* Payload to be inserted */
5072 
5073   pData = &aMem[pOp->p2];
5074   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5075   assert( memIsValid(pData) );
5076   pC = p->apCsr[pOp->p1];
5077   assert( pC!=0 );
5078   assert( pC->eCurType==CURTYPE_BTREE );
5079   assert( pC->deferredMoveto==0 );
5080   assert( pC->uc.pCursor!=0 );
5081   assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
5082   assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
5083   REGISTER_TRACE(pOp->p2, pData);
5084   sqlite3VdbeIncrWriteCounter(p, pC);
5085 
5086   pKey = &aMem[pOp->p3];
5087   assert( pKey->flags & MEM_Int );
5088   assert( memIsValid(pKey) );
5089   REGISTER_TRACE(pOp->p3, pKey);
5090   x.nKey = pKey->u.i;
5091 
5092   if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
5093     assert( pC->iDb>=0 );
5094     zDb = db->aDb[pC->iDb].zDbSName;
5095     pTab = pOp->p4.pTab;
5096     assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
5097   }else{
5098     pTab = 0;
5099     zDb = 0;  /* Not needed.  Silence a compiler warning. */
5100   }
5101 
5102 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
5103   /* Invoke the pre-update hook, if any */
5104   if( pTab ){
5105     if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
5106       sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2);
5107     }
5108     if( db->xUpdateCallback==0 || pTab->aCol==0 ){
5109       /* Prevent post-update hook from running in cases when it should not */
5110       pTab = 0;
5111     }
5112   }
5113   if( pOp->p5 & OPFLAG_ISNOOP ) break;
5114 #endif
5115 
5116   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
5117   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
5118   assert( (pData->flags & (MEM_Blob|MEM_Str))!=0 || pData->n==0 );
5119   x.pData = pData->z;
5120   x.nData = pData->n;
5121   seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
5122   if( pData->flags & MEM_Zero ){
5123     x.nZero = pData->u.nZero;
5124   }else{
5125     x.nZero = 0;
5126   }
5127   x.pKey = 0;
5128   rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
5129       (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
5130   );
5131   pC->deferredMoveto = 0;
5132   pC->cacheStatus = CACHE_STALE;
5133 
5134   /* Invoke the update-hook if required. */
5135   if( rc ) goto abort_due_to_error;
5136   if( pTab ){
5137     assert( db->xUpdateCallback!=0 );
5138     assert( pTab->aCol!=0 );
5139     db->xUpdateCallback(db->pUpdateArg,
5140            (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
5141            zDb, pTab->zName, x.nKey);
5142   }
5143   break;
5144 }
5145 
5146 /* Opcode: Delete P1 P2 P3 P4 P5
5147 **
5148 ** Delete the record at which the P1 cursor is currently pointing.
5149 **
5150 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
5151 ** the cursor will be left pointing at  either the next or the previous
5152 ** record in the table. If it is left pointing at the next record, then
5153 ** the next Next instruction will be a no-op. As a result, in this case
5154 ** it is ok to delete a record from within a Next loop. If
5155 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
5156 ** left in an undefined state.
5157 **
5158 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
5159 ** delete one of several associated with deleting a table row and all its
5160 ** associated index entries.  Exactly one of those deletes is the "primary"
5161 ** delete.  The others are all on OPFLAG_FORDELETE cursors or else are
5162 ** marked with the AUXDELETE flag.
5163 **
5164 ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
5165 ** change count is incremented (otherwise not).
5166 **
5167 ** P1 must not be pseudo-table.  It has to be a real table with
5168 ** multiple rows.
5169 **
5170 ** If P4 is not NULL then it points to a Table object. In this case either
5171 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
5172 ** have been positioned using OP_NotFound prior to invoking this opcode in
5173 ** this case. Specifically, if one is configured, the pre-update hook is
5174 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
5175 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
5176 **
5177 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
5178 ** of the memory cell that contains the value that the rowid of the row will
5179 ** be set to by the update.
5180 */
5181 case OP_Delete: {
5182   VdbeCursor *pC;
5183   const char *zDb;
5184   Table *pTab;
5185   int opflags;
5186 
5187   opflags = pOp->p2;
5188   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5189   pC = p->apCsr[pOp->p1];
5190   assert( pC!=0 );
5191   assert( pC->eCurType==CURTYPE_BTREE );
5192   assert( pC->uc.pCursor!=0 );
5193   assert( pC->deferredMoveto==0 );
5194   sqlite3VdbeIncrWriteCounter(p, pC);
5195 
5196 #ifdef SQLITE_DEBUG
5197   if( pOp->p4type==P4_TABLE
5198    && HasRowid(pOp->p4.pTab)
5199    && pOp->p5==0
5200    && sqlite3BtreeCursorIsValidNN(pC->uc.pCursor)
5201   ){
5202     /* If p5 is zero, the seek operation that positioned the cursor prior to
5203     ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
5204     ** the row that is being deleted */
5205     i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5206     assert( CORRUPT_DB || pC->movetoTarget==iKey );
5207   }
5208 #endif
5209 
5210   /* If the update-hook or pre-update-hook will be invoked, set zDb to
5211   ** the name of the db to pass as to it. Also set local pTab to a copy
5212   ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
5213   ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
5214   ** VdbeCursor.movetoTarget to the current rowid.  */
5215   if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
5216     assert( pC->iDb>=0 );
5217     assert( pOp->p4.pTab!=0 );
5218     zDb = db->aDb[pC->iDb].zDbSName;
5219     pTab = pOp->p4.pTab;
5220     if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
5221       pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5222     }
5223   }else{
5224     zDb = 0;   /* Not needed.  Silence a compiler warning. */
5225     pTab = 0;  /* Not needed.  Silence a compiler warning. */
5226   }
5227 
5228 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
5229   /* Invoke the pre-update-hook if required. */
5230   if( db->xPreUpdateCallback && pOp->p4.pTab ){
5231     assert( !(opflags & OPFLAG_ISUPDATE)
5232          || HasRowid(pTab)==0
5233          || (aMem[pOp->p3].flags & MEM_Int)
5234     );
5235     sqlite3VdbePreUpdateHook(p, pC,
5236         (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
5237         zDb, pTab, pC->movetoTarget,
5238         pOp->p3
5239     );
5240   }
5241   if( opflags & OPFLAG_ISNOOP ) break;
5242 #endif
5243 
5244   /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
5245   assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
5246   assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
5247   assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
5248 
5249 #ifdef SQLITE_DEBUG
5250   if( p->pFrame==0 ){
5251     if( pC->isEphemeral==0
5252         && (pOp->p5 & OPFLAG_AUXDELETE)==0
5253         && (pC->wrFlag & OPFLAG_FORDELETE)==0
5254       ){
5255       nExtraDelete++;
5256     }
5257     if( pOp->p2 & OPFLAG_NCHANGE ){
5258       nExtraDelete--;
5259     }
5260   }
5261 #endif
5262 
5263   rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
5264   pC->cacheStatus = CACHE_STALE;
5265   pC->seekResult = 0;
5266   if( rc ) goto abort_due_to_error;
5267 
5268   /* Invoke the update-hook if required. */
5269   if( opflags & OPFLAG_NCHANGE ){
5270     p->nChange++;
5271     if( db->xUpdateCallback && HasRowid(pTab) ){
5272       db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
5273           pC->movetoTarget);
5274       assert( pC->iDb>=0 );
5275     }
5276   }
5277 
5278   break;
5279 }
5280 /* Opcode: ResetCount * * * * *
5281 **
5282 ** The value of the change counter is copied to the database handle
5283 ** change counter (returned by subsequent calls to sqlite3_changes()).
5284 ** Then the VMs internal change counter resets to 0.
5285 ** This is used by trigger programs.
5286 */
5287 case OP_ResetCount: {
5288   sqlite3VdbeSetChanges(db, p->nChange);
5289   p->nChange = 0;
5290   break;
5291 }
5292 
5293 /* Opcode: SorterCompare P1 P2 P3 P4
5294 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
5295 **
5296 ** P1 is a sorter cursor. This instruction compares a prefix of the
5297 ** record blob in register P3 against a prefix of the entry that
5298 ** the sorter cursor currently points to.  Only the first P4 fields
5299 ** of r[P3] and the sorter record are compared.
5300 **
5301 ** If either P3 or the sorter contains a NULL in one of their significant
5302 ** fields (not counting the P4 fields at the end which are ignored) then
5303 ** the comparison is assumed to be equal.
5304 **
5305 ** Fall through to next instruction if the two records compare equal to
5306 ** each other.  Jump to P2 if they are different.
5307 */
5308 case OP_SorterCompare: {
5309   VdbeCursor *pC;
5310   int res;
5311   int nKeyCol;
5312 
5313   pC = p->apCsr[pOp->p1];
5314   assert( isSorter(pC) );
5315   assert( pOp->p4type==P4_INT32 );
5316   pIn3 = &aMem[pOp->p3];
5317   nKeyCol = pOp->p4.i;
5318   res = 0;
5319   rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
5320   VdbeBranchTaken(res!=0,2);
5321   if( rc ) goto abort_due_to_error;
5322   if( res ) goto jump_to_p2;
5323   break;
5324 };
5325 
5326 /* Opcode: SorterData P1 P2 P3 * *
5327 ** Synopsis: r[P2]=data
5328 **
5329 ** Write into register P2 the current sorter data for sorter cursor P1.
5330 ** Then clear the column header cache on cursor P3.
5331 **
5332 ** This opcode is normally use to move a record out of the sorter and into
5333 ** a register that is the source for a pseudo-table cursor created using
5334 ** OpenPseudo.  That pseudo-table cursor is the one that is identified by
5335 ** parameter P3.  Clearing the P3 column cache as part of this opcode saves
5336 ** us from having to issue a separate NullRow instruction to clear that cache.
5337 */
5338 case OP_SorterData: {
5339   VdbeCursor *pC;
5340 
5341   pOut = &aMem[pOp->p2];
5342   pC = p->apCsr[pOp->p1];
5343   assert( isSorter(pC) );
5344   rc = sqlite3VdbeSorterRowkey(pC, pOut);
5345   assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
5346   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5347   if( rc ) goto abort_due_to_error;
5348   p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
5349   break;
5350 }
5351 
5352 /* Opcode: RowData P1 P2 P3 * *
5353 ** Synopsis: r[P2]=data
5354 **
5355 ** Write into register P2 the complete row content for the row at
5356 ** which cursor P1 is currently pointing.
5357 ** There is no interpretation of the data.
5358 ** It is just copied onto the P2 register exactly as
5359 ** it is found in the database file.
5360 **
5361 ** If cursor P1 is an index, then the content is the key of the row.
5362 ** If cursor P2 is a table, then the content extracted is the data.
5363 **
5364 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
5365 ** of a real table, not a pseudo-table.
5366 **
5367 ** If P3!=0 then this opcode is allowed to make an ephemeral pointer
5368 ** into the database page.  That means that the content of the output
5369 ** register will be invalidated as soon as the cursor moves - including
5370 ** moves caused by other cursors that "save" the current cursors
5371 ** position in order that they can write to the same table.  If P3==0
5372 ** then a copy of the data is made into memory.  P3!=0 is faster, but
5373 ** P3==0 is safer.
5374 **
5375 ** If P3!=0 then the content of the P2 register is unsuitable for use
5376 ** in OP_Result and any OP_Result will invalidate the P2 register content.
5377 ** The P2 register content is invalidated by opcodes like OP_Function or
5378 ** by any use of another cursor pointing to the same table.
5379 */
5380 case OP_RowData: {
5381   VdbeCursor *pC;
5382   BtCursor *pCrsr;
5383   u32 n;
5384 
5385   pOut = out2Prerelease(p, pOp);
5386 
5387   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5388   pC = p->apCsr[pOp->p1];
5389   assert( pC!=0 );
5390   assert( pC->eCurType==CURTYPE_BTREE );
5391   assert( isSorter(pC)==0 );
5392   assert( pC->nullRow==0 );
5393   assert( pC->uc.pCursor!=0 );
5394   pCrsr = pC->uc.pCursor;
5395 
5396   /* The OP_RowData opcodes always follow OP_NotExists or
5397   ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
5398   ** that might invalidate the cursor.
5399   ** If this where not the case, on of the following assert()s
5400   ** would fail.  Should this ever change (because of changes in the code
5401   ** generator) then the fix would be to insert a call to
5402   ** sqlite3VdbeCursorMoveto().
5403   */
5404   assert( pC->deferredMoveto==0 );
5405   assert( sqlite3BtreeCursorIsValid(pCrsr) );
5406 
5407   n = sqlite3BtreePayloadSize(pCrsr);
5408   if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
5409     goto too_big;
5410   }
5411   testcase( n==0 );
5412   rc = sqlite3VdbeMemFromBtreeZeroOffset(pCrsr, n, pOut);
5413   if( rc ) goto abort_due_to_error;
5414   if( !pOp->p3 ) Deephemeralize(pOut);
5415   UPDATE_MAX_BLOBSIZE(pOut);
5416   REGISTER_TRACE(pOp->p2, pOut);
5417   break;
5418 }
5419 
5420 /* Opcode: Rowid P1 P2 * * *
5421 ** Synopsis: r[P2]=rowid
5422 **
5423 ** Store in register P2 an integer which is the key of the table entry that
5424 ** P1 is currently point to.
5425 **
5426 ** P1 can be either an ordinary table or a virtual table.  There used to
5427 ** be a separate OP_VRowid opcode for use with virtual tables, but this
5428 ** one opcode now works for both table types.
5429 */
5430 case OP_Rowid: {                 /* out2 */
5431   VdbeCursor *pC;
5432   i64 v;
5433   sqlite3_vtab *pVtab;
5434   const sqlite3_module *pModule;
5435 
5436   pOut = out2Prerelease(p, pOp);
5437   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5438   pC = p->apCsr[pOp->p1];
5439   assert( pC!=0 );
5440   assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
5441   if( pC->nullRow ){
5442     pOut->flags = MEM_Null;
5443     break;
5444   }else if( pC->deferredMoveto ){
5445     v = pC->movetoTarget;
5446 #ifndef SQLITE_OMIT_VIRTUALTABLE
5447   }else if( pC->eCurType==CURTYPE_VTAB ){
5448     assert( pC->uc.pVCur!=0 );
5449     pVtab = pC->uc.pVCur->pVtab;
5450     pModule = pVtab->pModule;
5451     assert( pModule->xRowid );
5452     rc = pModule->xRowid(pC->uc.pVCur, &v);
5453     sqlite3VtabImportErrmsg(p, pVtab);
5454     if( rc ) goto abort_due_to_error;
5455 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5456   }else{
5457     assert( pC->eCurType==CURTYPE_BTREE );
5458     assert( pC->uc.pCursor!=0 );
5459     rc = sqlite3VdbeCursorRestore(pC);
5460     if( rc ) goto abort_due_to_error;
5461     if( pC->nullRow ){
5462       pOut->flags = MEM_Null;
5463       break;
5464     }
5465     v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5466   }
5467   pOut->u.i = v;
5468   break;
5469 }
5470 
5471 /* Opcode: NullRow P1 * * * *
5472 **
5473 ** Move the cursor P1 to a null row.  Any OP_Column operations
5474 ** that occur while the cursor is on the null row will always
5475 ** write a NULL.
5476 */
5477 case OP_NullRow: {
5478   VdbeCursor *pC;
5479 
5480   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5481   pC = p->apCsr[pOp->p1];
5482   assert( pC!=0 );
5483   pC->nullRow = 1;
5484   pC->cacheStatus = CACHE_STALE;
5485   if( pC->eCurType==CURTYPE_BTREE ){
5486     assert( pC->uc.pCursor!=0 );
5487     sqlite3BtreeClearCursor(pC->uc.pCursor);
5488   }
5489 #ifdef SQLITE_DEBUG
5490   if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
5491 #endif
5492   break;
5493 }
5494 
5495 /* Opcode: SeekEnd P1 * * * *
5496 **
5497 ** Position cursor P1 at the end of the btree for the purpose of
5498 ** appending a new entry onto the btree.
5499 **
5500 ** It is assumed that the cursor is used only for appending and so
5501 ** if the cursor is valid, then the cursor must already be pointing
5502 ** at the end of the btree and so no changes are made to
5503 ** the cursor.
5504 */
5505 /* Opcode: Last P1 P2 * * *
5506 **
5507 ** The next use of the Rowid or Column or Prev instruction for P1
5508 ** will refer to the last entry in the database table or index.
5509 ** If the table or index is empty and P2>0, then jump immediately to P2.
5510 ** If P2 is 0 or if the table or index is not empty, fall through
5511 ** to the following instruction.
5512 **
5513 ** This opcode leaves the cursor configured to move in reverse order,
5514 ** from the end toward the beginning.  In other words, the cursor is
5515 ** configured to use Prev, not Next.
5516 */
5517 case OP_SeekEnd:
5518 case OP_Last: {        /* jump */
5519   VdbeCursor *pC;
5520   BtCursor *pCrsr;
5521   int res;
5522 
5523   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5524   pC = p->apCsr[pOp->p1];
5525   assert( pC!=0 );
5526   assert( pC->eCurType==CURTYPE_BTREE );
5527   pCrsr = pC->uc.pCursor;
5528   res = 0;
5529   assert( pCrsr!=0 );
5530 #ifdef SQLITE_DEBUG
5531   pC->seekOp = pOp->opcode;
5532 #endif
5533   if( pOp->opcode==OP_SeekEnd ){
5534     assert( pOp->p2==0 );
5535     pC->seekResult = -1;
5536     if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
5537       break;
5538     }
5539   }
5540   rc = sqlite3BtreeLast(pCrsr, &res);
5541   pC->nullRow = (u8)res;
5542   pC->deferredMoveto = 0;
5543   pC->cacheStatus = CACHE_STALE;
5544   if( rc ) goto abort_due_to_error;
5545   if( pOp->p2>0 ){
5546     VdbeBranchTaken(res!=0,2);
5547     if( res ) goto jump_to_p2;
5548   }
5549   break;
5550 }
5551 
5552 /* Opcode: IfSmaller P1 P2 P3 * *
5553 **
5554 ** Estimate the number of rows in the table P1.  Jump to P2 if that
5555 ** estimate is less than approximately 2**(0.1*P3).
5556 */
5557 case OP_IfSmaller: {        /* jump */
5558   VdbeCursor *pC;
5559   BtCursor *pCrsr;
5560   int res;
5561   i64 sz;
5562 
5563   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5564   pC = p->apCsr[pOp->p1];
5565   assert( pC!=0 );
5566   pCrsr = pC->uc.pCursor;
5567   assert( pCrsr );
5568   rc = sqlite3BtreeFirst(pCrsr, &res);
5569   if( rc ) goto abort_due_to_error;
5570   if( res==0 ){
5571     sz = sqlite3BtreeRowCountEst(pCrsr);
5572     if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
5573   }
5574   VdbeBranchTaken(res!=0,2);
5575   if( res ) goto jump_to_p2;
5576   break;
5577 }
5578 
5579 
5580 /* Opcode: SorterSort P1 P2 * * *
5581 **
5582 ** After all records have been inserted into the Sorter object
5583 ** identified by P1, invoke this opcode to actually do the sorting.
5584 ** Jump to P2 if there are no records to be sorted.
5585 **
5586 ** This opcode is an alias for OP_Sort and OP_Rewind that is used
5587 ** for Sorter objects.
5588 */
5589 /* Opcode: Sort P1 P2 * * *
5590 **
5591 ** This opcode does exactly the same thing as OP_Rewind except that
5592 ** it increments an undocumented global variable used for testing.
5593 **
5594 ** Sorting is accomplished by writing records into a sorting index,
5595 ** then rewinding that index and playing it back from beginning to
5596 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
5597 ** rewinding so that the global variable will be incremented and
5598 ** regression tests can determine whether or not the optimizer is
5599 ** correctly optimizing out sorts.
5600 */
5601 case OP_SorterSort:    /* jump */
5602 case OP_Sort: {        /* jump */
5603 #ifdef SQLITE_TEST
5604   sqlite3_sort_count++;
5605   sqlite3_search_count--;
5606 #endif
5607   p->aCounter[SQLITE_STMTSTATUS_SORT]++;
5608   /* Fall through into OP_Rewind */
5609   /* no break */ deliberate_fall_through
5610 }
5611 /* Opcode: Rewind P1 P2 * * *
5612 **
5613 ** The next use of the Rowid or Column or Next instruction for P1
5614 ** will refer to the first entry in the database table or index.
5615 ** If the table or index is empty, jump immediately to P2.
5616 ** If the table or index is not empty, fall through to the following
5617 ** instruction.
5618 **
5619 ** This opcode leaves the cursor configured to move in forward order,
5620 ** from the beginning toward the end.  In other words, the cursor is
5621 ** configured to use Next, not Prev.
5622 */
5623 case OP_Rewind: {        /* jump */
5624   VdbeCursor *pC;
5625   BtCursor *pCrsr;
5626   int res;
5627 
5628   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5629   assert( pOp->p5==0 );
5630   pC = p->apCsr[pOp->p1];
5631   assert( pC!=0 );
5632   assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
5633   res = 1;
5634 #ifdef SQLITE_DEBUG
5635   pC->seekOp = OP_Rewind;
5636 #endif
5637   if( isSorter(pC) ){
5638     rc = sqlite3VdbeSorterRewind(pC, &res);
5639   }else{
5640     assert( pC->eCurType==CURTYPE_BTREE );
5641     pCrsr = pC->uc.pCursor;
5642     assert( pCrsr );
5643     rc = sqlite3BtreeFirst(pCrsr, &res);
5644     pC->deferredMoveto = 0;
5645     pC->cacheStatus = CACHE_STALE;
5646   }
5647   if( rc ) goto abort_due_to_error;
5648   pC->nullRow = (u8)res;
5649   assert( pOp->p2>0 && pOp->p2<p->nOp );
5650   VdbeBranchTaken(res!=0,2);
5651   if( res ) goto jump_to_p2;
5652   break;
5653 }
5654 
5655 /* Opcode: Next P1 P2 P3 P4 P5
5656 **
5657 ** Advance cursor P1 so that it points to the next key/data pair in its
5658 ** table or index.  If there are no more key/value pairs then fall through
5659 ** to the following instruction.  But if the cursor advance was successful,
5660 ** jump immediately to P2.
5661 **
5662 ** The Next opcode is only valid following an SeekGT, SeekGE, or
5663 ** OP_Rewind opcode used to position the cursor.  Next is not allowed
5664 ** to follow SeekLT, SeekLE, or OP_Last.
5665 **
5666 ** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
5667 ** been opened prior to this opcode or the program will segfault.
5668 **
5669 ** The P3 value is a hint to the btree implementation. If P3==1, that
5670 ** means P1 is an SQL index and that this instruction could have been
5671 ** omitted if that index had been unique.  P3 is usually 0.  P3 is
5672 ** always either 0 or 1.
5673 **
5674 ** P4 is always of type P4_ADVANCE. The function pointer points to
5675 ** sqlite3BtreeNext().
5676 **
5677 ** If P5 is positive and the jump is taken, then event counter
5678 ** number P5-1 in the prepared statement is incremented.
5679 **
5680 ** See also: Prev
5681 */
5682 /* Opcode: Prev P1 P2 P3 P4 P5
5683 **
5684 ** Back up cursor P1 so that it points to the previous key/data pair in its
5685 ** table or index.  If there is no previous key/value pairs then fall through
5686 ** to the following instruction.  But if the cursor backup was successful,
5687 ** jump immediately to P2.
5688 **
5689 **
5690 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
5691 ** OP_Last opcode used to position the cursor.  Prev is not allowed
5692 ** to follow SeekGT, SeekGE, or OP_Rewind.
5693 **
5694 ** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
5695 ** not open then the behavior is undefined.
5696 **
5697 ** The P3 value is a hint to the btree implementation. If P3==1, that
5698 ** means P1 is an SQL index and that this instruction could have been
5699 ** omitted if that index had been unique.  P3 is usually 0.  P3 is
5700 ** always either 0 or 1.
5701 **
5702 ** P4 is always of type P4_ADVANCE. The function pointer points to
5703 ** sqlite3BtreePrevious().
5704 **
5705 ** If P5 is positive and the jump is taken, then event counter
5706 ** number P5-1 in the prepared statement is incremented.
5707 */
5708 /* Opcode: SorterNext P1 P2 * * P5
5709 **
5710 ** This opcode works just like OP_Next except that P1 must be a
5711 ** sorter object for which the OP_SorterSort opcode has been
5712 ** invoked.  This opcode advances the cursor to the next sorted
5713 ** record, or jumps to P2 if there are no more sorted records.
5714 */
5715 case OP_SorterNext: {  /* jump */
5716   VdbeCursor *pC;
5717 
5718   pC = p->apCsr[pOp->p1];
5719   assert( isSorter(pC) );
5720   rc = sqlite3VdbeSorterNext(db, pC);
5721   goto next_tail;
5722 case OP_Prev:          /* jump */
5723 case OP_Next:          /* jump */
5724   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5725   assert( pOp->p5<ArraySize(p->aCounter) );
5726   pC = p->apCsr[pOp->p1];
5727   assert( pC!=0 );
5728   assert( pC->deferredMoveto==0 );
5729   assert( pC->eCurType==CURTYPE_BTREE );
5730   assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
5731   assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
5732 
5733   /* The Next opcode is only used after SeekGT, SeekGE, Rewind, and Found.
5734   ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
5735   assert( pOp->opcode!=OP_Next
5736        || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
5737        || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found
5738        || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid
5739        || pC->seekOp==OP_IfNoHope);
5740   assert( pOp->opcode!=OP_Prev
5741        || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
5742        || pC->seekOp==OP_Last   || pC->seekOp==OP_IfNoHope
5743        || pC->seekOp==OP_NullRow);
5744 
5745   rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
5746 next_tail:
5747   pC->cacheStatus = CACHE_STALE;
5748   VdbeBranchTaken(rc==SQLITE_OK,2);
5749   if( rc==SQLITE_OK ){
5750     pC->nullRow = 0;
5751     p->aCounter[pOp->p5]++;
5752 #ifdef SQLITE_TEST
5753     sqlite3_search_count++;
5754 #endif
5755     goto jump_to_p2_and_check_for_interrupt;
5756   }
5757   if( rc!=SQLITE_DONE ) goto abort_due_to_error;
5758   rc = SQLITE_OK;
5759   pC->nullRow = 1;
5760   goto check_for_interrupt;
5761 }
5762 
5763 /* Opcode: IdxInsert P1 P2 P3 P4 P5
5764 ** Synopsis: key=r[P2]
5765 **
5766 ** Register P2 holds an SQL index key made using the
5767 ** MakeRecord instructions.  This opcode writes that key
5768 ** into the index P1.  Data for the entry is nil.
5769 **
5770 ** If P4 is not zero, then it is the number of values in the unpacked
5771 ** key of reg(P2).  In that case, P3 is the index of the first register
5772 ** for the unpacked key.  The availability of the unpacked key can sometimes
5773 ** be an optimization.
5774 **
5775 ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
5776 ** that this insert is likely to be an append.
5777 **
5778 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
5779 ** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
5780 ** then the change counter is unchanged.
5781 **
5782 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
5783 ** run faster by avoiding an unnecessary seek on cursor P1.  However,
5784 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
5785 ** seeks on the cursor or if the most recent seek used a key equivalent
5786 ** to P2.
5787 **
5788 ** This instruction only works for indices.  The equivalent instruction
5789 ** for tables is OP_Insert.
5790 */
5791 case OP_IdxInsert: {        /* in2 */
5792   VdbeCursor *pC;
5793   BtreePayload x;
5794 
5795   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5796   pC = p->apCsr[pOp->p1];
5797   sqlite3VdbeIncrWriteCounter(p, pC);
5798   assert( pC!=0 );
5799   assert( !isSorter(pC) );
5800   pIn2 = &aMem[pOp->p2];
5801   assert( pIn2->flags & MEM_Blob );
5802   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
5803   assert( pC->eCurType==CURTYPE_BTREE );
5804   assert( pC->isTable==0 );
5805   rc = ExpandBlob(pIn2);
5806   if( rc ) goto abort_due_to_error;
5807   x.nKey = pIn2->n;
5808   x.pKey = pIn2->z;
5809   x.aMem = aMem + pOp->p3;
5810   x.nMem = (u16)pOp->p4.i;
5811   rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
5812        (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
5813       ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
5814       );
5815   assert( pC->deferredMoveto==0 );
5816   pC->cacheStatus = CACHE_STALE;
5817   if( rc) goto abort_due_to_error;
5818   break;
5819 }
5820 
5821 /* Opcode: SorterInsert P1 P2 * * *
5822 ** Synopsis: key=r[P2]
5823 **
5824 ** Register P2 holds an SQL index key made using the
5825 ** MakeRecord instructions.  This opcode writes that key
5826 ** into the sorter P1.  Data for the entry is nil.
5827 */
5828 case OP_SorterInsert: {     /* in2 */
5829   VdbeCursor *pC;
5830 
5831   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5832   pC = p->apCsr[pOp->p1];
5833   sqlite3VdbeIncrWriteCounter(p, pC);
5834   assert( pC!=0 );
5835   assert( isSorter(pC) );
5836   pIn2 = &aMem[pOp->p2];
5837   assert( pIn2->flags & MEM_Blob );
5838   assert( pC->isTable==0 );
5839   rc = ExpandBlob(pIn2);
5840   if( rc ) goto abort_due_to_error;
5841   rc = sqlite3VdbeSorterWrite(pC, pIn2);
5842   if( rc) goto abort_due_to_error;
5843   break;
5844 }
5845 
5846 /* Opcode: IdxDelete P1 P2 P3 * P5
5847 ** Synopsis: key=r[P2@P3]
5848 **
5849 ** The content of P3 registers starting at register P2 form
5850 ** an unpacked index key. This opcode removes that entry from the
5851 ** index opened by cursor P1.
5852 **
5853 ** If P5 is not zero, then raise an SQLITE_CORRUPT_INDEX error
5854 ** if no matching index entry is found.  This happens when running
5855 ** an UPDATE or DELETE statement and the index entry to be updated
5856 ** or deleted is not found.  For some uses of IdxDelete
5857 ** (example:  the EXCEPT operator) it does not matter that no matching
5858 ** entry is found.  For those cases, P5 is zero.
5859 */
5860 case OP_IdxDelete: {
5861   VdbeCursor *pC;
5862   BtCursor *pCrsr;
5863   int res;
5864   UnpackedRecord r;
5865 
5866   assert( pOp->p3>0 );
5867   assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
5868   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5869   pC = p->apCsr[pOp->p1];
5870   assert( pC!=0 );
5871   assert( pC->eCurType==CURTYPE_BTREE );
5872   sqlite3VdbeIncrWriteCounter(p, pC);
5873   pCrsr = pC->uc.pCursor;
5874   assert( pCrsr!=0 );
5875   r.pKeyInfo = pC->pKeyInfo;
5876   r.nField = (u16)pOp->p3;
5877   r.default_rc = 0;
5878   r.aMem = &aMem[pOp->p2];
5879   rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
5880   if( rc ) goto abort_due_to_error;
5881   if( res==0 ){
5882     rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
5883     if( rc ) goto abort_due_to_error;
5884   }else if( pOp->p5 ){
5885     rc = SQLITE_CORRUPT_INDEX;
5886     goto abort_due_to_error;
5887   }
5888   assert( pC->deferredMoveto==0 );
5889   pC->cacheStatus = CACHE_STALE;
5890   pC->seekResult = 0;
5891   break;
5892 }
5893 
5894 /* Opcode: DeferredSeek P1 * P3 P4 *
5895 ** Synopsis: Move P3 to P1.rowid if needed
5896 **
5897 ** P1 is an open index cursor and P3 is a cursor on the corresponding
5898 ** table.  This opcode does a deferred seek of the P3 table cursor
5899 ** to the row that corresponds to the current row of P1.
5900 **
5901 ** This is a deferred seek.  Nothing actually happens until
5902 ** the cursor is used to read a record.  That way, if no reads
5903 ** occur, no unnecessary I/O happens.
5904 **
5905 ** P4 may be an array of integers (type P4_INTARRAY) containing
5906 ** one entry for each column in the P3 table.  If array entry a(i)
5907 ** is non-zero, then reading column a(i)-1 from cursor P3 is
5908 ** equivalent to performing the deferred seek and then reading column i
5909 ** from P1.  This information is stored in P3 and used to redirect
5910 ** reads against P3 over to P1, thus possibly avoiding the need to
5911 ** seek and read cursor P3.
5912 */
5913 /* Opcode: IdxRowid P1 P2 * * *
5914 ** Synopsis: r[P2]=rowid
5915 **
5916 ** Write into register P2 an integer which is the last entry in the record at
5917 ** the end of the index key pointed to by cursor P1.  This integer should be
5918 ** the rowid of the table entry to which this index entry points.
5919 **
5920 ** See also: Rowid, MakeRecord.
5921 */
5922 case OP_DeferredSeek:
5923 case OP_IdxRowid: {           /* out2 */
5924   VdbeCursor *pC;             /* The P1 index cursor */
5925   VdbeCursor *pTabCur;        /* The P2 table cursor (OP_DeferredSeek only) */
5926   i64 rowid;                  /* Rowid that P1 current points to */
5927 
5928   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5929   pC = p->apCsr[pOp->p1];
5930   assert( pC!=0 );
5931   assert( pC->eCurType==CURTYPE_BTREE );
5932   assert( pC->uc.pCursor!=0 );
5933   assert( pC->isTable==0 );
5934   assert( pC->deferredMoveto==0 );
5935   assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
5936 
5937   /* The IdxRowid and Seek opcodes are combined because of the commonality
5938   ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
5939   rc = sqlite3VdbeCursorRestore(pC);
5940 
5941   /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
5942   ** out from under the cursor.  That will never happens for an IdxRowid
5943   ** or Seek opcode */
5944   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
5945 
5946   if( !pC->nullRow ){
5947     rowid = 0;  /* Not needed.  Only used to silence a warning. */
5948     rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
5949     if( rc!=SQLITE_OK ){
5950       goto abort_due_to_error;
5951     }
5952     if( pOp->opcode==OP_DeferredSeek ){
5953       assert( pOp->p3>=0 && pOp->p3<p->nCursor );
5954       pTabCur = p->apCsr[pOp->p3];
5955       assert( pTabCur!=0 );
5956       assert( pTabCur->eCurType==CURTYPE_BTREE );
5957       assert( pTabCur->uc.pCursor!=0 );
5958       assert( pTabCur->isTable );
5959       pTabCur->nullRow = 0;
5960       pTabCur->movetoTarget = rowid;
5961       pTabCur->deferredMoveto = 1;
5962       assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
5963       pTabCur->aAltMap = pOp->p4.ai;
5964       pTabCur->pAltCursor = pC;
5965     }else{
5966       pOut = out2Prerelease(p, pOp);
5967       pOut->u.i = rowid;
5968     }
5969   }else{
5970     assert( pOp->opcode==OP_IdxRowid );
5971     sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
5972   }
5973   break;
5974 }
5975 
5976 /* Opcode: FinishSeek P1 * * * *
5977 **
5978 ** If cursor P1 was previously moved via OP_DeferredSeek, complete that
5979 ** seek operation now, without further delay.  If the cursor seek has
5980 ** already occurred, this instruction is a no-op.
5981 */
5982 case OP_FinishSeek: {
5983   VdbeCursor *pC;             /* The P1 index cursor */
5984 
5985   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5986   pC = p->apCsr[pOp->p1];
5987   if( pC->deferredMoveto ){
5988     rc = sqlite3VdbeFinishMoveto(pC);
5989     if( rc ) goto abort_due_to_error;
5990   }
5991   break;
5992 }
5993 
5994 /* Opcode: IdxGE P1 P2 P3 P4 *
5995 ** Synopsis: key=r[P3@P4]
5996 **
5997 ** The P4 register values beginning with P3 form an unpacked index
5998 ** key that omits the PRIMARY KEY.  Compare this key value against the index
5999 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
6000 ** fields at the end.
6001 **
6002 ** If the P1 index entry is greater than or equal to the key value
6003 ** then jump to P2.  Otherwise fall through to the next instruction.
6004 */
6005 /* Opcode: IdxGT P1 P2 P3 P4 *
6006 ** Synopsis: key=r[P3@P4]
6007 **
6008 ** The P4 register values beginning with P3 form an unpacked index
6009 ** key that omits the PRIMARY KEY.  Compare this key value against the index
6010 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
6011 ** fields at the end.
6012 **
6013 ** If the P1 index entry is greater than the key value
6014 ** then jump to P2.  Otherwise fall through to the next instruction.
6015 */
6016 /* Opcode: IdxLT P1 P2 P3 P4 *
6017 ** Synopsis: key=r[P3@P4]
6018 **
6019 ** The P4 register values beginning with P3 form an unpacked index
6020 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
6021 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
6022 ** ROWID on the P1 index.
6023 **
6024 ** If the P1 index entry is less than the key value then jump to P2.
6025 ** Otherwise fall through to the next instruction.
6026 */
6027 /* Opcode: IdxLE P1 P2 P3 P4 *
6028 ** Synopsis: key=r[P3@P4]
6029 **
6030 ** The P4 register values beginning with P3 form an unpacked index
6031 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
6032 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
6033 ** ROWID on the P1 index.
6034 **
6035 ** If the P1 index entry is less than or equal to the key value then jump
6036 ** to P2. Otherwise fall through to the next instruction.
6037 */
6038 case OP_IdxLE:          /* jump */
6039 case OP_IdxGT:          /* jump */
6040 case OP_IdxLT:          /* jump */
6041 case OP_IdxGE:  {       /* jump */
6042   VdbeCursor *pC;
6043   int res;
6044   UnpackedRecord r;
6045 
6046   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6047   pC = p->apCsr[pOp->p1];
6048   assert( pC!=0 );
6049   assert( pC->isOrdered );
6050   assert( pC->eCurType==CURTYPE_BTREE );
6051   assert( pC->uc.pCursor!=0);
6052   assert( pC->deferredMoveto==0 );
6053   assert( pOp->p4type==P4_INT32 );
6054   r.pKeyInfo = pC->pKeyInfo;
6055   r.nField = (u16)pOp->p4.i;
6056   if( pOp->opcode<OP_IdxLT ){
6057     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
6058     r.default_rc = -1;
6059   }else{
6060     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
6061     r.default_rc = 0;
6062   }
6063   r.aMem = &aMem[pOp->p3];
6064 #ifdef SQLITE_DEBUG
6065   {
6066     int i;
6067     for(i=0; i<r.nField; i++){
6068       assert( memIsValid(&r.aMem[i]) );
6069       REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]);
6070     }
6071   }
6072 #endif
6073 
6074   /* Inlined version of sqlite3VdbeIdxKeyCompare() */
6075   {
6076     i64 nCellKey = 0;
6077     BtCursor *pCur;
6078     Mem m;
6079 
6080     assert( pC->eCurType==CURTYPE_BTREE );
6081     pCur = pC->uc.pCursor;
6082     assert( sqlite3BtreeCursorIsValid(pCur) );
6083     nCellKey = sqlite3BtreePayloadSize(pCur);
6084     /* nCellKey will always be between 0 and 0xffffffff because of the way
6085     ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
6086     if( nCellKey<=0 || nCellKey>0x7fffffff ){
6087       rc = SQLITE_CORRUPT_BKPT;
6088       goto abort_due_to_error;
6089     }
6090     sqlite3VdbeMemInit(&m, db, 0);
6091     rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
6092     if( rc ) goto abort_due_to_error;
6093     res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, &r, 0);
6094     sqlite3VdbeMemRelease(&m);
6095   }
6096   /* End of inlined sqlite3VdbeIdxKeyCompare() */
6097 
6098   assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
6099   if( (pOp->opcode&1)==(OP_IdxLT&1) ){
6100     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
6101     res = -res;
6102   }else{
6103     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
6104     res++;
6105   }
6106   VdbeBranchTaken(res>0,2);
6107   assert( rc==SQLITE_OK );
6108   if( res>0 ) goto jump_to_p2;
6109   break;
6110 }
6111 
6112 /* Opcode: Destroy P1 P2 P3 * *
6113 **
6114 ** Delete an entire database table or index whose root page in the database
6115 ** file is given by P1.
6116 **
6117 ** The table being destroyed is in the main database file if P3==0.  If
6118 ** P3==1 then the table to be clear is in the auxiliary database file
6119 ** that is used to store tables create using CREATE TEMPORARY TABLE.
6120 **
6121 ** If AUTOVACUUM is enabled then it is possible that another root page
6122 ** might be moved into the newly deleted root page in order to keep all
6123 ** root pages contiguous at the beginning of the database.  The former
6124 ** value of the root page that moved - its value before the move occurred -
6125 ** is stored in register P2. If no page movement was required (because the
6126 ** table being dropped was already the last one in the database) then a
6127 ** zero is stored in register P2.  If AUTOVACUUM is disabled then a zero
6128 ** is stored in register P2.
6129 **
6130 ** This opcode throws an error if there are any active reader VMs when
6131 ** it is invoked. This is done to avoid the difficulty associated with
6132 ** updating existing cursors when a root page is moved in an AUTOVACUUM
6133 ** database. This error is thrown even if the database is not an AUTOVACUUM
6134 ** db in order to avoid introducing an incompatibility between autovacuum
6135 ** and non-autovacuum modes.
6136 **
6137 ** See also: Clear
6138 */
6139 case OP_Destroy: {     /* out2 */
6140   int iMoved;
6141   int iDb;
6142 
6143   sqlite3VdbeIncrWriteCounter(p, 0);
6144   assert( p->readOnly==0 );
6145   assert( pOp->p1>1 );
6146   pOut = out2Prerelease(p, pOp);
6147   pOut->flags = MEM_Null;
6148   if( db->nVdbeRead > db->nVDestroy+1 ){
6149     rc = SQLITE_LOCKED;
6150     p->errorAction = OE_Abort;
6151     goto abort_due_to_error;
6152   }else{
6153     iDb = pOp->p3;
6154     assert( DbMaskTest(p->btreeMask, iDb) );
6155     iMoved = 0;  /* Not needed.  Only to silence a warning. */
6156     rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
6157     pOut->flags = MEM_Int;
6158     pOut->u.i = iMoved;
6159     if( rc ) goto abort_due_to_error;
6160 #ifndef SQLITE_OMIT_AUTOVACUUM
6161     if( iMoved!=0 ){
6162       sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
6163       /* All OP_Destroy operations occur on the same btree */
6164       assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
6165       resetSchemaOnFault = iDb+1;
6166     }
6167 #endif
6168   }
6169   break;
6170 }
6171 
6172 /* Opcode: Clear P1 P2 P3
6173 **
6174 ** Delete all contents of the database table or index whose root page
6175 ** in the database file is given by P1.  But, unlike Destroy, do not
6176 ** remove the table or index from the database file.
6177 **
6178 ** The table being clear is in the main database file if P2==0.  If
6179 ** P2==1 then the table to be clear is in the auxiliary database file
6180 ** that is used to store tables create using CREATE TEMPORARY TABLE.
6181 **
6182 ** If the P3 value is non-zero, then the table referred to must be an
6183 ** intkey table (an SQL table, not an index). In this case the row change
6184 ** count is incremented by the number of rows in the table being cleared.
6185 ** If P3 is greater than zero, then the value stored in register P3 is
6186 ** also incremented by the number of rows in the table being cleared.
6187 **
6188 ** See also: Destroy
6189 */
6190 case OP_Clear: {
6191   int nChange;
6192 
6193   sqlite3VdbeIncrWriteCounter(p, 0);
6194   nChange = 0;
6195   assert( p->readOnly==0 );
6196   assert( DbMaskTest(p->btreeMask, pOp->p2) );
6197   rc = sqlite3BtreeClearTable(
6198       db->aDb[pOp->p2].pBt, (u32)pOp->p1, (pOp->p3 ? &nChange : 0)
6199   );
6200   if( pOp->p3 ){
6201     p->nChange += nChange;
6202     if( pOp->p3>0 ){
6203       assert( memIsValid(&aMem[pOp->p3]) );
6204       memAboutToChange(p, &aMem[pOp->p3]);
6205       aMem[pOp->p3].u.i += nChange;
6206     }
6207   }
6208   if( rc ) goto abort_due_to_error;
6209   break;
6210 }
6211 
6212 /* Opcode: ResetSorter P1 * * * *
6213 **
6214 ** Delete all contents from the ephemeral table or sorter
6215 ** that is open on cursor P1.
6216 **
6217 ** This opcode only works for cursors used for sorting and
6218 ** opened with OP_OpenEphemeral or OP_SorterOpen.
6219 */
6220 case OP_ResetSorter: {
6221   VdbeCursor *pC;
6222 
6223   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6224   pC = p->apCsr[pOp->p1];
6225   assert( pC!=0 );
6226   if( isSorter(pC) ){
6227     sqlite3VdbeSorterReset(db, pC->uc.pSorter);
6228   }else{
6229     assert( pC->eCurType==CURTYPE_BTREE );
6230     assert( pC->isEphemeral );
6231     rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
6232     if( rc ) goto abort_due_to_error;
6233   }
6234   break;
6235 }
6236 
6237 /* Opcode: CreateBtree P1 P2 P3 * *
6238 ** Synopsis: r[P2]=root iDb=P1 flags=P3
6239 **
6240 ** Allocate a new b-tree in the main database file if P1==0 or in the
6241 ** TEMP database file if P1==1 or in an attached database if
6242 ** P1>1.  The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
6243 ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
6244 ** The root page number of the new b-tree is stored in register P2.
6245 */
6246 case OP_CreateBtree: {          /* out2 */
6247   Pgno pgno;
6248   Db *pDb;
6249 
6250   sqlite3VdbeIncrWriteCounter(p, 0);
6251   pOut = out2Prerelease(p, pOp);
6252   pgno = 0;
6253   assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
6254   assert( pOp->p1>=0 && pOp->p1<db->nDb );
6255   assert( DbMaskTest(p->btreeMask, pOp->p1) );
6256   assert( p->readOnly==0 );
6257   pDb = &db->aDb[pOp->p1];
6258   assert( pDb->pBt!=0 );
6259   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
6260   if( rc ) goto abort_due_to_error;
6261   pOut->u.i = pgno;
6262   break;
6263 }
6264 
6265 /* Opcode: SqlExec * * * P4 *
6266 **
6267 ** Run the SQL statement or statements specified in the P4 string.
6268 */
6269 case OP_SqlExec: {
6270   sqlite3VdbeIncrWriteCounter(p, 0);
6271   db->nSqlExec++;
6272   rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
6273   db->nSqlExec--;
6274   if( rc ) goto abort_due_to_error;
6275   break;
6276 }
6277 
6278 /* Opcode: ParseSchema P1 * * P4 *
6279 **
6280 ** Read and parse all entries from the schema table of database P1
6281 ** that match the WHERE clause P4.  If P4 is a NULL pointer, then the
6282 ** entire schema for P1 is reparsed.
6283 **
6284 ** This opcode invokes the parser to create a new virtual machine,
6285 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
6286 */
6287 case OP_ParseSchema: {
6288   int iDb;
6289   const char *zSchema;
6290   char *zSql;
6291   InitData initData;
6292 
6293   /* Any prepared statement that invokes this opcode will hold mutexes
6294   ** on every btree.  This is a prerequisite for invoking
6295   ** sqlite3InitCallback().
6296   */
6297 #ifdef SQLITE_DEBUG
6298   for(iDb=0; iDb<db->nDb; iDb++){
6299     assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
6300   }
6301 #endif
6302 
6303   iDb = pOp->p1;
6304   assert( iDb>=0 && iDb<db->nDb );
6305   assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
6306 
6307 #ifndef SQLITE_OMIT_ALTERTABLE
6308   if( pOp->p4.z==0 ){
6309     sqlite3SchemaClear(db->aDb[iDb].pSchema);
6310     db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
6311     rc = sqlite3InitOne(db, iDb, &p->zErrMsg, INITFLAG_AlterTable);
6312     db->mDbFlags |= DBFLAG_SchemaChange;
6313     p->expired = 0;
6314   }else
6315 #endif
6316   {
6317     zSchema = DFLT_SCHEMA_TABLE;
6318     initData.db = db;
6319     initData.iDb = iDb;
6320     initData.pzErrMsg = &p->zErrMsg;
6321     initData.mInitFlags = 0;
6322     initData.mxPage = sqlite3BtreeLastPage(db->aDb[iDb].pBt);
6323     zSql = sqlite3MPrintf(db,
6324        "SELECT*FROM\"%w\".%s WHERE %s ORDER BY rowid",
6325        db->aDb[iDb].zDbSName, zSchema, pOp->p4.z);
6326     if( zSql==0 ){
6327       rc = SQLITE_NOMEM_BKPT;
6328     }else{
6329       assert( db->init.busy==0 );
6330       db->init.busy = 1;
6331       initData.rc = SQLITE_OK;
6332       initData.nInitRow = 0;
6333       assert( !db->mallocFailed );
6334       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
6335       if( rc==SQLITE_OK ) rc = initData.rc;
6336       if( rc==SQLITE_OK && initData.nInitRow==0 ){
6337         /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse
6338         ** at least one SQL statement. Any less than that indicates that
6339         ** the sqlite_schema table is corrupt. */
6340         rc = SQLITE_CORRUPT_BKPT;
6341       }
6342       sqlite3DbFreeNN(db, zSql);
6343       db->init.busy = 0;
6344     }
6345   }
6346   if( rc ){
6347     sqlite3ResetAllSchemasOfConnection(db);
6348     if( rc==SQLITE_NOMEM ){
6349       goto no_mem;
6350     }
6351     goto abort_due_to_error;
6352   }
6353   break;
6354 }
6355 
6356 #if !defined(SQLITE_OMIT_ANALYZE)
6357 /* Opcode: LoadAnalysis P1 * * * *
6358 **
6359 ** Read the sqlite_stat1 table for database P1 and load the content
6360 ** of that table into the internal index hash table.  This will cause
6361 ** the analysis to be used when preparing all subsequent queries.
6362 */
6363 case OP_LoadAnalysis: {
6364   assert( pOp->p1>=0 && pOp->p1<db->nDb );
6365   rc = sqlite3AnalysisLoad(db, pOp->p1);
6366   if( rc ) goto abort_due_to_error;
6367   break;
6368 }
6369 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
6370 
6371 /* Opcode: DropTable P1 * * P4 *
6372 **
6373 ** Remove the internal (in-memory) data structures that describe
6374 ** the table named P4 in database P1.  This is called after a table
6375 ** is dropped from disk (using the Destroy opcode) in order to keep
6376 ** the internal representation of the
6377 ** schema consistent with what is on disk.
6378 */
6379 case OP_DropTable: {
6380   sqlite3VdbeIncrWriteCounter(p, 0);
6381   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
6382   break;
6383 }
6384 
6385 /* Opcode: DropIndex P1 * * P4 *
6386 **
6387 ** Remove the internal (in-memory) data structures that describe
6388 ** the index named P4 in database P1.  This is called after an index
6389 ** is dropped from disk (using the Destroy opcode)
6390 ** in order to keep the internal representation of the
6391 ** schema consistent with what is on disk.
6392 */
6393 case OP_DropIndex: {
6394   sqlite3VdbeIncrWriteCounter(p, 0);
6395   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
6396   break;
6397 }
6398 
6399 /* Opcode: DropTrigger P1 * * P4 *
6400 **
6401 ** Remove the internal (in-memory) data structures that describe
6402 ** the trigger named P4 in database P1.  This is called after a trigger
6403 ** is dropped from disk (using the Destroy opcode) in order to keep
6404 ** the internal representation of the
6405 ** schema consistent with what is on disk.
6406 */
6407 case OP_DropTrigger: {
6408   sqlite3VdbeIncrWriteCounter(p, 0);
6409   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
6410   break;
6411 }
6412 
6413 
6414 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
6415 /* Opcode: IntegrityCk P1 P2 P3 P4 P5
6416 **
6417 ** Do an analysis of the currently open database.  Store in
6418 ** register P1 the text of an error message describing any problems.
6419 ** If no problems are found, store a NULL in register P1.
6420 **
6421 ** The register P3 contains one less than the maximum number of allowed errors.
6422 ** At most reg(P3) errors will be reported.
6423 ** In other words, the analysis stops as soon as reg(P1) errors are
6424 ** seen.  Reg(P1) is updated with the number of errors remaining.
6425 **
6426 ** The root page numbers of all tables in the database are integers
6427 ** stored in P4_INTARRAY argument.
6428 **
6429 ** If P5 is not zero, the check is done on the auxiliary database
6430 ** file, not the main database file.
6431 **
6432 ** This opcode is used to implement the integrity_check pragma.
6433 */
6434 case OP_IntegrityCk: {
6435   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
6436   Pgno *aRoot;    /* Array of rootpage numbers for tables to be checked */
6437   int nErr;       /* Number of errors reported */
6438   char *z;        /* Text of the error report */
6439   Mem *pnErr;     /* Register keeping track of errors remaining */
6440 
6441   assert( p->bIsReader );
6442   nRoot = pOp->p2;
6443   aRoot = pOp->p4.ai;
6444   assert( nRoot>0 );
6445   assert( aRoot[0]==(Pgno)nRoot );
6446   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
6447   pnErr = &aMem[pOp->p3];
6448   assert( (pnErr->flags & MEM_Int)!=0 );
6449   assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
6450   pIn1 = &aMem[pOp->p1];
6451   assert( pOp->p5<db->nDb );
6452   assert( DbMaskTest(p->btreeMask, pOp->p5) );
6453   z = sqlite3BtreeIntegrityCheck(db, db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
6454                                  (int)pnErr->u.i+1, &nErr);
6455   sqlite3VdbeMemSetNull(pIn1);
6456   if( nErr==0 ){
6457     assert( z==0 );
6458   }else if( z==0 ){
6459     goto no_mem;
6460   }else{
6461     pnErr->u.i -= nErr-1;
6462     sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
6463   }
6464   UPDATE_MAX_BLOBSIZE(pIn1);
6465   sqlite3VdbeChangeEncoding(pIn1, encoding);
6466   goto check_for_interrupt;
6467 }
6468 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
6469 
6470 /* Opcode: RowSetAdd P1 P2 * * *
6471 ** Synopsis: rowset(P1)=r[P2]
6472 **
6473 ** Insert the integer value held by register P2 into a RowSet object
6474 ** held in register P1.
6475 **
6476 ** An assertion fails if P2 is not an integer.
6477 */
6478 case OP_RowSetAdd: {       /* in1, in2 */
6479   pIn1 = &aMem[pOp->p1];
6480   pIn2 = &aMem[pOp->p2];
6481   assert( (pIn2->flags & MEM_Int)!=0 );
6482   if( (pIn1->flags & MEM_Blob)==0 ){
6483     if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
6484   }
6485   assert( sqlite3VdbeMemIsRowSet(pIn1) );
6486   sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i);
6487   break;
6488 }
6489 
6490 /* Opcode: RowSetRead P1 P2 P3 * *
6491 ** Synopsis: r[P3]=rowset(P1)
6492 **
6493 ** Extract the smallest value from the RowSet object in P1
6494 ** and put that value into register P3.
6495 ** Or, if RowSet object P1 is initially empty, leave P3
6496 ** unchanged and jump to instruction P2.
6497 */
6498 case OP_RowSetRead: {       /* jump, in1, out3 */
6499   i64 val;
6500 
6501   pIn1 = &aMem[pOp->p1];
6502   assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) );
6503   if( (pIn1->flags & MEM_Blob)==0
6504    || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0
6505   ){
6506     /* The boolean index is empty */
6507     sqlite3VdbeMemSetNull(pIn1);
6508     VdbeBranchTaken(1,2);
6509     goto jump_to_p2_and_check_for_interrupt;
6510   }else{
6511     /* A value was pulled from the index */
6512     VdbeBranchTaken(0,2);
6513     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
6514   }
6515   goto check_for_interrupt;
6516 }
6517 
6518 /* Opcode: RowSetTest P1 P2 P3 P4
6519 ** Synopsis: if r[P3] in rowset(P1) goto P2
6520 **
6521 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
6522 ** contains a RowSet object and that RowSet object contains
6523 ** the value held in P3, jump to register P2. Otherwise, insert the
6524 ** integer in P3 into the RowSet and continue on to the
6525 ** next opcode.
6526 **
6527 ** The RowSet object is optimized for the case where sets of integers
6528 ** are inserted in distinct phases, which each set contains no duplicates.
6529 ** Each set is identified by a unique P4 value. The first set
6530 ** must have P4==0, the final set must have P4==-1, and for all other sets
6531 ** must have P4>0.
6532 **
6533 ** This allows optimizations: (a) when P4==0 there is no need to test
6534 ** the RowSet object for P3, as it is guaranteed not to contain it,
6535 ** (b) when P4==-1 there is no need to insert the value, as it will
6536 ** never be tested for, and (c) when a value that is part of set X is
6537 ** inserted, there is no need to search to see if the same value was
6538 ** previously inserted as part of set X (only if it was previously
6539 ** inserted as part of some other set).
6540 */
6541 case OP_RowSetTest: {                     /* jump, in1, in3 */
6542   int iSet;
6543   int exists;
6544 
6545   pIn1 = &aMem[pOp->p1];
6546   pIn3 = &aMem[pOp->p3];
6547   iSet = pOp->p4.i;
6548   assert( pIn3->flags&MEM_Int );
6549 
6550   /* If there is anything other than a rowset object in memory cell P1,
6551   ** delete it now and initialize P1 with an empty rowset
6552   */
6553   if( (pIn1->flags & MEM_Blob)==0 ){
6554     if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
6555   }
6556   assert( sqlite3VdbeMemIsRowSet(pIn1) );
6557   assert( pOp->p4type==P4_INT32 );
6558   assert( iSet==-1 || iSet>=0 );
6559   if( iSet ){
6560     exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i);
6561     VdbeBranchTaken(exists!=0,2);
6562     if( exists ) goto jump_to_p2;
6563   }
6564   if( iSet>=0 ){
6565     sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i);
6566   }
6567   break;
6568 }
6569 
6570 
6571 #ifndef SQLITE_OMIT_TRIGGER
6572 
6573 /* Opcode: Program P1 P2 P3 P4 P5
6574 **
6575 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
6576 **
6577 ** P1 contains the address of the memory cell that contains the first memory
6578 ** cell in an array of values used as arguments to the sub-program. P2
6579 ** contains the address to jump to if the sub-program throws an IGNORE
6580 ** exception using the RAISE() function. Register P3 contains the address
6581 ** of a memory cell in this (the parent) VM that is used to allocate the
6582 ** memory required by the sub-vdbe at runtime.
6583 **
6584 ** P4 is a pointer to the VM containing the trigger program.
6585 **
6586 ** If P5 is non-zero, then recursive program invocation is enabled.
6587 */
6588 case OP_Program: {        /* jump */
6589   int nMem;               /* Number of memory registers for sub-program */
6590   int nByte;              /* Bytes of runtime space required for sub-program */
6591   Mem *pRt;               /* Register to allocate runtime space */
6592   Mem *pMem;              /* Used to iterate through memory cells */
6593   Mem *pEnd;              /* Last memory cell in new array */
6594   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
6595   SubProgram *pProgram;   /* Sub-program to execute */
6596   void *t;                /* Token identifying trigger */
6597 
6598   pProgram = pOp->p4.pProgram;
6599   pRt = &aMem[pOp->p3];
6600   assert( pProgram->nOp>0 );
6601 
6602   /* If the p5 flag is clear, then recursive invocation of triggers is
6603   ** disabled for backwards compatibility (p5 is set if this sub-program
6604   ** is really a trigger, not a foreign key action, and the flag set
6605   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
6606   **
6607   ** It is recursive invocation of triggers, at the SQL level, that is
6608   ** disabled. In some cases a single trigger may generate more than one
6609   ** SubProgram (if the trigger may be executed with more than one different
6610   ** ON CONFLICT algorithm). SubProgram structures associated with a
6611   ** single trigger all have the same value for the SubProgram.token
6612   ** variable.  */
6613   if( pOp->p5 ){
6614     t = pProgram->token;
6615     for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
6616     if( pFrame ) break;
6617   }
6618 
6619   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
6620     rc = SQLITE_ERROR;
6621     sqlite3VdbeError(p, "too many levels of trigger recursion");
6622     goto abort_due_to_error;
6623   }
6624 
6625   /* Register pRt is used to store the memory required to save the state
6626   ** of the current program, and the memory required at runtime to execute
6627   ** the trigger program. If this trigger has been fired before, then pRt
6628   ** is already allocated. Otherwise, it must be initialized.  */
6629   if( (pRt->flags&MEM_Blob)==0 ){
6630     /* SubProgram.nMem is set to the number of memory cells used by the
6631     ** program stored in SubProgram.aOp. As well as these, one memory
6632     ** cell is required for each cursor used by the program. Set local
6633     ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
6634     */
6635     nMem = pProgram->nMem + pProgram->nCsr;
6636     assert( nMem>0 );
6637     if( pProgram->nCsr==0 ) nMem++;
6638     nByte = ROUND8(sizeof(VdbeFrame))
6639               + nMem * sizeof(Mem)
6640               + pProgram->nCsr * sizeof(VdbeCursor*)
6641               + (pProgram->nOp + 7)/8;
6642     pFrame = sqlite3DbMallocZero(db, nByte);
6643     if( !pFrame ){
6644       goto no_mem;
6645     }
6646     sqlite3VdbeMemRelease(pRt);
6647     pRt->flags = MEM_Blob|MEM_Dyn;
6648     pRt->z = (char*)pFrame;
6649     pRt->n = nByte;
6650     pRt->xDel = sqlite3VdbeFrameMemDel;
6651 
6652     pFrame->v = p;
6653     pFrame->nChildMem = nMem;
6654     pFrame->nChildCsr = pProgram->nCsr;
6655     pFrame->pc = (int)(pOp - aOp);
6656     pFrame->aMem = p->aMem;
6657     pFrame->nMem = p->nMem;
6658     pFrame->apCsr = p->apCsr;
6659     pFrame->nCursor = p->nCursor;
6660     pFrame->aOp = p->aOp;
6661     pFrame->nOp = p->nOp;
6662     pFrame->token = pProgram->token;
6663 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
6664     pFrame->anExec = p->anExec;
6665 #endif
6666 #ifdef SQLITE_DEBUG
6667     pFrame->iFrameMagic = SQLITE_FRAME_MAGIC;
6668 #endif
6669 
6670     pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
6671     for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
6672       pMem->flags = MEM_Undefined;
6673       pMem->db = db;
6674     }
6675   }else{
6676     pFrame = (VdbeFrame*)pRt->z;
6677     assert( pRt->xDel==sqlite3VdbeFrameMemDel );
6678     assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
6679         || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
6680     assert( pProgram->nCsr==pFrame->nChildCsr );
6681     assert( (int)(pOp - aOp)==pFrame->pc );
6682   }
6683 
6684   p->nFrame++;
6685   pFrame->pParent = p->pFrame;
6686   pFrame->lastRowid = db->lastRowid;
6687   pFrame->nChange = p->nChange;
6688   pFrame->nDbChange = p->db->nChange;
6689   assert( pFrame->pAuxData==0 );
6690   pFrame->pAuxData = p->pAuxData;
6691   p->pAuxData = 0;
6692   p->nChange = 0;
6693   p->pFrame = pFrame;
6694   p->aMem = aMem = VdbeFrameMem(pFrame);
6695   p->nMem = pFrame->nChildMem;
6696   p->nCursor = (u16)pFrame->nChildCsr;
6697   p->apCsr = (VdbeCursor **)&aMem[p->nMem];
6698   pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
6699   memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
6700   p->aOp = aOp = pProgram->aOp;
6701   p->nOp = pProgram->nOp;
6702 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
6703   p->anExec = 0;
6704 #endif
6705 #ifdef SQLITE_DEBUG
6706   /* Verify that second and subsequent executions of the same trigger do not
6707   ** try to reuse register values from the first use. */
6708   {
6709     int i;
6710     for(i=0; i<p->nMem; i++){
6711       aMem[i].pScopyFrom = 0;  /* Prevent false-positive AboutToChange() errs */
6712       MemSetTypeFlag(&aMem[i], MEM_Undefined); /* Fault if this reg is reused */
6713     }
6714   }
6715 #endif
6716   pOp = &aOp[-1];
6717   goto check_for_interrupt;
6718 }
6719 
6720 /* Opcode: Param P1 P2 * * *
6721 **
6722 ** This opcode is only ever present in sub-programs called via the
6723 ** OP_Program instruction. Copy a value currently stored in a memory
6724 ** cell of the calling (parent) frame to cell P2 in the current frames
6725 ** address space. This is used by trigger programs to access the new.*
6726 ** and old.* values.
6727 **
6728 ** The address of the cell in the parent frame is determined by adding
6729 ** the value of the P1 argument to the value of the P1 argument to the
6730 ** calling OP_Program instruction.
6731 */
6732 case OP_Param: {           /* out2 */
6733   VdbeFrame *pFrame;
6734   Mem *pIn;
6735   pOut = out2Prerelease(p, pOp);
6736   pFrame = p->pFrame;
6737   pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
6738   sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
6739   break;
6740 }
6741 
6742 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
6743 
6744 #ifndef SQLITE_OMIT_FOREIGN_KEY
6745 /* Opcode: FkCounter P1 P2 * * *
6746 ** Synopsis: fkctr[P1]+=P2
6747 **
6748 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
6749 ** If P1 is non-zero, the database constraint counter is incremented
6750 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
6751 ** statement counter is incremented (immediate foreign key constraints).
6752 */
6753 case OP_FkCounter: {
6754   if( db->flags & SQLITE_DeferFKs ){
6755     db->nDeferredImmCons += pOp->p2;
6756   }else if( pOp->p1 ){
6757     db->nDeferredCons += pOp->p2;
6758   }else{
6759     p->nFkConstraint += pOp->p2;
6760   }
6761   break;
6762 }
6763 
6764 /* Opcode: FkIfZero P1 P2 * * *
6765 ** Synopsis: if fkctr[P1]==0 goto P2
6766 **
6767 ** This opcode tests if a foreign key constraint-counter is currently zero.
6768 ** If so, jump to instruction P2. Otherwise, fall through to the next
6769 ** instruction.
6770 **
6771 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
6772 ** is zero (the one that counts deferred constraint violations). If P1 is
6773 ** zero, the jump is taken if the statement constraint-counter is zero
6774 ** (immediate foreign key constraint violations).
6775 */
6776 case OP_FkIfZero: {         /* jump */
6777   if( pOp->p1 ){
6778     VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
6779     if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
6780   }else{
6781     VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
6782     if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
6783   }
6784   break;
6785 }
6786 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
6787 
6788 #ifndef SQLITE_OMIT_AUTOINCREMENT
6789 /* Opcode: MemMax P1 P2 * * *
6790 ** Synopsis: r[P1]=max(r[P1],r[P2])
6791 **
6792 ** P1 is a register in the root frame of this VM (the root frame is
6793 ** different from the current frame if this instruction is being executed
6794 ** within a sub-program). Set the value of register P1 to the maximum of
6795 ** its current value and the value in register P2.
6796 **
6797 ** This instruction throws an error if the memory cell is not initially
6798 ** an integer.
6799 */
6800 case OP_MemMax: {        /* in2 */
6801   VdbeFrame *pFrame;
6802   if( p->pFrame ){
6803     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
6804     pIn1 = &pFrame->aMem[pOp->p1];
6805   }else{
6806     pIn1 = &aMem[pOp->p1];
6807   }
6808   assert( memIsValid(pIn1) );
6809   sqlite3VdbeMemIntegerify(pIn1);
6810   pIn2 = &aMem[pOp->p2];
6811   sqlite3VdbeMemIntegerify(pIn2);
6812   if( pIn1->u.i<pIn2->u.i){
6813     pIn1->u.i = pIn2->u.i;
6814   }
6815   break;
6816 }
6817 #endif /* SQLITE_OMIT_AUTOINCREMENT */
6818 
6819 /* Opcode: IfPos P1 P2 P3 * *
6820 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
6821 **
6822 ** Register P1 must contain an integer.
6823 ** If the value of register P1 is 1 or greater, subtract P3 from the
6824 ** value in P1 and jump to P2.
6825 **
6826 ** If the initial value of register P1 is less than 1, then the
6827 ** value is unchanged and control passes through to the next instruction.
6828 */
6829 case OP_IfPos: {        /* jump, in1 */
6830   pIn1 = &aMem[pOp->p1];
6831   assert( pIn1->flags&MEM_Int );
6832   VdbeBranchTaken( pIn1->u.i>0, 2);
6833   if( pIn1->u.i>0 ){
6834     pIn1->u.i -= pOp->p3;
6835     goto jump_to_p2;
6836   }
6837   break;
6838 }
6839 
6840 /* Opcode: OffsetLimit P1 P2 P3 * *
6841 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
6842 **
6843 ** This opcode performs a commonly used computation associated with
6844 ** LIMIT and OFFSET process.  r[P1] holds the limit counter.  r[P3]
6845 ** holds the offset counter.  The opcode computes the combined value
6846 ** of the LIMIT and OFFSET and stores that value in r[P2].  The r[P2]
6847 ** value computed is the total number of rows that will need to be
6848 ** visited in order to complete the query.
6849 **
6850 ** If r[P3] is zero or negative, that means there is no OFFSET
6851 ** and r[P2] is set to be the value of the LIMIT, r[P1].
6852 **
6853 ** if r[P1] is zero or negative, that means there is no LIMIT
6854 ** and r[P2] is set to -1.
6855 **
6856 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
6857 */
6858 case OP_OffsetLimit: {    /* in1, out2, in3 */
6859   i64 x;
6860   pIn1 = &aMem[pOp->p1];
6861   pIn3 = &aMem[pOp->p3];
6862   pOut = out2Prerelease(p, pOp);
6863   assert( pIn1->flags & MEM_Int );
6864   assert( pIn3->flags & MEM_Int );
6865   x = pIn1->u.i;
6866   if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
6867     /* If the LIMIT is less than or equal to zero, loop forever.  This
6868     ** is documented.  But also, if the LIMIT+OFFSET exceeds 2^63 then
6869     ** also loop forever.  This is undocumented.  In fact, one could argue
6870     ** that the loop should terminate.  But assuming 1 billion iterations
6871     ** per second (far exceeding the capabilities of any current hardware)
6872     ** it would take nearly 300 years to actually reach the limit.  So
6873     ** looping forever is a reasonable approximation. */
6874     pOut->u.i = -1;
6875   }else{
6876     pOut->u.i = x;
6877   }
6878   break;
6879 }
6880 
6881 /* Opcode: IfNotZero P1 P2 * * *
6882 ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
6883 **
6884 ** Register P1 must contain an integer.  If the content of register P1 is
6885 ** initially greater than zero, then decrement the value in register P1.
6886 ** If it is non-zero (negative or positive) and then also jump to P2.
6887 ** If register P1 is initially zero, leave it unchanged and fall through.
6888 */
6889 case OP_IfNotZero: {        /* jump, in1 */
6890   pIn1 = &aMem[pOp->p1];
6891   assert( pIn1->flags&MEM_Int );
6892   VdbeBranchTaken(pIn1->u.i<0, 2);
6893   if( pIn1->u.i ){
6894      if( pIn1->u.i>0 ) pIn1->u.i--;
6895      goto jump_to_p2;
6896   }
6897   break;
6898 }
6899 
6900 /* Opcode: DecrJumpZero P1 P2 * * *
6901 ** Synopsis: if (--r[P1])==0 goto P2
6902 **
6903 ** Register P1 must hold an integer.  Decrement the value in P1
6904 ** and jump to P2 if the new value is exactly zero.
6905 */
6906 case OP_DecrJumpZero: {      /* jump, in1 */
6907   pIn1 = &aMem[pOp->p1];
6908   assert( pIn1->flags&MEM_Int );
6909   if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
6910   VdbeBranchTaken(pIn1->u.i==0, 2);
6911   if( pIn1->u.i==0 ) goto jump_to_p2;
6912   break;
6913 }
6914 
6915 
6916 /* Opcode: AggStep * P2 P3 P4 P5
6917 ** Synopsis: accum=r[P3] step(r[P2@P5])
6918 **
6919 ** Execute the xStep function for an aggregate.
6920 ** The function has P5 arguments.  P4 is a pointer to the
6921 ** FuncDef structure that specifies the function.  Register P3 is the
6922 ** accumulator.
6923 **
6924 ** The P5 arguments are taken from register P2 and its
6925 ** successors.
6926 */
6927 /* Opcode: AggInverse * P2 P3 P4 P5
6928 ** Synopsis: accum=r[P3] inverse(r[P2@P5])
6929 **
6930 ** Execute the xInverse function for an aggregate.
6931 ** The function has P5 arguments.  P4 is a pointer to the
6932 ** FuncDef structure that specifies the function.  Register P3 is the
6933 ** accumulator.
6934 **
6935 ** The P5 arguments are taken from register P2 and its
6936 ** successors.
6937 */
6938 /* Opcode: AggStep1 P1 P2 P3 P4 P5
6939 ** Synopsis: accum=r[P3] step(r[P2@P5])
6940 **
6941 ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
6942 ** aggregate.  The function has P5 arguments.  P4 is a pointer to the
6943 ** FuncDef structure that specifies the function.  Register P3 is the
6944 ** accumulator.
6945 **
6946 ** The P5 arguments are taken from register P2 and its
6947 ** successors.
6948 **
6949 ** This opcode is initially coded as OP_AggStep0.  On first evaluation,
6950 ** the FuncDef stored in P4 is converted into an sqlite3_context and
6951 ** the opcode is changed.  In this way, the initialization of the
6952 ** sqlite3_context only happens once, instead of on each call to the
6953 ** step function.
6954 */
6955 case OP_AggInverse:
6956 case OP_AggStep: {
6957   int n;
6958   sqlite3_context *pCtx;
6959 
6960   assert( pOp->p4type==P4_FUNCDEF );
6961   n = pOp->p5;
6962   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
6963   assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
6964   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
6965   pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
6966                (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
6967   if( pCtx==0 ) goto no_mem;
6968   pCtx->pMem = 0;
6969   pCtx->pOut = (Mem*)&(pCtx->argv[n]);
6970   sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
6971   pCtx->pFunc = pOp->p4.pFunc;
6972   pCtx->iOp = (int)(pOp - aOp);
6973   pCtx->pVdbe = p;
6974   pCtx->skipFlag = 0;
6975   pCtx->isError = 0;
6976   pCtx->argc = n;
6977   pOp->p4type = P4_FUNCCTX;
6978   pOp->p4.pCtx = pCtx;
6979 
6980   /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */
6981   assert( pOp->p1==(pOp->opcode==OP_AggInverse) );
6982 
6983   pOp->opcode = OP_AggStep1;
6984   /* Fall through into OP_AggStep */
6985   /* no break */ deliberate_fall_through
6986 }
6987 case OP_AggStep1: {
6988   int i;
6989   sqlite3_context *pCtx;
6990   Mem *pMem;
6991 
6992   assert( pOp->p4type==P4_FUNCCTX );
6993   pCtx = pOp->p4.pCtx;
6994   pMem = &aMem[pOp->p3];
6995 
6996 #ifdef SQLITE_DEBUG
6997   if( pOp->p1 ){
6998     /* This is an OP_AggInverse call.  Verify that xStep has always
6999     ** been called at least once prior to any xInverse call. */
7000     assert( pMem->uTemp==0x1122e0e3 );
7001   }else{
7002     /* This is an OP_AggStep call.  Mark it as such. */
7003     pMem->uTemp = 0x1122e0e3;
7004   }
7005 #endif
7006 
7007   /* If this function is inside of a trigger, the register array in aMem[]
7008   ** might change from one evaluation to the next.  The next block of code
7009   ** checks to see if the register array has changed, and if so it
7010   ** reinitializes the relavant parts of the sqlite3_context object */
7011   if( pCtx->pMem != pMem ){
7012     pCtx->pMem = pMem;
7013     for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
7014   }
7015 
7016 #ifdef SQLITE_DEBUG
7017   for(i=0; i<pCtx->argc; i++){
7018     assert( memIsValid(pCtx->argv[i]) );
7019     REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
7020   }
7021 #endif
7022 
7023   pMem->n++;
7024   assert( pCtx->pOut->flags==MEM_Null );
7025   assert( pCtx->isError==0 );
7026   assert( pCtx->skipFlag==0 );
7027 #ifndef SQLITE_OMIT_WINDOWFUNC
7028   if( pOp->p1 ){
7029     (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv);
7030   }else
7031 #endif
7032   (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
7033 
7034   if( pCtx->isError ){
7035     if( pCtx->isError>0 ){
7036       sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
7037       rc = pCtx->isError;
7038     }
7039     if( pCtx->skipFlag ){
7040       assert( pOp[-1].opcode==OP_CollSeq );
7041       i = pOp[-1].p1;
7042       if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
7043       pCtx->skipFlag = 0;
7044     }
7045     sqlite3VdbeMemRelease(pCtx->pOut);
7046     pCtx->pOut->flags = MEM_Null;
7047     pCtx->isError = 0;
7048     if( rc ) goto abort_due_to_error;
7049   }
7050   assert( pCtx->pOut->flags==MEM_Null );
7051   assert( pCtx->skipFlag==0 );
7052   break;
7053 }
7054 
7055 /* Opcode: AggFinal P1 P2 * P4 *
7056 ** Synopsis: accum=r[P1] N=P2
7057 **
7058 ** P1 is the memory location that is the accumulator for an aggregate
7059 ** or window function.  Execute the finalizer function
7060 ** for an aggregate and store the result in P1.
7061 **
7062 ** P2 is the number of arguments that the step function takes and
7063 ** P4 is a pointer to the FuncDef for this function.  The P2
7064 ** argument is not used by this opcode.  It is only there to disambiguate
7065 ** functions that can take varying numbers of arguments.  The
7066 ** P4 argument is only needed for the case where
7067 ** the step function was not previously called.
7068 */
7069 /* Opcode: AggValue * P2 P3 P4 *
7070 ** Synopsis: r[P3]=value N=P2
7071 **
7072 ** Invoke the xValue() function and store the result in register P3.
7073 **
7074 ** P2 is the number of arguments that the step function takes and
7075 ** P4 is a pointer to the FuncDef for this function.  The P2
7076 ** argument is not used by this opcode.  It is only there to disambiguate
7077 ** functions that can take varying numbers of arguments.  The
7078 ** P4 argument is only needed for the case where
7079 ** the step function was not previously called.
7080 */
7081 case OP_AggValue:
7082 case OP_AggFinal: {
7083   Mem *pMem;
7084   assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
7085   assert( pOp->p3==0 || pOp->opcode==OP_AggValue );
7086   pMem = &aMem[pOp->p1];
7087   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
7088 #ifndef SQLITE_OMIT_WINDOWFUNC
7089   if( pOp->p3 ){
7090     memAboutToChange(p, &aMem[pOp->p3]);
7091     rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc);
7092     pMem = &aMem[pOp->p3];
7093   }else
7094 #endif
7095   {
7096     rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
7097   }
7098 
7099   if( rc ){
7100     sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
7101     goto abort_due_to_error;
7102   }
7103   sqlite3VdbeChangeEncoding(pMem, encoding);
7104   UPDATE_MAX_BLOBSIZE(pMem);
7105   if( sqlite3VdbeMemTooBig(pMem) ){
7106     goto too_big;
7107   }
7108   break;
7109 }
7110 
7111 #ifndef SQLITE_OMIT_WAL
7112 /* Opcode: Checkpoint P1 P2 P3 * *
7113 **
7114 ** Checkpoint database P1. This is a no-op if P1 is not currently in
7115 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
7116 ** RESTART, or TRUNCATE.  Write 1 or 0 into mem[P3] if the checkpoint returns
7117 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
7118 ** WAL after the checkpoint into mem[P3+1] and the number of pages
7119 ** in the WAL that have been checkpointed after the checkpoint
7120 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
7121 ** mem[P3+2] are initialized to -1.
7122 */
7123 case OP_Checkpoint: {
7124   int i;                          /* Loop counter */
7125   int aRes[3];                    /* Results */
7126   Mem *pMem;                      /* Write results here */
7127 
7128   assert( p->readOnly==0 );
7129   aRes[0] = 0;
7130   aRes[1] = aRes[2] = -1;
7131   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
7132        || pOp->p2==SQLITE_CHECKPOINT_FULL
7133        || pOp->p2==SQLITE_CHECKPOINT_RESTART
7134        || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
7135   );
7136   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
7137   if( rc ){
7138     if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
7139     rc = SQLITE_OK;
7140     aRes[0] = 1;
7141   }
7142   for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
7143     sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
7144   }
7145   break;
7146 };
7147 #endif
7148 
7149 #ifndef SQLITE_OMIT_PRAGMA
7150 /* Opcode: JournalMode P1 P2 P3 * *
7151 **
7152 ** Change the journal mode of database P1 to P3. P3 must be one of the
7153 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
7154 ** modes (delete, truncate, persist, off and memory), this is a simple
7155 ** operation. No IO is required.
7156 **
7157 ** If changing into or out of WAL mode the procedure is more complicated.
7158 **
7159 ** Write a string containing the final journal-mode to register P2.
7160 */
7161 case OP_JournalMode: {    /* out2 */
7162   Btree *pBt;                     /* Btree to change journal mode of */
7163   Pager *pPager;                  /* Pager associated with pBt */
7164   int eNew;                       /* New journal mode */
7165   int eOld;                       /* The old journal mode */
7166 #ifndef SQLITE_OMIT_WAL
7167   const char *zFilename;          /* Name of database file for pPager */
7168 #endif
7169 
7170   pOut = out2Prerelease(p, pOp);
7171   eNew = pOp->p3;
7172   assert( eNew==PAGER_JOURNALMODE_DELETE
7173        || eNew==PAGER_JOURNALMODE_TRUNCATE
7174        || eNew==PAGER_JOURNALMODE_PERSIST
7175        || eNew==PAGER_JOURNALMODE_OFF
7176        || eNew==PAGER_JOURNALMODE_MEMORY
7177        || eNew==PAGER_JOURNALMODE_WAL
7178        || eNew==PAGER_JOURNALMODE_QUERY
7179   );
7180   assert( pOp->p1>=0 && pOp->p1<db->nDb );
7181   assert( p->readOnly==0 );
7182 
7183   pBt = db->aDb[pOp->p1].pBt;
7184   pPager = sqlite3BtreePager(pBt);
7185   eOld = sqlite3PagerGetJournalMode(pPager);
7186   if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
7187   if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
7188 
7189 #ifndef SQLITE_OMIT_WAL
7190   zFilename = sqlite3PagerFilename(pPager, 1);
7191 
7192   /* Do not allow a transition to journal_mode=WAL for a database
7193   ** in temporary storage or if the VFS does not support shared memory
7194   */
7195   if( eNew==PAGER_JOURNALMODE_WAL
7196    && (sqlite3Strlen30(zFilename)==0           /* Temp file */
7197        || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
7198   ){
7199     eNew = eOld;
7200   }
7201 
7202   if( (eNew!=eOld)
7203    && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
7204   ){
7205     if( !db->autoCommit || db->nVdbeRead>1 ){
7206       rc = SQLITE_ERROR;
7207       sqlite3VdbeError(p,
7208           "cannot change %s wal mode from within a transaction",
7209           (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
7210       );
7211       goto abort_due_to_error;
7212     }else{
7213 
7214       if( eOld==PAGER_JOURNALMODE_WAL ){
7215         /* If leaving WAL mode, close the log file. If successful, the call
7216         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
7217         ** file. An EXCLUSIVE lock may still be held on the database file
7218         ** after a successful return.
7219         */
7220         rc = sqlite3PagerCloseWal(pPager, db);
7221         if( rc==SQLITE_OK ){
7222           sqlite3PagerSetJournalMode(pPager, eNew);
7223         }
7224       }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
7225         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
7226         ** as an intermediate */
7227         sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
7228       }
7229 
7230       /* Open a transaction on the database file. Regardless of the journal
7231       ** mode, this transaction always uses a rollback journal.
7232       */
7233       assert( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE );
7234       if( rc==SQLITE_OK ){
7235         rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
7236       }
7237     }
7238   }
7239 #endif /* ifndef SQLITE_OMIT_WAL */
7240 
7241   if( rc ) eNew = eOld;
7242   eNew = sqlite3PagerSetJournalMode(pPager, eNew);
7243 
7244   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
7245   pOut->z = (char *)sqlite3JournalModename(eNew);
7246   pOut->n = sqlite3Strlen30(pOut->z);
7247   pOut->enc = SQLITE_UTF8;
7248   sqlite3VdbeChangeEncoding(pOut, encoding);
7249   if( rc ) goto abort_due_to_error;
7250   break;
7251 };
7252 #endif /* SQLITE_OMIT_PRAGMA */
7253 
7254 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
7255 /* Opcode: Vacuum P1 P2 * * *
7256 **
7257 ** Vacuum the entire database P1.  P1 is 0 for "main", and 2 or more
7258 ** for an attached database.  The "temp" database may not be vacuumed.
7259 **
7260 ** If P2 is not zero, then it is a register holding a string which is
7261 ** the file into which the result of vacuum should be written.  When
7262 ** P2 is zero, the vacuum overwrites the original database.
7263 */
7264 case OP_Vacuum: {
7265   assert( p->readOnly==0 );
7266   rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1,
7267                         pOp->p2 ? &aMem[pOp->p2] : 0);
7268   if( rc ) goto abort_due_to_error;
7269   break;
7270 }
7271 #endif
7272 
7273 #if !defined(SQLITE_OMIT_AUTOVACUUM)
7274 /* Opcode: IncrVacuum P1 P2 * * *
7275 **
7276 ** Perform a single step of the incremental vacuum procedure on
7277 ** the P1 database. If the vacuum has finished, jump to instruction
7278 ** P2. Otherwise, fall through to the next instruction.
7279 */
7280 case OP_IncrVacuum: {        /* jump */
7281   Btree *pBt;
7282 
7283   assert( pOp->p1>=0 && pOp->p1<db->nDb );
7284   assert( DbMaskTest(p->btreeMask, pOp->p1) );
7285   assert( p->readOnly==0 );
7286   pBt = db->aDb[pOp->p1].pBt;
7287   rc = sqlite3BtreeIncrVacuum(pBt);
7288   VdbeBranchTaken(rc==SQLITE_DONE,2);
7289   if( rc ){
7290     if( rc!=SQLITE_DONE ) goto abort_due_to_error;
7291     rc = SQLITE_OK;
7292     goto jump_to_p2;
7293   }
7294   break;
7295 }
7296 #endif
7297 
7298 /* Opcode: Expire P1 P2 * * *
7299 **
7300 ** Cause precompiled statements to expire.  When an expired statement
7301 ** is executed using sqlite3_step() it will either automatically
7302 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
7303 ** or it will fail with SQLITE_SCHEMA.
7304 **
7305 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
7306 ** then only the currently executing statement is expired.
7307 **
7308 ** If P2 is 0, then SQL statements are expired immediately.  If P2 is 1,
7309 ** then running SQL statements are allowed to continue to run to completion.
7310 ** The P2==1 case occurs when a CREATE INDEX or similar schema change happens
7311 ** that might help the statement run faster but which does not affect the
7312 ** correctness of operation.
7313 */
7314 case OP_Expire: {
7315   assert( pOp->p2==0 || pOp->p2==1 );
7316   if( !pOp->p1 ){
7317     sqlite3ExpirePreparedStatements(db, pOp->p2);
7318   }else{
7319     p->expired = pOp->p2+1;
7320   }
7321   break;
7322 }
7323 
7324 /* Opcode: CursorLock P1 * * * *
7325 **
7326 ** Lock the btree to which cursor P1 is pointing so that the btree cannot be
7327 ** written by an other cursor.
7328 */
7329 case OP_CursorLock: {
7330   VdbeCursor *pC;
7331   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
7332   pC = p->apCsr[pOp->p1];
7333   assert( pC!=0 );
7334   assert( pC->eCurType==CURTYPE_BTREE );
7335   sqlite3BtreeCursorPin(pC->uc.pCursor);
7336   break;
7337 }
7338 
7339 /* Opcode: CursorUnlock P1 * * * *
7340 **
7341 ** Unlock the btree to which cursor P1 is pointing so that it can be
7342 ** written by other cursors.
7343 */
7344 case OP_CursorUnlock: {
7345   VdbeCursor *pC;
7346   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
7347   pC = p->apCsr[pOp->p1];
7348   assert( pC!=0 );
7349   assert( pC->eCurType==CURTYPE_BTREE );
7350   sqlite3BtreeCursorUnpin(pC->uc.pCursor);
7351   break;
7352 }
7353 
7354 #ifndef SQLITE_OMIT_SHARED_CACHE
7355 /* Opcode: TableLock P1 P2 P3 P4 *
7356 ** Synopsis: iDb=P1 root=P2 write=P3
7357 **
7358 ** Obtain a lock on a particular table. This instruction is only used when
7359 ** the shared-cache feature is enabled.
7360 **
7361 ** P1 is the index of the database in sqlite3.aDb[] of the database
7362 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
7363 ** a write lock if P3==1.
7364 **
7365 ** P2 contains the root-page of the table to lock.
7366 **
7367 ** P4 contains a pointer to the name of the table being locked. This is only
7368 ** used to generate an error message if the lock cannot be obtained.
7369 */
7370 case OP_TableLock: {
7371   u8 isWriteLock = (u8)pOp->p3;
7372   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
7373     int p1 = pOp->p1;
7374     assert( p1>=0 && p1<db->nDb );
7375     assert( DbMaskTest(p->btreeMask, p1) );
7376     assert( isWriteLock==0 || isWriteLock==1 );
7377     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
7378     if( rc ){
7379       if( (rc&0xFF)==SQLITE_LOCKED ){
7380         const char *z = pOp->p4.z;
7381         sqlite3VdbeError(p, "database table is locked: %s", z);
7382       }
7383       goto abort_due_to_error;
7384     }
7385   }
7386   break;
7387 }
7388 #endif /* SQLITE_OMIT_SHARED_CACHE */
7389 
7390 #ifndef SQLITE_OMIT_VIRTUALTABLE
7391 /* Opcode: VBegin * * * P4 *
7392 **
7393 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
7394 ** xBegin method for that table.
7395 **
7396 ** Also, whether or not P4 is set, check that this is not being called from
7397 ** within a callback to a virtual table xSync() method. If it is, the error
7398 ** code will be set to SQLITE_LOCKED.
7399 */
7400 case OP_VBegin: {
7401   VTable *pVTab;
7402   pVTab = pOp->p4.pVtab;
7403   rc = sqlite3VtabBegin(db, pVTab);
7404   if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
7405   if( rc ) goto abort_due_to_error;
7406   break;
7407 }
7408 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7409 
7410 #ifndef SQLITE_OMIT_VIRTUALTABLE
7411 /* Opcode: VCreate P1 P2 * * *
7412 **
7413 ** P2 is a register that holds the name of a virtual table in database
7414 ** P1. Call the xCreate method for that table.
7415 */
7416 case OP_VCreate: {
7417   Mem sMem;          /* For storing the record being decoded */
7418   const char *zTab;  /* Name of the virtual table */
7419 
7420   memset(&sMem, 0, sizeof(sMem));
7421   sMem.db = db;
7422   /* Because P2 is always a static string, it is impossible for the
7423   ** sqlite3VdbeMemCopy() to fail */
7424   assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
7425   assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
7426   rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
7427   assert( rc==SQLITE_OK );
7428   zTab = (const char*)sqlite3_value_text(&sMem);
7429   assert( zTab || db->mallocFailed );
7430   if( zTab ){
7431     rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
7432   }
7433   sqlite3VdbeMemRelease(&sMem);
7434   if( rc ) goto abort_due_to_error;
7435   break;
7436 }
7437 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7438 
7439 #ifndef SQLITE_OMIT_VIRTUALTABLE
7440 /* Opcode: VDestroy P1 * * P4 *
7441 **
7442 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
7443 ** of that table.
7444 */
7445 case OP_VDestroy: {
7446   db->nVDestroy++;
7447   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
7448   db->nVDestroy--;
7449   assert( p->errorAction==OE_Abort && p->usesStmtJournal );
7450   if( rc ) goto abort_due_to_error;
7451   break;
7452 }
7453 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7454 
7455 #ifndef SQLITE_OMIT_VIRTUALTABLE
7456 /* Opcode: VOpen P1 * * P4 *
7457 **
7458 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
7459 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
7460 ** table and stores that cursor in P1.
7461 */
7462 case OP_VOpen: {
7463   VdbeCursor *pCur;
7464   sqlite3_vtab_cursor *pVCur;
7465   sqlite3_vtab *pVtab;
7466   const sqlite3_module *pModule;
7467 
7468   assert( p->bIsReader );
7469   pCur = 0;
7470   pVCur = 0;
7471   pVtab = pOp->p4.pVtab->pVtab;
7472   if( pVtab==0 || NEVER(pVtab->pModule==0) ){
7473     rc = SQLITE_LOCKED;
7474     goto abort_due_to_error;
7475   }
7476   pModule = pVtab->pModule;
7477   rc = pModule->xOpen(pVtab, &pVCur);
7478   sqlite3VtabImportErrmsg(p, pVtab);
7479   if( rc ) goto abort_due_to_error;
7480 
7481   /* Initialize sqlite3_vtab_cursor base class */
7482   pVCur->pVtab = pVtab;
7483 
7484   /* Initialize vdbe cursor object */
7485   pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
7486   if( pCur ){
7487     pCur->uc.pVCur = pVCur;
7488     pVtab->nRef++;
7489   }else{
7490     assert( db->mallocFailed );
7491     pModule->xClose(pVCur);
7492     goto no_mem;
7493   }
7494   break;
7495 }
7496 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7497 
7498 #ifndef SQLITE_OMIT_VIRTUALTABLE
7499 /* Opcode: VFilter P1 P2 P3 P4 *
7500 ** Synopsis: iplan=r[P3] zplan='P4'
7501 **
7502 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
7503 ** the filtered result set is empty.
7504 **
7505 ** P4 is either NULL or a string that was generated by the xBestIndex
7506 ** method of the module.  The interpretation of the P4 string is left
7507 ** to the module implementation.
7508 **
7509 ** This opcode invokes the xFilter method on the virtual table specified
7510 ** by P1.  The integer query plan parameter to xFilter is stored in register
7511 ** P3. Register P3+1 stores the argc parameter to be passed to the
7512 ** xFilter method. Registers P3+2..P3+1+argc are the argc
7513 ** additional parameters which are passed to
7514 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
7515 **
7516 ** A jump is made to P2 if the result set after filtering would be empty.
7517 */
7518 case OP_VFilter: {   /* jump */
7519   int nArg;
7520   int iQuery;
7521   const sqlite3_module *pModule;
7522   Mem *pQuery;
7523   Mem *pArgc;
7524   sqlite3_vtab_cursor *pVCur;
7525   sqlite3_vtab *pVtab;
7526   VdbeCursor *pCur;
7527   int res;
7528   int i;
7529   Mem **apArg;
7530 
7531   pQuery = &aMem[pOp->p3];
7532   pArgc = &pQuery[1];
7533   pCur = p->apCsr[pOp->p1];
7534   assert( memIsValid(pQuery) );
7535   REGISTER_TRACE(pOp->p3, pQuery);
7536   assert( pCur->eCurType==CURTYPE_VTAB );
7537   pVCur = pCur->uc.pVCur;
7538   pVtab = pVCur->pVtab;
7539   pModule = pVtab->pModule;
7540 
7541   /* Grab the index number and argc parameters */
7542   assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
7543   nArg = (int)pArgc->u.i;
7544   iQuery = (int)pQuery->u.i;
7545 
7546   /* Invoke the xFilter method */
7547   res = 0;
7548   apArg = p->apArg;
7549   for(i = 0; i<nArg; i++){
7550     apArg[i] = &pArgc[i+1];
7551   }
7552   rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
7553   sqlite3VtabImportErrmsg(p, pVtab);
7554   if( rc ) goto abort_due_to_error;
7555   res = pModule->xEof(pVCur);
7556   pCur->nullRow = 0;
7557   VdbeBranchTaken(res!=0,2);
7558   if( res ) goto jump_to_p2;
7559   break;
7560 }
7561 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7562 
7563 #ifndef SQLITE_OMIT_VIRTUALTABLE
7564 /* Opcode: VColumn P1 P2 P3 * P5
7565 ** Synopsis: r[P3]=vcolumn(P2)
7566 **
7567 ** Store in register P3 the value of the P2-th column of
7568 ** the current row of the virtual-table of cursor P1.
7569 **
7570 ** If the VColumn opcode is being used to fetch the value of
7571 ** an unchanging column during an UPDATE operation, then the P5
7572 ** value is OPFLAG_NOCHNG.  This will cause the sqlite3_vtab_nochange()
7573 ** function to return true inside the xColumn method of the virtual
7574 ** table implementation.  The P5 column might also contain other
7575 ** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are
7576 ** unused by OP_VColumn.
7577 */
7578 case OP_VColumn: {
7579   sqlite3_vtab *pVtab;
7580   const sqlite3_module *pModule;
7581   Mem *pDest;
7582   sqlite3_context sContext;
7583 
7584   VdbeCursor *pCur = p->apCsr[pOp->p1];
7585   assert( pCur->eCurType==CURTYPE_VTAB );
7586   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
7587   pDest = &aMem[pOp->p3];
7588   memAboutToChange(p, pDest);
7589   if( pCur->nullRow ){
7590     sqlite3VdbeMemSetNull(pDest);
7591     break;
7592   }
7593   pVtab = pCur->uc.pVCur->pVtab;
7594   pModule = pVtab->pModule;
7595   assert( pModule->xColumn );
7596   memset(&sContext, 0, sizeof(sContext));
7597   sContext.pOut = pDest;
7598   assert( pOp->p5==OPFLAG_NOCHNG || pOp->p5==0 );
7599   if( pOp->p5 & OPFLAG_NOCHNG ){
7600     sqlite3VdbeMemSetNull(pDest);
7601     pDest->flags = MEM_Null|MEM_Zero;
7602     pDest->u.nZero = 0;
7603   }else{
7604     MemSetTypeFlag(pDest, MEM_Null);
7605   }
7606   rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
7607   sqlite3VtabImportErrmsg(p, pVtab);
7608   if( sContext.isError>0 ){
7609     sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
7610     rc = sContext.isError;
7611   }
7612   sqlite3VdbeChangeEncoding(pDest, encoding);
7613   REGISTER_TRACE(pOp->p3, pDest);
7614   UPDATE_MAX_BLOBSIZE(pDest);
7615 
7616   if( sqlite3VdbeMemTooBig(pDest) ){
7617     goto too_big;
7618   }
7619   if( rc ) goto abort_due_to_error;
7620   break;
7621 }
7622 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7623 
7624 #ifndef SQLITE_OMIT_VIRTUALTABLE
7625 /* Opcode: VNext P1 P2 * * *
7626 **
7627 ** Advance virtual table P1 to the next row in its result set and
7628 ** jump to instruction P2.  Or, if the virtual table has reached
7629 ** the end of its result set, then fall through to the next instruction.
7630 */
7631 case OP_VNext: {   /* jump */
7632   sqlite3_vtab *pVtab;
7633   const sqlite3_module *pModule;
7634   int res;
7635   VdbeCursor *pCur;
7636 
7637   res = 0;
7638   pCur = p->apCsr[pOp->p1];
7639   assert( pCur->eCurType==CURTYPE_VTAB );
7640   if( pCur->nullRow ){
7641     break;
7642   }
7643   pVtab = pCur->uc.pVCur->pVtab;
7644   pModule = pVtab->pModule;
7645   assert( pModule->xNext );
7646 
7647   /* Invoke the xNext() method of the module. There is no way for the
7648   ** underlying implementation to return an error if one occurs during
7649   ** xNext(). Instead, if an error occurs, true is returned (indicating that
7650   ** data is available) and the error code returned when xColumn or
7651   ** some other method is next invoked on the save virtual table cursor.
7652   */
7653   rc = pModule->xNext(pCur->uc.pVCur);
7654   sqlite3VtabImportErrmsg(p, pVtab);
7655   if( rc ) goto abort_due_to_error;
7656   res = pModule->xEof(pCur->uc.pVCur);
7657   VdbeBranchTaken(!res,2);
7658   if( !res ){
7659     /* If there is data, jump to P2 */
7660     goto jump_to_p2_and_check_for_interrupt;
7661   }
7662   goto check_for_interrupt;
7663 }
7664 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7665 
7666 #ifndef SQLITE_OMIT_VIRTUALTABLE
7667 /* Opcode: VRename P1 * * P4 *
7668 **
7669 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
7670 ** This opcode invokes the corresponding xRename method. The value
7671 ** in register P1 is passed as the zName argument to the xRename method.
7672 */
7673 case OP_VRename: {
7674   sqlite3_vtab *pVtab;
7675   Mem *pName;
7676   int isLegacy;
7677 
7678   isLegacy = (db->flags & SQLITE_LegacyAlter);
7679   db->flags |= SQLITE_LegacyAlter;
7680   pVtab = pOp->p4.pVtab->pVtab;
7681   pName = &aMem[pOp->p1];
7682   assert( pVtab->pModule->xRename );
7683   assert( memIsValid(pName) );
7684   assert( p->readOnly==0 );
7685   REGISTER_TRACE(pOp->p1, pName);
7686   assert( pName->flags & MEM_Str );
7687   testcase( pName->enc==SQLITE_UTF8 );
7688   testcase( pName->enc==SQLITE_UTF16BE );
7689   testcase( pName->enc==SQLITE_UTF16LE );
7690   rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
7691   if( rc ) goto abort_due_to_error;
7692   rc = pVtab->pModule->xRename(pVtab, pName->z);
7693   if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter;
7694   sqlite3VtabImportErrmsg(p, pVtab);
7695   p->expired = 0;
7696   if( rc ) goto abort_due_to_error;
7697   break;
7698 }
7699 #endif
7700 
7701 #ifndef SQLITE_OMIT_VIRTUALTABLE
7702 /* Opcode: VUpdate P1 P2 P3 P4 P5
7703 ** Synopsis: data=r[P3@P2]
7704 **
7705 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
7706 ** This opcode invokes the corresponding xUpdate method. P2 values
7707 ** are contiguous memory cells starting at P3 to pass to the xUpdate
7708 ** invocation. The value in register (P3+P2-1) corresponds to the
7709 ** p2th element of the argv array passed to xUpdate.
7710 **
7711 ** The xUpdate method will do a DELETE or an INSERT or both.
7712 ** The argv[0] element (which corresponds to memory cell P3)
7713 ** is the rowid of a row to delete.  If argv[0] is NULL then no
7714 ** deletion occurs.  The argv[1] element is the rowid of the new
7715 ** row.  This can be NULL to have the virtual table select the new
7716 ** rowid for itself.  The subsequent elements in the array are
7717 ** the values of columns in the new row.
7718 **
7719 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
7720 ** a row to delete.
7721 **
7722 ** P1 is a boolean flag. If it is set to true and the xUpdate call
7723 ** is successful, then the value returned by sqlite3_last_insert_rowid()
7724 ** is set to the value of the rowid for the row just inserted.
7725 **
7726 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
7727 ** apply in the case of a constraint failure on an insert or update.
7728 */
7729 case OP_VUpdate: {
7730   sqlite3_vtab *pVtab;
7731   const sqlite3_module *pModule;
7732   int nArg;
7733   int i;
7734   sqlite_int64 rowid;
7735   Mem **apArg;
7736   Mem *pX;
7737 
7738   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
7739        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
7740   );
7741   assert( p->readOnly==0 );
7742   if( db->mallocFailed ) goto no_mem;
7743   sqlite3VdbeIncrWriteCounter(p, 0);
7744   pVtab = pOp->p4.pVtab->pVtab;
7745   if( pVtab==0 || NEVER(pVtab->pModule==0) ){
7746     rc = SQLITE_LOCKED;
7747     goto abort_due_to_error;
7748   }
7749   pModule = pVtab->pModule;
7750   nArg = pOp->p2;
7751   assert( pOp->p4type==P4_VTAB );
7752   if( ALWAYS(pModule->xUpdate) ){
7753     u8 vtabOnConflict = db->vtabOnConflict;
7754     apArg = p->apArg;
7755     pX = &aMem[pOp->p3];
7756     for(i=0; i<nArg; i++){
7757       assert( memIsValid(pX) );
7758       memAboutToChange(p, pX);
7759       apArg[i] = pX;
7760       pX++;
7761     }
7762     db->vtabOnConflict = pOp->p5;
7763     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
7764     db->vtabOnConflict = vtabOnConflict;
7765     sqlite3VtabImportErrmsg(p, pVtab);
7766     if( rc==SQLITE_OK && pOp->p1 ){
7767       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
7768       db->lastRowid = rowid;
7769     }
7770     if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
7771       if( pOp->p5==OE_Ignore ){
7772         rc = SQLITE_OK;
7773       }else{
7774         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
7775       }
7776     }else{
7777       p->nChange++;
7778     }
7779     if( rc ) goto abort_due_to_error;
7780   }
7781   break;
7782 }
7783 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7784 
7785 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
7786 /* Opcode: Pagecount P1 P2 * * *
7787 **
7788 ** Write the current number of pages in database P1 to memory cell P2.
7789 */
7790 case OP_Pagecount: {            /* out2 */
7791   pOut = out2Prerelease(p, pOp);
7792   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
7793   break;
7794 }
7795 #endif
7796 
7797 
7798 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
7799 /* Opcode: MaxPgcnt P1 P2 P3 * *
7800 **
7801 ** Try to set the maximum page count for database P1 to the value in P3.
7802 ** Do not let the maximum page count fall below the current page count and
7803 ** do not change the maximum page count value if P3==0.
7804 **
7805 ** Store the maximum page count after the change in register P2.
7806 */
7807 case OP_MaxPgcnt: {            /* out2 */
7808   unsigned int newMax;
7809   Btree *pBt;
7810 
7811   pOut = out2Prerelease(p, pOp);
7812   pBt = db->aDb[pOp->p1].pBt;
7813   newMax = 0;
7814   if( pOp->p3 ){
7815     newMax = sqlite3BtreeLastPage(pBt);
7816     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
7817   }
7818   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
7819   break;
7820 }
7821 #endif
7822 
7823 /* Opcode: Function P1 P2 P3 P4 *
7824 ** Synopsis: r[P3]=func(r[P2@NP])
7825 **
7826 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
7827 ** contains a pointer to the function to be run) with arguments taken
7828 ** from register P2 and successors.  The number of arguments is in
7829 ** the sqlite3_context object that P4 points to.
7830 ** The result of the function is stored
7831 ** in register P3.  Register P3 must not be one of the function inputs.
7832 **
7833 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
7834 ** function was determined to be constant at compile time. If the first
7835 ** argument was constant then bit 0 of P1 is set. This is used to determine
7836 ** whether meta data associated with a user function argument using the
7837 ** sqlite3_set_auxdata() API may be safely retained until the next
7838 ** invocation of this opcode.
7839 **
7840 ** See also: AggStep, AggFinal, PureFunc
7841 */
7842 /* Opcode: PureFunc P1 P2 P3 P4 *
7843 ** Synopsis: r[P3]=func(r[P2@NP])
7844 **
7845 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
7846 ** contains a pointer to the function to be run) with arguments taken
7847 ** from register P2 and successors.  The number of arguments is in
7848 ** the sqlite3_context object that P4 points to.
7849 ** The result of the function is stored
7850 ** in register P3.  Register P3 must not be one of the function inputs.
7851 **
7852 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
7853 ** function was determined to be constant at compile time. If the first
7854 ** argument was constant then bit 0 of P1 is set. This is used to determine
7855 ** whether meta data associated with a user function argument using the
7856 ** sqlite3_set_auxdata() API may be safely retained until the next
7857 ** invocation of this opcode.
7858 **
7859 ** This opcode works exactly like OP_Function.  The only difference is in
7860 ** its name.  This opcode is used in places where the function must be
7861 ** purely non-deterministic.  Some built-in date/time functions can be
7862 ** either determinitic of non-deterministic, depending on their arguments.
7863 ** When those function are used in a non-deterministic way, they will check
7864 ** to see if they were called using OP_PureFunc instead of OP_Function, and
7865 ** if they were, they throw an error.
7866 **
7867 ** See also: AggStep, AggFinal, Function
7868 */
7869 case OP_PureFunc:              /* group */
7870 case OP_Function: {            /* group */
7871   int i;
7872   sqlite3_context *pCtx;
7873 
7874   assert( pOp->p4type==P4_FUNCCTX );
7875   pCtx = pOp->p4.pCtx;
7876 
7877   /* If this function is inside of a trigger, the register array in aMem[]
7878   ** might change from one evaluation to the next.  The next block of code
7879   ** checks to see if the register array has changed, and if so it
7880   ** reinitializes the relavant parts of the sqlite3_context object */
7881   pOut = &aMem[pOp->p3];
7882   if( pCtx->pOut != pOut ){
7883     pCtx->pVdbe = p;
7884     pCtx->pOut = pOut;
7885     for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
7886   }
7887   assert( pCtx->pVdbe==p );
7888 
7889   memAboutToChange(p, pOut);
7890 #ifdef SQLITE_DEBUG
7891   for(i=0; i<pCtx->argc; i++){
7892     assert( memIsValid(pCtx->argv[i]) );
7893     REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
7894   }
7895 #endif
7896   MemSetTypeFlag(pOut, MEM_Null);
7897   assert( pCtx->isError==0 );
7898   (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
7899 
7900   /* If the function returned an error, throw an exception */
7901   if( pCtx->isError ){
7902     if( pCtx->isError>0 ){
7903       sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
7904       rc = pCtx->isError;
7905     }
7906     sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
7907     pCtx->isError = 0;
7908     if( rc ) goto abort_due_to_error;
7909   }
7910 
7911   /* Copy the result of the function into register P3 */
7912   if( pOut->flags & (MEM_Str|MEM_Blob) ){
7913     sqlite3VdbeChangeEncoding(pOut, encoding);
7914     if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
7915   }
7916 
7917   REGISTER_TRACE(pOp->p3, pOut);
7918   UPDATE_MAX_BLOBSIZE(pOut);
7919   break;
7920 }
7921 
7922 /* Opcode: Trace P1 P2 * P4 *
7923 **
7924 ** Write P4 on the statement trace output if statement tracing is
7925 ** enabled.
7926 **
7927 ** Operand P1 must be 0x7fffffff and P2 must positive.
7928 */
7929 /* Opcode: Init P1 P2 P3 P4 *
7930 ** Synopsis: Start at P2
7931 **
7932 ** Programs contain a single instance of this opcode as the very first
7933 ** opcode.
7934 **
7935 ** If tracing is enabled (by the sqlite3_trace()) interface, then
7936 ** the UTF-8 string contained in P4 is emitted on the trace callback.
7937 ** Or if P4 is blank, use the string returned by sqlite3_sql().
7938 **
7939 ** If P2 is not zero, jump to instruction P2.
7940 **
7941 ** Increment the value of P1 so that OP_Once opcodes will jump the
7942 ** first time they are evaluated for this run.
7943 **
7944 ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
7945 ** error is encountered.
7946 */
7947 case OP_Trace:
7948 case OP_Init: {          /* jump */
7949   int i;
7950 #ifndef SQLITE_OMIT_TRACE
7951   char *zTrace;
7952 #endif
7953 
7954   /* If the P4 argument is not NULL, then it must be an SQL comment string.
7955   ** The "--" string is broken up to prevent false-positives with srcck1.c.
7956   **
7957   ** This assert() provides evidence for:
7958   ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
7959   ** would have been returned by the legacy sqlite3_trace() interface by
7960   ** using the X argument when X begins with "--" and invoking
7961   ** sqlite3_expanded_sql(P) otherwise.
7962   */
7963   assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
7964 
7965   /* OP_Init is always instruction 0 */
7966   assert( pOp==p->aOp || pOp->opcode==OP_Trace );
7967 
7968 #ifndef SQLITE_OMIT_TRACE
7969   if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
7970    && !p->doingRerun
7971    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
7972   ){
7973 #ifndef SQLITE_OMIT_DEPRECATED
7974     if( db->mTrace & SQLITE_TRACE_LEGACY ){
7975       char *z = sqlite3VdbeExpandSql(p, zTrace);
7976       db->trace.xLegacy(db->pTraceArg, z);
7977       sqlite3_free(z);
7978     }else
7979 #endif
7980     if( db->nVdbeExec>1 ){
7981       char *z = sqlite3MPrintf(db, "-- %s", zTrace);
7982       (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
7983       sqlite3DbFree(db, z);
7984     }else{
7985       (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
7986     }
7987   }
7988 #ifdef SQLITE_USE_FCNTL_TRACE
7989   zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
7990   if( zTrace ){
7991     int j;
7992     for(j=0; j<db->nDb; j++){
7993       if( DbMaskTest(p->btreeMask, j)==0 ) continue;
7994       sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
7995     }
7996   }
7997 #endif /* SQLITE_USE_FCNTL_TRACE */
7998 #ifdef SQLITE_DEBUG
7999   if( (db->flags & SQLITE_SqlTrace)!=0
8000    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
8001   ){
8002     sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
8003   }
8004 #endif /* SQLITE_DEBUG */
8005 #endif /* SQLITE_OMIT_TRACE */
8006   assert( pOp->p2>0 );
8007   if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
8008     if( pOp->opcode==OP_Trace ) break;
8009     for(i=1; i<p->nOp; i++){
8010       if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
8011     }
8012     pOp->p1 = 0;
8013   }
8014   pOp->p1++;
8015   p->aCounter[SQLITE_STMTSTATUS_RUN]++;
8016   goto jump_to_p2;
8017 }
8018 
8019 #ifdef SQLITE_ENABLE_CURSOR_HINTS
8020 /* Opcode: CursorHint P1 * * P4 *
8021 **
8022 ** Provide a hint to cursor P1 that it only needs to return rows that
8023 ** satisfy the Expr in P4.  TK_REGISTER terms in the P4 expression refer
8024 ** to values currently held in registers.  TK_COLUMN terms in the P4
8025 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
8026 */
8027 case OP_CursorHint: {
8028   VdbeCursor *pC;
8029 
8030   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
8031   assert( pOp->p4type==P4_EXPR );
8032   pC = p->apCsr[pOp->p1];
8033   if( pC ){
8034     assert( pC->eCurType==CURTYPE_BTREE );
8035     sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
8036                            pOp->p4.pExpr, aMem);
8037   }
8038   break;
8039 }
8040 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
8041 
8042 #ifdef SQLITE_DEBUG
8043 /* Opcode:  Abortable   * * * * *
8044 **
8045 ** Verify that an Abort can happen.  Assert if an Abort at this point
8046 ** might cause database corruption.  This opcode only appears in debugging
8047 ** builds.
8048 **
8049 ** An Abort is safe if either there have been no writes, or if there is
8050 ** an active statement journal.
8051 */
8052 case OP_Abortable: {
8053   sqlite3VdbeAssertAbortable(p);
8054   break;
8055 }
8056 #endif
8057 
8058 #ifdef SQLITE_DEBUG
8059 /* Opcode:  ReleaseReg   P1 P2 P3 * P5
8060 ** Synopsis: release r[P1@P2] mask P3
8061 **
8062 ** Release registers from service.  Any content that was in the
8063 ** the registers is unreliable after this opcode completes.
8064 **
8065 ** The registers released will be the P2 registers starting at P1,
8066 ** except if bit ii of P3 set, then do not release register P1+ii.
8067 ** In other words, P3 is a mask of registers to preserve.
8068 **
8069 ** Releasing a register clears the Mem.pScopyFrom pointer.  That means
8070 ** that if the content of the released register was set using OP_SCopy,
8071 ** a change to the value of the source register for the OP_SCopy will no longer
8072 ** generate an assertion fault in sqlite3VdbeMemAboutToChange().
8073 **
8074 ** If P5 is set, then all released registers have their type set
8075 ** to MEM_Undefined so that any subsequent attempt to read the released
8076 ** register (before it is reinitialized) will generate an assertion fault.
8077 **
8078 ** P5 ought to be set on every call to this opcode.
8079 ** However, there are places in the code generator will release registers
8080 ** before their are used, under the (valid) assumption that the registers
8081 ** will not be reallocated for some other purpose before they are used and
8082 ** hence are safe to release.
8083 **
8084 ** This opcode is only available in testing and debugging builds.  It is
8085 ** not generated for release builds.  The purpose of this opcode is to help
8086 ** validate the generated bytecode.  This opcode does not actually contribute
8087 ** to computing an answer.
8088 */
8089 case OP_ReleaseReg: {
8090   Mem *pMem;
8091   int i;
8092   u32 constMask;
8093   assert( pOp->p1>0 );
8094   assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
8095   pMem = &aMem[pOp->p1];
8096   constMask = pOp->p3;
8097   for(i=0; i<pOp->p2; i++, pMem++){
8098     if( i>=32 || (constMask & MASKBIT32(i))==0 ){
8099       pMem->pScopyFrom = 0;
8100       if( i<32 && pOp->p5 ) MemSetTypeFlag(pMem, MEM_Undefined);
8101     }
8102   }
8103   break;
8104 }
8105 #endif
8106 
8107 /* Opcode: Noop * * * * *
8108 **
8109 ** Do nothing.  This instruction is often useful as a jump
8110 ** destination.
8111 */
8112 /*
8113 ** The magic Explain opcode are only inserted when explain==2 (which
8114 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
8115 ** This opcode records information from the optimizer.  It is the
8116 ** the same as a no-op.  This opcodesnever appears in a real VM program.
8117 */
8118 default: {          /* This is really OP_Noop, OP_Explain */
8119   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
8120 
8121   break;
8122 }
8123 
8124 /*****************************************************************************
8125 ** The cases of the switch statement above this line should all be indented
8126 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
8127 ** readability.  From this point on down, the normal indentation rules are
8128 ** restored.
8129 *****************************************************************************/
8130     }
8131 
8132 #ifdef VDBE_PROFILE
8133     {
8134       u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
8135       if( endTime>start ) pOrigOp->cycles += endTime - start;
8136       pOrigOp->cnt++;
8137     }
8138 #endif
8139 
8140     /* The following code adds nothing to the actual functionality
8141     ** of the program.  It is only here for testing and debugging.
8142     ** On the other hand, it does burn CPU cycles every time through
8143     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
8144     */
8145 #ifndef NDEBUG
8146     assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
8147 
8148 #ifdef SQLITE_DEBUG
8149     if( db->flags & SQLITE_VdbeTrace ){
8150       u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
8151       if( rc!=0 ) printf("rc=%d\n",rc);
8152       if( opProperty & (OPFLG_OUT2) ){
8153         registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
8154       }
8155       if( opProperty & OPFLG_OUT3 ){
8156         registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
8157       }
8158       if( opProperty==0xff ){
8159         /* Never happens.  This code exists to avoid a harmless linkage
8160         ** warning aboud sqlite3VdbeRegisterDump() being defined but not
8161         ** used. */
8162         sqlite3VdbeRegisterDump(p);
8163       }
8164     }
8165 #endif  /* SQLITE_DEBUG */
8166 #endif  /* NDEBUG */
8167   }  /* The end of the for(;;) loop the loops through opcodes */
8168 
8169   /* If we reach this point, it means that execution is finished with
8170   ** an error of some kind.
8171   */
8172 abort_due_to_error:
8173   if( db->mallocFailed ){
8174     rc = SQLITE_NOMEM_BKPT;
8175   }else if( rc==SQLITE_IOERR_CORRUPTFS ){
8176     rc = SQLITE_CORRUPT_BKPT;
8177   }
8178   assert( rc );
8179   if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
8180     sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
8181   }
8182   p->rc = rc;
8183   sqlite3SystemError(db, rc);
8184   testcase( sqlite3GlobalConfig.xLog!=0 );
8185   sqlite3_log(rc, "statement aborts at %d: [%s] %s",
8186                    (int)(pOp - aOp), p->zSql, p->zErrMsg);
8187   sqlite3VdbeHalt(p);
8188   if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
8189   rc = SQLITE_ERROR;
8190   if( resetSchemaOnFault>0 ){
8191     sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
8192   }
8193 
8194   /* This is the only way out of this procedure.  We have to
8195   ** release the mutexes on btrees that were acquired at the
8196   ** top. */
8197 vdbe_return:
8198 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8199   while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
8200     nProgressLimit += db->nProgressOps;
8201     if( db->xProgress(db->pProgressArg) ){
8202       nProgressLimit = LARGEST_UINT64;
8203       rc = SQLITE_INTERRUPT;
8204       goto abort_due_to_error;
8205     }
8206   }
8207 #endif
8208   p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
8209   sqlite3VdbeLeave(p);
8210   assert( rc!=SQLITE_OK || nExtraDelete==0
8211        || sqlite3_strlike("DELETE%",p->zSql,0)!=0
8212   );
8213   return rc;
8214 
8215   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
8216   ** is encountered.
8217   */
8218 too_big:
8219   sqlite3VdbeError(p, "string or blob too big");
8220   rc = SQLITE_TOOBIG;
8221   goto abort_due_to_error;
8222 
8223   /* Jump to here if a malloc() fails.
8224   */
8225 no_mem:
8226   sqlite3OomFault(db);
8227   sqlite3VdbeError(p, "out of memory");
8228   rc = SQLITE_NOMEM_BKPT;
8229   goto abort_due_to_error;
8230 
8231   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
8232   ** flag.
8233   */
8234 abort_due_to_interrupt:
8235   assert( AtomicLoad(&db->u1.isInterrupted) );
8236   rc = SQLITE_INTERRUPT;
8237   goto abort_due_to_error;
8238 }
8239