xref: /sqlite-3.40.0/src/vdbe.c (revision bb0c5428)
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 P3 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 ** GENERATED ALWAYS AS ... STATIC columns are only checked if P3
2914 ** is zero.  When P3 is non-zero, no type checking occurs for
2915 ** static generated columns.  Virtual columns are computed at query time
2916 ** and so they are never checked.
2917 **
2918 ** Preconditions:
2919 **
2920 ** <ul>
2921 ** <li> P2 should be the number of non-virtual columns in the
2922 **      table of P4.
2923 ** <li> Table P4 should be a STRICT table.
2924 ** </ul>
2925 **
2926 ** If any precondition is false, an assertion fault occurs.
2927 */
2928 case OP_TypeCheck: {
2929   Table *pTab;
2930   Column *aCol;
2931   int i;
2932 
2933   assert( pOp->p4type==P4_TABLE );
2934   pTab = pOp->p4.pTab;
2935   assert( pTab->tabFlags & TF_Strict );
2936   assert( pTab->nNVCol==pOp->p2 );
2937   aCol = pTab->aCol;
2938   pIn1 = &aMem[pOp->p1];
2939   for(i=0; i<pTab->nCol; i++){
2940     if( aCol[i].colFlags & COLFLAG_GENERATED ){
2941       if( aCol[i].colFlags & COLFLAG_VIRTUAL ) continue;
2942       if( pOp->p3 ){ pIn1++; continue; }
2943     }
2944     assert( pIn1 < &aMem[pOp->p1+pOp->p2] );
2945     applyAffinity(pIn1, aCol[i].affinity, encoding);
2946     if( (pIn1->flags & MEM_Null)==0 ){
2947       switch( aCol[i].eCType ){
2948         case COLTYPE_BLOB: {
2949           if( (pIn1->flags & MEM_Blob)==0 ) goto vdbe_type_error;
2950           break;
2951         }
2952         case COLTYPE_INTEGER:
2953         case COLTYPE_INT: {
2954           if( (pIn1->flags & MEM_Int)==0 ) goto vdbe_type_error;
2955           break;
2956         }
2957         case COLTYPE_TEXT: {
2958           if( (pIn1->flags & MEM_Str)==0 ) goto vdbe_type_error;
2959           break;
2960         }
2961         case COLTYPE_REAL: {
2962           if( pIn1->flags & MEM_Int ){
2963             /* When applying REAL affinity, if the result is still an MEM_Int
2964             ** that will fit in 6 bytes, then change the type to MEM_IntReal
2965             ** so that we keep the high-resolution integer value but know that
2966             ** the type really wants to be REAL. */
2967             testcase( pIn1->u.i==140737488355328LL );
2968             testcase( pIn1->u.i==140737488355327LL );
2969             testcase( pIn1->u.i==-140737488355328LL );
2970             testcase( pIn1->u.i==-140737488355329LL );
2971             if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL){
2972               pIn1->flags |= MEM_IntReal;
2973               pIn1->flags &= ~MEM_Int;
2974             }else{
2975               pIn1->u.r = (double)pIn1->u.i;
2976               pIn1->flags |= MEM_Real;
2977               pIn1->flags &= ~MEM_Int;
2978             }
2979           }else if( (pIn1->flags & MEM_Real)==0 ){
2980             goto vdbe_type_error;
2981           }
2982           break;
2983         }
2984         default: {
2985           /* COLTYPE_ANY.  Accept anything. */
2986           break;
2987         }
2988       }
2989     }
2990     REGISTER_TRACE((int)(pIn1-aMem), pIn1);
2991     pIn1++;
2992   }
2993   assert( pIn1 == &aMem[pOp->p1+pOp->p2] );
2994   break;
2995 
2996 vdbe_type_error:
2997   sqlite3VdbeError(p, "cannot store %s value in %s column %s.%s",
2998      vdbeMemTypeName(pIn1), sqlite3StdType[aCol[i].eCType-1],
2999      pTab->zName, aCol[i].zCnName);
3000   rc = SQLITE_CONSTRAINT_DATATYPE;
3001   goto abort_due_to_error;
3002 }
3003 
3004 /* Opcode: Affinity P1 P2 * P4 *
3005 ** Synopsis: affinity(r[P1@P2])
3006 **
3007 ** Apply affinities to a range of P2 registers starting with P1.
3008 **
3009 ** P4 is a string that is P2 characters long. The N-th character of the
3010 ** string indicates the column affinity that should be used for the N-th
3011 ** memory cell in the range.
3012 */
3013 case OP_Affinity: {
3014   const char *zAffinity;   /* The affinity to be applied */
3015 
3016   zAffinity = pOp->p4.z;
3017   assert( zAffinity!=0 );
3018   assert( pOp->p2>0 );
3019   assert( zAffinity[pOp->p2]==0 );
3020   pIn1 = &aMem[pOp->p1];
3021   while( 1 /*exit-by-break*/ ){
3022     assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
3023     assert( zAffinity[0]==SQLITE_AFF_NONE || memIsValid(pIn1) );
3024     applyAffinity(pIn1, zAffinity[0], encoding);
3025     if( zAffinity[0]==SQLITE_AFF_REAL && (pIn1->flags & MEM_Int)!=0 ){
3026       /* When applying REAL affinity, if the result is still an MEM_Int
3027       ** that will fit in 6 bytes, then change the type to MEM_IntReal
3028       ** so that we keep the high-resolution integer value but know that
3029       ** the type really wants to be REAL. */
3030       testcase( pIn1->u.i==140737488355328LL );
3031       testcase( pIn1->u.i==140737488355327LL );
3032       testcase( pIn1->u.i==-140737488355328LL );
3033       testcase( pIn1->u.i==-140737488355329LL );
3034       if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL ){
3035         pIn1->flags |= MEM_IntReal;
3036         pIn1->flags &= ~MEM_Int;
3037       }else{
3038         pIn1->u.r = (double)pIn1->u.i;
3039         pIn1->flags |= MEM_Real;
3040         pIn1->flags &= ~MEM_Int;
3041       }
3042     }
3043     REGISTER_TRACE((int)(pIn1-aMem), pIn1);
3044     zAffinity++;
3045     if( zAffinity[0]==0 ) break;
3046     pIn1++;
3047   }
3048   break;
3049 }
3050 
3051 /* Opcode: MakeRecord P1 P2 P3 P4 *
3052 ** Synopsis: r[P3]=mkrec(r[P1@P2])
3053 **
3054 ** Convert P2 registers beginning with P1 into the [record format]
3055 ** use as a data record in a database table or as a key
3056 ** in an index.  The OP_Column opcode can decode the record later.
3057 **
3058 ** P4 may be a string that is P2 characters long.  The N-th character of the
3059 ** string indicates the column affinity that should be used for the N-th
3060 ** field of the index key.
3061 **
3062 ** The mapping from character to affinity is given by the SQLITE_AFF_
3063 ** macros defined in sqliteInt.h.
3064 **
3065 ** If P4 is NULL then all index fields have the affinity BLOB.
3066 **
3067 ** The meaning of P5 depends on whether or not the SQLITE_ENABLE_NULL_TRIM
3068 ** compile-time option is enabled:
3069 **
3070 **   * If SQLITE_ENABLE_NULL_TRIM is enabled, then the P5 is the index
3071 **     of the right-most table that can be null-trimmed.
3072 **
3073 **   * If SQLITE_ENABLE_NULL_TRIM is omitted, then P5 has the value
3074 **     OPFLAG_NOCHNG_MAGIC if the OP_MakeRecord opcode is allowed to
3075 **     accept no-change records with serial_type 10.  This value is
3076 **     only used inside an assert() and does not affect the end result.
3077 */
3078 case OP_MakeRecord: {
3079   Mem *pRec;             /* The new record */
3080   u64 nData;             /* Number of bytes of data space */
3081   int nHdr;              /* Number of bytes of header space */
3082   i64 nByte;             /* Data space required for this record */
3083   i64 nZero;             /* Number of zero bytes at the end of the record */
3084   int nVarint;           /* Number of bytes in a varint */
3085   u32 serial_type;       /* Type field */
3086   Mem *pData0;           /* First field to be combined into the record */
3087   Mem *pLast;            /* Last field of the record */
3088   int nField;            /* Number of fields in the record */
3089   char *zAffinity;       /* The affinity string for the record */
3090   int file_format;       /* File format to use for encoding */
3091   u32 len;               /* Length of a field */
3092   u8 *zHdr;              /* Where to write next byte of the header */
3093   u8 *zPayload;          /* Where to write next byte of the payload */
3094 
3095   /* Assuming the record contains N fields, the record format looks
3096   ** like this:
3097   **
3098   ** ------------------------------------------------------------------------
3099   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
3100   ** ------------------------------------------------------------------------
3101   **
3102   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
3103   ** and so forth.
3104   **
3105   ** Each type field is a varint representing the serial type of the
3106   ** corresponding data element (see sqlite3VdbeSerialType()). The
3107   ** hdr-size field is also a varint which is the offset from the beginning
3108   ** of the record to data0.
3109   */
3110   nData = 0;         /* Number of bytes of data space */
3111   nHdr = 0;          /* Number of bytes of header space */
3112   nZero = 0;         /* Number of zero bytes at the end of the record */
3113   nField = pOp->p1;
3114   zAffinity = pOp->p4.z;
3115   assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
3116   pData0 = &aMem[nField];
3117   nField = pOp->p2;
3118   pLast = &pData0[nField-1];
3119   file_format = p->minWriteFileFormat;
3120 
3121   /* Identify the output register */
3122   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
3123   pOut = &aMem[pOp->p3];
3124   memAboutToChange(p, pOut);
3125 
3126   /* Apply the requested affinity to all inputs
3127   */
3128   assert( pData0<=pLast );
3129   if( zAffinity ){
3130     pRec = pData0;
3131     do{
3132       applyAffinity(pRec, zAffinity[0], encoding);
3133       if( zAffinity[0]==SQLITE_AFF_REAL && (pRec->flags & MEM_Int) ){
3134         pRec->flags |= MEM_IntReal;
3135         pRec->flags &= ~(MEM_Int);
3136       }
3137       REGISTER_TRACE((int)(pRec-aMem), pRec);
3138       zAffinity++;
3139       pRec++;
3140       assert( zAffinity[0]==0 || pRec<=pLast );
3141     }while( zAffinity[0] );
3142   }
3143 
3144 #ifdef SQLITE_ENABLE_NULL_TRIM
3145   /* NULLs can be safely trimmed from the end of the record, as long as
3146   ** as the schema format is 2 or more and none of the omitted columns
3147   ** have a non-NULL default value.  Also, the record must be left with
3148   ** at least one field.  If P5>0 then it will be one more than the
3149   ** index of the right-most column with a non-NULL default value */
3150   if( pOp->p5 ){
3151     while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
3152       pLast--;
3153       nField--;
3154     }
3155   }
3156 #endif
3157 
3158   /* Loop through the elements that will make up the record to figure
3159   ** out how much space is required for the new record.  After this loop,
3160   ** the Mem.uTemp field of each term should hold the serial-type that will
3161   ** be used for that term in the generated record:
3162   **
3163   **   Mem.uTemp value    type
3164   **   ---------------    ---------------
3165   **      0               NULL
3166   **      1               1-byte signed integer
3167   **      2               2-byte signed integer
3168   **      3               3-byte signed integer
3169   **      4               4-byte signed integer
3170   **      5               6-byte signed integer
3171   **      6               8-byte signed integer
3172   **      7               IEEE float
3173   **      8               Integer constant 0
3174   **      9               Integer constant 1
3175   **     10,11            reserved for expansion
3176   **    N>=12 and even    BLOB
3177   **    N>=13 and odd     text
3178   **
3179   ** The following additional values are computed:
3180   **     nHdr        Number of bytes needed for the record header
3181   **     nData       Number of bytes of data space needed for the record
3182   **     nZero       Zero bytes at the end of the record
3183   */
3184   pRec = pLast;
3185   do{
3186     assert( memIsValid(pRec) );
3187     if( pRec->flags & MEM_Null ){
3188       if( pRec->flags & MEM_Zero ){
3189         /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
3190         ** table methods that never invoke sqlite3_result_xxxxx() while
3191         ** computing an unchanging column value in an UPDATE statement.
3192         ** Give such values a special internal-use-only serial-type of 10
3193         ** so that they can be passed through to xUpdate and have
3194         ** a true sqlite3_value_nochange(). */
3195 #ifndef SQLITE_ENABLE_NULL_TRIM
3196         assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
3197 #endif
3198         pRec->uTemp = 10;
3199       }else{
3200         pRec->uTemp = 0;
3201       }
3202       nHdr++;
3203     }else if( pRec->flags & (MEM_Int|MEM_IntReal) ){
3204       /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
3205       i64 i = pRec->u.i;
3206       u64 uu;
3207       testcase( pRec->flags & MEM_Int );
3208       testcase( pRec->flags & MEM_IntReal );
3209       if( i<0 ){
3210         uu = ~i;
3211       }else{
3212         uu = i;
3213       }
3214       nHdr++;
3215       testcase( uu==127 );               testcase( uu==128 );
3216       testcase( uu==32767 );             testcase( uu==32768 );
3217       testcase( uu==8388607 );           testcase( uu==8388608 );
3218       testcase( uu==2147483647 );        testcase( uu==2147483648 );
3219       testcase( uu==140737488355327LL ); testcase( uu==140737488355328LL );
3220       if( uu<=127 ){
3221         if( (i&1)==i && file_format>=4 ){
3222           pRec->uTemp = 8+(u32)uu;
3223         }else{
3224           nData++;
3225           pRec->uTemp = 1;
3226         }
3227       }else if( uu<=32767 ){
3228         nData += 2;
3229         pRec->uTemp = 2;
3230       }else if( uu<=8388607 ){
3231         nData += 3;
3232         pRec->uTemp = 3;
3233       }else if( uu<=2147483647 ){
3234         nData += 4;
3235         pRec->uTemp = 4;
3236       }else if( uu<=140737488355327LL ){
3237         nData += 6;
3238         pRec->uTemp = 5;
3239       }else{
3240         nData += 8;
3241         if( pRec->flags & MEM_IntReal ){
3242           /* If the value is IntReal and is going to take up 8 bytes to store
3243           ** as an integer, then we might as well make it an 8-byte floating
3244           ** point value */
3245           pRec->u.r = (double)pRec->u.i;
3246           pRec->flags &= ~MEM_IntReal;
3247           pRec->flags |= MEM_Real;
3248           pRec->uTemp = 7;
3249         }else{
3250           pRec->uTemp = 6;
3251         }
3252       }
3253     }else if( pRec->flags & MEM_Real ){
3254       nHdr++;
3255       nData += 8;
3256       pRec->uTemp = 7;
3257     }else{
3258       assert( db->mallocFailed || pRec->flags&(MEM_Str|MEM_Blob) );
3259       assert( pRec->n>=0 );
3260       len = (u32)pRec->n;
3261       serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0);
3262       if( pRec->flags & MEM_Zero ){
3263         serial_type += pRec->u.nZero*2;
3264         if( nData ){
3265           if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
3266           len += pRec->u.nZero;
3267         }else{
3268           nZero += pRec->u.nZero;
3269         }
3270       }
3271       nData += len;
3272       nHdr += sqlite3VarintLen(serial_type);
3273       pRec->uTemp = serial_type;
3274     }
3275     if( pRec==pData0 ) break;
3276     pRec--;
3277   }while(1);
3278 
3279   /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
3280   ** which determines the total number of bytes in the header. The varint
3281   ** value is the size of the header in bytes including the size varint
3282   ** itself. */
3283   testcase( nHdr==126 );
3284   testcase( nHdr==127 );
3285   if( nHdr<=126 ){
3286     /* The common case */
3287     nHdr += 1;
3288   }else{
3289     /* Rare case of a really large header */
3290     nVarint = sqlite3VarintLen(nHdr);
3291     nHdr += nVarint;
3292     if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
3293   }
3294   nByte = nHdr+nData;
3295 
3296   /* Make sure the output register has a buffer large enough to store
3297   ** the new record. The output register (pOp->p3) is not allowed to
3298   ** be one of the input registers (because the following call to
3299   ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
3300   */
3301   if( nByte+nZero<=pOut->szMalloc ){
3302     /* The output register is already large enough to hold the record.
3303     ** No error checks or buffer enlargement is required */
3304     pOut->z = pOut->zMalloc;
3305   }else{
3306     /* Need to make sure that the output is not too big and then enlarge
3307     ** the output register to hold the full result */
3308     if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
3309       goto too_big;
3310     }
3311     if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
3312       goto no_mem;
3313     }
3314   }
3315   pOut->n = (int)nByte;
3316   pOut->flags = MEM_Blob;
3317   if( nZero ){
3318     pOut->u.nZero = nZero;
3319     pOut->flags |= MEM_Zero;
3320   }
3321   UPDATE_MAX_BLOBSIZE(pOut);
3322   zHdr = (u8 *)pOut->z;
3323   zPayload = zHdr + nHdr;
3324 
3325   /* Write the record */
3326   zHdr += putVarint32(zHdr, nHdr);
3327   assert( pData0<=pLast );
3328   pRec = pData0;
3329   do{
3330     serial_type = pRec->uTemp;
3331     /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
3332     ** additional varints, one per column. */
3333     zHdr += putVarint32(zHdr, serial_type);            /* serial type */
3334     /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
3335     ** immediately follow the header. */
3336     zPayload += sqlite3VdbeSerialPut(zPayload, pRec, serial_type); /* content */
3337   }while( (++pRec)<=pLast );
3338   assert( nHdr==(int)(zHdr - (u8*)pOut->z) );
3339   assert( nByte==(int)(zPayload - (u8*)pOut->z) );
3340 
3341   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
3342   REGISTER_TRACE(pOp->p3, pOut);
3343   break;
3344 }
3345 
3346 /* Opcode: Count P1 P2 p3 * *
3347 ** Synopsis: r[P2]=count()
3348 **
3349 ** Store the number of entries (an integer value) in the table or index
3350 ** opened by cursor P1 in register P2.
3351 **
3352 ** If P3==0, then an exact count is obtained, which involves visiting
3353 ** every btree page of the table.  But if P3 is non-zero, an estimate
3354 ** is returned based on the current cursor position.
3355 */
3356 case OP_Count: {         /* out2 */
3357   i64 nEntry;
3358   BtCursor *pCrsr;
3359 
3360   assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
3361   pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
3362   assert( pCrsr );
3363   if( pOp->p3 ){
3364     nEntry = sqlite3BtreeRowCountEst(pCrsr);
3365   }else{
3366     nEntry = 0;  /* Not needed.  Only used to silence a warning. */
3367     rc = sqlite3BtreeCount(db, pCrsr, &nEntry);
3368     if( rc ) goto abort_due_to_error;
3369   }
3370   pOut = out2Prerelease(p, pOp);
3371   pOut->u.i = nEntry;
3372   goto check_for_interrupt;
3373 }
3374 
3375 /* Opcode: Savepoint P1 * * P4 *
3376 **
3377 ** Open, release or rollback the savepoint named by parameter P4, depending
3378 ** on the value of P1. To open a new savepoint set P1==0 (SAVEPOINT_BEGIN).
3379 ** To release (commit) an existing savepoint set P1==1 (SAVEPOINT_RELEASE).
3380 ** To rollback an existing savepoint set P1==2 (SAVEPOINT_ROLLBACK).
3381 */
3382 case OP_Savepoint: {
3383   int p1;                         /* Value of P1 operand */
3384   char *zName;                    /* Name of savepoint */
3385   int nName;
3386   Savepoint *pNew;
3387   Savepoint *pSavepoint;
3388   Savepoint *pTmp;
3389   int iSavepoint;
3390   int ii;
3391 
3392   p1 = pOp->p1;
3393   zName = pOp->p4.z;
3394 
3395   /* Assert that the p1 parameter is valid. Also that if there is no open
3396   ** transaction, then there cannot be any savepoints.
3397   */
3398   assert( db->pSavepoint==0 || db->autoCommit==0 );
3399   assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
3400   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
3401   assert( checkSavepointCount(db) );
3402   assert( p->bIsReader );
3403 
3404   if( p1==SAVEPOINT_BEGIN ){
3405     if( db->nVdbeWrite>0 ){
3406       /* A new savepoint cannot be created if there are active write
3407       ** statements (i.e. open read/write incremental blob handles).
3408       */
3409       sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
3410       rc = SQLITE_BUSY;
3411     }else{
3412       nName = sqlite3Strlen30(zName);
3413 
3414 #ifndef SQLITE_OMIT_VIRTUALTABLE
3415       /* This call is Ok even if this savepoint is actually a transaction
3416       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
3417       ** If this is a transaction savepoint being opened, it is guaranteed
3418       ** that the db->aVTrans[] array is empty.  */
3419       assert( db->autoCommit==0 || db->nVTrans==0 );
3420       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
3421                                 db->nStatement+db->nSavepoint);
3422       if( rc!=SQLITE_OK ) goto abort_due_to_error;
3423 #endif
3424 
3425       /* Create a new savepoint structure. */
3426       pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
3427       if( pNew ){
3428         pNew->zName = (char *)&pNew[1];
3429         memcpy(pNew->zName, zName, nName+1);
3430 
3431         /* If there is no open transaction, then mark this as a special
3432         ** "transaction savepoint". */
3433         if( db->autoCommit ){
3434           db->autoCommit = 0;
3435           db->isTransactionSavepoint = 1;
3436         }else{
3437           db->nSavepoint++;
3438         }
3439 
3440         /* Link the new savepoint into the database handle's list. */
3441         pNew->pNext = db->pSavepoint;
3442         db->pSavepoint = pNew;
3443         pNew->nDeferredCons = db->nDeferredCons;
3444         pNew->nDeferredImmCons = db->nDeferredImmCons;
3445       }
3446     }
3447   }else{
3448     assert( p1==SAVEPOINT_RELEASE || p1==SAVEPOINT_ROLLBACK );
3449     iSavepoint = 0;
3450 
3451     /* Find the named savepoint. If there is no such savepoint, then an
3452     ** an error is returned to the user.  */
3453     for(
3454       pSavepoint = db->pSavepoint;
3455       pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
3456       pSavepoint = pSavepoint->pNext
3457     ){
3458       iSavepoint++;
3459     }
3460     if( !pSavepoint ){
3461       sqlite3VdbeError(p, "no such savepoint: %s", zName);
3462       rc = SQLITE_ERROR;
3463     }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
3464       /* It is not possible to release (commit) a savepoint if there are
3465       ** active write statements.
3466       */
3467       sqlite3VdbeError(p, "cannot release savepoint - "
3468                           "SQL statements in progress");
3469       rc = SQLITE_BUSY;
3470     }else{
3471 
3472       /* Determine whether or not this is a transaction savepoint. If so,
3473       ** and this is a RELEASE command, then the current transaction
3474       ** is committed.
3475       */
3476       int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
3477       if( isTransaction && p1==SAVEPOINT_RELEASE ){
3478         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3479           goto vdbe_return;
3480         }
3481         db->autoCommit = 1;
3482         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3483           p->pc = (int)(pOp - aOp);
3484           db->autoCommit = 0;
3485           p->rc = rc = SQLITE_BUSY;
3486           goto vdbe_return;
3487         }
3488         rc = p->rc;
3489         if( rc ){
3490           db->autoCommit = 0;
3491         }else{
3492           db->isTransactionSavepoint = 0;
3493         }
3494       }else{
3495         int isSchemaChange;
3496         iSavepoint = db->nSavepoint - iSavepoint - 1;
3497         if( p1==SAVEPOINT_ROLLBACK ){
3498           isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
3499           for(ii=0; ii<db->nDb; ii++){
3500             rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
3501                                        SQLITE_ABORT_ROLLBACK,
3502                                        isSchemaChange==0);
3503             if( rc!=SQLITE_OK ) goto abort_due_to_error;
3504           }
3505         }else{
3506           assert( p1==SAVEPOINT_RELEASE );
3507           isSchemaChange = 0;
3508         }
3509         for(ii=0; ii<db->nDb; ii++){
3510           rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
3511           if( rc!=SQLITE_OK ){
3512             goto abort_due_to_error;
3513           }
3514         }
3515         if( isSchemaChange ){
3516           sqlite3ExpirePreparedStatements(db, 0);
3517           sqlite3ResetAllSchemasOfConnection(db);
3518           db->mDbFlags |= DBFLAG_SchemaChange;
3519         }
3520       }
3521       if( rc ) goto abort_due_to_error;
3522 
3523       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
3524       ** savepoints nested inside of the savepoint being operated on. */
3525       while( db->pSavepoint!=pSavepoint ){
3526         pTmp = db->pSavepoint;
3527         db->pSavepoint = pTmp->pNext;
3528         sqlite3DbFree(db, pTmp);
3529         db->nSavepoint--;
3530       }
3531 
3532       /* If it is a RELEASE, then destroy the savepoint being operated on
3533       ** too. If it is a ROLLBACK TO, then set the number of deferred
3534       ** constraint violations present in the database to the value stored
3535       ** when the savepoint was created.  */
3536       if( p1==SAVEPOINT_RELEASE ){
3537         assert( pSavepoint==db->pSavepoint );
3538         db->pSavepoint = pSavepoint->pNext;
3539         sqlite3DbFree(db, pSavepoint);
3540         if( !isTransaction ){
3541           db->nSavepoint--;
3542         }
3543       }else{
3544         assert( p1==SAVEPOINT_ROLLBACK );
3545         db->nDeferredCons = pSavepoint->nDeferredCons;
3546         db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
3547       }
3548 
3549       if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
3550         rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
3551         if( rc!=SQLITE_OK ) goto abort_due_to_error;
3552       }
3553     }
3554   }
3555   if( rc ) goto abort_due_to_error;
3556 
3557   break;
3558 }
3559 
3560 /* Opcode: AutoCommit P1 P2 * * *
3561 **
3562 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
3563 ** back any currently active btree transactions. If there are any active
3564 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
3565 ** there are active writing VMs or active VMs that use shared cache.
3566 **
3567 ** This instruction causes the VM to halt.
3568 */
3569 case OP_AutoCommit: {
3570   int desiredAutoCommit;
3571   int iRollback;
3572 
3573   desiredAutoCommit = pOp->p1;
3574   iRollback = pOp->p2;
3575   assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
3576   assert( desiredAutoCommit==1 || iRollback==0 );
3577   assert( db->nVdbeActive>0 );  /* At least this one VM is active */
3578   assert( p->bIsReader );
3579 
3580   if( desiredAutoCommit!=db->autoCommit ){
3581     if( iRollback ){
3582       assert( desiredAutoCommit==1 );
3583       sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
3584       db->autoCommit = 1;
3585     }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
3586       /* If this instruction implements a COMMIT and other VMs are writing
3587       ** return an error indicating that the other VMs must complete first.
3588       */
3589       sqlite3VdbeError(p, "cannot commit transaction - "
3590                           "SQL statements in progress");
3591       rc = SQLITE_BUSY;
3592       goto abort_due_to_error;
3593     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3594       goto vdbe_return;
3595     }else{
3596       db->autoCommit = (u8)desiredAutoCommit;
3597     }
3598     if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3599       p->pc = (int)(pOp - aOp);
3600       db->autoCommit = (u8)(1-desiredAutoCommit);
3601       p->rc = rc = SQLITE_BUSY;
3602       goto vdbe_return;
3603     }
3604     sqlite3CloseSavepoints(db);
3605     if( p->rc==SQLITE_OK ){
3606       rc = SQLITE_DONE;
3607     }else{
3608       rc = SQLITE_ERROR;
3609     }
3610     goto vdbe_return;
3611   }else{
3612     sqlite3VdbeError(p,
3613         (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
3614         (iRollback)?"cannot rollback - no transaction is active":
3615                    "cannot commit - no transaction is active"));
3616 
3617     rc = SQLITE_ERROR;
3618     goto abort_due_to_error;
3619   }
3620   /*NOTREACHED*/ assert(0);
3621 }
3622 
3623 /* Opcode: Transaction P1 P2 P3 P4 P5
3624 **
3625 ** Begin a transaction on database P1 if a transaction is not already
3626 ** active.
3627 ** If P2 is non-zero, then a write-transaction is started, or if a
3628 ** read-transaction is already active, it is upgraded to a write-transaction.
3629 ** If P2 is zero, then a read-transaction is started.  If P2 is 2 or more
3630 ** then an exclusive transaction is started.
3631 **
3632 ** P1 is the index of the database file on which the transaction is
3633 ** started.  Index 0 is the main database file and index 1 is the
3634 ** file used for temporary tables.  Indices of 2 or more are used for
3635 ** attached databases.
3636 **
3637 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
3638 ** true (this flag is set if the Vdbe may modify more than one row and may
3639 ** throw an ABORT exception), a statement transaction may also be opened.
3640 ** More specifically, a statement transaction is opened iff the database
3641 ** connection is currently not in autocommit mode, or if there are other
3642 ** active statements. A statement transaction allows the changes made by this
3643 ** VDBE to be rolled back after an error without having to roll back the
3644 ** entire transaction. If no error is encountered, the statement transaction
3645 ** will automatically commit when the VDBE halts.
3646 **
3647 ** If P5!=0 then this opcode also checks the schema cookie against P3
3648 ** and the schema generation counter against P4.
3649 ** The cookie changes its value whenever the database schema changes.
3650 ** This operation is used to detect when that the cookie has changed
3651 ** and that the current process needs to reread the schema.  If the schema
3652 ** cookie in P3 differs from the schema cookie in the database header or
3653 ** if the schema generation counter in P4 differs from the current
3654 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
3655 ** halts.  The sqlite3_step() wrapper function might then reprepare the
3656 ** statement and rerun it from the beginning.
3657 */
3658 case OP_Transaction: {
3659   Btree *pBt;
3660   int iMeta = 0;
3661 
3662   assert( p->bIsReader );
3663   assert( p->readOnly==0 || pOp->p2==0 );
3664   assert( pOp->p2>=0 && pOp->p2<=2 );
3665   assert( pOp->p1>=0 && pOp->p1<db->nDb );
3666   assert( DbMaskTest(p->btreeMask, pOp->p1) );
3667   assert( rc==SQLITE_OK );
3668   if( pOp->p2 && (db->flags & (SQLITE_QueryOnly|SQLITE_CorruptRdOnly))!=0 ){
3669     if( db->flags & SQLITE_QueryOnly ){
3670       /* Writes prohibited by the "PRAGMA query_only=TRUE" statement */
3671       rc = SQLITE_READONLY;
3672     }else{
3673       /* Writes prohibited due to a prior SQLITE_CORRUPT in the current
3674       ** transaction */
3675       rc = SQLITE_CORRUPT;
3676     }
3677     goto abort_due_to_error;
3678   }
3679   pBt = db->aDb[pOp->p1].pBt;
3680 
3681   if( pBt ){
3682     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta);
3683     testcase( rc==SQLITE_BUSY_SNAPSHOT );
3684     testcase( rc==SQLITE_BUSY_RECOVERY );
3685     if( rc!=SQLITE_OK ){
3686       if( (rc&0xff)==SQLITE_BUSY ){
3687         p->pc = (int)(pOp - aOp);
3688         p->rc = rc;
3689         goto vdbe_return;
3690       }
3691       goto abort_due_to_error;
3692     }
3693 
3694     if( p->usesStmtJournal
3695      && pOp->p2
3696      && (db->autoCommit==0 || db->nVdbeRead>1)
3697     ){
3698       assert( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE );
3699       if( p->iStatement==0 ){
3700         assert( db->nStatement>=0 && db->nSavepoint>=0 );
3701         db->nStatement++;
3702         p->iStatement = db->nSavepoint + db->nStatement;
3703       }
3704 
3705       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
3706       if( rc==SQLITE_OK ){
3707         rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
3708       }
3709 
3710       /* Store the current value of the database handles deferred constraint
3711       ** counter. If the statement transaction needs to be rolled back,
3712       ** the value of this counter needs to be restored too.  */
3713       p->nStmtDefCons = db->nDeferredCons;
3714       p->nStmtDefImmCons = db->nDeferredImmCons;
3715     }
3716   }
3717   assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
3718   if( rc==SQLITE_OK
3719    && pOp->p5
3720    && (iMeta!=pOp->p3
3721       || db->aDb[pOp->p1].pSchema->iGeneration!=pOp->p4.i)
3722   ){
3723     /*
3724     ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
3725     ** version is checked to ensure that the schema has not changed since the
3726     ** SQL statement was prepared.
3727     */
3728     sqlite3DbFree(db, p->zErrMsg);
3729     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
3730     /* If the schema-cookie from the database file matches the cookie
3731     ** stored with the in-memory representation of the schema, do
3732     ** not reload the schema from the database file.
3733     **
3734     ** If virtual-tables are in use, this is not just an optimization.
3735     ** Often, v-tables store their data in other SQLite tables, which
3736     ** are queried from within xNext() and other v-table methods using
3737     ** prepared queries. If such a query is out-of-date, we do not want to
3738     ** discard the database schema, as the user code implementing the
3739     ** v-table would have to be ready for the sqlite3_vtab structure itself
3740     ** to be invalidated whenever sqlite3_step() is called from within
3741     ** a v-table method.
3742     */
3743     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
3744       sqlite3ResetOneSchema(db, pOp->p1);
3745     }
3746     p->expired = 1;
3747     rc = SQLITE_SCHEMA;
3748   }
3749   if( rc ) goto abort_due_to_error;
3750   break;
3751 }
3752 
3753 /* Opcode: ReadCookie P1 P2 P3 * *
3754 **
3755 ** Read cookie number P3 from database P1 and write it into register P2.
3756 ** P3==1 is the schema version.  P3==2 is the database format.
3757 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
3758 ** the main database file and P1==1 is the database file used to store
3759 ** temporary tables.
3760 **
3761 ** There must be a read-lock on the database (either a transaction
3762 ** must be started or there must be an open cursor) before
3763 ** executing this instruction.
3764 */
3765 case OP_ReadCookie: {               /* out2 */
3766   int iMeta;
3767   int iDb;
3768   int iCookie;
3769 
3770   assert( p->bIsReader );
3771   iDb = pOp->p1;
3772   iCookie = pOp->p3;
3773   assert( pOp->p3<SQLITE_N_BTREE_META );
3774   assert( iDb>=0 && iDb<db->nDb );
3775   assert( db->aDb[iDb].pBt!=0 );
3776   assert( DbMaskTest(p->btreeMask, iDb) );
3777 
3778   sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
3779   pOut = out2Prerelease(p, pOp);
3780   pOut->u.i = iMeta;
3781   break;
3782 }
3783 
3784 /* Opcode: SetCookie P1 P2 P3 * P5
3785 **
3786 ** Write the integer value P3 into cookie number P2 of database P1.
3787 ** P2==1 is the schema version.  P2==2 is the database format.
3788 ** P2==3 is the recommended pager cache
3789 ** size, and so forth.  P1==0 is the main database file and P1==1 is the
3790 ** database file used to store temporary tables.
3791 **
3792 ** A transaction must be started before executing this opcode.
3793 **
3794 ** If P2 is the SCHEMA_VERSION cookie (cookie number 1) then the internal
3795 ** schema version is set to P3-P5.  The "PRAGMA schema_version=N" statement
3796 ** has P5 set to 1, so that the internal schema version will be different
3797 ** from the database schema version, resulting in a schema reset.
3798 */
3799 case OP_SetCookie: {
3800   Db *pDb;
3801 
3802   sqlite3VdbeIncrWriteCounter(p, 0);
3803   assert( pOp->p2<SQLITE_N_BTREE_META );
3804   assert( pOp->p1>=0 && pOp->p1<db->nDb );
3805   assert( DbMaskTest(p->btreeMask, pOp->p1) );
3806   assert( p->readOnly==0 );
3807   pDb = &db->aDb[pOp->p1];
3808   assert( pDb->pBt!=0 );
3809   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
3810   /* See note about index shifting on OP_ReadCookie */
3811   rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
3812   if( pOp->p2==BTREE_SCHEMA_VERSION ){
3813     /* When the schema cookie changes, record the new cookie internally */
3814     pDb->pSchema->schema_cookie = pOp->p3 - pOp->p5;
3815     db->mDbFlags |= DBFLAG_SchemaChange;
3816   }else if( pOp->p2==BTREE_FILE_FORMAT ){
3817     /* Record changes in the file format */
3818     pDb->pSchema->file_format = pOp->p3;
3819   }
3820   if( pOp->p1==1 ){
3821     /* Invalidate all prepared statements whenever the TEMP database
3822     ** schema is changed.  Ticket #1644 */
3823     sqlite3ExpirePreparedStatements(db, 0);
3824     p->expired = 0;
3825   }
3826   if( rc ) goto abort_due_to_error;
3827   break;
3828 }
3829 
3830 /* Opcode: OpenRead P1 P2 P3 P4 P5
3831 ** Synopsis: root=P2 iDb=P3
3832 **
3833 ** Open a read-only cursor for the database table whose root page is
3834 ** P2 in a database file.  The database file is determined by P3.
3835 ** P3==0 means the main database, P3==1 means the database used for
3836 ** temporary tables, and P3>1 means used the corresponding attached
3837 ** database.  Give the new cursor an identifier of P1.  The P1
3838 ** values need not be contiguous but all P1 values should be small integers.
3839 ** It is an error for P1 to be negative.
3840 **
3841 ** Allowed P5 bits:
3842 ** <ul>
3843 ** <li>  <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
3844 **       equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
3845 **       of OP_SeekLE/OP_IdxLT)
3846 ** </ul>
3847 **
3848 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3849 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3850 ** object, then table being opened must be an [index b-tree] where the
3851 ** KeyInfo object defines the content and collating
3852 ** sequence of that index b-tree. Otherwise, if P4 is an integer
3853 ** value, then the table being opened must be a [table b-tree] with a
3854 ** number of columns no less than the value of P4.
3855 **
3856 ** See also: OpenWrite, ReopenIdx
3857 */
3858 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
3859 ** Synopsis: root=P2 iDb=P3
3860 **
3861 ** The ReopenIdx opcode works like OP_OpenRead except that it first
3862 ** checks to see if the cursor on P1 is already open on the same
3863 ** b-tree and if it is this opcode becomes a no-op.  In other words,
3864 ** if the cursor is already open, do not reopen it.
3865 **
3866 ** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ
3867 ** and with P4 being a P4_KEYINFO object.  Furthermore, the P3 value must
3868 ** be the same as every other ReopenIdx or OpenRead for the same cursor
3869 ** number.
3870 **
3871 ** Allowed P5 bits:
3872 ** <ul>
3873 ** <li>  <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
3874 **       equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
3875 **       of OP_SeekLE/OP_IdxLT)
3876 ** </ul>
3877 **
3878 ** See also: OP_OpenRead, OP_OpenWrite
3879 */
3880 /* Opcode: OpenWrite P1 P2 P3 P4 P5
3881 ** Synopsis: root=P2 iDb=P3
3882 **
3883 ** Open a read/write cursor named P1 on the table or index whose root
3884 ** page is P2 (or whose root page is held in register P2 if the
3885 ** OPFLAG_P2ISREG bit is set in P5 - see below).
3886 **
3887 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3888 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3889 ** object, then table being opened must be an [index b-tree] where the
3890 ** KeyInfo object defines the content and collating
3891 ** sequence of that index b-tree. Otherwise, if P4 is an integer
3892 ** value, then the table being opened must be a [table b-tree] with a
3893 ** number of columns no less than the value of P4.
3894 **
3895 ** Allowed P5 bits:
3896 ** <ul>
3897 ** <li>  <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
3898 **       equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
3899 **       of OP_SeekLE/OP_IdxLT)
3900 ** <li>  <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek
3901 **       and subsequently delete entries in an index btree.  This is a
3902 **       hint to the storage engine that the storage engine is allowed to
3903 **       ignore.  The hint is not used by the official SQLite b*tree storage
3904 **       engine, but is used by COMDB2.
3905 ** <li>  <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2
3906 **       as the root page, not the value of P2 itself.
3907 ** </ul>
3908 **
3909 ** This instruction works like OpenRead except that it opens the cursor
3910 ** in read/write mode.
3911 **
3912 ** See also: OP_OpenRead, OP_ReopenIdx
3913 */
3914 case OP_ReopenIdx: {
3915   int nField;
3916   KeyInfo *pKeyInfo;
3917   u32 p2;
3918   int iDb;
3919   int wrFlag;
3920   Btree *pX;
3921   VdbeCursor *pCur;
3922   Db *pDb;
3923 
3924   assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
3925   assert( pOp->p4type==P4_KEYINFO );
3926   pCur = p->apCsr[pOp->p1];
3927   if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
3928     assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
3929     assert( pCur->eCurType==CURTYPE_BTREE );
3930     sqlite3BtreeClearCursor(pCur->uc.pCursor);
3931     goto open_cursor_set_hints;
3932   }
3933   /* If the cursor is not currently open or is open on a different
3934   ** index, then fall through into OP_OpenRead to force a reopen */
3935 case OP_OpenRead:
3936 case OP_OpenWrite:
3937 
3938   assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
3939   assert( p->bIsReader );
3940   assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
3941           || p->readOnly==0 );
3942 
3943   if( p->expired==1 ){
3944     rc = SQLITE_ABORT_ROLLBACK;
3945     goto abort_due_to_error;
3946   }
3947 
3948   nField = 0;
3949   pKeyInfo = 0;
3950   p2 = (u32)pOp->p2;
3951   iDb = pOp->p3;
3952   assert( iDb>=0 && iDb<db->nDb );
3953   assert( DbMaskTest(p->btreeMask, iDb) );
3954   pDb = &db->aDb[iDb];
3955   pX = pDb->pBt;
3956   assert( pX!=0 );
3957   if( pOp->opcode==OP_OpenWrite ){
3958     assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
3959     wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
3960     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3961     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
3962       p->minWriteFileFormat = pDb->pSchema->file_format;
3963     }
3964   }else{
3965     wrFlag = 0;
3966   }
3967   if( pOp->p5 & OPFLAG_P2ISREG ){
3968     assert( p2>0 );
3969     assert( p2<=(u32)(p->nMem+1 - p->nCursor) );
3970     assert( pOp->opcode==OP_OpenWrite );
3971     pIn2 = &aMem[p2];
3972     assert( memIsValid(pIn2) );
3973     assert( (pIn2->flags & MEM_Int)!=0 );
3974     sqlite3VdbeMemIntegerify(pIn2);
3975     p2 = (int)pIn2->u.i;
3976     /* The p2 value always comes from a prior OP_CreateBtree opcode and
3977     ** that opcode will always set the p2 value to 2 or more or else fail.
3978     ** If there were a failure, the prepared statement would have halted
3979     ** before reaching this instruction. */
3980     assert( p2>=2 );
3981   }
3982   if( pOp->p4type==P4_KEYINFO ){
3983     pKeyInfo = pOp->p4.pKeyInfo;
3984     assert( pKeyInfo->enc==ENC(db) );
3985     assert( pKeyInfo->db==db );
3986     nField = pKeyInfo->nAllField;
3987   }else if( pOp->p4type==P4_INT32 ){
3988     nField = pOp->p4.i;
3989   }
3990   assert( pOp->p1>=0 );
3991   assert( nField>=0 );
3992   testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
3993   pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
3994   if( pCur==0 ) goto no_mem;
3995   pCur->nullRow = 1;
3996   pCur->isOrdered = 1;
3997   pCur->pgnoRoot = p2;
3998 #ifdef SQLITE_DEBUG
3999   pCur->wrFlag = wrFlag;
4000 #endif
4001   rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
4002   pCur->pKeyInfo = pKeyInfo;
4003   /* Set the VdbeCursor.isTable variable. Previous versions of
4004   ** SQLite used to check if the root-page flags were sane at this point
4005   ** and report database corruption if they were not, but this check has
4006   ** since moved into the btree layer.  */
4007   pCur->isTable = pOp->p4type!=P4_KEYINFO;
4008 
4009 open_cursor_set_hints:
4010   assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
4011   assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
4012   testcase( pOp->p5 & OPFLAG_BULKCSR );
4013   testcase( pOp->p2 & OPFLAG_SEEKEQ );
4014   sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
4015                                (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
4016   if( rc ) goto abort_due_to_error;
4017   break;
4018 }
4019 
4020 /* Opcode: OpenDup P1 P2 * * *
4021 **
4022 ** Open a new cursor P1 that points to the same ephemeral table as
4023 ** cursor P2.  The P2 cursor must have been opened by a prior OP_OpenEphemeral
4024 ** opcode.  Only ephemeral cursors may be duplicated.
4025 **
4026 ** Duplicate ephemeral cursors are used for self-joins of materialized views.
4027 */
4028 case OP_OpenDup: {
4029   VdbeCursor *pOrig;    /* The original cursor to be duplicated */
4030   VdbeCursor *pCx;      /* The new cursor */
4031 
4032   pOrig = p->apCsr[pOp->p2];
4033   assert( pOrig );
4034   assert( pOrig->isEphemeral );  /* Only ephemeral cursors can be duplicated */
4035 
4036   pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
4037   if( pCx==0 ) goto no_mem;
4038   pCx->nullRow = 1;
4039   pCx->isEphemeral = 1;
4040   pCx->pKeyInfo = pOrig->pKeyInfo;
4041   pCx->isTable = pOrig->isTable;
4042   pCx->pgnoRoot = pOrig->pgnoRoot;
4043   pCx->isOrdered = pOrig->isOrdered;
4044   pCx->pBtx = pOrig->pBtx;
4045   pCx->hasBeenDuped = 1;
4046   pOrig->hasBeenDuped = 1;
4047   rc = sqlite3BtreeCursor(pCx->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
4048                           pCx->pKeyInfo, pCx->uc.pCursor);
4049   /* The sqlite3BtreeCursor() routine can only fail for the first cursor
4050   ** opened for a database.  Since there is already an open cursor when this
4051   ** opcode is run, the sqlite3BtreeCursor() cannot fail */
4052   assert( rc==SQLITE_OK );
4053   break;
4054 }
4055 
4056 
4057 /* Opcode: OpenEphemeral P1 P2 P3 P4 P5
4058 ** Synopsis: nColumn=P2
4059 **
4060 ** Open a new cursor P1 to a transient table.
4061 ** The cursor is always opened read/write even if
4062 ** the main database is read-only.  The ephemeral
4063 ** table is deleted automatically when the cursor is closed.
4064 **
4065 ** If the cursor P1 is already opened on an ephemeral table, the table
4066 ** is cleared (all content is erased).
4067 **
4068 ** P2 is the number of columns in the ephemeral table.
4069 ** The cursor points to a BTree table if P4==0 and to a BTree index
4070 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
4071 ** that defines the format of keys in the index.
4072 **
4073 ** The P5 parameter can be a mask of the BTREE_* flags defined
4074 ** in btree.h.  These flags control aspects of the operation of
4075 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
4076 ** added automatically.
4077 **
4078 ** If P3 is positive, then reg[P3] is modified slightly so that it
4079 ** can be used as zero-length data for OP_Insert.  This is an optimization
4080 ** that avoids an extra OP_Blob opcode to initialize that register.
4081 */
4082 /* Opcode: OpenAutoindex P1 P2 * P4 *
4083 ** Synopsis: nColumn=P2
4084 **
4085 ** This opcode works the same as OP_OpenEphemeral.  It has a
4086 ** different name to distinguish its use.  Tables created using
4087 ** by this opcode will be used for automatically created transient
4088 ** indices in joins.
4089 */
4090 case OP_OpenAutoindex:
4091 case OP_OpenEphemeral: {
4092   VdbeCursor *pCx;
4093   KeyInfo *pKeyInfo;
4094 
4095   static const int vfsFlags =
4096       SQLITE_OPEN_READWRITE |
4097       SQLITE_OPEN_CREATE |
4098       SQLITE_OPEN_EXCLUSIVE |
4099       SQLITE_OPEN_DELETEONCLOSE |
4100       SQLITE_OPEN_TRANSIENT_DB;
4101   assert( pOp->p1>=0 );
4102   assert( pOp->p2>=0 );
4103   if( pOp->p3>0 ){
4104     /* Make register reg[P3] into a value that can be used as the data
4105     ** form sqlite3BtreeInsert() where the length of the data is zero. */
4106     assert( pOp->p2==0 ); /* Only used when number of columns is zero */
4107     assert( pOp->opcode==OP_OpenEphemeral );
4108     assert( aMem[pOp->p3].flags & MEM_Null );
4109     aMem[pOp->p3].n = 0;
4110     aMem[pOp->p3].z = "";
4111   }
4112   pCx = p->apCsr[pOp->p1];
4113   if( pCx && !pCx->hasBeenDuped &&  ALWAYS(pOp->p2<=pCx->nField) ){
4114     /* If the ephermeral table is already open and has no duplicates from
4115     ** OP_OpenDup, then erase all existing content so that the table is
4116     ** empty again, rather than creating a new table. */
4117     assert( pCx->isEphemeral );
4118     pCx->seqCount = 0;
4119     pCx->cacheStatus = CACHE_STALE;
4120     rc = sqlite3BtreeClearTable(pCx->pBtx, pCx->pgnoRoot, 0);
4121   }else{
4122     pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
4123     if( pCx==0 ) goto no_mem;
4124     pCx->isEphemeral = 1;
4125     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
4126                           BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5,
4127                           vfsFlags);
4128     if( rc==SQLITE_OK ){
4129       rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1, 0);
4130       if( rc==SQLITE_OK ){
4131         /* If a transient index is required, create it by calling
4132         ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
4133         ** opening it. If a transient table is required, just use the
4134         ** automatically created table with root-page 1 (an BLOB_INTKEY table).
4135         */
4136         if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
4137           assert( pOp->p4type==P4_KEYINFO );
4138           rc = sqlite3BtreeCreateTable(pCx->pBtx, &pCx->pgnoRoot,
4139               BTREE_BLOBKEY | pOp->p5);
4140           if( rc==SQLITE_OK ){
4141             assert( pCx->pgnoRoot==SCHEMA_ROOT+1 );
4142             assert( pKeyInfo->db==db );
4143             assert( pKeyInfo->enc==ENC(db) );
4144             rc = sqlite3BtreeCursor(pCx->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
4145                 pKeyInfo, pCx->uc.pCursor);
4146           }
4147           pCx->isTable = 0;
4148         }else{
4149           pCx->pgnoRoot = SCHEMA_ROOT;
4150           rc = sqlite3BtreeCursor(pCx->pBtx, SCHEMA_ROOT, BTREE_WRCSR,
4151               0, pCx->uc.pCursor);
4152           pCx->isTable = 1;
4153         }
4154       }
4155       pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
4156       if( rc ){
4157         sqlite3BtreeClose(pCx->pBtx);
4158       }
4159     }
4160   }
4161   if( rc ) goto abort_due_to_error;
4162   pCx->nullRow = 1;
4163   break;
4164 }
4165 
4166 /* Opcode: SorterOpen P1 P2 P3 P4 *
4167 **
4168 ** This opcode works like OP_OpenEphemeral except that it opens
4169 ** a transient index that is specifically designed to sort large
4170 ** tables using an external merge-sort algorithm.
4171 **
4172 ** If argument P3 is non-zero, then it indicates that the sorter may
4173 ** assume that a stable sort considering the first P3 fields of each
4174 ** key is sufficient to produce the required results.
4175 */
4176 case OP_SorterOpen: {
4177   VdbeCursor *pCx;
4178 
4179   assert( pOp->p1>=0 );
4180   assert( pOp->p2>=0 );
4181   pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
4182   if( pCx==0 ) goto no_mem;
4183   pCx->pKeyInfo = pOp->p4.pKeyInfo;
4184   assert( pCx->pKeyInfo->db==db );
4185   assert( pCx->pKeyInfo->enc==ENC(db) );
4186   rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
4187   if( rc ) goto abort_due_to_error;
4188   break;
4189 }
4190 
4191 /* Opcode: SequenceTest P1 P2 * * *
4192 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
4193 **
4194 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
4195 ** to P2. Regardless of whether or not the jump is taken, increment the
4196 ** the sequence value.
4197 */
4198 case OP_SequenceTest: {
4199   VdbeCursor *pC;
4200   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4201   pC = p->apCsr[pOp->p1];
4202   assert( isSorter(pC) );
4203   if( (pC->seqCount++)==0 ){
4204     goto jump_to_p2;
4205   }
4206   break;
4207 }
4208 
4209 /* Opcode: OpenPseudo P1 P2 P3 * *
4210 ** Synopsis: P3 columns in r[P2]
4211 **
4212 ** Open a new cursor that points to a fake table that contains a single
4213 ** row of data.  The content of that one row is the content of memory
4214 ** register P2.  In other words, cursor P1 becomes an alias for the
4215 ** MEM_Blob content contained in register P2.
4216 **
4217 ** A pseudo-table created by this opcode is used to hold a single
4218 ** row output from the sorter so that the row can be decomposed into
4219 ** individual columns using the OP_Column opcode.  The OP_Column opcode
4220 ** is the only cursor opcode that works with a pseudo-table.
4221 **
4222 ** P3 is the number of fields in the records that will be stored by
4223 ** the pseudo-table.
4224 */
4225 case OP_OpenPseudo: {
4226   VdbeCursor *pCx;
4227 
4228   assert( pOp->p1>=0 );
4229   assert( pOp->p3>=0 );
4230   pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
4231   if( pCx==0 ) goto no_mem;
4232   pCx->nullRow = 1;
4233   pCx->seekResult = pOp->p2;
4234   pCx->isTable = 1;
4235   /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
4236   ** can be safely passed to sqlite3VdbeCursorMoveto().  This avoids a test
4237   ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
4238   ** which is a performance optimization */
4239   pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
4240   assert( pOp->p5==0 );
4241   break;
4242 }
4243 
4244 /* Opcode: Close P1 * * * *
4245 **
4246 ** Close a cursor previously opened as P1.  If P1 is not
4247 ** currently open, this instruction is a no-op.
4248 */
4249 case OP_Close: {
4250   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4251   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
4252   p->apCsr[pOp->p1] = 0;
4253   break;
4254 }
4255 
4256 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
4257 /* Opcode: ColumnsUsed P1 * * P4 *
4258 **
4259 ** This opcode (which only exists if SQLite was compiled with
4260 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
4261 ** table or index for cursor P1 are used.  P4 is a 64-bit integer
4262 ** (P4_INT64) in which the first 63 bits are one for each of the
4263 ** first 63 columns of the table or index that are actually used
4264 ** by the cursor.  The high-order bit is set if any column after
4265 ** the 64th is used.
4266 */
4267 case OP_ColumnsUsed: {
4268   VdbeCursor *pC;
4269   pC = p->apCsr[pOp->p1];
4270   assert( pC->eCurType==CURTYPE_BTREE );
4271   pC->maskUsed = *(u64*)pOp->p4.pI64;
4272   break;
4273 }
4274 #endif
4275 
4276 /* Opcode: SeekGE P1 P2 P3 P4 *
4277 ** Synopsis: key=r[P3@P4]
4278 **
4279 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4280 ** use the value in register P3 as the key.  If cursor P1 refers
4281 ** to an SQL index, then P3 is the first in an array of P4 registers
4282 ** that are used as an unpacked index key.
4283 **
4284 ** Reposition cursor P1 so that  it points to the smallest entry that
4285 ** is greater than or equal to the key value. If there are no records
4286 ** greater than or equal to the key and P2 is not zero, then jump to P2.
4287 **
4288 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
4289 ** opcode will either land on a record that exactly matches the key, or
4290 ** else it will cause a jump to P2.  When the cursor is OPFLAG_SEEKEQ,
4291 ** this opcode must be followed by an IdxLE opcode with the same arguments.
4292 ** The IdxGT opcode will be skipped if this opcode succeeds, but the
4293 ** IdxGT opcode will be used on subsequent loop iterations.  The
4294 ** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
4295 ** is an equality search.
4296 **
4297 ** This opcode leaves the cursor configured to move in forward order,
4298 ** from the beginning toward the end.  In other words, the cursor is
4299 ** configured to use Next, not Prev.
4300 **
4301 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
4302 */
4303 /* Opcode: SeekGT P1 P2 P3 P4 *
4304 ** Synopsis: key=r[P3@P4]
4305 **
4306 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4307 ** use the value in register P3 as a key. If cursor P1 refers
4308 ** to an SQL index, then P3 is the first in an array of P4 registers
4309 ** that are used as an unpacked index key.
4310 **
4311 ** Reposition cursor P1 so that it points to the smallest entry that
4312 ** is greater than the key value. If there are no records greater than
4313 ** the key and P2 is not zero, then jump to P2.
4314 **
4315 ** This opcode leaves the cursor configured to move in forward order,
4316 ** from the beginning toward the end.  In other words, the cursor is
4317 ** configured to use Next, not Prev.
4318 **
4319 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
4320 */
4321 /* Opcode: SeekLT P1 P2 P3 P4 *
4322 ** Synopsis: key=r[P3@P4]
4323 **
4324 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4325 ** use the value in register P3 as a key. If cursor P1 refers
4326 ** to an SQL index, then P3 is the first in an array of P4 registers
4327 ** that are used as an unpacked index key.
4328 **
4329 ** Reposition cursor P1 so that  it points to the largest entry that
4330 ** is less than the key value. If there are no records less than
4331 ** the key and P2 is not zero, then jump to P2.
4332 **
4333 ** This opcode leaves the cursor configured to move in reverse order,
4334 ** from the end toward the beginning.  In other words, the cursor is
4335 ** configured to use Prev, not Next.
4336 **
4337 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
4338 */
4339 /* Opcode: SeekLE P1 P2 P3 P4 *
4340 ** Synopsis: key=r[P3@P4]
4341 **
4342 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4343 ** use the value in register P3 as a key. If cursor P1 refers
4344 ** to an SQL index, then P3 is the first in an array of P4 registers
4345 ** that are used as an unpacked index key.
4346 **
4347 ** Reposition cursor P1 so that it points to the largest entry that
4348 ** is less than or equal to the key value. If there are no records
4349 ** less than or equal to the key and P2 is not zero, then jump to P2.
4350 **
4351 ** This opcode leaves the cursor configured to move in reverse order,
4352 ** from the end toward the beginning.  In other words, the cursor is
4353 ** configured to use Prev, not Next.
4354 **
4355 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
4356 ** opcode will either land on a record that exactly matches the key, or
4357 ** else it will cause a jump to P2.  When the cursor is OPFLAG_SEEKEQ,
4358 ** this opcode must be followed by an IdxLE opcode with the same arguments.
4359 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
4360 ** IdxGE opcode will be used on subsequent loop iterations.  The
4361 ** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
4362 ** is an equality search.
4363 **
4364 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
4365 */
4366 case OP_SeekLT:         /* jump, in3, group */
4367 case OP_SeekLE:         /* jump, in3, group */
4368 case OP_SeekGE:         /* jump, in3, group */
4369 case OP_SeekGT: {       /* jump, in3, group */
4370   int res;           /* Comparison result */
4371   int oc;            /* Opcode */
4372   VdbeCursor *pC;    /* The cursor to seek */
4373   UnpackedRecord r;  /* The key to seek for */
4374   int nField;        /* Number of columns or fields in the key */
4375   i64 iKey;          /* The rowid we are to seek to */
4376   int eqOnly;        /* Only interested in == results */
4377 
4378   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4379   assert( pOp->p2!=0 );
4380   pC = p->apCsr[pOp->p1];
4381   assert( pC!=0 );
4382   assert( pC->eCurType==CURTYPE_BTREE );
4383   assert( OP_SeekLE == OP_SeekLT+1 );
4384   assert( OP_SeekGE == OP_SeekLT+2 );
4385   assert( OP_SeekGT == OP_SeekLT+3 );
4386   assert( pC->isOrdered );
4387   assert( pC->uc.pCursor!=0 );
4388   oc = pOp->opcode;
4389   eqOnly = 0;
4390   pC->nullRow = 0;
4391 #ifdef SQLITE_DEBUG
4392   pC->seekOp = pOp->opcode;
4393 #endif
4394 
4395   pC->deferredMoveto = 0;
4396   pC->cacheStatus = CACHE_STALE;
4397   if( pC->isTable ){
4398     u16 flags3, newType;
4399     /* The OPFLAG_SEEKEQ/BTREE_SEEK_EQ flag is only set on index cursors */
4400     assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
4401               || CORRUPT_DB );
4402 
4403     /* The input value in P3 might be of any type: integer, real, string,
4404     ** blob, or NULL.  But it needs to be an integer before we can do
4405     ** the seek, so convert it. */
4406     pIn3 = &aMem[pOp->p3];
4407     flags3 = pIn3->flags;
4408     if( (flags3 & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Str))==MEM_Str ){
4409       applyNumericAffinity(pIn3, 0);
4410     }
4411     iKey = sqlite3VdbeIntValue(pIn3); /* Get the integer key value */
4412     newType = pIn3->flags; /* Record the type after applying numeric affinity */
4413     pIn3->flags = flags3;  /* But convert the type back to its original */
4414 
4415     /* If the P3 value could not be converted into an integer without
4416     ** loss of information, then special processing is required... */
4417     if( (newType & (MEM_Int|MEM_IntReal))==0 ){
4418       int c;
4419       if( (newType & MEM_Real)==0 ){
4420         if( (newType & MEM_Null) || oc>=OP_SeekGE ){
4421           VdbeBranchTaken(1,2);
4422           goto jump_to_p2;
4423         }else{
4424           rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
4425           if( rc!=SQLITE_OK ) goto abort_due_to_error;
4426           goto seek_not_found;
4427         }
4428       }
4429       c = sqlite3IntFloatCompare(iKey, pIn3->u.r);
4430 
4431       /* If the approximation iKey is larger than the actual real search
4432       ** term, substitute >= for > and < for <=. e.g. if the search term
4433       ** is 4.9 and the integer approximation 5:
4434       **
4435       **        (x >  4.9)    ->     (x >= 5)
4436       **        (x <= 4.9)    ->     (x <  5)
4437       */
4438       if( c>0 ){
4439         assert( OP_SeekGE==(OP_SeekGT-1) );
4440         assert( OP_SeekLT==(OP_SeekLE-1) );
4441         assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
4442         if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
4443       }
4444 
4445       /* If the approximation iKey is smaller than the actual real search
4446       ** term, substitute <= for < and > for >=.  */
4447       else if( c<0 ){
4448         assert( OP_SeekLE==(OP_SeekLT+1) );
4449         assert( OP_SeekGT==(OP_SeekGE+1) );
4450         assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
4451         if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
4452       }
4453     }
4454     rc = sqlite3BtreeTableMoveto(pC->uc.pCursor, (u64)iKey, 0, &res);
4455     pC->movetoTarget = iKey;  /* Used by OP_Delete */
4456     if( rc!=SQLITE_OK ){
4457       goto abort_due_to_error;
4458     }
4459   }else{
4460     /* For a cursor with the OPFLAG_SEEKEQ/BTREE_SEEK_EQ hint, only the
4461     ** OP_SeekGE and OP_SeekLE opcodes are allowed, and these must be
4462     ** immediately followed by an OP_IdxGT or OP_IdxLT opcode, respectively,
4463     ** with the same key.
4464     */
4465     if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
4466       eqOnly = 1;
4467       assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
4468       assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
4469       assert( pOp->opcode==OP_SeekGE || pOp[1].opcode==OP_IdxLT );
4470       assert( pOp->opcode==OP_SeekLE || pOp[1].opcode==OP_IdxGT );
4471       assert( pOp[1].p1==pOp[0].p1 );
4472       assert( pOp[1].p2==pOp[0].p2 );
4473       assert( pOp[1].p3==pOp[0].p3 );
4474       assert( pOp[1].p4.i==pOp[0].p4.i );
4475     }
4476 
4477     nField = pOp->p4.i;
4478     assert( pOp->p4type==P4_INT32 );
4479     assert( nField>0 );
4480     r.pKeyInfo = pC->pKeyInfo;
4481     r.nField = (u16)nField;
4482 
4483     /* The next line of code computes as follows, only faster:
4484     **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
4485     **     r.default_rc = -1;
4486     **   }else{
4487     **     r.default_rc = +1;
4488     **   }
4489     */
4490     r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
4491     assert( oc!=OP_SeekGT || r.default_rc==-1 );
4492     assert( oc!=OP_SeekLE || r.default_rc==-1 );
4493     assert( oc!=OP_SeekGE || r.default_rc==+1 );
4494     assert( oc!=OP_SeekLT || r.default_rc==+1 );
4495 
4496     r.aMem = &aMem[pOp->p3];
4497 #ifdef SQLITE_DEBUG
4498     { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
4499 #endif
4500     r.eqSeen = 0;
4501     rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, &r, &res);
4502     if( rc!=SQLITE_OK ){
4503       goto abort_due_to_error;
4504     }
4505     if( eqOnly && r.eqSeen==0 ){
4506       assert( res!=0 );
4507       goto seek_not_found;
4508     }
4509   }
4510 #ifdef SQLITE_TEST
4511   sqlite3_search_count++;
4512 #endif
4513   if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
4514     if( res<0 || (res==0 && oc==OP_SeekGT) ){
4515       res = 0;
4516       rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
4517       if( rc!=SQLITE_OK ){
4518         if( rc==SQLITE_DONE ){
4519           rc = SQLITE_OK;
4520           res = 1;
4521         }else{
4522           goto abort_due_to_error;
4523         }
4524       }
4525     }else{
4526       res = 0;
4527     }
4528   }else{
4529     assert( oc==OP_SeekLT || oc==OP_SeekLE );
4530     if( res>0 || (res==0 && oc==OP_SeekLT) ){
4531       res = 0;
4532       rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
4533       if( rc!=SQLITE_OK ){
4534         if( rc==SQLITE_DONE ){
4535           rc = SQLITE_OK;
4536           res = 1;
4537         }else{
4538           goto abort_due_to_error;
4539         }
4540       }
4541     }else{
4542       /* res might be negative because the table is empty.  Check to
4543       ** see if this is the case.
4544       */
4545       res = sqlite3BtreeEof(pC->uc.pCursor);
4546     }
4547   }
4548 seek_not_found:
4549   assert( pOp->p2>0 );
4550   VdbeBranchTaken(res!=0,2);
4551   if( res ){
4552     goto jump_to_p2;
4553   }else if( eqOnly ){
4554     assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
4555     pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
4556   }
4557   break;
4558 }
4559 
4560 
4561 /* Opcode: SeekScan  P1 P2 * * *
4562 ** Synopsis: Scan-ahead up to P1 rows
4563 **
4564 ** This opcode is a prefix opcode to OP_SeekGE.  In other words, this
4565 ** opcode must be immediately followed by OP_SeekGE. This constraint is
4566 ** checked by assert() statements.
4567 **
4568 ** This opcode uses the P1 through P4 operands of the subsequent
4569 ** OP_SeekGE.  In the text that follows, the operands of the subsequent
4570 ** OP_SeekGE opcode are denoted as SeekOP.P1 through SeekOP.P4.   Only
4571 ** the P1 and P2 operands of this opcode are also used, and  are called
4572 ** This.P1 and This.P2.
4573 **
4574 ** This opcode helps to optimize IN operators on a multi-column index
4575 ** where the IN operator is on the later terms of the index by avoiding
4576 ** unnecessary seeks on the btree, substituting steps to the next row
4577 ** of the b-tree instead.  A correct answer is obtained if this opcode
4578 ** is omitted or is a no-op.
4579 **
4580 ** The SeekGE.P3 and SeekGE.P4 operands identify an unpacked key which
4581 ** is the desired entry that we want the cursor SeekGE.P1 to be pointing
4582 ** to.  Call this SeekGE.P4/P5 row the "target".
4583 **
4584 ** If the SeekGE.P1 cursor is not currently pointing to a valid row,
4585 ** then this opcode is a no-op and control passes through into the OP_SeekGE.
4586 **
4587 ** If the SeekGE.P1 cursor is pointing to a valid row, then that row
4588 ** might be the target row, or it might be near and slightly before the
4589 ** target row.  This opcode attempts to position the cursor on the target
4590 ** row by, perhaps by invoking sqlite3BtreeStep() on the cursor
4591 ** between 0 and This.P1 times.
4592 **
4593 ** There are three possible outcomes from this opcode:<ol>
4594 **
4595 ** <li> If after This.P1 steps, the cursor is still pointing to a place that
4596 **      is earlier in the btree than the target row, then fall through
4597 **      into the subsquence OP_SeekGE opcode.
4598 **
4599 ** <li> If the cursor is successfully moved to the target row by 0 or more
4600 **      sqlite3BtreeNext() calls, then jump to This.P2, which will land just
4601 **      past the OP_IdxGT or OP_IdxGE opcode that follows the OP_SeekGE.
4602 **
4603 ** <li> If the cursor ends up past the target row (indicating the the target
4604 **      row does not exist in the btree) then jump to SeekOP.P2.
4605 ** </ol>
4606 */
4607 case OP_SeekScan: {
4608   VdbeCursor *pC;
4609   int res;
4610   int nStep;
4611   UnpackedRecord r;
4612 
4613   assert( pOp[1].opcode==OP_SeekGE );
4614 
4615   /* pOp->p2 points to the first instruction past the OP_IdxGT that
4616   ** follows the OP_SeekGE.  */
4617   assert( pOp->p2>=(int)(pOp-aOp)+2 );
4618   assert( aOp[pOp->p2-1].opcode==OP_IdxGT || aOp[pOp->p2-1].opcode==OP_IdxGE );
4619   testcase( aOp[pOp->p2-1].opcode==OP_IdxGE );
4620   assert( pOp[1].p1==aOp[pOp->p2-1].p1 );
4621   assert( pOp[1].p2==aOp[pOp->p2-1].p2 );
4622   assert( pOp[1].p3==aOp[pOp->p2-1].p3 );
4623 
4624   assert( pOp->p1>0 );
4625   pC = p->apCsr[pOp[1].p1];
4626   assert( pC!=0 );
4627   assert( pC->eCurType==CURTYPE_BTREE );
4628   assert( !pC->isTable );
4629   if( !sqlite3BtreeCursorIsValidNN(pC->uc.pCursor) ){
4630 #ifdef SQLITE_DEBUG
4631      if( db->flags&SQLITE_VdbeTrace ){
4632        printf("... cursor not valid - fall through\n");
4633      }
4634 #endif
4635     break;
4636   }
4637   nStep = pOp->p1;
4638   assert( nStep>=1 );
4639   r.pKeyInfo = pC->pKeyInfo;
4640   r.nField = (u16)pOp[1].p4.i;
4641   r.default_rc = 0;
4642   r.aMem = &aMem[pOp[1].p3];
4643 #ifdef SQLITE_DEBUG
4644   {
4645     int i;
4646     for(i=0; i<r.nField; i++){
4647       assert( memIsValid(&r.aMem[i]) );
4648       REGISTER_TRACE(pOp[1].p3+i, &aMem[pOp[1].p3+i]);
4649     }
4650   }
4651 #endif
4652   res = 0;  /* Not needed.  Only used to silence a warning. */
4653   while(1){
4654     rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
4655     if( rc ) goto abort_due_to_error;
4656     if( res>0 ){
4657       seekscan_search_fail:
4658 #ifdef SQLITE_DEBUG
4659       if( db->flags&SQLITE_VdbeTrace ){
4660         printf("... %d steps and then skip\n", pOp->p1 - nStep);
4661       }
4662 #endif
4663       VdbeBranchTaken(1,3);
4664       pOp++;
4665       goto jump_to_p2;
4666     }
4667     if( res==0 ){
4668 #ifdef SQLITE_DEBUG
4669       if( db->flags&SQLITE_VdbeTrace ){
4670         printf("... %d steps and then success\n", pOp->p1 - nStep);
4671       }
4672 #endif
4673       VdbeBranchTaken(2,3);
4674       goto jump_to_p2;
4675       break;
4676     }
4677     if( nStep<=0 ){
4678 #ifdef SQLITE_DEBUG
4679       if( db->flags&SQLITE_VdbeTrace ){
4680         printf("... fall through after %d steps\n", pOp->p1);
4681       }
4682 #endif
4683       VdbeBranchTaken(0,3);
4684       break;
4685     }
4686     nStep--;
4687     rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
4688     if( rc ){
4689       if( rc==SQLITE_DONE ){
4690         rc = SQLITE_OK;
4691         goto seekscan_search_fail;
4692       }else{
4693         goto abort_due_to_error;
4694       }
4695     }
4696   }
4697 
4698   break;
4699 }
4700 
4701 
4702 /* Opcode: SeekHit P1 P2 P3 * *
4703 ** Synopsis: set P2<=seekHit<=P3
4704 **
4705 ** Increase or decrease the seekHit value for cursor P1, if necessary,
4706 ** so that it is no less than P2 and no greater than P3.
4707 **
4708 ** The seekHit integer represents the maximum of terms in an index for which
4709 ** there is known to be at least one match.  If the seekHit value is smaller
4710 ** than the total number of equality terms in an index lookup, then the
4711 ** OP_IfNoHope opcode might run to see if the IN loop can be abandoned
4712 ** early, thus saving work.  This is part of the IN-early-out optimization.
4713 **
4714 ** P1 must be a valid b-tree cursor.
4715 */
4716 case OP_SeekHit: {
4717   VdbeCursor *pC;
4718   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4719   pC = p->apCsr[pOp->p1];
4720   assert( pC!=0 );
4721   assert( pOp->p3>=pOp->p2 );
4722   if( pC->seekHit<pOp->p2 ){
4723 #ifdef SQLITE_DEBUG
4724     if( db->flags&SQLITE_VdbeTrace ){
4725       printf("seekHit changes from %d to %d\n", pC->seekHit, pOp->p2);
4726     }
4727 #endif
4728     pC->seekHit = pOp->p2;
4729   }else if( pC->seekHit>pOp->p3 ){
4730 #ifdef SQLITE_DEBUG
4731     if( db->flags&SQLITE_VdbeTrace ){
4732       printf("seekHit changes from %d to %d\n", pC->seekHit, pOp->p3);
4733     }
4734 #endif
4735     pC->seekHit = pOp->p3;
4736   }
4737   break;
4738 }
4739 
4740 /* Opcode: IfNotOpen P1 P2 * * *
4741 ** Synopsis: if( !csr[P1] ) goto P2
4742 **
4743 ** If cursor P1 is not open, jump to instruction P2. Otherwise, fall through.
4744 */
4745 case OP_IfNotOpen: {        /* jump */
4746   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4747   VdbeBranchTaken(p->apCsr[pOp->p1]==0, 2);
4748   if( !p->apCsr[pOp->p1] ){
4749     goto jump_to_p2_and_check_for_interrupt;
4750   }
4751   break;
4752 }
4753 
4754 /* Opcode: Found 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 a prefix of any entry in P1 then a jump is made to P2 and
4763 ** P1 is left pointing at the matching entry.
4764 **
4765 ** This operation leaves the cursor in a state where it can be
4766 ** advanced in the forward direction.  The Next instruction will work,
4767 ** but not the Prev instruction.
4768 **
4769 ** See also: NotFound, NoConflict, NotExists. SeekGe
4770 */
4771 /* Opcode: NotFound P1 P2 P3 P4 *
4772 ** Synopsis: key=r[P3@P4]
4773 **
4774 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
4775 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4776 ** record.
4777 **
4778 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
4779 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
4780 ** does contain an entry whose prefix matches the P3/P4 record then control
4781 ** falls through to the next instruction and P1 is left pointing at the
4782 ** matching entry.
4783 **
4784 ** This operation leaves the cursor in a state where it cannot be
4785 ** advanced in either direction.  In other words, the Next and Prev
4786 ** opcodes do not work after this operation.
4787 **
4788 ** See also: Found, NotExists, NoConflict, IfNoHope
4789 */
4790 /* Opcode: IfNoHope P1 P2 P3 P4 *
4791 ** Synopsis: key=r[P3@P4]
4792 **
4793 ** Register P3 is the first of P4 registers that form an unpacked
4794 ** record.  Cursor P1 is an index btree.  P2 is a jump destination.
4795 ** In other words, the operands to this opcode are the same as the
4796 ** operands to OP_NotFound and OP_IdxGT.
4797 **
4798 ** This opcode is an optimization attempt only.  If this opcode always
4799 ** falls through, the correct answer is still obtained, but extra works
4800 ** is performed.
4801 **
4802 ** A value of N in the seekHit flag of cursor P1 means that there exists
4803 ** a key P3:N that will match some record in the index.  We want to know
4804 ** if it is possible for a record P3:P4 to match some record in the
4805 ** index.  If it is not possible, we can skips some work.  So if seekHit
4806 ** is less than P4, attempt to find out if a match is possible by running
4807 ** OP_NotFound.
4808 **
4809 ** This opcode is used in IN clause processing for a multi-column key.
4810 ** If an IN clause is attached to an element of the key other than the
4811 ** left-most element, and if there are no matches on the most recent
4812 ** seek over the whole key, then it might be that one of the key element
4813 ** to the left is prohibiting a match, and hence there is "no hope" of
4814 ** any match regardless of how many IN clause elements are checked.
4815 ** In such a case, we abandon the IN clause search early, using this
4816 ** opcode.  The opcode name comes from the fact that the
4817 ** jump is taken if there is "no hope" of achieving a match.
4818 **
4819 ** See also: NotFound, SeekHit
4820 */
4821 /* Opcode: NoConflict P1 P2 P3 P4 *
4822 ** Synopsis: key=r[P3@P4]
4823 **
4824 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
4825 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4826 ** record.
4827 **
4828 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
4829 ** contains any NULL value, jump immediately to P2.  If all terms of the
4830 ** record are not-NULL then a check is done to determine if any row in the
4831 ** P1 index btree has a matching key prefix.  If there are no matches, jump
4832 ** immediately to P2.  If there is a match, fall through and leave the P1
4833 ** cursor pointing to the matching row.
4834 **
4835 ** This opcode is similar to OP_NotFound with the exceptions that the
4836 ** branch is always taken if any part of the search key input is NULL.
4837 **
4838 ** This operation leaves the cursor in a state where it cannot be
4839 ** advanced in either direction.  In other words, the Next and Prev
4840 ** opcodes do not work after this operation.
4841 **
4842 ** See also: NotFound, Found, NotExists
4843 */
4844 case OP_IfNoHope: {     /* jump, in3 */
4845   VdbeCursor *pC;
4846   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4847   pC = p->apCsr[pOp->p1];
4848   assert( pC!=0 );
4849 #ifdef SQLITE_DEBUG
4850   if( db->flags&SQLITE_VdbeTrace ){
4851     printf("seekHit is %d\n", pC->seekHit);
4852   }
4853 #endif
4854   if( pC->seekHit>=pOp->p4.i ) break;
4855   /* Fall through into OP_NotFound */
4856   /* no break */ deliberate_fall_through
4857 }
4858 case OP_NoConflict:     /* jump, in3 */
4859 case OP_NotFound:       /* jump, in3 */
4860 case OP_Found: {        /* jump, in3 */
4861   int alreadyExists;
4862   int takeJump;
4863   int ii;
4864   VdbeCursor *pC;
4865   int res;
4866   UnpackedRecord *pFree;
4867   UnpackedRecord *pIdxKey;
4868   UnpackedRecord r;
4869 
4870 #ifdef SQLITE_TEST
4871   if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
4872 #endif
4873 
4874   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4875   assert( pOp->p4type==P4_INT32 );
4876   pC = p->apCsr[pOp->p1];
4877   assert( pC!=0 );
4878 #ifdef SQLITE_DEBUG
4879   pC->seekOp = pOp->opcode;
4880 #endif
4881   pIn3 = &aMem[pOp->p3];
4882   assert( pC->eCurType==CURTYPE_BTREE );
4883   assert( pC->uc.pCursor!=0 );
4884   assert( pC->isTable==0 );
4885   if( pOp->p4.i>0 ){
4886     r.pKeyInfo = pC->pKeyInfo;
4887     r.nField = (u16)pOp->p4.i;
4888     r.aMem = pIn3;
4889 #ifdef SQLITE_DEBUG
4890     for(ii=0; ii<r.nField; ii++){
4891       assert( memIsValid(&r.aMem[ii]) );
4892       assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
4893       if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
4894     }
4895 #endif
4896     pIdxKey = &r;
4897     pFree = 0;
4898   }else{
4899     assert( pIn3->flags & MEM_Blob );
4900     rc = ExpandBlob(pIn3);
4901     assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
4902     if( rc ) goto no_mem;
4903     pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
4904     if( pIdxKey==0 ) goto no_mem;
4905     sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
4906   }
4907   pIdxKey->default_rc = 0;
4908   takeJump = 0;
4909   if( pOp->opcode==OP_NoConflict ){
4910     /* For the OP_NoConflict opcode, take the jump if any of the
4911     ** input fields are NULL, since any key with a NULL will not
4912     ** conflict */
4913     for(ii=0; ii<pIdxKey->nField; ii++){
4914       if( pIdxKey->aMem[ii].flags & MEM_Null ){
4915         takeJump = 1;
4916         break;
4917       }
4918     }
4919   }
4920   rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, pIdxKey, &res);
4921   if( pFree ) sqlite3DbFreeNN(db, pFree);
4922   if( rc!=SQLITE_OK ){
4923     goto abort_due_to_error;
4924   }
4925   pC->seekResult = res;
4926   alreadyExists = (res==0);
4927   pC->nullRow = 1-alreadyExists;
4928   pC->deferredMoveto = 0;
4929   pC->cacheStatus = CACHE_STALE;
4930   if( pOp->opcode==OP_Found ){
4931     VdbeBranchTaken(alreadyExists!=0,2);
4932     if( alreadyExists ) goto jump_to_p2;
4933   }else{
4934     VdbeBranchTaken(takeJump||alreadyExists==0,2);
4935     if( takeJump || !alreadyExists ) goto jump_to_p2;
4936     if( pOp->opcode==OP_IfNoHope ) pC->seekHit = pOp->p4.i;
4937   }
4938   break;
4939 }
4940 
4941 /* Opcode: SeekRowid P1 P2 P3 * *
4942 ** Synopsis: intkey=r[P3]
4943 **
4944 ** P1 is the index of a cursor open on an SQL table btree (with integer
4945 ** keys).  If register P3 does not contain an integer or if P1 does not
4946 ** contain a record with rowid P3 then jump immediately to P2.
4947 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
4948 ** a record with rowid P3 then
4949 ** leave the cursor pointing at that record and fall through to the next
4950 ** instruction.
4951 **
4952 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
4953 ** the P3 register must be guaranteed to contain an integer value.  With this
4954 ** opcode, register P3 might not contain an integer.
4955 **
4956 ** The OP_NotFound opcode performs the same operation on index btrees
4957 ** (with arbitrary multi-value keys).
4958 **
4959 ** This opcode leaves the cursor in a state where it cannot be advanced
4960 ** in either direction.  In other words, the Next and Prev opcodes will
4961 ** not work following this opcode.
4962 **
4963 ** See also: Found, NotFound, NoConflict, SeekRowid
4964 */
4965 /* Opcode: NotExists P1 P2 P3 * *
4966 ** Synopsis: intkey=r[P3]
4967 **
4968 ** P1 is the index of a cursor open on an SQL table btree (with integer
4969 ** keys).  P3 is an integer rowid.  If P1 does not contain a record with
4970 ** rowid P3 then jump immediately to P2.  Or, if P2 is 0, raise an
4971 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
4972 ** leave the cursor pointing at that record and fall through to the next
4973 ** instruction.
4974 **
4975 ** The OP_SeekRowid opcode performs the same operation but also allows the
4976 ** P3 register to contain a non-integer value, in which case the jump is
4977 ** always taken.  This opcode requires that P3 always contain an integer.
4978 **
4979 ** The OP_NotFound opcode performs the same operation on index btrees
4980 ** (with arbitrary multi-value keys).
4981 **
4982 ** This opcode leaves the cursor in a state where it cannot be advanced
4983 ** in either direction.  In other words, the Next and Prev opcodes will
4984 ** not work following this opcode.
4985 **
4986 ** See also: Found, NotFound, NoConflict, SeekRowid
4987 */
4988 case OP_SeekRowid: {        /* jump, in3 */
4989   VdbeCursor *pC;
4990   BtCursor *pCrsr;
4991   int res;
4992   u64 iKey;
4993 
4994   pIn3 = &aMem[pOp->p3];
4995   testcase( pIn3->flags & MEM_Int );
4996   testcase( pIn3->flags & MEM_IntReal );
4997   testcase( pIn3->flags & MEM_Real );
4998   testcase( (pIn3->flags & (MEM_Str|MEM_Int))==MEM_Str );
4999   if( (pIn3->flags & (MEM_Int|MEM_IntReal))==0 ){
5000     /* If pIn3->u.i does not contain an integer, compute iKey as the
5001     ** integer value of pIn3.  Jump to P2 if pIn3 cannot be converted
5002     ** into an integer without loss of information.  Take care to avoid
5003     ** changing the datatype of pIn3, however, as it is used by other
5004     ** parts of the prepared statement. */
5005     Mem x = pIn3[0];
5006     applyAffinity(&x, SQLITE_AFF_NUMERIC, encoding);
5007     if( (x.flags & MEM_Int)==0 ) goto jump_to_p2;
5008     iKey = x.u.i;
5009     goto notExistsWithKey;
5010   }
5011   /* Fall through into OP_NotExists */
5012   /* no break */ deliberate_fall_through
5013 case OP_NotExists:          /* jump, in3 */
5014   pIn3 = &aMem[pOp->p3];
5015   assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid );
5016   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5017   iKey = pIn3->u.i;
5018 notExistsWithKey:
5019   pC = p->apCsr[pOp->p1];
5020   assert( pC!=0 );
5021 #ifdef SQLITE_DEBUG
5022   if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid;
5023 #endif
5024   assert( pC->isTable );
5025   assert( pC->eCurType==CURTYPE_BTREE );
5026   pCrsr = pC->uc.pCursor;
5027   assert( pCrsr!=0 );
5028   res = 0;
5029   rc = sqlite3BtreeTableMoveto(pCrsr, iKey, 0, &res);
5030   assert( rc==SQLITE_OK || res==0 );
5031   pC->movetoTarget = iKey;  /* Used by OP_Delete */
5032   pC->nullRow = 0;
5033   pC->cacheStatus = CACHE_STALE;
5034   pC->deferredMoveto = 0;
5035   VdbeBranchTaken(res!=0,2);
5036   pC->seekResult = res;
5037   if( res!=0 ){
5038     assert( rc==SQLITE_OK );
5039     if( pOp->p2==0 ){
5040       rc = SQLITE_CORRUPT_BKPT;
5041     }else{
5042       goto jump_to_p2;
5043     }
5044   }
5045   if( rc ) goto abort_due_to_error;
5046   break;
5047 }
5048 
5049 /* Opcode: Sequence P1 P2 * * *
5050 ** Synopsis: r[P2]=cursor[P1].ctr++
5051 **
5052 ** Find the next available sequence number for cursor P1.
5053 ** Write the sequence number into register P2.
5054 ** The sequence number on the cursor is incremented after this
5055 ** instruction.
5056 */
5057 case OP_Sequence: {           /* out2 */
5058   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5059   assert( p->apCsr[pOp->p1]!=0 );
5060   assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
5061   pOut = out2Prerelease(p, pOp);
5062   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
5063   break;
5064 }
5065 
5066 
5067 /* Opcode: NewRowid P1 P2 P3 * *
5068 ** Synopsis: r[P2]=rowid
5069 **
5070 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
5071 ** The record number is not previously used as a key in the database
5072 ** table that cursor P1 points to.  The new record number is written
5073 ** written to register P2.
5074 **
5075 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
5076 ** the largest previously generated record number. No new record numbers are
5077 ** allowed to be less than this value. When this value reaches its maximum,
5078 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
5079 ** generated record number. This P3 mechanism is used to help implement the
5080 ** AUTOINCREMENT feature.
5081 */
5082 case OP_NewRowid: {           /* out2 */
5083   i64 v;                 /* The new rowid */
5084   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
5085   int res;               /* Result of an sqlite3BtreeLast() */
5086   int cnt;               /* Counter to limit the number of searches */
5087 #ifndef SQLITE_OMIT_AUTOINCREMENT
5088   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
5089   VdbeFrame *pFrame;     /* Root frame of VDBE */
5090 #endif
5091 
5092   v = 0;
5093   res = 0;
5094   pOut = out2Prerelease(p, pOp);
5095   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5096   pC = p->apCsr[pOp->p1];
5097   assert( pC!=0 );
5098   assert( pC->isTable );
5099   assert( pC->eCurType==CURTYPE_BTREE );
5100   assert( pC->uc.pCursor!=0 );
5101   {
5102     /* The next rowid or record number (different terms for the same
5103     ** thing) is obtained in a two-step algorithm.
5104     **
5105     ** First we attempt to find the largest existing rowid and add one
5106     ** to that.  But if the largest existing rowid is already the maximum
5107     ** positive integer, we have to fall through to the second
5108     ** probabilistic algorithm
5109     **
5110     ** The second algorithm is to select a rowid at random and see if
5111     ** it already exists in the table.  If it does not exist, we have
5112     ** succeeded.  If the random rowid does exist, we select a new one
5113     ** and try again, up to 100 times.
5114     */
5115     assert( pC->isTable );
5116 
5117 #ifdef SQLITE_32BIT_ROWID
5118 #   define MAX_ROWID 0x7fffffff
5119 #else
5120     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
5121     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
5122     ** to provide the constant while making all compilers happy.
5123     */
5124 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
5125 #endif
5126 
5127     if( !pC->useRandomRowid ){
5128       rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
5129       if( rc!=SQLITE_OK ){
5130         goto abort_due_to_error;
5131       }
5132       if( res ){
5133         v = 1;   /* IMP: R-61914-48074 */
5134       }else{
5135         assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
5136         v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5137         if( v>=MAX_ROWID ){
5138           pC->useRandomRowid = 1;
5139         }else{
5140           v++;   /* IMP: R-29538-34987 */
5141         }
5142       }
5143     }
5144 
5145 #ifndef SQLITE_OMIT_AUTOINCREMENT
5146     if( pOp->p3 ){
5147       /* Assert that P3 is a valid memory cell. */
5148       assert( pOp->p3>0 );
5149       if( p->pFrame ){
5150         for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
5151         /* Assert that P3 is a valid memory cell. */
5152         assert( pOp->p3<=pFrame->nMem );
5153         pMem = &pFrame->aMem[pOp->p3];
5154       }else{
5155         /* Assert that P3 is a valid memory cell. */
5156         assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
5157         pMem = &aMem[pOp->p3];
5158         memAboutToChange(p, pMem);
5159       }
5160       assert( memIsValid(pMem) );
5161 
5162       REGISTER_TRACE(pOp->p3, pMem);
5163       sqlite3VdbeMemIntegerify(pMem);
5164       assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
5165       if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
5166         rc = SQLITE_FULL;   /* IMP: R-17817-00630 */
5167         goto abort_due_to_error;
5168       }
5169       if( v<pMem->u.i+1 ){
5170         v = pMem->u.i + 1;
5171       }
5172       pMem->u.i = v;
5173     }
5174 #endif
5175     if( pC->useRandomRowid ){
5176       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
5177       ** largest possible integer (9223372036854775807) then the database
5178       ** engine starts picking positive candidate ROWIDs at random until
5179       ** it finds one that is not previously used. */
5180       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
5181                              ** an AUTOINCREMENT table. */
5182       cnt = 0;
5183       do{
5184         sqlite3_randomness(sizeof(v), &v);
5185         v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */
5186       }while(  ((rc = sqlite3BtreeTableMoveto(pC->uc.pCursor, (u64)v,
5187                                                  0, &res))==SQLITE_OK)
5188             && (res==0)
5189             && (++cnt<100));
5190       if( rc ) goto abort_due_to_error;
5191       if( res==0 ){
5192         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
5193         goto abort_due_to_error;
5194       }
5195       assert( v>0 );  /* EV: R-40812-03570 */
5196     }
5197     pC->deferredMoveto = 0;
5198     pC->cacheStatus = CACHE_STALE;
5199   }
5200   pOut->u.i = v;
5201   break;
5202 }
5203 
5204 /* Opcode: Insert P1 P2 P3 P4 P5
5205 ** Synopsis: intkey=r[P3] data=r[P2]
5206 **
5207 ** Write an entry into the table of cursor P1.  A new entry is
5208 ** created if it doesn't already exist or the data for an existing
5209 ** entry is overwritten.  The data is the value MEM_Blob stored in register
5210 ** number P2. The key is stored in register P3. The key must
5211 ** be a MEM_Int.
5212 **
5213 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
5214 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
5215 ** then rowid is stored for subsequent return by the
5216 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
5217 **
5218 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
5219 ** run faster by avoiding an unnecessary seek on cursor P1.  However,
5220 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
5221 ** seeks on the cursor or if the most recent seek used a key equal to P3.
5222 **
5223 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
5224 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
5225 ** is part of an INSERT operation.  The difference is only important to
5226 ** the update hook.
5227 **
5228 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
5229 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
5230 ** following a successful insert.
5231 **
5232 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
5233 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
5234 ** and register P2 becomes ephemeral.  If the cursor is changed, the
5235 ** value of register P2 will then change.  Make sure this does not
5236 ** cause any problems.)
5237 **
5238 ** This instruction only works on tables.  The equivalent instruction
5239 ** for indices is OP_IdxInsert.
5240 */
5241 case OP_Insert: {
5242   Mem *pData;       /* MEM cell holding data for the record to be inserted */
5243   Mem *pKey;        /* MEM cell holding key  for the record */
5244   VdbeCursor *pC;   /* Cursor to table into which insert is written */
5245   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
5246   const char *zDb;  /* database name - used by the update hook */
5247   Table *pTab;      /* Table structure - used by update and pre-update hooks */
5248   BtreePayload x;   /* Payload to be inserted */
5249 
5250   pData = &aMem[pOp->p2];
5251   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5252   assert( memIsValid(pData) );
5253   pC = p->apCsr[pOp->p1];
5254   assert( pC!=0 );
5255   assert( pC->eCurType==CURTYPE_BTREE );
5256   assert( pC->deferredMoveto==0 );
5257   assert( pC->uc.pCursor!=0 );
5258   assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
5259   assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
5260   REGISTER_TRACE(pOp->p2, pData);
5261   sqlite3VdbeIncrWriteCounter(p, pC);
5262 
5263   pKey = &aMem[pOp->p3];
5264   assert( pKey->flags & MEM_Int );
5265   assert( memIsValid(pKey) );
5266   REGISTER_TRACE(pOp->p3, pKey);
5267   x.nKey = pKey->u.i;
5268 
5269   if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
5270     assert( pC->iDb>=0 );
5271     zDb = db->aDb[pC->iDb].zDbSName;
5272     pTab = pOp->p4.pTab;
5273     assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
5274   }else{
5275     pTab = 0;
5276     zDb = 0;
5277   }
5278 
5279 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
5280   /* Invoke the pre-update hook, if any */
5281   if( pTab ){
5282     if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
5283       sqlite3VdbePreUpdateHook(p,pC,SQLITE_INSERT,zDb,pTab,x.nKey,pOp->p2,-1);
5284     }
5285     if( db->xUpdateCallback==0 || pTab->aCol==0 ){
5286       /* Prevent post-update hook from running in cases when it should not */
5287       pTab = 0;
5288     }
5289   }
5290   if( pOp->p5 & OPFLAG_ISNOOP ) break;
5291 #endif
5292 
5293   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
5294   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
5295   assert( (pData->flags & (MEM_Blob|MEM_Str))!=0 || pData->n==0 );
5296   x.pData = pData->z;
5297   x.nData = pData->n;
5298   seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
5299   if( pData->flags & MEM_Zero ){
5300     x.nZero = pData->u.nZero;
5301   }else{
5302     x.nZero = 0;
5303   }
5304   x.pKey = 0;
5305   rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
5306       (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
5307       seekResult
5308   );
5309   pC->deferredMoveto = 0;
5310   pC->cacheStatus = CACHE_STALE;
5311 
5312   /* Invoke the update-hook if required. */
5313   if( rc ) goto abort_due_to_error;
5314   if( pTab ){
5315     assert( db->xUpdateCallback!=0 );
5316     assert( pTab->aCol!=0 );
5317     db->xUpdateCallback(db->pUpdateArg,
5318            (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
5319            zDb, pTab->zName, x.nKey);
5320   }
5321   break;
5322 }
5323 
5324 /* Opcode: RowCell P1 P2 P3 * *
5325 **
5326 ** P1 and P2 are both open cursors. Both must be opened on the same type
5327 ** of table - intkey or index. This opcode is used as part of copying
5328 ** the current row from P2 into P1. If the cursors are opened on intkey
5329 ** tables, register P3 contains the rowid to use with the new record in
5330 ** P1. If they are opened on index tables, P3 is not used.
5331 **
5332 ** This opcode must be followed by either an Insert or InsertIdx opcode
5333 ** with the OPFLAG_PREFORMAT flag set to complete the insert operation.
5334 */
5335 case OP_RowCell: {
5336   VdbeCursor *pDest;              /* Cursor to write to */
5337   VdbeCursor *pSrc;               /* Cursor to read from */
5338   i64 iKey;                       /* Rowid value to insert with */
5339   assert( pOp[1].opcode==OP_Insert || pOp[1].opcode==OP_IdxInsert );
5340   assert( pOp[1].opcode==OP_Insert    || pOp->p3==0 );
5341   assert( pOp[1].opcode==OP_IdxInsert || pOp->p3>0 );
5342   assert( pOp[1].p5 & OPFLAG_PREFORMAT );
5343   pDest = p->apCsr[pOp->p1];
5344   pSrc = p->apCsr[pOp->p2];
5345   iKey = pOp->p3 ? aMem[pOp->p3].u.i : 0;
5346   rc = sqlite3BtreeTransferRow(pDest->uc.pCursor, pSrc->uc.pCursor, iKey);
5347   if( rc!=SQLITE_OK ) goto abort_due_to_error;
5348   break;
5349 };
5350 
5351 /* Opcode: Delete P1 P2 P3 P4 P5
5352 **
5353 ** Delete the record at which the P1 cursor is currently pointing.
5354 **
5355 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
5356 ** the cursor will be left pointing at  either the next or the previous
5357 ** record in the table. If it is left pointing at the next record, then
5358 ** the next Next instruction will be a no-op. As a result, in this case
5359 ** it is ok to delete a record from within a Next loop. If
5360 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
5361 ** left in an undefined state.
5362 **
5363 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
5364 ** delete one of several associated with deleting a table row and all its
5365 ** associated index entries.  Exactly one of those deletes is the "primary"
5366 ** delete.  The others are all on OPFLAG_FORDELETE cursors or else are
5367 ** marked with the AUXDELETE flag.
5368 **
5369 ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
5370 ** change count is incremented (otherwise not).
5371 **
5372 ** P1 must not be pseudo-table.  It has to be a real table with
5373 ** multiple rows.
5374 **
5375 ** If P4 is not NULL then it points to a Table object. In this case either
5376 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
5377 ** have been positioned using OP_NotFound prior to invoking this opcode in
5378 ** this case. Specifically, if one is configured, the pre-update hook is
5379 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
5380 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
5381 **
5382 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
5383 ** of the memory cell that contains the value that the rowid of the row will
5384 ** be set to by the update.
5385 */
5386 case OP_Delete: {
5387   VdbeCursor *pC;
5388   const char *zDb;
5389   Table *pTab;
5390   int opflags;
5391 
5392   opflags = pOp->p2;
5393   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5394   pC = p->apCsr[pOp->p1];
5395   assert( pC!=0 );
5396   assert( pC->eCurType==CURTYPE_BTREE );
5397   assert( pC->uc.pCursor!=0 );
5398   assert( pC->deferredMoveto==0 );
5399   sqlite3VdbeIncrWriteCounter(p, pC);
5400 
5401 #ifdef SQLITE_DEBUG
5402   if( pOp->p4type==P4_TABLE
5403    && HasRowid(pOp->p4.pTab)
5404    && pOp->p5==0
5405    && sqlite3BtreeCursorIsValidNN(pC->uc.pCursor)
5406   ){
5407     /* If p5 is zero, the seek operation that positioned the cursor prior to
5408     ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
5409     ** the row that is being deleted */
5410     i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5411     assert( CORRUPT_DB || pC->movetoTarget==iKey );
5412   }
5413 #endif
5414 
5415   /* If the update-hook or pre-update-hook will be invoked, set zDb to
5416   ** the name of the db to pass as to it. Also set local pTab to a copy
5417   ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
5418   ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
5419   ** VdbeCursor.movetoTarget to the current rowid.  */
5420   if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
5421     assert( pC->iDb>=0 );
5422     assert( pOp->p4.pTab!=0 );
5423     zDb = db->aDb[pC->iDb].zDbSName;
5424     pTab = pOp->p4.pTab;
5425     if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
5426       pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5427     }
5428   }else{
5429     zDb = 0;
5430     pTab = 0;
5431   }
5432 
5433 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
5434   /* Invoke the pre-update-hook if required. */
5435   assert( db->xPreUpdateCallback==0 || pTab==pOp->p4.pTab );
5436   if( db->xPreUpdateCallback && pTab ){
5437     assert( !(opflags & OPFLAG_ISUPDATE)
5438          || HasRowid(pTab)==0
5439          || (aMem[pOp->p3].flags & MEM_Int)
5440     );
5441     sqlite3VdbePreUpdateHook(p, pC,
5442         (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
5443         zDb, pTab, pC->movetoTarget,
5444         pOp->p3, -1
5445     );
5446   }
5447   if( opflags & OPFLAG_ISNOOP ) break;
5448 #endif
5449 
5450   /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
5451   assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
5452   assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
5453   assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
5454 
5455 #ifdef SQLITE_DEBUG
5456   if( p->pFrame==0 ){
5457     if( pC->isEphemeral==0
5458         && (pOp->p5 & OPFLAG_AUXDELETE)==0
5459         && (pC->wrFlag & OPFLAG_FORDELETE)==0
5460       ){
5461       nExtraDelete++;
5462     }
5463     if( pOp->p2 & OPFLAG_NCHANGE ){
5464       nExtraDelete--;
5465     }
5466   }
5467 #endif
5468 
5469   rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
5470   pC->cacheStatus = CACHE_STALE;
5471   pC->seekResult = 0;
5472   if( rc ) goto abort_due_to_error;
5473 
5474   /* Invoke the update-hook if required. */
5475   if( opflags & OPFLAG_NCHANGE ){
5476     p->nChange++;
5477     if( db->xUpdateCallback && ALWAYS(pTab!=0) && HasRowid(pTab) ){
5478       db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
5479           pC->movetoTarget);
5480       assert( pC->iDb>=0 );
5481     }
5482   }
5483 
5484   break;
5485 }
5486 /* Opcode: ResetCount * * * * *
5487 **
5488 ** The value of the change counter is copied to the database handle
5489 ** change counter (returned by subsequent calls to sqlite3_changes()).
5490 ** Then the VMs internal change counter resets to 0.
5491 ** This is used by trigger programs.
5492 */
5493 case OP_ResetCount: {
5494   sqlite3VdbeSetChanges(db, p->nChange);
5495   p->nChange = 0;
5496   break;
5497 }
5498 
5499 /* Opcode: SorterCompare P1 P2 P3 P4
5500 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
5501 **
5502 ** P1 is a sorter cursor. This instruction compares a prefix of the
5503 ** record blob in register P3 against a prefix of the entry that
5504 ** the sorter cursor currently points to.  Only the first P4 fields
5505 ** of r[P3] and the sorter record are compared.
5506 **
5507 ** If either P3 or the sorter contains a NULL in one of their significant
5508 ** fields (not counting the P4 fields at the end which are ignored) then
5509 ** the comparison is assumed to be equal.
5510 **
5511 ** Fall through to next instruction if the two records compare equal to
5512 ** each other.  Jump to P2 if they are different.
5513 */
5514 case OP_SorterCompare: {
5515   VdbeCursor *pC;
5516   int res;
5517   int nKeyCol;
5518 
5519   pC = p->apCsr[pOp->p1];
5520   assert( isSorter(pC) );
5521   assert( pOp->p4type==P4_INT32 );
5522   pIn3 = &aMem[pOp->p3];
5523   nKeyCol = pOp->p4.i;
5524   res = 0;
5525   rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
5526   VdbeBranchTaken(res!=0,2);
5527   if( rc ) goto abort_due_to_error;
5528   if( res ) goto jump_to_p2;
5529   break;
5530 };
5531 
5532 /* Opcode: SorterData P1 P2 P3 * *
5533 ** Synopsis: r[P2]=data
5534 **
5535 ** Write into register P2 the current sorter data for sorter cursor P1.
5536 ** Then clear the column header cache on cursor P3.
5537 **
5538 ** This opcode is normally use to move a record out of the sorter and into
5539 ** a register that is the source for a pseudo-table cursor created using
5540 ** OpenPseudo.  That pseudo-table cursor is the one that is identified by
5541 ** parameter P3.  Clearing the P3 column cache as part of this opcode saves
5542 ** us from having to issue a separate NullRow instruction to clear that cache.
5543 */
5544 case OP_SorterData: {
5545   VdbeCursor *pC;
5546 
5547   pOut = &aMem[pOp->p2];
5548   pC = p->apCsr[pOp->p1];
5549   assert( isSorter(pC) );
5550   rc = sqlite3VdbeSorterRowkey(pC, pOut);
5551   assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
5552   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5553   if( rc ) goto abort_due_to_error;
5554   p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
5555   break;
5556 }
5557 
5558 /* Opcode: RowData P1 P2 P3 * *
5559 ** Synopsis: r[P2]=data
5560 **
5561 ** Write into register P2 the complete row content for the row at
5562 ** which cursor P1 is currently pointing.
5563 ** There is no interpretation of the data.
5564 ** It is just copied onto the P2 register exactly as
5565 ** it is found in the database file.
5566 **
5567 ** If cursor P1 is an index, then the content is the key of the row.
5568 ** If cursor P2 is a table, then the content extracted is the data.
5569 **
5570 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
5571 ** of a real table, not a pseudo-table.
5572 **
5573 ** If P3!=0 then this opcode is allowed to make an ephemeral pointer
5574 ** into the database page.  That means that the content of the output
5575 ** register will be invalidated as soon as the cursor moves - including
5576 ** moves caused by other cursors that "save" the current cursors
5577 ** position in order that they can write to the same table.  If P3==0
5578 ** then a copy of the data is made into memory.  P3!=0 is faster, but
5579 ** P3==0 is safer.
5580 **
5581 ** If P3!=0 then the content of the P2 register is unsuitable for use
5582 ** in OP_Result and any OP_Result will invalidate the P2 register content.
5583 ** The P2 register content is invalidated by opcodes like OP_Function or
5584 ** by any use of another cursor pointing to the same table.
5585 */
5586 case OP_RowData: {
5587   VdbeCursor *pC;
5588   BtCursor *pCrsr;
5589   u32 n;
5590 
5591   pOut = out2Prerelease(p, pOp);
5592 
5593   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5594   pC = p->apCsr[pOp->p1];
5595   assert( pC!=0 );
5596   assert( pC->eCurType==CURTYPE_BTREE );
5597   assert( isSorter(pC)==0 );
5598   assert( pC->nullRow==0 );
5599   assert( pC->uc.pCursor!=0 );
5600   pCrsr = pC->uc.pCursor;
5601 
5602   /* The OP_RowData opcodes always follow OP_NotExists or
5603   ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
5604   ** that might invalidate the cursor.
5605   ** If this where not the case, on of the following assert()s
5606   ** would fail.  Should this ever change (because of changes in the code
5607   ** generator) then the fix would be to insert a call to
5608   ** sqlite3VdbeCursorMoveto().
5609   */
5610   assert( pC->deferredMoveto==0 );
5611   assert( sqlite3BtreeCursorIsValid(pCrsr) );
5612 
5613   n = sqlite3BtreePayloadSize(pCrsr);
5614   if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
5615     goto too_big;
5616   }
5617   testcase( n==0 );
5618   rc = sqlite3VdbeMemFromBtreeZeroOffset(pCrsr, n, pOut);
5619   if( rc ) goto abort_due_to_error;
5620   if( !pOp->p3 ) Deephemeralize(pOut);
5621   UPDATE_MAX_BLOBSIZE(pOut);
5622   REGISTER_TRACE(pOp->p2, pOut);
5623   break;
5624 }
5625 
5626 /* Opcode: Rowid P1 P2 * * *
5627 ** Synopsis: r[P2]=rowid
5628 **
5629 ** Store in register P2 an integer which is the key of the table entry that
5630 ** P1 is currently point to.
5631 **
5632 ** P1 can be either an ordinary table or a virtual table.  There used to
5633 ** be a separate OP_VRowid opcode for use with virtual tables, but this
5634 ** one opcode now works for both table types.
5635 */
5636 case OP_Rowid: {                 /* out2 */
5637   VdbeCursor *pC;
5638   i64 v;
5639   sqlite3_vtab *pVtab;
5640   const sqlite3_module *pModule;
5641 
5642   pOut = out2Prerelease(p, pOp);
5643   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5644   pC = p->apCsr[pOp->p1];
5645   assert( pC!=0 );
5646   assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
5647   if( pC->nullRow ){
5648     pOut->flags = MEM_Null;
5649     break;
5650   }else if( pC->deferredMoveto ){
5651     v = pC->movetoTarget;
5652 #ifndef SQLITE_OMIT_VIRTUALTABLE
5653   }else if( pC->eCurType==CURTYPE_VTAB ){
5654     assert( pC->uc.pVCur!=0 );
5655     pVtab = pC->uc.pVCur->pVtab;
5656     pModule = pVtab->pModule;
5657     assert( pModule->xRowid );
5658     rc = pModule->xRowid(pC->uc.pVCur, &v);
5659     sqlite3VtabImportErrmsg(p, pVtab);
5660     if( rc ) goto abort_due_to_error;
5661 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5662   }else{
5663     assert( pC->eCurType==CURTYPE_BTREE );
5664     assert( pC->uc.pCursor!=0 );
5665     rc = sqlite3VdbeCursorRestore(pC);
5666     if( rc ) goto abort_due_to_error;
5667     if( pC->nullRow ){
5668       pOut->flags = MEM_Null;
5669       break;
5670     }
5671     v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5672   }
5673   pOut->u.i = v;
5674   break;
5675 }
5676 
5677 /* Opcode: NullRow P1 * * * *
5678 **
5679 ** Move the cursor P1 to a null row.  Any OP_Column operations
5680 ** that occur while the cursor is on the null row will always
5681 ** write a NULL.
5682 */
5683 case OP_NullRow: {
5684   VdbeCursor *pC;
5685 
5686   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5687   pC = p->apCsr[pOp->p1];
5688   assert( pC!=0 );
5689   pC->nullRow = 1;
5690   pC->cacheStatus = CACHE_STALE;
5691   if( pC->eCurType==CURTYPE_BTREE ){
5692     assert( pC->uc.pCursor!=0 );
5693     sqlite3BtreeClearCursor(pC->uc.pCursor);
5694   }
5695 #ifdef SQLITE_DEBUG
5696   if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
5697 #endif
5698   break;
5699 }
5700 
5701 /* Opcode: SeekEnd P1 * * * *
5702 **
5703 ** Position cursor P1 at the end of the btree for the purpose of
5704 ** appending a new entry onto the btree.
5705 **
5706 ** It is assumed that the cursor is used only for appending and so
5707 ** if the cursor is valid, then the cursor must already be pointing
5708 ** at the end of the btree and so no changes are made to
5709 ** the cursor.
5710 */
5711 /* Opcode: Last P1 P2 * * *
5712 **
5713 ** The next use of the Rowid or Column or Prev instruction for P1
5714 ** will refer to the last entry in the database table or index.
5715 ** If the table or index is empty and P2>0, then jump immediately to P2.
5716 ** If P2 is 0 or if the table or index is not empty, fall through
5717 ** to the following instruction.
5718 **
5719 ** This opcode leaves the cursor configured to move in reverse order,
5720 ** from the end toward the beginning.  In other words, the cursor is
5721 ** configured to use Prev, not Next.
5722 */
5723 case OP_SeekEnd:
5724 case OP_Last: {        /* jump */
5725   VdbeCursor *pC;
5726   BtCursor *pCrsr;
5727   int res;
5728 
5729   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5730   pC = p->apCsr[pOp->p1];
5731   assert( pC!=0 );
5732   assert( pC->eCurType==CURTYPE_BTREE );
5733   pCrsr = pC->uc.pCursor;
5734   res = 0;
5735   assert( pCrsr!=0 );
5736 #ifdef SQLITE_DEBUG
5737   pC->seekOp = pOp->opcode;
5738 #endif
5739   if( pOp->opcode==OP_SeekEnd ){
5740     assert( pOp->p2==0 );
5741     pC->seekResult = -1;
5742     if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
5743       break;
5744     }
5745   }
5746   rc = sqlite3BtreeLast(pCrsr, &res);
5747   pC->nullRow = (u8)res;
5748   pC->deferredMoveto = 0;
5749   pC->cacheStatus = CACHE_STALE;
5750   if( rc ) goto abort_due_to_error;
5751   if( pOp->p2>0 ){
5752     VdbeBranchTaken(res!=0,2);
5753     if( res ) goto jump_to_p2;
5754   }
5755   break;
5756 }
5757 
5758 /* Opcode: IfSmaller P1 P2 P3 * *
5759 **
5760 ** Estimate the number of rows in the table P1.  Jump to P2 if that
5761 ** estimate is less than approximately 2**(0.1*P3).
5762 */
5763 case OP_IfSmaller: {        /* jump */
5764   VdbeCursor *pC;
5765   BtCursor *pCrsr;
5766   int res;
5767   i64 sz;
5768 
5769   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5770   pC = p->apCsr[pOp->p1];
5771   assert( pC!=0 );
5772   pCrsr = pC->uc.pCursor;
5773   assert( pCrsr );
5774   rc = sqlite3BtreeFirst(pCrsr, &res);
5775   if( rc ) goto abort_due_to_error;
5776   if( res==0 ){
5777     sz = sqlite3BtreeRowCountEst(pCrsr);
5778     if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
5779   }
5780   VdbeBranchTaken(res!=0,2);
5781   if( res ) goto jump_to_p2;
5782   break;
5783 }
5784 
5785 
5786 /* Opcode: SorterSort P1 P2 * * *
5787 **
5788 ** After all records have been inserted into the Sorter object
5789 ** identified by P1, invoke this opcode to actually do the sorting.
5790 ** Jump to P2 if there are no records to be sorted.
5791 **
5792 ** This opcode is an alias for OP_Sort and OP_Rewind that is used
5793 ** for Sorter objects.
5794 */
5795 /* Opcode: Sort P1 P2 * * *
5796 **
5797 ** This opcode does exactly the same thing as OP_Rewind except that
5798 ** it increments an undocumented global variable used for testing.
5799 **
5800 ** Sorting is accomplished by writing records into a sorting index,
5801 ** then rewinding that index and playing it back from beginning to
5802 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
5803 ** rewinding so that the global variable will be incremented and
5804 ** regression tests can determine whether or not the optimizer is
5805 ** correctly optimizing out sorts.
5806 */
5807 case OP_SorterSort:    /* jump */
5808 case OP_Sort: {        /* jump */
5809 #ifdef SQLITE_TEST
5810   sqlite3_sort_count++;
5811   sqlite3_search_count--;
5812 #endif
5813   p->aCounter[SQLITE_STMTSTATUS_SORT]++;
5814   /* Fall through into OP_Rewind */
5815   /* no break */ deliberate_fall_through
5816 }
5817 /* Opcode: Rewind P1 P2 * * *
5818 **
5819 ** The next use of the Rowid or Column or Next instruction for P1
5820 ** will refer to the first entry in the database table or index.
5821 ** If the table or index is empty, jump immediately to P2.
5822 ** If the table or index is not empty, fall through to the following
5823 ** instruction.
5824 **
5825 ** This opcode leaves the cursor configured to move in forward order,
5826 ** from the beginning toward the end.  In other words, the cursor is
5827 ** configured to use Next, not Prev.
5828 */
5829 case OP_Rewind: {        /* jump */
5830   VdbeCursor *pC;
5831   BtCursor *pCrsr;
5832   int res;
5833 
5834   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5835   assert( pOp->p5==0 );
5836   pC = p->apCsr[pOp->p1];
5837   assert( pC!=0 );
5838   assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
5839   res = 1;
5840 #ifdef SQLITE_DEBUG
5841   pC->seekOp = OP_Rewind;
5842 #endif
5843   if( isSorter(pC) ){
5844     rc = sqlite3VdbeSorterRewind(pC, &res);
5845   }else{
5846     assert( pC->eCurType==CURTYPE_BTREE );
5847     pCrsr = pC->uc.pCursor;
5848     assert( pCrsr );
5849     rc = sqlite3BtreeFirst(pCrsr, &res);
5850     pC->deferredMoveto = 0;
5851     pC->cacheStatus = CACHE_STALE;
5852   }
5853   if( rc ) goto abort_due_to_error;
5854   pC->nullRow = (u8)res;
5855   assert( pOp->p2>0 && pOp->p2<p->nOp );
5856   VdbeBranchTaken(res!=0,2);
5857   if( res ) goto jump_to_p2;
5858   break;
5859 }
5860 
5861 /* Opcode: Next P1 P2 P3 P4 P5
5862 **
5863 ** Advance cursor P1 so that it points to the next key/data pair in its
5864 ** table or index.  If there are no more key/value pairs then fall through
5865 ** to the following instruction.  But if the cursor advance was successful,
5866 ** jump immediately to P2.
5867 **
5868 ** The Next opcode is only valid following an SeekGT, SeekGE, or
5869 ** OP_Rewind opcode used to position the cursor.  Next is not allowed
5870 ** to follow SeekLT, SeekLE, or OP_Last.
5871 **
5872 ** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
5873 ** been opened prior to this opcode or the program will segfault.
5874 **
5875 ** The P3 value is a hint to the btree implementation. If P3==1, that
5876 ** means P1 is an SQL index and that this instruction could have been
5877 ** omitted if that index had been unique.  P3 is usually 0.  P3 is
5878 ** always either 0 or 1.
5879 **
5880 ** P4 is always of type P4_ADVANCE. The function pointer points to
5881 ** sqlite3BtreeNext().
5882 **
5883 ** If P5 is positive and the jump is taken, then event counter
5884 ** number P5-1 in the prepared statement is incremented.
5885 **
5886 ** See also: Prev
5887 */
5888 /* Opcode: Prev P1 P2 P3 P4 P5
5889 **
5890 ** Back up cursor P1 so that it points to the previous key/data pair in its
5891 ** table or index.  If there is no previous key/value pairs then fall through
5892 ** to the following instruction.  But if the cursor backup was successful,
5893 ** jump immediately to P2.
5894 **
5895 **
5896 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
5897 ** OP_Last opcode used to position the cursor.  Prev is not allowed
5898 ** to follow SeekGT, SeekGE, or OP_Rewind.
5899 **
5900 ** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
5901 ** not open then the behavior is undefined.
5902 **
5903 ** The P3 value is a hint to the btree implementation. If P3==1, that
5904 ** means P1 is an SQL index and that this instruction could have been
5905 ** omitted if that index had been unique.  P3 is usually 0.  P3 is
5906 ** always either 0 or 1.
5907 **
5908 ** P4 is always of type P4_ADVANCE. The function pointer points to
5909 ** sqlite3BtreePrevious().
5910 **
5911 ** If P5 is positive and the jump is taken, then event counter
5912 ** number P5-1 in the prepared statement is incremented.
5913 */
5914 /* Opcode: SorterNext P1 P2 * * P5
5915 **
5916 ** This opcode works just like OP_Next except that P1 must be a
5917 ** sorter object for which the OP_SorterSort opcode has been
5918 ** invoked.  This opcode advances the cursor to the next sorted
5919 ** record, or jumps to P2 if there are no more sorted records.
5920 */
5921 case OP_SorterNext: {  /* jump */
5922   VdbeCursor *pC;
5923 
5924   pC = p->apCsr[pOp->p1];
5925   assert( isSorter(pC) );
5926   rc = sqlite3VdbeSorterNext(db, pC);
5927   goto next_tail;
5928 case OP_Prev:          /* jump */
5929 case OP_Next:          /* jump */
5930   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5931   assert( pOp->p5<ArraySize(p->aCounter) );
5932   pC = p->apCsr[pOp->p1];
5933   assert( pC!=0 );
5934   assert( pC->deferredMoveto==0 );
5935   assert( pC->eCurType==CURTYPE_BTREE );
5936   assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
5937   assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
5938 
5939   /* The Next opcode is only used after SeekGT, SeekGE, Rewind, and Found.
5940   ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
5941   assert( pOp->opcode!=OP_Next
5942        || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
5943        || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found
5944        || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid
5945        || pC->seekOp==OP_IfNoHope);
5946   assert( pOp->opcode!=OP_Prev
5947        || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
5948        || pC->seekOp==OP_Last   || pC->seekOp==OP_IfNoHope
5949        || pC->seekOp==OP_NullRow);
5950 
5951   rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
5952 next_tail:
5953   pC->cacheStatus = CACHE_STALE;
5954   VdbeBranchTaken(rc==SQLITE_OK,2);
5955   if( rc==SQLITE_OK ){
5956     pC->nullRow = 0;
5957     p->aCounter[pOp->p5]++;
5958 #ifdef SQLITE_TEST
5959     sqlite3_search_count++;
5960 #endif
5961     goto jump_to_p2_and_check_for_interrupt;
5962   }
5963   if( rc!=SQLITE_DONE ) goto abort_due_to_error;
5964   rc = SQLITE_OK;
5965   pC->nullRow = 1;
5966   goto check_for_interrupt;
5967 }
5968 
5969 /* Opcode: IdxInsert P1 P2 P3 P4 P5
5970 ** Synopsis: key=r[P2]
5971 **
5972 ** Register P2 holds an SQL index key made using the
5973 ** MakeRecord instructions.  This opcode writes that key
5974 ** into the index P1.  Data for the entry is nil.
5975 **
5976 ** If P4 is not zero, then it is the number of values in the unpacked
5977 ** key of reg(P2).  In that case, P3 is the index of the first register
5978 ** for the unpacked key.  The availability of the unpacked key can sometimes
5979 ** be an optimization.
5980 **
5981 ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
5982 ** that this insert is likely to be an append.
5983 **
5984 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
5985 ** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
5986 ** then the change counter is unchanged.
5987 **
5988 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
5989 ** run faster by avoiding an unnecessary seek on cursor P1.  However,
5990 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
5991 ** seeks on the cursor or if the most recent seek used a key equivalent
5992 ** to P2.
5993 **
5994 ** This instruction only works for indices.  The equivalent instruction
5995 ** for tables is OP_Insert.
5996 */
5997 case OP_IdxInsert: {        /* in2 */
5998   VdbeCursor *pC;
5999   BtreePayload x;
6000 
6001   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6002   pC = p->apCsr[pOp->p1];
6003   sqlite3VdbeIncrWriteCounter(p, pC);
6004   assert( pC!=0 );
6005   assert( !isSorter(pC) );
6006   pIn2 = &aMem[pOp->p2];
6007   assert( (pIn2->flags & MEM_Blob) || (pOp->p5 & OPFLAG_PREFORMAT) );
6008   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
6009   assert( pC->eCurType==CURTYPE_BTREE );
6010   assert( pC->isTable==0 );
6011   rc = ExpandBlob(pIn2);
6012   if( rc ) goto abort_due_to_error;
6013   x.nKey = pIn2->n;
6014   x.pKey = pIn2->z;
6015   x.aMem = aMem + pOp->p3;
6016   x.nMem = (u16)pOp->p4.i;
6017   rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
6018        (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
6019       ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
6020       );
6021   assert( pC->deferredMoveto==0 );
6022   pC->cacheStatus = CACHE_STALE;
6023   if( rc) goto abort_due_to_error;
6024   break;
6025 }
6026 
6027 /* Opcode: SorterInsert P1 P2 * * *
6028 ** Synopsis: key=r[P2]
6029 **
6030 ** Register P2 holds an SQL index key made using the
6031 ** MakeRecord instructions.  This opcode writes that key
6032 ** into the sorter P1.  Data for the entry is nil.
6033 */
6034 case OP_SorterInsert: {     /* in2 */
6035   VdbeCursor *pC;
6036 
6037   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6038   pC = p->apCsr[pOp->p1];
6039   sqlite3VdbeIncrWriteCounter(p, pC);
6040   assert( pC!=0 );
6041   assert( isSorter(pC) );
6042   pIn2 = &aMem[pOp->p2];
6043   assert( pIn2->flags & MEM_Blob );
6044   assert( pC->isTable==0 );
6045   rc = ExpandBlob(pIn2);
6046   if( rc ) goto abort_due_to_error;
6047   rc = sqlite3VdbeSorterWrite(pC, pIn2);
6048   if( rc) goto abort_due_to_error;
6049   break;
6050 }
6051 
6052 /* Opcode: IdxDelete P1 P2 P3 * P5
6053 ** Synopsis: key=r[P2@P3]
6054 **
6055 ** The content of P3 registers starting at register P2 form
6056 ** an unpacked index key. This opcode removes that entry from the
6057 ** index opened by cursor P1.
6058 **
6059 ** If P5 is not zero, then raise an SQLITE_CORRUPT_INDEX error
6060 ** if no matching index entry is found.  This happens when running
6061 ** an UPDATE or DELETE statement and the index entry to be updated
6062 ** or deleted is not found.  For some uses of IdxDelete
6063 ** (example:  the EXCEPT operator) it does not matter that no matching
6064 ** entry is found.  For those cases, P5 is zero.  Also, do not raise
6065 ** this (self-correcting and non-critical) error if in writable_schema mode.
6066 */
6067 case OP_IdxDelete: {
6068   VdbeCursor *pC;
6069   BtCursor *pCrsr;
6070   int res;
6071   UnpackedRecord r;
6072 
6073   assert( pOp->p3>0 );
6074   assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
6075   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6076   pC = p->apCsr[pOp->p1];
6077   assert( pC!=0 );
6078   assert( pC->eCurType==CURTYPE_BTREE );
6079   sqlite3VdbeIncrWriteCounter(p, pC);
6080   pCrsr = pC->uc.pCursor;
6081   assert( pCrsr!=0 );
6082   r.pKeyInfo = pC->pKeyInfo;
6083   r.nField = (u16)pOp->p3;
6084   r.default_rc = 0;
6085   r.aMem = &aMem[pOp->p2];
6086   rc = sqlite3BtreeIndexMoveto(pCrsr, &r, &res);
6087   if( rc ) goto abort_due_to_error;
6088   if( res==0 ){
6089     rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
6090     if( rc ) goto abort_due_to_error;
6091   }else if( pOp->p5 && !sqlite3WritableSchema(db) ){
6092     rc = sqlite3ReportError(SQLITE_CORRUPT_INDEX, __LINE__, "index corruption");
6093     goto abort_due_to_error;
6094   }
6095   assert( pC->deferredMoveto==0 );
6096   pC->cacheStatus = CACHE_STALE;
6097   pC->seekResult = 0;
6098   break;
6099 }
6100 
6101 /* Opcode: DeferredSeek P1 * P3 P4 *
6102 ** Synopsis: Move P3 to P1.rowid if needed
6103 **
6104 ** P1 is an open index cursor and P3 is a cursor on the corresponding
6105 ** table.  This opcode does a deferred seek of the P3 table cursor
6106 ** to the row that corresponds to the current row of P1.
6107 **
6108 ** This is a deferred seek.  Nothing actually happens until
6109 ** the cursor is used to read a record.  That way, if no reads
6110 ** occur, no unnecessary I/O happens.
6111 **
6112 ** P4 may be an array of integers (type P4_INTARRAY) containing
6113 ** one entry for each column in the P3 table.  If array entry a(i)
6114 ** is non-zero, then reading column a(i)-1 from cursor P3 is
6115 ** equivalent to performing the deferred seek and then reading column i
6116 ** from P1.  This information is stored in P3 and used to redirect
6117 ** reads against P3 over to P1, thus possibly avoiding the need to
6118 ** seek and read cursor P3.
6119 */
6120 /* Opcode: IdxRowid P1 P2 * * *
6121 ** Synopsis: r[P2]=rowid
6122 **
6123 ** Write into register P2 an integer which is the last entry in the record at
6124 ** the end of the index key pointed to by cursor P1.  This integer should be
6125 ** the rowid of the table entry to which this index entry points.
6126 **
6127 ** See also: Rowid, MakeRecord.
6128 */
6129 case OP_DeferredSeek:
6130 case OP_IdxRowid: {           /* out2 */
6131   VdbeCursor *pC;             /* The P1 index cursor */
6132   VdbeCursor *pTabCur;        /* The P2 table cursor (OP_DeferredSeek only) */
6133   i64 rowid;                  /* Rowid that P1 current points to */
6134 
6135   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6136   pC = p->apCsr[pOp->p1];
6137   assert( pC!=0 );
6138   assert( pC->eCurType==CURTYPE_BTREE );
6139   assert( pC->uc.pCursor!=0 );
6140   assert( pC->isTable==0 );
6141   assert( pC->deferredMoveto==0 );
6142   assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
6143 
6144   /* The IdxRowid and Seek opcodes are combined because of the commonality
6145   ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
6146   rc = sqlite3VdbeCursorRestore(pC);
6147 
6148   /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
6149   ** out from under the cursor.  That will never happens for an IdxRowid
6150   ** or Seek opcode */
6151   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
6152 
6153   if( !pC->nullRow ){
6154     rowid = 0;  /* Not needed.  Only used to silence a warning. */
6155     rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
6156     if( rc!=SQLITE_OK ){
6157       goto abort_due_to_error;
6158     }
6159     if( pOp->opcode==OP_DeferredSeek ){
6160       assert( pOp->p3>=0 && pOp->p3<p->nCursor );
6161       pTabCur = p->apCsr[pOp->p3];
6162       assert( pTabCur!=0 );
6163       assert( pTabCur->eCurType==CURTYPE_BTREE );
6164       assert( pTabCur->uc.pCursor!=0 );
6165       assert( pTabCur->isTable );
6166       pTabCur->nullRow = 0;
6167       pTabCur->movetoTarget = rowid;
6168       pTabCur->deferredMoveto = 1;
6169       assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
6170       pTabCur->aAltMap = pOp->p4.ai;
6171       assert( !pC->isEphemeral );
6172       assert( !pTabCur->isEphemeral );
6173       pTabCur->pAltCursor = pC;
6174     }else{
6175       pOut = out2Prerelease(p, pOp);
6176       pOut->u.i = rowid;
6177     }
6178   }else{
6179     assert( pOp->opcode==OP_IdxRowid );
6180     sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
6181   }
6182   break;
6183 }
6184 
6185 /* Opcode: FinishSeek P1 * * * *
6186 **
6187 ** If cursor P1 was previously moved via OP_DeferredSeek, complete that
6188 ** seek operation now, without further delay.  If the cursor seek has
6189 ** already occurred, this instruction is a no-op.
6190 */
6191 case OP_FinishSeek: {
6192   VdbeCursor *pC;             /* The P1 index cursor */
6193 
6194   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6195   pC = p->apCsr[pOp->p1];
6196   if( pC->deferredMoveto ){
6197     rc = sqlite3VdbeFinishMoveto(pC);
6198     if( rc ) goto abort_due_to_error;
6199   }
6200   break;
6201 }
6202 
6203 /* Opcode: IdxGE P1 P2 P3 P4 *
6204 ** Synopsis: key=r[P3@P4]
6205 **
6206 ** The P4 register values beginning with P3 form an unpacked index
6207 ** key that omits the PRIMARY KEY.  Compare this key value against the index
6208 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
6209 ** fields at the end.
6210 **
6211 ** If the P1 index entry is greater than or equal to the key value
6212 ** then jump to P2.  Otherwise fall through to the next instruction.
6213 */
6214 /* Opcode: IdxGT P1 P2 P3 P4 *
6215 ** Synopsis: key=r[P3@P4]
6216 **
6217 ** The P4 register values beginning with P3 form an unpacked index
6218 ** key that omits the PRIMARY KEY.  Compare this key value against the index
6219 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
6220 ** fields at the end.
6221 **
6222 ** If the P1 index entry is greater than the key value
6223 ** then jump to P2.  Otherwise fall through to the next instruction.
6224 */
6225 /* Opcode: IdxLT P1 P2 P3 P4 *
6226 ** Synopsis: key=r[P3@P4]
6227 **
6228 ** The P4 register values beginning with P3 form an unpacked index
6229 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
6230 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
6231 ** ROWID on the P1 index.
6232 **
6233 ** If the P1 index entry is less than the key value then jump to P2.
6234 ** Otherwise fall through to the next instruction.
6235 */
6236 /* Opcode: IdxLE P1 P2 P3 P4 *
6237 ** Synopsis: key=r[P3@P4]
6238 **
6239 ** The P4 register values beginning with P3 form an unpacked index
6240 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
6241 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
6242 ** ROWID on the P1 index.
6243 **
6244 ** If the P1 index entry is less than or equal to the key value then jump
6245 ** to P2. Otherwise fall through to the next instruction.
6246 */
6247 case OP_IdxLE:          /* jump */
6248 case OP_IdxGT:          /* jump */
6249 case OP_IdxLT:          /* jump */
6250 case OP_IdxGE:  {       /* jump */
6251   VdbeCursor *pC;
6252   int res;
6253   UnpackedRecord r;
6254 
6255   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6256   pC = p->apCsr[pOp->p1];
6257   assert( pC!=0 );
6258   assert( pC->isOrdered );
6259   assert( pC->eCurType==CURTYPE_BTREE );
6260   assert( pC->uc.pCursor!=0);
6261   assert( pC->deferredMoveto==0 );
6262   assert( pOp->p4type==P4_INT32 );
6263   r.pKeyInfo = pC->pKeyInfo;
6264   r.nField = (u16)pOp->p4.i;
6265   if( pOp->opcode<OP_IdxLT ){
6266     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
6267     r.default_rc = -1;
6268   }else{
6269     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
6270     r.default_rc = 0;
6271   }
6272   r.aMem = &aMem[pOp->p3];
6273 #ifdef SQLITE_DEBUG
6274   {
6275     int i;
6276     for(i=0; i<r.nField; i++){
6277       assert( memIsValid(&r.aMem[i]) );
6278       REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]);
6279     }
6280   }
6281 #endif
6282 
6283   /* Inlined version of sqlite3VdbeIdxKeyCompare() */
6284   {
6285     i64 nCellKey = 0;
6286     BtCursor *pCur;
6287     Mem m;
6288 
6289     assert( pC->eCurType==CURTYPE_BTREE );
6290     pCur = pC->uc.pCursor;
6291     assert( sqlite3BtreeCursorIsValid(pCur) );
6292     nCellKey = sqlite3BtreePayloadSize(pCur);
6293     /* nCellKey will always be between 0 and 0xffffffff because of the way
6294     ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
6295     if( nCellKey<=0 || nCellKey>0x7fffffff ){
6296       rc = SQLITE_CORRUPT_BKPT;
6297       goto abort_due_to_error;
6298     }
6299     sqlite3VdbeMemInit(&m, db, 0);
6300     rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
6301     if( rc ) goto abort_due_to_error;
6302     res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, &r, 0);
6303     sqlite3VdbeMemRelease(&m);
6304   }
6305   /* End of inlined sqlite3VdbeIdxKeyCompare() */
6306 
6307   assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
6308   if( (pOp->opcode&1)==(OP_IdxLT&1) ){
6309     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
6310     res = -res;
6311   }else{
6312     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
6313     res++;
6314   }
6315   VdbeBranchTaken(res>0,2);
6316   assert( rc==SQLITE_OK );
6317   if( res>0 ) goto jump_to_p2;
6318   break;
6319 }
6320 
6321 /* Opcode: Destroy P1 P2 P3 * *
6322 **
6323 ** Delete an entire database table or index whose root page in the database
6324 ** file is given by P1.
6325 **
6326 ** The table being destroyed is in the main database file if P3==0.  If
6327 ** P3==1 then the table to be clear is in the auxiliary database file
6328 ** that is used to store tables create using CREATE TEMPORARY TABLE.
6329 **
6330 ** If AUTOVACUUM is enabled then it is possible that another root page
6331 ** might be moved into the newly deleted root page in order to keep all
6332 ** root pages contiguous at the beginning of the database.  The former
6333 ** value of the root page that moved - its value before the move occurred -
6334 ** is stored in register P2. If no page movement was required (because the
6335 ** table being dropped was already the last one in the database) then a
6336 ** zero is stored in register P2.  If AUTOVACUUM is disabled then a zero
6337 ** is stored in register P2.
6338 **
6339 ** This opcode throws an error if there are any active reader VMs when
6340 ** it is invoked. This is done to avoid the difficulty associated with
6341 ** updating existing cursors when a root page is moved in an AUTOVACUUM
6342 ** database. This error is thrown even if the database is not an AUTOVACUUM
6343 ** db in order to avoid introducing an incompatibility between autovacuum
6344 ** and non-autovacuum modes.
6345 **
6346 ** See also: Clear
6347 */
6348 case OP_Destroy: {     /* out2 */
6349   int iMoved;
6350   int iDb;
6351 
6352   sqlite3VdbeIncrWriteCounter(p, 0);
6353   assert( p->readOnly==0 );
6354   assert( pOp->p1>1 );
6355   pOut = out2Prerelease(p, pOp);
6356   pOut->flags = MEM_Null;
6357   if( db->nVdbeRead > db->nVDestroy+1 ){
6358     rc = SQLITE_LOCKED;
6359     p->errorAction = OE_Abort;
6360     goto abort_due_to_error;
6361   }else{
6362     iDb = pOp->p3;
6363     assert( DbMaskTest(p->btreeMask, iDb) );
6364     iMoved = 0;  /* Not needed.  Only to silence a warning. */
6365     rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
6366     pOut->flags = MEM_Int;
6367     pOut->u.i = iMoved;
6368     if( rc ) goto abort_due_to_error;
6369 #ifndef SQLITE_OMIT_AUTOVACUUM
6370     if( iMoved!=0 ){
6371       sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
6372       /* All OP_Destroy operations occur on the same btree */
6373       assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
6374       resetSchemaOnFault = iDb+1;
6375     }
6376 #endif
6377   }
6378   break;
6379 }
6380 
6381 /* Opcode: Clear P1 P2 P3
6382 **
6383 ** Delete all contents of the database table or index whose root page
6384 ** in the database file is given by P1.  But, unlike Destroy, do not
6385 ** remove the table or index from the database file.
6386 **
6387 ** The table being clear is in the main database file if P2==0.  If
6388 ** P2==1 then the table to be clear is in the auxiliary database file
6389 ** that is used to store tables create using CREATE TEMPORARY TABLE.
6390 **
6391 ** If the P3 value is non-zero, then the row change count is incremented
6392 ** by the number of rows in the table being cleared. If P3 is greater
6393 ** than zero, then the value stored in register P3 is also incremented
6394 ** by the number of rows in the table being cleared.
6395 **
6396 ** See also: Destroy
6397 */
6398 case OP_Clear: {
6399   i64 nChange;
6400 
6401   sqlite3VdbeIncrWriteCounter(p, 0);
6402   nChange = 0;
6403   assert( p->readOnly==0 );
6404   assert( DbMaskTest(p->btreeMask, pOp->p2) );
6405   rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, (u32)pOp->p1, &nChange);
6406   if( pOp->p3 ){
6407     p->nChange += nChange;
6408     if( pOp->p3>0 ){
6409       assert( memIsValid(&aMem[pOp->p3]) );
6410       memAboutToChange(p, &aMem[pOp->p3]);
6411       aMem[pOp->p3].u.i += nChange;
6412     }
6413   }
6414   if( rc ) goto abort_due_to_error;
6415   break;
6416 }
6417 
6418 /* Opcode: ResetSorter P1 * * * *
6419 **
6420 ** Delete all contents from the ephemeral table or sorter
6421 ** that is open on cursor P1.
6422 **
6423 ** This opcode only works for cursors used for sorting and
6424 ** opened with OP_OpenEphemeral or OP_SorterOpen.
6425 */
6426 case OP_ResetSorter: {
6427   VdbeCursor *pC;
6428 
6429   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6430   pC = p->apCsr[pOp->p1];
6431   assert( pC!=0 );
6432   if( isSorter(pC) ){
6433     sqlite3VdbeSorterReset(db, pC->uc.pSorter);
6434   }else{
6435     assert( pC->eCurType==CURTYPE_BTREE );
6436     assert( pC->isEphemeral );
6437     rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
6438     if( rc ) goto abort_due_to_error;
6439   }
6440   break;
6441 }
6442 
6443 /* Opcode: CreateBtree P1 P2 P3 * *
6444 ** Synopsis: r[P2]=root iDb=P1 flags=P3
6445 **
6446 ** Allocate a new b-tree in the main database file if P1==0 or in the
6447 ** TEMP database file if P1==1 or in an attached database if
6448 ** P1>1.  The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
6449 ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
6450 ** The root page number of the new b-tree is stored in register P2.
6451 */
6452 case OP_CreateBtree: {          /* out2 */
6453   Pgno pgno;
6454   Db *pDb;
6455 
6456   sqlite3VdbeIncrWriteCounter(p, 0);
6457   pOut = out2Prerelease(p, pOp);
6458   pgno = 0;
6459   assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
6460   assert( pOp->p1>=0 && pOp->p1<db->nDb );
6461   assert( DbMaskTest(p->btreeMask, pOp->p1) );
6462   assert( p->readOnly==0 );
6463   pDb = &db->aDb[pOp->p1];
6464   assert( pDb->pBt!=0 );
6465   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
6466   if( rc ) goto abort_due_to_error;
6467   pOut->u.i = pgno;
6468   break;
6469 }
6470 
6471 /* Opcode: SqlExec * * * P4 *
6472 **
6473 ** Run the SQL statement or statements specified in the P4 string.
6474 */
6475 case OP_SqlExec: {
6476   sqlite3VdbeIncrWriteCounter(p, 0);
6477   db->nSqlExec++;
6478   rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
6479   db->nSqlExec--;
6480   if( rc ) goto abort_due_to_error;
6481   break;
6482 }
6483 
6484 /* Opcode: ParseSchema P1 * * P4 *
6485 **
6486 ** Read and parse all entries from the schema table of database P1
6487 ** that match the WHERE clause P4.  If P4 is a NULL pointer, then the
6488 ** entire schema for P1 is reparsed.
6489 **
6490 ** This opcode invokes the parser to create a new virtual machine,
6491 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
6492 */
6493 case OP_ParseSchema: {
6494   int iDb;
6495   const char *zSchema;
6496   char *zSql;
6497   InitData initData;
6498 
6499   /* Any prepared statement that invokes this opcode will hold mutexes
6500   ** on every btree.  This is a prerequisite for invoking
6501   ** sqlite3InitCallback().
6502   */
6503 #ifdef SQLITE_DEBUG
6504   for(iDb=0; iDb<db->nDb; iDb++){
6505     assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
6506   }
6507 #endif
6508 
6509   iDb = pOp->p1;
6510   assert( iDb>=0 && iDb<db->nDb );
6511   assert( DbHasProperty(db, iDb, DB_SchemaLoaded)
6512            || db->mallocFailed
6513            || (CORRUPT_DB && (db->flags & SQLITE_NoSchemaError)!=0) );
6514 
6515 #ifndef SQLITE_OMIT_ALTERTABLE
6516   if( pOp->p4.z==0 ){
6517     sqlite3SchemaClear(db->aDb[iDb].pSchema);
6518     db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
6519     rc = sqlite3InitOne(db, iDb, &p->zErrMsg, pOp->p5);
6520     db->mDbFlags |= DBFLAG_SchemaChange;
6521     p->expired = 0;
6522   }else
6523 #endif
6524   {
6525     zSchema = LEGACY_SCHEMA_TABLE;
6526     initData.db = db;
6527     initData.iDb = iDb;
6528     initData.pzErrMsg = &p->zErrMsg;
6529     initData.mInitFlags = 0;
6530     initData.mxPage = sqlite3BtreeLastPage(db->aDb[iDb].pBt);
6531     zSql = sqlite3MPrintf(db,
6532        "SELECT*FROM\"%w\".%s WHERE %s ORDER BY rowid",
6533        db->aDb[iDb].zDbSName, zSchema, pOp->p4.z);
6534     if( zSql==0 ){
6535       rc = SQLITE_NOMEM_BKPT;
6536     }else{
6537       assert( db->init.busy==0 );
6538       db->init.busy = 1;
6539       initData.rc = SQLITE_OK;
6540       initData.nInitRow = 0;
6541       assert( !db->mallocFailed );
6542       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
6543       if( rc==SQLITE_OK ) rc = initData.rc;
6544       if( rc==SQLITE_OK && initData.nInitRow==0 ){
6545         /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse
6546         ** at least one SQL statement. Any less than that indicates that
6547         ** the sqlite_schema table is corrupt. */
6548         rc = SQLITE_CORRUPT_BKPT;
6549       }
6550       sqlite3DbFreeNN(db, zSql);
6551       db->init.busy = 0;
6552     }
6553   }
6554   if( rc ){
6555     sqlite3ResetAllSchemasOfConnection(db);
6556     if( rc==SQLITE_NOMEM ){
6557       goto no_mem;
6558     }
6559     goto abort_due_to_error;
6560   }
6561   break;
6562 }
6563 
6564 #if !defined(SQLITE_OMIT_ANALYZE)
6565 /* Opcode: LoadAnalysis P1 * * * *
6566 **
6567 ** Read the sqlite_stat1 table for database P1 and load the content
6568 ** of that table into the internal index hash table.  This will cause
6569 ** the analysis to be used when preparing all subsequent queries.
6570 */
6571 case OP_LoadAnalysis: {
6572   assert( pOp->p1>=0 && pOp->p1<db->nDb );
6573   rc = sqlite3AnalysisLoad(db, pOp->p1);
6574   if( rc ) goto abort_due_to_error;
6575   break;
6576 }
6577 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
6578 
6579 /* Opcode: DropTable P1 * * P4 *
6580 **
6581 ** Remove the internal (in-memory) data structures that describe
6582 ** the table named P4 in database P1.  This is called after a table
6583 ** is dropped from disk (using the Destroy opcode) in order to keep
6584 ** the internal representation of the
6585 ** schema consistent with what is on disk.
6586 */
6587 case OP_DropTable: {
6588   sqlite3VdbeIncrWriteCounter(p, 0);
6589   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
6590   break;
6591 }
6592 
6593 /* Opcode: DropIndex P1 * * P4 *
6594 **
6595 ** Remove the internal (in-memory) data structures that describe
6596 ** the index named P4 in database P1.  This is called after an index
6597 ** is dropped from disk (using the Destroy opcode)
6598 ** in order to keep the internal representation of the
6599 ** schema consistent with what is on disk.
6600 */
6601 case OP_DropIndex: {
6602   sqlite3VdbeIncrWriteCounter(p, 0);
6603   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
6604   break;
6605 }
6606 
6607 /* Opcode: DropTrigger P1 * * P4 *
6608 **
6609 ** Remove the internal (in-memory) data structures that describe
6610 ** the trigger named P4 in database P1.  This is called after a trigger
6611 ** is dropped from disk (using the Destroy opcode) in order to keep
6612 ** the internal representation of the
6613 ** schema consistent with what is on disk.
6614 */
6615 case OP_DropTrigger: {
6616   sqlite3VdbeIncrWriteCounter(p, 0);
6617   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
6618   break;
6619 }
6620 
6621 
6622 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
6623 /* Opcode: IntegrityCk P1 P2 P3 P4 P5
6624 **
6625 ** Do an analysis of the currently open database.  Store in
6626 ** register P1 the text of an error message describing any problems.
6627 ** If no problems are found, store a NULL in register P1.
6628 **
6629 ** The register P3 contains one less than the maximum number of allowed errors.
6630 ** At most reg(P3) errors will be reported.
6631 ** In other words, the analysis stops as soon as reg(P1) errors are
6632 ** seen.  Reg(P1) is updated with the number of errors remaining.
6633 **
6634 ** The root page numbers of all tables in the database are integers
6635 ** stored in P4_INTARRAY argument.
6636 **
6637 ** If P5 is not zero, the check is done on the auxiliary database
6638 ** file, not the main database file.
6639 **
6640 ** This opcode is used to implement the integrity_check pragma.
6641 */
6642 case OP_IntegrityCk: {
6643   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
6644   Pgno *aRoot;    /* Array of rootpage numbers for tables to be checked */
6645   int nErr;       /* Number of errors reported */
6646   char *z;        /* Text of the error report */
6647   Mem *pnErr;     /* Register keeping track of errors remaining */
6648 
6649   assert( p->bIsReader );
6650   nRoot = pOp->p2;
6651   aRoot = pOp->p4.ai;
6652   assert( nRoot>0 );
6653   assert( aRoot[0]==(Pgno)nRoot );
6654   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
6655   pnErr = &aMem[pOp->p3];
6656   assert( (pnErr->flags & MEM_Int)!=0 );
6657   assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
6658   pIn1 = &aMem[pOp->p1];
6659   assert( pOp->p5<db->nDb );
6660   assert( DbMaskTest(p->btreeMask, pOp->p5) );
6661   z = sqlite3BtreeIntegrityCheck(db, db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
6662                                  (int)pnErr->u.i+1, &nErr);
6663   sqlite3VdbeMemSetNull(pIn1);
6664   if( nErr==0 ){
6665     assert( z==0 );
6666   }else if( z==0 ){
6667     goto no_mem;
6668   }else{
6669     pnErr->u.i -= nErr-1;
6670     sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
6671   }
6672   UPDATE_MAX_BLOBSIZE(pIn1);
6673   sqlite3VdbeChangeEncoding(pIn1, encoding);
6674   goto check_for_interrupt;
6675 }
6676 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
6677 
6678 /* Opcode: RowSetAdd P1 P2 * * *
6679 ** Synopsis: rowset(P1)=r[P2]
6680 **
6681 ** Insert the integer value held by register P2 into a RowSet object
6682 ** held in register P1.
6683 **
6684 ** An assertion fails if P2 is not an integer.
6685 */
6686 case OP_RowSetAdd: {       /* in1, in2 */
6687   pIn1 = &aMem[pOp->p1];
6688   pIn2 = &aMem[pOp->p2];
6689   assert( (pIn2->flags & MEM_Int)!=0 );
6690   if( (pIn1->flags & MEM_Blob)==0 ){
6691     if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
6692   }
6693   assert( sqlite3VdbeMemIsRowSet(pIn1) );
6694   sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i);
6695   break;
6696 }
6697 
6698 /* Opcode: RowSetRead P1 P2 P3 * *
6699 ** Synopsis: r[P3]=rowset(P1)
6700 **
6701 ** Extract the smallest value from the RowSet object in P1
6702 ** and put that value into register P3.
6703 ** Or, if RowSet object P1 is initially empty, leave P3
6704 ** unchanged and jump to instruction P2.
6705 */
6706 case OP_RowSetRead: {       /* jump, in1, out3 */
6707   i64 val;
6708 
6709   pIn1 = &aMem[pOp->p1];
6710   assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) );
6711   if( (pIn1->flags & MEM_Blob)==0
6712    || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0
6713   ){
6714     /* The boolean index is empty */
6715     sqlite3VdbeMemSetNull(pIn1);
6716     VdbeBranchTaken(1,2);
6717     goto jump_to_p2_and_check_for_interrupt;
6718   }else{
6719     /* A value was pulled from the index */
6720     VdbeBranchTaken(0,2);
6721     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
6722   }
6723   goto check_for_interrupt;
6724 }
6725 
6726 /* Opcode: RowSetTest P1 P2 P3 P4
6727 ** Synopsis: if r[P3] in rowset(P1) goto P2
6728 **
6729 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
6730 ** contains a RowSet object and that RowSet object contains
6731 ** the value held in P3, jump to register P2. Otherwise, insert the
6732 ** integer in P3 into the RowSet and continue on to the
6733 ** next opcode.
6734 **
6735 ** The RowSet object is optimized for the case where sets of integers
6736 ** are inserted in distinct phases, which each set contains no duplicates.
6737 ** Each set is identified by a unique P4 value. The first set
6738 ** must have P4==0, the final set must have P4==-1, and for all other sets
6739 ** must have P4>0.
6740 **
6741 ** This allows optimizations: (a) when P4==0 there is no need to test
6742 ** the RowSet object for P3, as it is guaranteed not to contain it,
6743 ** (b) when P4==-1 there is no need to insert the value, as it will
6744 ** never be tested for, and (c) when a value that is part of set X is
6745 ** inserted, there is no need to search to see if the same value was
6746 ** previously inserted as part of set X (only if it was previously
6747 ** inserted as part of some other set).
6748 */
6749 case OP_RowSetTest: {                     /* jump, in1, in3 */
6750   int iSet;
6751   int exists;
6752 
6753   pIn1 = &aMem[pOp->p1];
6754   pIn3 = &aMem[pOp->p3];
6755   iSet = pOp->p4.i;
6756   assert( pIn3->flags&MEM_Int );
6757 
6758   /* If there is anything other than a rowset object in memory cell P1,
6759   ** delete it now and initialize P1 with an empty rowset
6760   */
6761   if( (pIn1->flags & MEM_Blob)==0 ){
6762     if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
6763   }
6764   assert( sqlite3VdbeMemIsRowSet(pIn1) );
6765   assert( pOp->p4type==P4_INT32 );
6766   assert( iSet==-1 || iSet>=0 );
6767   if( iSet ){
6768     exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i);
6769     VdbeBranchTaken(exists!=0,2);
6770     if( exists ) goto jump_to_p2;
6771   }
6772   if( iSet>=0 ){
6773     sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i);
6774   }
6775   break;
6776 }
6777 
6778 
6779 #ifndef SQLITE_OMIT_TRIGGER
6780 
6781 /* Opcode: Program P1 P2 P3 P4 P5
6782 **
6783 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
6784 **
6785 ** P1 contains the address of the memory cell that contains the first memory
6786 ** cell in an array of values used as arguments to the sub-program. P2
6787 ** contains the address to jump to if the sub-program throws an IGNORE
6788 ** exception using the RAISE() function. Register P3 contains the address
6789 ** of a memory cell in this (the parent) VM that is used to allocate the
6790 ** memory required by the sub-vdbe at runtime.
6791 **
6792 ** P4 is a pointer to the VM containing the trigger program.
6793 **
6794 ** If P5 is non-zero, then recursive program invocation is enabled.
6795 */
6796 case OP_Program: {        /* jump */
6797   int nMem;               /* Number of memory registers for sub-program */
6798   int nByte;              /* Bytes of runtime space required for sub-program */
6799   Mem *pRt;               /* Register to allocate runtime space */
6800   Mem *pMem;              /* Used to iterate through memory cells */
6801   Mem *pEnd;              /* Last memory cell in new array */
6802   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
6803   SubProgram *pProgram;   /* Sub-program to execute */
6804   void *t;                /* Token identifying trigger */
6805 
6806   pProgram = pOp->p4.pProgram;
6807   pRt = &aMem[pOp->p3];
6808   assert( pProgram->nOp>0 );
6809 
6810   /* If the p5 flag is clear, then recursive invocation of triggers is
6811   ** disabled for backwards compatibility (p5 is set if this sub-program
6812   ** is really a trigger, not a foreign key action, and the flag set
6813   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
6814   **
6815   ** It is recursive invocation of triggers, at the SQL level, that is
6816   ** disabled. In some cases a single trigger may generate more than one
6817   ** SubProgram (if the trigger may be executed with more than one different
6818   ** ON CONFLICT algorithm). SubProgram structures associated with a
6819   ** single trigger all have the same value for the SubProgram.token
6820   ** variable.  */
6821   if( pOp->p5 ){
6822     t = pProgram->token;
6823     for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
6824     if( pFrame ) break;
6825   }
6826 
6827   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
6828     rc = SQLITE_ERROR;
6829     sqlite3VdbeError(p, "too many levels of trigger recursion");
6830     goto abort_due_to_error;
6831   }
6832 
6833   /* Register pRt is used to store the memory required to save the state
6834   ** of the current program, and the memory required at runtime to execute
6835   ** the trigger program. If this trigger has been fired before, then pRt
6836   ** is already allocated. Otherwise, it must be initialized.  */
6837   if( (pRt->flags&MEM_Blob)==0 ){
6838     /* SubProgram.nMem is set to the number of memory cells used by the
6839     ** program stored in SubProgram.aOp. As well as these, one memory
6840     ** cell is required for each cursor used by the program. Set local
6841     ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
6842     */
6843     nMem = pProgram->nMem + pProgram->nCsr;
6844     assert( nMem>0 );
6845     if( pProgram->nCsr==0 ) nMem++;
6846     nByte = ROUND8(sizeof(VdbeFrame))
6847               + nMem * sizeof(Mem)
6848               + pProgram->nCsr * sizeof(VdbeCursor*)
6849               + (pProgram->nOp + 7)/8;
6850     pFrame = sqlite3DbMallocZero(db, nByte);
6851     if( !pFrame ){
6852       goto no_mem;
6853     }
6854     sqlite3VdbeMemRelease(pRt);
6855     pRt->flags = MEM_Blob|MEM_Dyn;
6856     pRt->z = (char*)pFrame;
6857     pRt->n = nByte;
6858     pRt->xDel = sqlite3VdbeFrameMemDel;
6859 
6860     pFrame->v = p;
6861     pFrame->nChildMem = nMem;
6862     pFrame->nChildCsr = pProgram->nCsr;
6863     pFrame->pc = (int)(pOp - aOp);
6864     pFrame->aMem = p->aMem;
6865     pFrame->nMem = p->nMem;
6866     pFrame->apCsr = p->apCsr;
6867     pFrame->nCursor = p->nCursor;
6868     pFrame->aOp = p->aOp;
6869     pFrame->nOp = p->nOp;
6870     pFrame->token = pProgram->token;
6871 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
6872     pFrame->anExec = p->anExec;
6873 #endif
6874 #ifdef SQLITE_DEBUG
6875     pFrame->iFrameMagic = SQLITE_FRAME_MAGIC;
6876 #endif
6877 
6878     pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
6879     for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
6880       pMem->flags = MEM_Undefined;
6881       pMem->db = db;
6882     }
6883   }else{
6884     pFrame = (VdbeFrame*)pRt->z;
6885     assert( pRt->xDel==sqlite3VdbeFrameMemDel );
6886     assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
6887         || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
6888     assert( pProgram->nCsr==pFrame->nChildCsr );
6889     assert( (int)(pOp - aOp)==pFrame->pc );
6890   }
6891 
6892   p->nFrame++;
6893   pFrame->pParent = p->pFrame;
6894   pFrame->lastRowid = db->lastRowid;
6895   pFrame->nChange = p->nChange;
6896   pFrame->nDbChange = p->db->nChange;
6897   assert( pFrame->pAuxData==0 );
6898   pFrame->pAuxData = p->pAuxData;
6899   p->pAuxData = 0;
6900   p->nChange = 0;
6901   p->pFrame = pFrame;
6902   p->aMem = aMem = VdbeFrameMem(pFrame);
6903   p->nMem = pFrame->nChildMem;
6904   p->nCursor = (u16)pFrame->nChildCsr;
6905   p->apCsr = (VdbeCursor **)&aMem[p->nMem];
6906   pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
6907   memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
6908   p->aOp = aOp = pProgram->aOp;
6909   p->nOp = pProgram->nOp;
6910 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
6911   p->anExec = 0;
6912 #endif
6913 #ifdef SQLITE_DEBUG
6914   /* Verify that second and subsequent executions of the same trigger do not
6915   ** try to reuse register values from the first use. */
6916   {
6917     int i;
6918     for(i=0; i<p->nMem; i++){
6919       aMem[i].pScopyFrom = 0;  /* Prevent false-positive AboutToChange() errs */
6920       MemSetTypeFlag(&aMem[i], MEM_Undefined); /* Fault if this reg is reused */
6921     }
6922   }
6923 #endif
6924   pOp = &aOp[-1];
6925   goto check_for_interrupt;
6926 }
6927 
6928 /* Opcode: Param P1 P2 * * *
6929 **
6930 ** This opcode is only ever present in sub-programs called via the
6931 ** OP_Program instruction. Copy a value currently stored in a memory
6932 ** cell of the calling (parent) frame to cell P2 in the current frames
6933 ** address space. This is used by trigger programs to access the new.*
6934 ** and old.* values.
6935 **
6936 ** The address of the cell in the parent frame is determined by adding
6937 ** the value of the P1 argument to the value of the P1 argument to the
6938 ** calling OP_Program instruction.
6939 */
6940 case OP_Param: {           /* out2 */
6941   VdbeFrame *pFrame;
6942   Mem *pIn;
6943   pOut = out2Prerelease(p, pOp);
6944   pFrame = p->pFrame;
6945   pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
6946   sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
6947   break;
6948 }
6949 
6950 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
6951 
6952 #ifndef SQLITE_OMIT_FOREIGN_KEY
6953 /* Opcode: FkCounter P1 P2 * * *
6954 ** Synopsis: fkctr[P1]+=P2
6955 **
6956 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
6957 ** If P1 is non-zero, the database constraint counter is incremented
6958 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
6959 ** statement counter is incremented (immediate foreign key constraints).
6960 */
6961 case OP_FkCounter: {
6962   if( db->flags & SQLITE_DeferFKs ){
6963     db->nDeferredImmCons += pOp->p2;
6964   }else if( pOp->p1 ){
6965     db->nDeferredCons += pOp->p2;
6966   }else{
6967     p->nFkConstraint += pOp->p2;
6968   }
6969   break;
6970 }
6971 
6972 /* Opcode: FkIfZero P1 P2 * * *
6973 ** Synopsis: if fkctr[P1]==0 goto P2
6974 **
6975 ** This opcode tests if a foreign key constraint-counter is currently zero.
6976 ** If so, jump to instruction P2. Otherwise, fall through to the next
6977 ** instruction.
6978 **
6979 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
6980 ** is zero (the one that counts deferred constraint violations). If P1 is
6981 ** zero, the jump is taken if the statement constraint-counter is zero
6982 ** (immediate foreign key constraint violations).
6983 */
6984 case OP_FkIfZero: {         /* jump */
6985   if( pOp->p1 ){
6986     VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
6987     if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
6988   }else{
6989     VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
6990     if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
6991   }
6992   break;
6993 }
6994 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
6995 
6996 #ifndef SQLITE_OMIT_AUTOINCREMENT
6997 /* Opcode: MemMax P1 P2 * * *
6998 ** Synopsis: r[P1]=max(r[P1],r[P2])
6999 **
7000 ** P1 is a register in the root frame of this VM (the root frame is
7001 ** different from the current frame if this instruction is being executed
7002 ** within a sub-program). Set the value of register P1 to the maximum of
7003 ** its current value and the value in register P2.
7004 **
7005 ** This instruction throws an error if the memory cell is not initially
7006 ** an integer.
7007 */
7008 case OP_MemMax: {        /* in2 */
7009   VdbeFrame *pFrame;
7010   if( p->pFrame ){
7011     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
7012     pIn1 = &pFrame->aMem[pOp->p1];
7013   }else{
7014     pIn1 = &aMem[pOp->p1];
7015   }
7016   assert( memIsValid(pIn1) );
7017   sqlite3VdbeMemIntegerify(pIn1);
7018   pIn2 = &aMem[pOp->p2];
7019   sqlite3VdbeMemIntegerify(pIn2);
7020   if( pIn1->u.i<pIn2->u.i){
7021     pIn1->u.i = pIn2->u.i;
7022   }
7023   break;
7024 }
7025 #endif /* SQLITE_OMIT_AUTOINCREMENT */
7026 
7027 /* Opcode: IfPos P1 P2 P3 * *
7028 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
7029 **
7030 ** Register P1 must contain an integer.
7031 ** If the value of register P1 is 1 or greater, subtract P3 from the
7032 ** value in P1 and jump to P2.
7033 **
7034 ** If the initial value of register P1 is less than 1, then the
7035 ** value is unchanged and control passes through to the next instruction.
7036 */
7037 case OP_IfPos: {        /* jump, in1 */
7038   pIn1 = &aMem[pOp->p1];
7039   assert( pIn1->flags&MEM_Int );
7040   VdbeBranchTaken( pIn1->u.i>0, 2);
7041   if( pIn1->u.i>0 ){
7042     pIn1->u.i -= pOp->p3;
7043     goto jump_to_p2;
7044   }
7045   break;
7046 }
7047 
7048 /* Opcode: OffsetLimit P1 P2 P3 * *
7049 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
7050 **
7051 ** This opcode performs a commonly used computation associated with
7052 ** LIMIT and OFFSET process.  r[P1] holds the limit counter.  r[P3]
7053 ** holds the offset counter.  The opcode computes the combined value
7054 ** of the LIMIT and OFFSET and stores that value in r[P2].  The r[P2]
7055 ** value computed is the total number of rows that will need to be
7056 ** visited in order to complete the query.
7057 **
7058 ** If r[P3] is zero or negative, that means there is no OFFSET
7059 ** and r[P2] is set to be the value of the LIMIT, r[P1].
7060 **
7061 ** if r[P1] is zero or negative, that means there is no LIMIT
7062 ** and r[P2] is set to -1.
7063 **
7064 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
7065 */
7066 case OP_OffsetLimit: {    /* in1, out2, in3 */
7067   i64 x;
7068   pIn1 = &aMem[pOp->p1];
7069   pIn3 = &aMem[pOp->p3];
7070   pOut = out2Prerelease(p, pOp);
7071   assert( pIn1->flags & MEM_Int );
7072   assert( pIn3->flags & MEM_Int );
7073   x = pIn1->u.i;
7074   if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
7075     /* If the LIMIT is less than or equal to zero, loop forever.  This
7076     ** is documented.  But also, if the LIMIT+OFFSET exceeds 2^63 then
7077     ** also loop forever.  This is undocumented.  In fact, one could argue
7078     ** that the loop should terminate.  But assuming 1 billion iterations
7079     ** per second (far exceeding the capabilities of any current hardware)
7080     ** it would take nearly 300 years to actually reach the limit.  So
7081     ** looping forever is a reasonable approximation. */
7082     pOut->u.i = -1;
7083   }else{
7084     pOut->u.i = x;
7085   }
7086   break;
7087 }
7088 
7089 /* Opcode: IfNotZero P1 P2 * * *
7090 ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
7091 **
7092 ** Register P1 must contain an integer.  If the content of register P1 is
7093 ** initially greater than zero, then decrement the value in register P1.
7094 ** If it is non-zero (negative or positive) and then also jump to P2.
7095 ** If register P1 is initially zero, leave it unchanged and fall through.
7096 */
7097 case OP_IfNotZero: {        /* jump, in1 */
7098   pIn1 = &aMem[pOp->p1];
7099   assert( pIn1->flags&MEM_Int );
7100   VdbeBranchTaken(pIn1->u.i<0, 2);
7101   if( pIn1->u.i ){
7102      if( pIn1->u.i>0 ) pIn1->u.i--;
7103      goto jump_to_p2;
7104   }
7105   break;
7106 }
7107 
7108 /* Opcode: DecrJumpZero P1 P2 * * *
7109 ** Synopsis: if (--r[P1])==0 goto P2
7110 **
7111 ** Register P1 must hold an integer.  Decrement the value in P1
7112 ** and jump to P2 if the new value is exactly zero.
7113 */
7114 case OP_DecrJumpZero: {      /* jump, in1 */
7115   pIn1 = &aMem[pOp->p1];
7116   assert( pIn1->flags&MEM_Int );
7117   if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
7118   VdbeBranchTaken(pIn1->u.i==0, 2);
7119   if( pIn1->u.i==0 ) goto jump_to_p2;
7120   break;
7121 }
7122 
7123 
7124 /* Opcode: AggStep * P2 P3 P4 P5
7125 ** Synopsis: accum=r[P3] step(r[P2@P5])
7126 **
7127 ** Execute the xStep function for an aggregate.
7128 ** The function has P5 arguments.  P4 is a pointer to the
7129 ** FuncDef structure that specifies the function.  Register P3 is the
7130 ** accumulator.
7131 **
7132 ** The P5 arguments are taken from register P2 and its
7133 ** successors.
7134 */
7135 /* Opcode: AggInverse * P2 P3 P4 P5
7136 ** Synopsis: accum=r[P3] inverse(r[P2@P5])
7137 **
7138 ** Execute the xInverse function for an aggregate.
7139 ** The function has P5 arguments.  P4 is a pointer to the
7140 ** FuncDef structure that specifies the function.  Register P3 is the
7141 ** accumulator.
7142 **
7143 ** The P5 arguments are taken from register P2 and its
7144 ** successors.
7145 */
7146 /* Opcode: AggStep1 P1 P2 P3 P4 P5
7147 ** Synopsis: accum=r[P3] step(r[P2@P5])
7148 **
7149 ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
7150 ** aggregate.  The function has P5 arguments.  P4 is a pointer to the
7151 ** FuncDef structure that specifies the function.  Register P3 is the
7152 ** accumulator.
7153 **
7154 ** The P5 arguments are taken from register P2 and its
7155 ** successors.
7156 **
7157 ** This opcode is initially coded as OP_AggStep0.  On first evaluation,
7158 ** the FuncDef stored in P4 is converted into an sqlite3_context and
7159 ** the opcode is changed.  In this way, the initialization of the
7160 ** sqlite3_context only happens once, instead of on each call to the
7161 ** step function.
7162 */
7163 case OP_AggInverse:
7164 case OP_AggStep: {
7165   int n;
7166   sqlite3_context *pCtx;
7167 
7168   assert( pOp->p4type==P4_FUNCDEF );
7169   n = pOp->p5;
7170   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
7171   assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
7172   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
7173   pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
7174                (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
7175   if( pCtx==0 ) goto no_mem;
7176   pCtx->pMem = 0;
7177   pCtx->pOut = (Mem*)&(pCtx->argv[n]);
7178   sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
7179   pCtx->pFunc = pOp->p4.pFunc;
7180   pCtx->iOp = (int)(pOp - aOp);
7181   pCtx->pVdbe = p;
7182   pCtx->skipFlag = 0;
7183   pCtx->isError = 0;
7184   pCtx->argc = n;
7185   pOp->p4type = P4_FUNCCTX;
7186   pOp->p4.pCtx = pCtx;
7187 
7188   /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */
7189   assert( pOp->p1==(pOp->opcode==OP_AggInverse) );
7190 
7191   pOp->opcode = OP_AggStep1;
7192   /* Fall through into OP_AggStep */
7193   /* no break */ deliberate_fall_through
7194 }
7195 case OP_AggStep1: {
7196   int i;
7197   sqlite3_context *pCtx;
7198   Mem *pMem;
7199 
7200   assert( pOp->p4type==P4_FUNCCTX );
7201   pCtx = pOp->p4.pCtx;
7202   pMem = &aMem[pOp->p3];
7203 
7204 #ifdef SQLITE_DEBUG
7205   if( pOp->p1 ){
7206     /* This is an OP_AggInverse call.  Verify that xStep has always
7207     ** been called at least once prior to any xInverse call. */
7208     assert( pMem->uTemp==0x1122e0e3 );
7209   }else{
7210     /* This is an OP_AggStep call.  Mark it as such. */
7211     pMem->uTemp = 0x1122e0e3;
7212   }
7213 #endif
7214 
7215   /* If this function is inside of a trigger, the register array in aMem[]
7216   ** might change from one evaluation to the next.  The next block of code
7217   ** checks to see if the register array has changed, and if so it
7218   ** reinitializes the relavant parts of the sqlite3_context object */
7219   if( pCtx->pMem != pMem ){
7220     pCtx->pMem = pMem;
7221     for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
7222   }
7223 
7224 #ifdef SQLITE_DEBUG
7225   for(i=0; i<pCtx->argc; i++){
7226     assert( memIsValid(pCtx->argv[i]) );
7227     REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
7228   }
7229 #endif
7230 
7231   pMem->n++;
7232   assert( pCtx->pOut->flags==MEM_Null );
7233   assert( pCtx->isError==0 );
7234   assert( pCtx->skipFlag==0 );
7235 #ifndef SQLITE_OMIT_WINDOWFUNC
7236   if( pOp->p1 ){
7237     (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv);
7238   }else
7239 #endif
7240   (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
7241 
7242   if( pCtx->isError ){
7243     if( pCtx->isError>0 ){
7244       sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
7245       rc = pCtx->isError;
7246     }
7247     if( pCtx->skipFlag ){
7248       assert( pOp[-1].opcode==OP_CollSeq );
7249       i = pOp[-1].p1;
7250       if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
7251       pCtx->skipFlag = 0;
7252     }
7253     sqlite3VdbeMemRelease(pCtx->pOut);
7254     pCtx->pOut->flags = MEM_Null;
7255     pCtx->isError = 0;
7256     if( rc ) goto abort_due_to_error;
7257   }
7258   assert( pCtx->pOut->flags==MEM_Null );
7259   assert( pCtx->skipFlag==0 );
7260   break;
7261 }
7262 
7263 /* Opcode: AggFinal P1 P2 * P4 *
7264 ** Synopsis: accum=r[P1] N=P2
7265 **
7266 ** P1 is the memory location that is the accumulator for an aggregate
7267 ** or window function.  Execute the finalizer function
7268 ** for an aggregate and store the result in P1.
7269 **
7270 ** P2 is the number of arguments that the step function takes and
7271 ** P4 is a pointer to the FuncDef for this function.  The P2
7272 ** argument is not used by this opcode.  It is only there to disambiguate
7273 ** functions that can take varying numbers of arguments.  The
7274 ** P4 argument is only needed for the case where
7275 ** the step function was not previously called.
7276 */
7277 /* Opcode: AggValue * P2 P3 P4 *
7278 ** Synopsis: r[P3]=value N=P2
7279 **
7280 ** Invoke the xValue() function and store the result in register P3.
7281 **
7282 ** P2 is the number of arguments that the step function takes and
7283 ** P4 is a pointer to the FuncDef for this function.  The P2
7284 ** argument is not used by this opcode.  It is only there to disambiguate
7285 ** functions that can take varying numbers of arguments.  The
7286 ** P4 argument is only needed for the case where
7287 ** the step function was not previously called.
7288 */
7289 case OP_AggValue:
7290 case OP_AggFinal: {
7291   Mem *pMem;
7292   assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
7293   assert( pOp->p3==0 || pOp->opcode==OP_AggValue );
7294   pMem = &aMem[pOp->p1];
7295   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
7296 #ifndef SQLITE_OMIT_WINDOWFUNC
7297   if( pOp->p3 ){
7298     memAboutToChange(p, &aMem[pOp->p3]);
7299     rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc);
7300     pMem = &aMem[pOp->p3];
7301   }else
7302 #endif
7303   {
7304     rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
7305   }
7306 
7307   if( rc ){
7308     sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
7309     goto abort_due_to_error;
7310   }
7311   sqlite3VdbeChangeEncoding(pMem, encoding);
7312   UPDATE_MAX_BLOBSIZE(pMem);
7313   if( sqlite3VdbeMemTooBig(pMem) ){
7314     goto too_big;
7315   }
7316   break;
7317 }
7318 
7319 #ifndef SQLITE_OMIT_WAL
7320 /* Opcode: Checkpoint P1 P2 P3 * *
7321 **
7322 ** Checkpoint database P1. This is a no-op if P1 is not currently in
7323 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
7324 ** RESTART, or TRUNCATE.  Write 1 or 0 into mem[P3] if the checkpoint returns
7325 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
7326 ** WAL after the checkpoint into mem[P3+1] and the number of pages
7327 ** in the WAL that have been checkpointed after the checkpoint
7328 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
7329 ** mem[P3+2] are initialized to -1.
7330 */
7331 case OP_Checkpoint: {
7332   int i;                          /* Loop counter */
7333   int aRes[3];                    /* Results */
7334   Mem *pMem;                      /* Write results here */
7335 
7336   assert( p->readOnly==0 );
7337   aRes[0] = 0;
7338   aRes[1] = aRes[2] = -1;
7339   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
7340        || pOp->p2==SQLITE_CHECKPOINT_FULL
7341        || pOp->p2==SQLITE_CHECKPOINT_RESTART
7342        || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
7343   );
7344   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
7345   if( rc ){
7346     if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
7347     rc = SQLITE_OK;
7348     aRes[0] = 1;
7349   }
7350   for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
7351     sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
7352   }
7353   break;
7354 };
7355 #endif
7356 
7357 #ifndef SQLITE_OMIT_PRAGMA
7358 /* Opcode: JournalMode P1 P2 P3 * *
7359 **
7360 ** Change the journal mode of database P1 to P3. P3 must be one of the
7361 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
7362 ** modes (delete, truncate, persist, off and memory), this is a simple
7363 ** operation. No IO is required.
7364 **
7365 ** If changing into or out of WAL mode the procedure is more complicated.
7366 **
7367 ** Write a string containing the final journal-mode to register P2.
7368 */
7369 case OP_JournalMode: {    /* out2 */
7370   Btree *pBt;                     /* Btree to change journal mode of */
7371   Pager *pPager;                  /* Pager associated with pBt */
7372   int eNew;                       /* New journal mode */
7373   int eOld;                       /* The old journal mode */
7374 #ifndef SQLITE_OMIT_WAL
7375   const char *zFilename;          /* Name of database file for pPager */
7376 #endif
7377 
7378   pOut = out2Prerelease(p, pOp);
7379   eNew = pOp->p3;
7380   assert( eNew==PAGER_JOURNALMODE_DELETE
7381        || eNew==PAGER_JOURNALMODE_TRUNCATE
7382        || eNew==PAGER_JOURNALMODE_PERSIST
7383        || eNew==PAGER_JOURNALMODE_OFF
7384        || eNew==PAGER_JOURNALMODE_MEMORY
7385        || eNew==PAGER_JOURNALMODE_WAL
7386        || eNew==PAGER_JOURNALMODE_QUERY
7387   );
7388   assert( pOp->p1>=0 && pOp->p1<db->nDb );
7389   assert( p->readOnly==0 );
7390 
7391   pBt = db->aDb[pOp->p1].pBt;
7392   pPager = sqlite3BtreePager(pBt);
7393   eOld = sqlite3PagerGetJournalMode(pPager);
7394   if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
7395   assert( sqlite3BtreeHoldsMutex(pBt) );
7396   if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
7397 
7398 #ifndef SQLITE_OMIT_WAL
7399   zFilename = sqlite3PagerFilename(pPager, 1);
7400 
7401   /* Do not allow a transition to journal_mode=WAL for a database
7402   ** in temporary storage or if the VFS does not support shared memory
7403   */
7404   if( eNew==PAGER_JOURNALMODE_WAL
7405    && (sqlite3Strlen30(zFilename)==0           /* Temp file */
7406        || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
7407   ){
7408     eNew = eOld;
7409   }
7410 
7411   if( (eNew!=eOld)
7412    && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
7413   ){
7414     if( !db->autoCommit || db->nVdbeRead>1 ){
7415       rc = SQLITE_ERROR;
7416       sqlite3VdbeError(p,
7417           "cannot change %s wal mode from within a transaction",
7418           (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
7419       );
7420       goto abort_due_to_error;
7421     }else{
7422 
7423       if( eOld==PAGER_JOURNALMODE_WAL ){
7424         /* If leaving WAL mode, close the log file. If successful, the call
7425         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
7426         ** file. An EXCLUSIVE lock may still be held on the database file
7427         ** after a successful return.
7428         */
7429         rc = sqlite3PagerCloseWal(pPager, db);
7430         if( rc==SQLITE_OK ){
7431           sqlite3PagerSetJournalMode(pPager, eNew);
7432         }
7433       }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
7434         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
7435         ** as an intermediate */
7436         sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
7437       }
7438 
7439       /* Open a transaction on the database file. Regardless of the journal
7440       ** mode, this transaction always uses a rollback journal.
7441       */
7442       assert( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE );
7443       if( rc==SQLITE_OK ){
7444         rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
7445       }
7446     }
7447   }
7448 #endif /* ifndef SQLITE_OMIT_WAL */
7449 
7450   if( rc ) eNew = eOld;
7451   eNew = sqlite3PagerSetJournalMode(pPager, eNew);
7452 
7453   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
7454   pOut->z = (char *)sqlite3JournalModename(eNew);
7455   pOut->n = sqlite3Strlen30(pOut->z);
7456   pOut->enc = SQLITE_UTF8;
7457   sqlite3VdbeChangeEncoding(pOut, encoding);
7458   if( rc ) goto abort_due_to_error;
7459   break;
7460 };
7461 #endif /* SQLITE_OMIT_PRAGMA */
7462 
7463 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
7464 /* Opcode: Vacuum P1 P2 * * *
7465 **
7466 ** Vacuum the entire database P1.  P1 is 0 for "main", and 2 or more
7467 ** for an attached database.  The "temp" database may not be vacuumed.
7468 **
7469 ** If P2 is not zero, then it is a register holding a string which is
7470 ** the file into which the result of vacuum should be written.  When
7471 ** P2 is zero, the vacuum overwrites the original database.
7472 */
7473 case OP_Vacuum: {
7474   assert( p->readOnly==0 );
7475   rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1,
7476                         pOp->p2 ? &aMem[pOp->p2] : 0);
7477   if( rc ) goto abort_due_to_error;
7478   break;
7479 }
7480 #endif
7481 
7482 #if !defined(SQLITE_OMIT_AUTOVACUUM)
7483 /* Opcode: IncrVacuum P1 P2 * * *
7484 **
7485 ** Perform a single step of the incremental vacuum procedure on
7486 ** the P1 database. If the vacuum has finished, jump to instruction
7487 ** P2. Otherwise, fall through to the next instruction.
7488 */
7489 case OP_IncrVacuum: {        /* jump */
7490   Btree *pBt;
7491 
7492   assert( pOp->p1>=0 && pOp->p1<db->nDb );
7493   assert( DbMaskTest(p->btreeMask, pOp->p1) );
7494   assert( p->readOnly==0 );
7495   pBt = db->aDb[pOp->p1].pBt;
7496   rc = sqlite3BtreeIncrVacuum(pBt);
7497   VdbeBranchTaken(rc==SQLITE_DONE,2);
7498   if( rc ){
7499     if( rc!=SQLITE_DONE ) goto abort_due_to_error;
7500     rc = SQLITE_OK;
7501     goto jump_to_p2;
7502   }
7503   break;
7504 }
7505 #endif
7506 
7507 /* Opcode: Expire P1 P2 * * *
7508 **
7509 ** Cause precompiled statements to expire.  When an expired statement
7510 ** is executed using sqlite3_step() it will either automatically
7511 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
7512 ** or it will fail with SQLITE_SCHEMA.
7513 **
7514 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
7515 ** then only the currently executing statement is expired.
7516 **
7517 ** If P2 is 0, then SQL statements are expired immediately.  If P2 is 1,
7518 ** then running SQL statements are allowed to continue to run to completion.
7519 ** The P2==1 case occurs when a CREATE INDEX or similar schema change happens
7520 ** that might help the statement run faster but which does not affect the
7521 ** correctness of operation.
7522 */
7523 case OP_Expire: {
7524   assert( pOp->p2==0 || pOp->p2==1 );
7525   if( !pOp->p1 ){
7526     sqlite3ExpirePreparedStatements(db, pOp->p2);
7527   }else{
7528     p->expired = pOp->p2+1;
7529   }
7530   break;
7531 }
7532 
7533 /* Opcode: CursorLock P1 * * * *
7534 **
7535 ** Lock the btree to which cursor P1 is pointing so that the btree cannot be
7536 ** written by an other cursor.
7537 */
7538 case OP_CursorLock: {
7539   VdbeCursor *pC;
7540   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
7541   pC = p->apCsr[pOp->p1];
7542   assert( pC!=0 );
7543   assert( pC->eCurType==CURTYPE_BTREE );
7544   sqlite3BtreeCursorPin(pC->uc.pCursor);
7545   break;
7546 }
7547 
7548 /* Opcode: CursorUnlock P1 * * * *
7549 **
7550 ** Unlock the btree to which cursor P1 is pointing so that it can be
7551 ** written by other cursors.
7552 */
7553 case OP_CursorUnlock: {
7554   VdbeCursor *pC;
7555   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
7556   pC = p->apCsr[pOp->p1];
7557   assert( pC!=0 );
7558   assert( pC->eCurType==CURTYPE_BTREE );
7559   sqlite3BtreeCursorUnpin(pC->uc.pCursor);
7560   break;
7561 }
7562 
7563 #ifndef SQLITE_OMIT_SHARED_CACHE
7564 /* Opcode: TableLock P1 P2 P3 P4 *
7565 ** Synopsis: iDb=P1 root=P2 write=P3
7566 **
7567 ** Obtain a lock on a particular table. This instruction is only used when
7568 ** the shared-cache feature is enabled.
7569 **
7570 ** P1 is the index of the database in sqlite3.aDb[] of the database
7571 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
7572 ** a write lock if P3==1.
7573 **
7574 ** P2 contains the root-page of the table to lock.
7575 **
7576 ** P4 contains a pointer to the name of the table being locked. This is only
7577 ** used to generate an error message if the lock cannot be obtained.
7578 */
7579 case OP_TableLock: {
7580   u8 isWriteLock = (u8)pOp->p3;
7581   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
7582     int p1 = pOp->p1;
7583     assert( p1>=0 && p1<db->nDb );
7584     assert( DbMaskTest(p->btreeMask, p1) );
7585     assert( isWriteLock==0 || isWriteLock==1 );
7586     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
7587     if( rc ){
7588       if( (rc&0xFF)==SQLITE_LOCKED ){
7589         const char *z = pOp->p4.z;
7590         sqlite3VdbeError(p, "database table is locked: %s", z);
7591       }
7592       goto abort_due_to_error;
7593     }
7594   }
7595   break;
7596 }
7597 #endif /* SQLITE_OMIT_SHARED_CACHE */
7598 
7599 #ifndef SQLITE_OMIT_VIRTUALTABLE
7600 /* Opcode: VBegin * * * P4 *
7601 **
7602 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
7603 ** xBegin method for that table.
7604 **
7605 ** Also, whether or not P4 is set, check that this is not being called from
7606 ** within a callback to a virtual table xSync() method. If it is, the error
7607 ** code will be set to SQLITE_LOCKED.
7608 */
7609 case OP_VBegin: {
7610   VTable *pVTab;
7611   pVTab = pOp->p4.pVtab;
7612   rc = sqlite3VtabBegin(db, pVTab);
7613   if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
7614   if( rc ) goto abort_due_to_error;
7615   break;
7616 }
7617 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7618 
7619 #ifndef SQLITE_OMIT_VIRTUALTABLE
7620 /* Opcode: VCreate P1 P2 * * *
7621 **
7622 ** P2 is a register that holds the name of a virtual table in database
7623 ** P1. Call the xCreate method for that table.
7624 */
7625 case OP_VCreate: {
7626   Mem sMem;          /* For storing the record being decoded */
7627   const char *zTab;  /* Name of the virtual table */
7628 
7629   memset(&sMem, 0, sizeof(sMem));
7630   sMem.db = db;
7631   /* Because P2 is always a static string, it is impossible for the
7632   ** sqlite3VdbeMemCopy() to fail */
7633   assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
7634   assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
7635   rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
7636   assert( rc==SQLITE_OK );
7637   zTab = (const char*)sqlite3_value_text(&sMem);
7638   assert( zTab || db->mallocFailed );
7639   if( zTab ){
7640     rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
7641   }
7642   sqlite3VdbeMemRelease(&sMem);
7643   if( rc ) goto abort_due_to_error;
7644   break;
7645 }
7646 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7647 
7648 #ifndef SQLITE_OMIT_VIRTUALTABLE
7649 /* Opcode: VDestroy P1 * * P4 *
7650 **
7651 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
7652 ** of that table.
7653 */
7654 case OP_VDestroy: {
7655   db->nVDestroy++;
7656   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
7657   db->nVDestroy--;
7658   assert( p->errorAction==OE_Abort && p->usesStmtJournal );
7659   if( rc ) goto abort_due_to_error;
7660   break;
7661 }
7662 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7663 
7664 #ifndef SQLITE_OMIT_VIRTUALTABLE
7665 /* Opcode: VOpen P1 * * P4 *
7666 **
7667 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
7668 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
7669 ** table and stores that cursor in P1.
7670 */
7671 case OP_VOpen: {
7672   VdbeCursor *pCur;
7673   sqlite3_vtab_cursor *pVCur;
7674   sqlite3_vtab *pVtab;
7675   const sqlite3_module *pModule;
7676 
7677   assert( p->bIsReader );
7678   pCur = 0;
7679   pVCur = 0;
7680   pVtab = pOp->p4.pVtab->pVtab;
7681   if( pVtab==0 || NEVER(pVtab->pModule==0) ){
7682     rc = SQLITE_LOCKED;
7683     goto abort_due_to_error;
7684   }
7685   pModule = pVtab->pModule;
7686   rc = pModule->xOpen(pVtab, &pVCur);
7687   sqlite3VtabImportErrmsg(p, pVtab);
7688   if( rc ) goto abort_due_to_error;
7689 
7690   /* Initialize sqlite3_vtab_cursor base class */
7691   pVCur->pVtab = pVtab;
7692 
7693   /* Initialize vdbe cursor object */
7694   pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
7695   if( pCur ){
7696     pCur->uc.pVCur = pVCur;
7697     pVtab->nRef++;
7698   }else{
7699     assert( db->mallocFailed );
7700     pModule->xClose(pVCur);
7701     goto no_mem;
7702   }
7703   break;
7704 }
7705 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7706 
7707 #ifndef SQLITE_OMIT_VIRTUALTABLE
7708 /* Opcode: VFilter P1 P2 P3 P4 *
7709 ** Synopsis: iplan=r[P3] zplan='P4'
7710 **
7711 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
7712 ** the filtered result set is empty.
7713 **
7714 ** P4 is either NULL or a string that was generated by the xBestIndex
7715 ** method of the module.  The interpretation of the P4 string is left
7716 ** to the module implementation.
7717 **
7718 ** This opcode invokes the xFilter method on the virtual table specified
7719 ** by P1.  The integer query plan parameter to xFilter is stored in register
7720 ** P3. Register P3+1 stores the argc parameter to be passed to the
7721 ** xFilter method. Registers P3+2..P3+1+argc are the argc
7722 ** additional parameters which are passed to
7723 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
7724 **
7725 ** A jump is made to P2 if the result set after filtering would be empty.
7726 */
7727 case OP_VFilter: {   /* jump */
7728   int nArg;
7729   int iQuery;
7730   const sqlite3_module *pModule;
7731   Mem *pQuery;
7732   Mem *pArgc;
7733   sqlite3_vtab_cursor *pVCur;
7734   sqlite3_vtab *pVtab;
7735   VdbeCursor *pCur;
7736   int res;
7737   int i;
7738   Mem **apArg;
7739 
7740   pQuery = &aMem[pOp->p3];
7741   pArgc = &pQuery[1];
7742   pCur = p->apCsr[pOp->p1];
7743   assert( memIsValid(pQuery) );
7744   REGISTER_TRACE(pOp->p3, pQuery);
7745   assert( pCur!=0 );
7746   assert( pCur->eCurType==CURTYPE_VTAB );
7747   pVCur = pCur->uc.pVCur;
7748   pVtab = pVCur->pVtab;
7749   pModule = pVtab->pModule;
7750 
7751   /* Grab the index number and argc parameters */
7752   assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
7753   nArg = (int)pArgc->u.i;
7754   iQuery = (int)pQuery->u.i;
7755 
7756   /* Invoke the xFilter method */
7757   apArg = p->apArg;
7758   for(i = 0; i<nArg; i++){
7759     apArg[i] = &pArgc[i+1];
7760   }
7761   rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
7762   sqlite3VtabImportErrmsg(p, pVtab);
7763   if( rc ) goto abort_due_to_error;
7764   res = pModule->xEof(pVCur);
7765   pCur->nullRow = 0;
7766   VdbeBranchTaken(res!=0,2);
7767   if( res ) goto jump_to_p2;
7768   break;
7769 }
7770 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7771 
7772 #ifndef SQLITE_OMIT_VIRTUALTABLE
7773 /* Opcode: VColumn P1 P2 P3 * P5
7774 ** Synopsis: r[P3]=vcolumn(P2)
7775 **
7776 ** Store in register P3 the value of the P2-th column of
7777 ** the current row of the virtual-table of cursor P1.
7778 **
7779 ** If the VColumn opcode is being used to fetch the value of
7780 ** an unchanging column during an UPDATE operation, then the P5
7781 ** value is OPFLAG_NOCHNG.  This will cause the sqlite3_vtab_nochange()
7782 ** function to return true inside the xColumn method of the virtual
7783 ** table implementation.  The P5 column might also contain other
7784 ** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are
7785 ** unused by OP_VColumn.
7786 */
7787 case OP_VColumn: {
7788   sqlite3_vtab *pVtab;
7789   const sqlite3_module *pModule;
7790   Mem *pDest;
7791   sqlite3_context sContext;
7792 
7793   VdbeCursor *pCur = p->apCsr[pOp->p1];
7794   assert( pCur!=0 );
7795   assert( pCur->eCurType==CURTYPE_VTAB );
7796   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
7797   pDest = &aMem[pOp->p3];
7798   memAboutToChange(p, pDest);
7799   if( pCur->nullRow ){
7800     sqlite3VdbeMemSetNull(pDest);
7801     break;
7802   }
7803   pVtab = pCur->uc.pVCur->pVtab;
7804   pModule = pVtab->pModule;
7805   assert( pModule->xColumn );
7806   memset(&sContext, 0, sizeof(sContext));
7807   sContext.pOut = pDest;
7808   assert( pOp->p5==OPFLAG_NOCHNG || pOp->p5==0 );
7809   if( pOp->p5 & OPFLAG_NOCHNG ){
7810     sqlite3VdbeMemSetNull(pDest);
7811     pDest->flags = MEM_Null|MEM_Zero;
7812     pDest->u.nZero = 0;
7813   }else{
7814     MemSetTypeFlag(pDest, MEM_Null);
7815   }
7816   rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
7817   sqlite3VtabImportErrmsg(p, pVtab);
7818   if( sContext.isError>0 ){
7819     sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
7820     rc = sContext.isError;
7821   }
7822   sqlite3VdbeChangeEncoding(pDest, encoding);
7823   REGISTER_TRACE(pOp->p3, pDest);
7824   UPDATE_MAX_BLOBSIZE(pDest);
7825 
7826   if( sqlite3VdbeMemTooBig(pDest) ){
7827     goto too_big;
7828   }
7829   if( rc ) goto abort_due_to_error;
7830   break;
7831 }
7832 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7833 
7834 #ifndef SQLITE_OMIT_VIRTUALTABLE
7835 /* Opcode: VNext P1 P2 * * *
7836 **
7837 ** Advance virtual table P1 to the next row in its result set and
7838 ** jump to instruction P2.  Or, if the virtual table has reached
7839 ** the end of its result set, then fall through to the next instruction.
7840 */
7841 case OP_VNext: {   /* jump */
7842   sqlite3_vtab *pVtab;
7843   const sqlite3_module *pModule;
7844   int res;
7845   VdbeCursor *pCur;
7846 
7847   pCur = p->apCsr[pOp->p1];
7848   assert( pCur!=0 );
7849   assert( pCur->eCurType==CURTYPE_VTAB );
7850   if( pCur->nullRow ){
7851     break;
7852   }
7853   pVtab = pCur->uc.pVCur->pVtab;
7854   pModule = pVtab->pModule;
7855   assert( pModule->xNext );
7856 
7857   /* Invoke the xNext() method of the module. There is no way for the
7858   ** underlying implementation to return an error if one occurs during
7859   ** xNext(). Instead, if an error occurs, true is returned (indicating that
7860   ** data is available) and the error code returned when xColumn or
7861   ** some other method is next invoked on the save virtual table cursor.
7862   */
7863   rc = pModule->xNext(pCur->uc.pVCur);
7864   sqlite3VtabImportErrmsg(p, pVtab);
7865   if( rc ) goto abort_due_to_error;
7866   res = pModule->xEof(pCur->uc.pVCur);
7867   VdbeBranchTaken(!res,2);
7868   if( !res ){
7869     /* If there is data, jump to P2 */
7870     goto jump_to_p2_and_check_for_interrupt;
7871   }
7872   goto check_for_interrupt;
7873 }
7874 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7875 
7876 #ifndef SQLITE_OMIT_VIRTUALTABLE
7877 /* Opcode: VRename P1 * * P4 *
7878 **
7879 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
7880 ** This opcode invokes the corresponding xRename method. The value
7881 ** in register P1 is passed as the zName argument to the xRename method.
7882 */
7883 case OP_VRename: {
7884   sqlite3_vtab *pVtab;
7885   Mem *pName;
7886   int isLegacy;
7887 
7888   isLegacy = (db->flags & SQLITE_LegacyAlter);
7889   db->flags |= SQLITE_LegacyAlter;
7890   pVtab = pOp->p4.pVtab->pVtab;
7891   pName = &aMem[pOp->p1];
7892   assert( pVtab->pModule->xRename );
7893   assert( memIsValid(pName) );
7894   assert( p->readOnly==0 );
7895   REGISTER_TRACE(pOp->p1, pName);
7896   assert( pName->flags & MEM_Str );
7897   testcase( pName->enc==SQLITE_UTF8 );
7898   testcase( pName->enc==SQLITE_UTF16BE );
7899   testcase( pName->enc==SQLITE_UTF16LE );
7900   rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
7901   if( rc ) goto abort_due_to_error;
7902   rc = pVtab->pModule->xRename(pVtab, pName->z);
7903   if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter;
7904   sqlite3VtabImportErrmsg(p, pVtab);
7905   p->expired = 0;
7906   if( rc ) goto abort_due_to_error;
7907   break;
7908 }
7909 #endif
7910 
7911 #ifndef SQLITE_OMIT_VIRTUALTABLE
7912 /* Opcode: VUpdate P1 P2 P3 P4 P5
7913 ** Synopsis: data=r[P3@P2]
7914 **
7915 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
7916 ** This opcode invokes the corresponding xUpdate method. P2 values
7917 ** are contiguous memory cells starting at P3 to pass to the xUpdate
7918 ** invocation. The value in register (P3+P2-1) corresponds to the
7919 ** p2th element of the argv array passed to xUpdate.
7920 **
7921 ** The xUpdate method will do a DELETE or an INSERT or both.
7922 ** The argv[0] element (which corresponds to memory cell P3)
7923 ** is the rowid of a row to delete.  If argv[0] is NULL then no
7924 ** deletion occurs.  The argv[1] element is the rowid of the new
7925 ** row.  This can be NULL to have the virtual table select the new
7926 ** rowid for itself.  The subsequent elements in the array are
7927 ** the values of columns in the new row.
7928 **
7929 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
7930 ** a row to delete.
7931 **
7932 ** P1 is a boolean flag. If it is set to true and the xUpdate call
7933 ** is successful, then the value returned by sqlite3_last_insert_rowid()
7934 ** is set to the value of the rowid for the row just inserted.
7935 **
7936 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
7937 ** apply in the case of a constraint failure on an insert or update.
7938 */
7939 case OP_VUpdate: {
7940   sqlite3_vtab *pVtab;
7941   const sqlite3_module *pModule;
7942   int nArg;
7943   int i;
7944   sqlite_int64 rowid = 0;
7945   Mem **apArg;
7946   Mem *pX;
7947 
7948   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
7949        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
7950   );
7951   assert( p->readOnly==0 );
7952   if( db->mallocFailed ) goto no_mem;
7953   sqlite3VdbeIncrWriteCounter(p, 0);
7954   pVtab = pOp->p4.pVtab->pVtab;
7955   if( pVtab==0 || NEVER(pVtab->pModule==0) ){
7956     rc = SQLITE_LOCKED;
7957     goto abort_due_to_error;
7958   }
7959   pModule = pVtab->pModule;
7960   nArg = pOp->p2;
7961   assert( pOp->p4type==P4_VTAB );
7962   if( ALWAYS(pModule->xUpdate) ){
7963     u8 vtabOnConflict = db->vtabOnConflict;
7964     apArg = p->apArg;
7965     pX = &aMem[pOp->p3];
7966     for(i=0; i<nArg; i++){
7967       assert( memIsValid(pX) );
7968       memAboutToChange(p, pX);
7969       apArg[i] = pX;
7970       pX++;
7971     }
7972     db->vtabOnConflict = pOp->p5;
7973     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
7974     db->vtabOnConflict = vtabOnConflict;
7975     sqlite3VtabImportErrmsg(p, pVtab);
7976     if( rc==SQLITE_OK && pOp->p1 ){
7977       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
7978       db->lastRowid = rowid;
7979     }
7980     if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
7981       if( pOp->p5==OE_Ignore ){
7982         rc = SQLITE_OK;
7983       }else{
7984         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
7985       }
7986     }else{
7987       p->nChange++;
7988     }
7989     if( rc ) goto abort_due_to_error;
7990   }
7991   break;
7992 }
7993 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7994 
7995 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
7996 /* Opcode: Pagecount P1 P2 * * *
7997 **
7998 ** Write the current number of pages in database P1 to memory cell P2.
7999 */
8000 case OP_Pagecount: {            /* out2 */
8001   pOut = out2Prerelease(p, pOp);
8002   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
8003   break;
8004 }
8005 #endif
8006 
8007 
8008 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
8009 /* Opcode: MaxPgcnt P1 P2 P3 * *
8010 **
8011 ** Try to set the maximum page count for database P1 to the value in P3.
8012 ** Do not let the maximum page count fall below the current page count and
8013 ** do not change the maximum page count value if P3==0.
8014 **
8015 ** Store the maximum page count after the change in register P2.
8016 */
8017 case OP_MaxPgcnt: {            /* out2 */
8018   unsigned int newMax;
8019   Btree *pBt;
8020 
8021   pOut = out2Prerelease(p, pOp);
8022   pBt = db->aDb[pOp->p1].pBt;
8023   newMax = 0;
8024   if( pOp->p3 ){
8025     newMax = sqlite3BtreeLastPage(pBt);
8026     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
8027   }
8028   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
8029   break;
8030 }
8031 #endif
8032 
8033 /* Opcode: Function P1 P2 P3 P4 *
8034 ** Synopsis: r[P3]=func(r[P2@NP])
8035 **
8036 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
8037 ** contains a pointer to the function to be run) with arguments taken
8038 ** from register P2 and successors.  The number of arguments is in
8039 ** the sqlite3_context object that P4 points to.
8040 ** The result of the function is stored
8041 ** in register P3.  Register P3 must not be one of the function inputs.
8042 **
8043 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
8044 ** function was determined to be constant at compile time. If the first
8045 ** argument was constant then bit 0 of P1 is set. This is used to determine
8046 ** whether meta data associated with a user function argument using the
8047 ** sqlite3_set_auxdata() API may be safely retained until the next
8048 ** invocation of this opcode.
8049 **
8050 ** See also: AggStep, AggFinal, PureFunc
8051 */
8052 /* Opcode: PureFunc P1 P2 P3 P4 *
8053 ** Synopsis: r[P3]=func(r[P2@NP])
8054 **
8055 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
8056 ** contains a pointer to the function to be run) with arguments taken
8057 ** from register P2 and successors.  The number of arguments is in
8058 ** the sqlite3_context object that P4 points to.
8059 ** The result of the function is stored
8060 ** in register P3.  Register P3 must not be one of the function inputs.
8061 **
8062 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
8063 ** function was determined to be constant at compile time. If the first
8064 ** argument was constant then bit 0 of P1 is set. This is used to determine
8065 ** whether meta data associated with a user function argument using the
8066 ** sqlite3_set_auxdata() API may be safely retained until the next
8067 ** invocation of this opcode.
8068 **
8069 ** This opcode works exactly like OP_Function.  The only difference is in
8070 ** its name.  This opcode is used in places where the function must be
8071 ** purely non-deterministic.  Some built-in date/time functions can be
8072 ** either determinitic of non-deterministic, depending on their arguments.
8073 ** When those function are used in a non-deterministic way, they will check
8074 ** to see if they were called using OP_PureFunc instead of OP_Function, and
8075 ** if they were, they throw an error.
8076 **
8077 ** See also: AggStep, AggFinal, Function
8078 */
8079 case OP_PureFunc:              /* group */
8080 case OP_Function: {            /* group */
8081   int i;
8082   sqlite3_context *pCtx;
8083 
8084   assert( pOp->p4type==P4_FUNCCTX );
8085   pCtx = pOp->p4.pCtx;
8086 
8087   /* If this function is inside of a trigger, the register array in aMem[]
8088   ** might change from one evaluation to the next.  The next block of code
8089   ** checks to see if the register array has changed, and if so it
8090   ** reinitializes the relavant parts of the sqlite3_context object */
8091   pOut = &aMem[pOp->p3];
8092   if( pCtx->pOut != pOut ){
8093     pCtx->pVdbe = p;
8094     pCtx->pOut = pOut;
8095     for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
8096   }
8097   assert( pCtx->pVdbe==p );
8098 
8099   memAboutToChange(p, pOut);
8100 #ifdef SQLITE_DEBUG
8101   for(i=0; i<pCtx->argc; i++){
8102     assert( memIsValid(pCtx->argv[i]) );
8103     REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
8104   }
8105 #endif
8106   MemSetTypeFlag(pOut, MEM_Null);
8107   assert( pCtx->isError==0 );
8108   (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
8109 
8110   /* If the function returned an error, throw an exception */
8111   if( pCtx->isError ){
8112     if( pCtx->isError>0 ){
8113       sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
8114       rc = pCtx->isError;
8115     }
8116     sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
8117     pCtx->isError = 0;
8118     if( rc ) goto abort_due_to_error;
8119   }
8120 
8121   /* Copy the result of the function into register P3 */
8122   if( pOut->flags & (MEM_Str|MEM_Blob) ){
8123     sqlite3VdbeChangeEncoding(pOut, encoding);
8124     if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
8125   }
8126 
8127   REGISTER_TRACE(pOp->p3, pOut);
8128   UPDATE_MAX_BLOBSIZE(pOut);
8129   break;
8130 }
8131 
8132 /* Opcode: Trace P1 P2 * P4 *
8133 **
8134 ** Write P4 on the statement trace output if statement tracing is
8135 ** enabled.
8136 **
8137 ** Operand P1 must be 0x7fffffff and P2 must positive.
8138 */
8139 /* Opcode: Init P1 P2 P3 P4 *
8140 ** Synopsis: Start at P2
8141 **
8142 ** Programs contain a single instance of this opcode as the very first
8143 ** opcode.
8144 **
8145 ** If tracing is enabled (by the sqlite3_trace()) interface, then
8146 ** the UTF-8 string contained in P4 is emitted on the trace callback.
8147 ** Or if P4 is blank, use the string returned by sqlite3_sql().
8148 **
8149 ** If P2 is not zero, jump to instruction P2.
8150 **
8151 ** Increment the value of P1 so that OP_Once opcodes will jump the
8152 ** first time they are evaluated for this run.
8153 **
8154 ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
8155 ** error is encountered.
8156 */
8157 case OP_Trace:
8158 case OP_Init: {          /* jump */
8159   int i;
8160 #ifndef SQLITE_OMIT_TRACE
8161   char *zTrace;
8162 #endif
8163 
8164   /* If the P4 argument is not NULL, then it must be an SQL comment string.
8165   ** The "--" string is broken up to prevent false-positives with srcck1.c.
8166   **
8167   ** This assert() provides evidence for:
8168   ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
8169   ** would have been returned by the legacy sqlite3_trace() interface by
8170   ** using the X argument when X begins with "--" and invoking
8171   ** sqlite3_expanded_sql(P) otherwise.
8172   */
8173   assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
8174 
8175   /* OP_Init is always instruction 0 */
8176   assert( pOp==p->aOp || pOp->opcode==OP_Trace );
8177 
8178 #ifndef SQLITE_OMIT_TRACE
8179   if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
8180    && !p->doingRerun
8181    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
8182   ){
8183 #ifndef SQLITE_OMIT_DEPRECATED
8184     if( db->mTrace & SQLITE_TRACE_LEGACY ){
8185       char *z = sqlite3VdbeExpandSql(p, zTrace);
8186       db->trace.xLegacy(db->pTraceArg, z);
8187       sqlite3_free(z);
8188     }else
8189 #endif
8190     if( db->nVdbeExec>1 ){
8191       char *z = sqlite3MPrintf(db, "-- %s", zTrace);
8192       (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
8193       sqlite3DbFree(db, z);
8194     }else{
8195       (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
8196     }
8197   }
8198 #ifdef SQLITE_USE_FCNTL_TRACE
8199   zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
8200   if( zTrace ){
8201     int j;
8202     for(j=0; j<db->nDb; j++){
8203       if( DbMaskTest(p->btreeMask, j)==0 ) continue;
8204       sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
8205     }
8206   }
8207 #endif /* SQLITE_USE_FCNTL_TRACE */
8208 #ifdef SQLITE_DEBUG
8209   if( (db->flags & SQLITE_SqlTrace)!=0
8210    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
8211   ){
8212     sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
8213   }
8214 #endif /* SQLITE_DEBUG */
8215 #endif /* SQLITE_OMIT_TRACE */
8216   assert( pOp->p2>0 );
8217   if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
8218     if( pOp->opcode==OP_Trace ) break;
8219     for(i=1; i<p->nOp; i++){
8220       if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
8221     }
8222     pOp->p1 = 0;
8223   }
8224   pOp->p1++;
8225   p->aCounter[SQLITE_STMTSTATUS_RUN]++;
8226   goto jump_to_p2;
8227 }
8228 
8229 #ifdef SQLITE_ENABLE_CURSOR_HINTS
8230 /* Opcode: CursorHint P1 * * P4 *
8231 **
8232 ** Provide a hint to cursor P1 that it only needs to return rows that
8233 ** satisfy the Expr in P4.  TK_REGISTER terms in the P4 expression refer
8234 ** to values currently held in registers.  TK_COLUMN terms in the P4
8235 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
8236 */
8237 case OP_CursorHint: {
8238   VdbeCursor *pC;
8239 
8240   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
8241   assert( pOp->p4type==P4_EXPR );
8242   pC = p->apCsr[pOp->p1];
8243   if( pC ){
8244     assert( pC->eCurType==CURTYPE_BTREE );
8245     sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
8246                            pOp->p4.pExpr, aMem);
8247   }
8248   break;
8249 }
8250 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
8251 
8252 #ifdef SQLITE_DEBUG
8253 /* Opcode:  Abortable   * * * * *
8254 **
8255 ** Verify that an Abort can happen.  Assert if an Abort at this point
8256 ** might cause database corruption.  This opcode only appears in debugging
8257 ** builds.
8258 **
8259 ** An Abort is safe if either there have been no writes, or if there is
8260 ** an active statement journal.
8261 */
8262 case OP_Abortable: {
8263   sqlite3VdbeAssertAbortable(p);
8264   break;
8265 }
8266 #endif
8267 
8268 #ifdef SQLITE_DEBUG
8269 /* Opcode:  ReleaseReg   P1 P2 P3 * P5
8270 ** Synopsis: release r[P1@P2] mask P3
8271 **
8272 ** Release registers from service.  Any content that was in the
8273 ** the registers is unreliable after this opcode completes.
8274 **
8275 ** The registers released will be the P2 registers starting at P1,
8276 ** except if bit ii of P3 set, then do not release register P1+ii.
8277 ** In other words, P3 is a mask of registers to preserve.
8278 **
8279 ** Releasing a register clears the Mem.pScopyFrom pointer.  That means
8280 ** that if the content of the released register was set using OP_SCopy,
8281 ** a change to the value of the source register for the OP_SCopy will no longer
8282 ** generate an assertion fault in sqlite3VdbeMemAboutToChange().
8283 **
8284 ** If P5 is set, then all released registers have their type set
8285 ** to MEM_Undefined so that any subsequent attempt to read the released
8286 ** register (before it is reinitialized) will generate an assertion fault.
8287 **
8288 ** P5 ought to be set on every call to this opcode.
8289 ** However, there are places in the code generator will release registers
8290 ** before their are used, under the (valid) assumption that the registers
8291 ** will not be reallocated for some other purpose before they are used and
8292 ** hence are safe to release.
8293 **
8294 ** This opcode is only available in testing and debugging builds.  It is
8295 ** not generated for release builds.  The purpose of this opcode is to help
8296 ** validate the generated bytecode.  This opcode does not actually contribute
8297 ** to computing an answer.
8298 */
8299 case OP_ReleaseReg: {
8300   Mem *pMem;
8301   int i;
8302   u32 constMask;
8303   assert( pOp->p1>0 );
8304   assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
8305   pMem = &aMem[pOp->p1];
8306   constMask = pOp->p3;
8307   for(i=0; i<pOp->p2; i++, pMem++){
8308     if( i>=32 || (constMask & MASKBIT32(i))==0 ){
8309       pMem->pScopyFrom = 0;
8310       if( i<32 && pOp->p5 ) MemSetTypeFlag(pMem, MEM_Undefined);
8311     }
8312   }
8313   break;
8314 }
8315 #endif
8316 
8317 /* Opcode: Noop * * * * *
8318 **
8319 ** Do nothing.  This instruction is often useful as a jump
8320 ** destination.
8321 */
8322 /*
8323 ** The magic Explain opcode are only inserted when explain==2 (which
8324 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
8325 ** This opcode records information from the optimizer.  It is the
8326 ** the same as a no-op.  This opcodesnever appears in a real VM program.
8327 */
8328 default: {          /* This is really OP_Noop, OP_Explain */
8329   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
8330 
8331   break;
8332 }
8333 
8334 /*****************************************************************************
8335 ** The cases of the switch statement above this line should all be indented
8336 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
8337 ** readability.  From this point on down, the normal indentation rules are
8338 ** restored.
8339 *****************************************************************************/
8340     }
8341 
8342 #ifdef VDBE_PROFILE
8343     {
8344       u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
8345       if( endTime>start ) pOrigOp->cycles += endTime - start;
8346       pOrigOp->cnt++;
8347     }
8348 #endif
8349 
8350     /* The following code adds nothing to the actual functionality
8351     ** of the program.  It is only here for testing and debugging.
8352     ** On the other hand, it does burn CPU cycles every time through
8353     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
8354     */
8355 #ifndef NDEBUG
8356     assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
8357 
8358 #ifdef SQLITE_DEBUG
8359     if( db->flags & SQLITE_VdbeTrace ){
8360       u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
8361       if( rc!=0 ) printf("rc=%d\n",rc);
8362       if( opProperty & (OPFLG_OUT2) ){
8363         registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
8364       }
8365       if( opProperty & OPFLG_OUT3 ){
8366         registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
8367       }
8368       if( opProperty==0xff ){
8369         /* Never happens.  This code exists to avoid a harmless linkage
8370         ** warning aboud sqlite3VdbeRegisterDump() being defined but not
8371         ** used. */
8372         sqlite3VdbeRegisterDump(p);
8373       }
8374     }
8375 #endif  /* SQLITE_DEBUG */
8376 #endif  /* NDEBUG */
8377   }  /* The end of the for(;;) loop the loops through opcodes */
8378 
8379   /* If we reach this point, it means that execution is finished with
8380   ** an error of some kind.
8381   */
8382 abort_due_to_error:
8383   if( db->mallocFailed ){
8384     rc = SQLITE_NOMEM_BKPT;
8385   }else if( rc==SQLITE_IOERR_CORRUPTFS ){
8386     rc = SQLITE_CORRUPT_BKPT;
8387   }
8388   assert( rc );
8389 #ifdef SQLITE_DEBUG
8390   if( db->flags & SQLITE_VdbeTrace ){
8391     const char *zTrace = p->zSql;
8392     if( zTrace==0 ){
8393       if( aOp[0].opcode==OP_Trace ){
8394         zTrace = aOp[0].p4.z;
8395       }
8396       if( zTrace==0 ) zTrace = "???";
8397     }
8398     printf("ABORT-due-to-error (rc=%d): %s\n", rc, zTrace);
8399   }
8400 #endif
8401   if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
8402     sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
8403   }
8404   p->rc = rc;
8405   sqlite3SystemError(db, rc);
8406   testcase( sqlite3GlobalConfig.xLog!=0 );
8407   sqlite3_log(rc, "statement aborts at %d: [%s] %s",
8408                    (int)(pOp - aOp), p->zSql, p->zErrMsg);
8409   sqlite3VdbeHalt(p);
8410   if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
8411   if( rc==SQLITE_CORRUPT && db->autoCommit==0 ){
8412     db->flags |= SQLITE_CorruptRdOnly;
8413   }
8414   rc = SQLITE_ERROR;
8415   if( resetSchemaOnFault>0 ){
8416     sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
8417   }
8418 
8419   /* This is the only way out of this procedure.  We have to
8420   ** release the mutexes on btrees that were acquired at the
8421   ** top. */
8422 vdbe_return:
8423 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8424   while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
8425     nProgressLimit += db->nProgressOps;
8426     if( db->xProgress(db->pProgressArg) ){
8427       nProgressLimit = LARGEST_UINT64;
8428       rc = SQLITE_INTERRUPT;
8429       goto abort_due_to_error;
8430     }
8431   }
8432 #endif
8433   p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
8434   sqlite3VdbeLeave(p);
8435   assert( rc!=SQLITE_OK || nExtraDelete==0
8436        || sqlite3_strlike("DELETE%",p->zSql,0)!=0
8437   );
8438   return rc;
8439 
8440   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
8441   ** is encountered.
8442   */
8443 too_big:
8444   sqlite3VdbeError(p, "string or blob too big");
8445   rc = SQLITE_TOOBIG;
8446   goto abort_due_to_error;
8447 
8448   /* Jump to here if a malloc() fails.
8449   */
8450 no_mem:
8451   sqlite3OomFault(db);
8452   sqlite3VdbeError(p, "out of memory");
8453   rc = SQLITE_NOMEM_BKPT;
8454   goto abort_due_to_error;
8455 
8456   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
8457   ** flag.
8458   */
8459 abort_due_to_interrupt:
8460   assert( AtomicLoad(&db->u1.isInterrupted) );
8461   rc = SQLITE_INTERRUPT;
8462   goto abort_due_to_error;
8463 }
8464