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