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