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