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