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