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