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