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