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