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