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