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