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