xref: /sqlite-3.40.0/src/vdbe.c (revision 768ab1f2)
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( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){
2646     sqlite3VdbeMemSetNull(pOut);
2647   }else{
2648     sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
2649   }
2650   break;
2651 }
2652 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
2653 
2654 /* Opcode: Column P1 P2 P3 P4 P5
2655 ** Synopsis: r[P3]=PX
2656 **
2657 ** Interpret the data that cursor P1 points to as a structure built using
2658 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
2659 ** information about the format of the data.)  Extract the P2-th column
2660 ** from this record.  If there are less that (P2+1)
2661 ** values in the record, extract a NULL.
2662 **
2663 ** The value extracted is stored in register P3.
2664 **
2665 ** If the record contains fewer than P2 fields, then extract a NULL.  Or,
2666 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
2667 ** the result.
2668 **
2669 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
2670 ** the result is guaranteed to only be used as the argument of a length()
2671 ** or typeof() function, respectively.  The loading of large blobs can be
2672 ** skipped for length() and all content loading can be skipped for typeof().
2673 */
2674 case OP_Column: {
2675   u32 p2;            /* column number to retrieve */
2676   VdbeCursor *pC;    /* The VDBE cursor */
2677   BtCursor *pCrsr;   /* The B-Tree cursor corresponding to pC */
2678   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
2679   int len;           /* The length of the serialized data for the column */
2680   int i;             /* Loop counter */
2681   Mem *pDest;        /* Where to write the extracted value */
2682   Mem sMem;          /* For storing the record being decoded */
2683   const u8 *zData;   /* Part of the record being decoded */
2684   const u8 *zHdr;    /* Next unparsed byte of the header */
2685   const u8 *zEndHdr; /* Pointer to first byte after the header */
2686   u64 offset64;      /* 64-bit offset */
2687   u32 t;             /* A type code from the record header */
2688   Mem *pReg;         /* PseudoTable input register */
2689 
2690   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2691   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
2692   pC = p->apCsr[pOp->p1];
2693   p2 = (u32)pOp->p2;
2694 
2695 op_column_restart:
2696   assert( pC!=0 );
2697   assert( p2<(u32)pC->nField );
2698   aOffset = pC->aOffset;
2699   assert( aOffset==pC->aType+pC->nField );
2700   assert( pC->eCurType!=CURTYPE_VTAB );
2701   assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
2702   assert( pC->eCurType!=CURTYPE_SORTER );
2703 
2704   if( pC->cacheStatus!=p->cacheCtr ){                /*OPTIMIZATION-IF-FALSE*/
2705     if( pC->nullRow ){
2706       if( pC->eCurType==CURTYPE_PSEUDO ){
2707         /* For the special case of as pseudo-cursor, the seekResult field
2708         ** identifies the register that holds the record */
2709         assert( pC->seekResult>0 );
2710         pReg = &aMem[pC->seekResult];
2711         assert( pReg->flags & MEM_Blob );
2712         assert( memIsValid(pReg) );
2713         pC->payloadSize = pC->szRow = pReg->n;
2714         pC->aRow = (u8*)pReg->z;
2715       }else{
2716         pDest = &aMem[pOp->p3];
2717         memAboutToChange(p, pDest);
2718         sqlite3VdbeMemSetNull(pDest);
2719         goto op_column_out;
2720       }
2721     }else{
2722       pCrsr = pC->uc.pCursor;
2723       if( pC->deferredMoveto ){
2724         u32 iMap;
2725         assert( !pC->isEphemeral );
2726         if( pC->ub.aAltMap && (iMap = pC->ub.aAltMap[1+p2])>0  ){
2727           pC = pC->pAltCursor;
2728           p2 = iMap - 1;
2729           goto op_column_restart;
2730         }
2731         rc = sqlite3VdbeFinishMoveto(pC);
2732         if( rc ) goto abort_due_to_error;
2733       }else if( sqlite3BtreeCursorHasMoved(pCrsr) ){
2734         rc = sqlite3VdbeHandleMovedCursor(pC);
2735         if( rc ) goto abort_due_to_error;
2736         goto op_column_restart;
2737       }
2738       assert( pC->eCurType==CURTYPE_BTREE );
2739       assert( pCrsr );
2740       assert( sqlite3BtreeCursorIsValid(pCrsr) );
2741       pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
2742       pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
2743       assert( pC->szRow<=pC->payloadSize );
2744       assert( pC->szRow<=65536 );  /* Maximum page size is 64KiB */
2745     }
2746     pC->cacheStatus = p->cacheCtr;
2747     pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);
2748     pC->nHdrParsed = 0;
2749 
2750     if( pC->szRow<aOffset[0] ){      /*OPTIMIZATION-IF-FALSE*/
2751       /* pC->aRow does not have to hold the entire row, but it does at least
2752       ** need to cover the header of the record.  If pC->aRow does not contain
2753       ** the complete header, then set it to zero, forcing the header to be
2754       ** dynamically allocated. */
2755       pC->aRow = 0;
2756       pC->szRow = 0;
2757 
2758       /* Make sure a corrupt database has not given us an oversize header.
2759       ** Do this now to avoid an oversize memory allocation.
2760       **
2761       ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
2762       ** types use so much data space that there can only be 4096 and 32 of
2763       ** them, respectively.  So the maximum header length results from a
2764       ** 3-byte type for each of the maximum of 32768 columns plus three
2765       ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
2766       */
2767       if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
2768         goto op_column_corrupt;
2769       }
2770     }else{
2771       /* This is an optimization.  By skipping over the first few tests
2772       ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
2773       ** measurable performance gain.
2774       **
2775       ** This branch is taken even if aOffset[0]==0.  Such a record is never
2776       ** generated by SQLite, and could be considered corruption, but we
2777       ** accept it for historical reasons.  When aOffset[0]==0, the code this
2778       ** branch jumps to reads past the end of the record, but never more
2779       ** than a few bytes.  Even if the record occurs at the end of the page
2780       ** content area, the "page header" comes after the page content and so
2781       ** this overread is harmless.  Similar overreads can occur for a corrupt
2782       ** database file.
2783       */
2784       zData = pC->aRow;
2785       assert( pC->nHdrParsed<=p2 );         /* Conditional skipped */
2786       testcase( aOffset[0]==0 );
2787       goto op_column_read_header;
2788     }
2789   }else if( sqlite3BtreeCursorHasMoved(pC->uc.pCursor) ){
2790     rc = sqlite3VdbeHandleMovedCursor(pC);
2791     if( rc ) goto abort_due_to_error;
2792     goto op_column_restart;
2793   }
2794 
2795   /* Make sure at least the first p2+1 entries of the header have been
2796   ** parsed and valid information is in aOffset[] and pC->aType[].
2797   */
2798   if( pC->nHdrParsed<=p2 ){
2799     /* If there is more header available for parsing in the record, try
2800     ** to extract additional fields up through the p2+1-th field
2801     */
2802     if( pC->iHdrOffset<aOffset[0] ){
2803       /* Make sure zData points to enough of the record to cover the header. */
2804       if( pC->aRow==0 ){
2805         memset(&sMem, 0, sizeof(sMem));
2806         rc = sqlite3VdbeMemFromBtreeZeroOffset(pC->uc.pCursor,aOffset[0],&sMem);
2807         if( rc!=SQLITE_OK ) goto abort_due_to_error;
2808         zData = (u8*)sMem.z;
2809       }else{
2810         zData = pC->aRow;
2811       }
2812 
2813       /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
2814     op_column_read_header:
2815       i = pC->nHdrParsed;
2816       offset64 = aOffset[i];
2817       zHdr = zData + pC->iHdrOffset;
2818       zEndHdr = zData + aOffset[0];
2819       testcase( zHdr>=zEndHdr );
2820       do{
2821         if( (pC->aType[i] = t = zHdr[0])<0x80 ){
2822           zHdr++;
2823           offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
2824         }else{
2825           zHdr += sqlite3GetVarint32(zHdr, &t);
2826           pC->aType[i] = t;
2827           offset64 += sqlite3VdbeSerialTypeLen(t);
2828         }
2829         aOffset[++i] = (u32)(offset64 & 0xffffffff);
2830       }while( (u32)i<=p2 && zHdr<zEndHdr );
2831 
2832       /* The record is corrupt if any of the following are true:
2833       ** (1) the bytes of the header extend past the declared header size
2834       ** (2) the entire header was used but not all data was used
2835       ** (3) the end of the data extends beyond the end of the record.
2836       */
2837       if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
2838        || (offset64 > pC->payloadSize)
2839       ){
2840         if( aOffset[0]==0 ){
2841           i = 0;
2842           zHdr = zEndHdr;
2843         }else{
2844           if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
2845           goto op_column_corrupt;
2846         }
2847       }
2848 
2849       pC->nHdrParsed = i;
2850       pC->iHdrOffset = (u32)(zHdr - zData);
2851       if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
2852     }else{
2853       t = 0;
2854     }
2855 
2856     /* If after trying to extract new entries from the header, nHdrParsed is
2857     ** still not up to p2, that means that the record has fewer than p2
2858     ** columns.  So the result will be either the default value or a NULL.
2859     */
2860     if( pC->nHdrParsed<=p2 ){
2861       pDest = &aMem[pOp->p3];
2862       memAboutToChange(p, pDest);
2863       if( pOp->p4type==P4_MEM ){
2864         sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
2865       }else{
2866         sqlite3VdbeMemSetNull(pDest);
2867       }
2868       goto op_column_out;
2869     }
2870   }else{
2871     t = pC->aType[p2];
2872   }
2873 
2874   /* Extract the content for the p2+1-th column.  Control can only
2875   ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
2876   ** all valid.
2877   */
2878   assert( p2<pC->nHdrParsed );
2879   assert( rc==SQLITE_OK );
2880   pDest = &aMem[pOp->p3];
2881   memAboutToChange(p, pDest);
2882   assert( sqlite3VdbeCheckMemInvariants(pDest) );
2883   if( VdbeMemDynamic(pDest) ){
2884     sqlite3VdbeMemSetNull(pDest);
2885   }
2886   assert( t==pC->aType[p2] );
2887   if( pC->szRow>=aOffset[p2+1] ){
2888     /* This is the common case where the desired content fits on the original
2889     ** page - where the content is not on an overflow page */
2890     zData = pC->aRow + aOffset[p2];
2891     if( t<12 ){
2892       sqlite3VdbeSerialGet(zData, t, pDest);
2893     }else{
2894       /* If the column value is a string, we need a persistent value, not
2895       ** a MEM_Ephem value.  This branch is a fast short-cut that is equivalent
2896       ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
2897       */
2898       static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
2899       pDest->n = len = (t-12)/2;
2900       pDest->enc = encoding;
2901       if( pDest->szMalloc < len+2 ){
2902         if( len>db->aLimit[SQLITE_LIMIT_LENGTH] ) goto too_big;
2903         pDest->flags = MEM_Null;
2904         if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
2905       }else{
2906         pDest->z = pDest->zMalloc;
2907       }
2908       memcpy(pDest->z, zData, len);
2909       pDest->z[len] = 0;
2910       pDest->z[len+1] = 0;
2911       pDest->flags = aFlag[t&1];
2912     }
2913   }else{
2914     pDest->enc = encoding;
2915     /* This branch happens only when content is on overflow pages */
2916     if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
2917           && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
2918      || (len = sqlite3VdbeSerialTypeLen(t))==0
2919     ){
2920       /* Content is irrelevant for
2921       **    1. the typeof() function,
2922       **    2. the length(X) function if X is a blob, and
2923       **    3. if the content length is zero.
2924       ** So we might as well use bogus content rather than reading
2925       ** content from disk.
2926       **
2927       ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
2928       ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
2929       ** read more.  Use the global constant sqlite3CtypeMap[] as the array,
2930       ** as that array is 256 bytes long (plenty for VdbeMemPrettyPrint())
2931       ** and it begins with a bunch of zeros.
2932       */
2933       sqlite3VdbeSerialGet((u8*)sqlite3CtypeMap, t, pDest);
2934     }else{
2935       if( len>db->aLimit[SQLITE_LIMIT_LENGTH] ) goto too_big;
2936       rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
2937       if( rc!=SQLITE_OK ) goto abort_due_to_error;
2938       sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
2939       pDest->flags &= ~MEM_Ephem;
2940     }
2941   }
2942 
2943 op_column_out:
2944   UPDATE_MAX_BLOBSIZE(pDest);
2945   REGISTER_TRACE(pOp->p3, pDest);
2946   break;
2947 
2948 op_column_corrupt:
2949   if( aOp[0].p3>0 ){
2950     pOp = &aOp[aOp[0].p3-1];
2951     break;
2952   }else{
2953     rc = SQLITE_CORRUPT_BKPT;
2954     goto abort_due_to_error;
2955   }
2956 }
2957 
2958 /* Opcode: TypeCheck P1 P2 P3 P4 *
2959 ** Synopsis: typecheck(r[P1@P2])
2960 **
2961 ** Apply affinities to the range of P2 registers beginning with P1.
2962 ** Take the affinities from the Table object in P4.  If any value
2963 ** cannot be coerced into the correct type, then raise an error.
2964 **
2965 ** This opcode is similar to OP_Affinity except that this opcode
2966 ** forces the register type to the Table column type.  This is used
2967 ** to implement "strict affinity".
2968 **
2969 ** GENERATED ALWAYS AS ... STATIC columns are only checked if P3
2970 ** is zero.  When P3 is non-zero, no type checking occurs for
2971 ** static generated columns.  Virtual columns are computed at query time
2972 ** and so they are never checked.
2973 **
2974 ** Preconditions:
2975 **
2976 ** <ul>
2977 ** <li> P2 should be the number of non-virtual columns in the
2978 **      table of P4.
2979 ** <li> Table P4 should be a STRICT table.
2980 ** </ul>
2981 **
2982 ** If any precondition is false, an assertion fault occurs.
2983 */
2984 case OP_TypeCheck: {
2985   Table *pTab;
2986   Column *aCol;
2987   int i;
2988 
2989   assert( pOp->p4type==P4_TABLE );
2990   pTab = pOp->p4.pTab;
2991   assert( pTab->tabFlags & TF_Strict );
2992   assert( pTab->nNVCol==pOp->p2 );
2993   aCol = pTab->aCol;
2994   pIn1 = &aMem[pOp->p1];
2995   for(i=0; i<pTab->nCol; i++){
2996     if( aCol[i].colFlags & COLFLAG_GENERATED ){
2997       if( aCol[i].colFlags & COLFLAG_VIRTUAL ) continue;
2998       if( pOp->p3 ){ pIn1++; continue; }
2999     }
3000     assert( pIn1 < &aMem[pOp->p1+pOp->p2] );
3001     applyAffinity(pIn1, aCol[i].affinity, encoding);
3002     if( (pIn1->flags & MEM_Null)==0 ){
3003       switch( aCol[i].eCType ){
3004         case COLTYPE_BLOB: {
3005           if( (pIn1->flags & MEM_Blob)==0 ) goto vdbe_type_error;
3006           break;
3007         }
3008         case COLTYPE_INTEGER:
3009         case COLTYPE_INT: {
3010           if( (pIn1->flags & MEM_Int)==0 ) goto vdbe_type_error;
3011           break;
3012         }
3013         case COLTYPE_TEXT: {
3014           if( (pIn1->flags & MEM_Str)==0 ) goto vdbe_type_error;
3015           break;
3016         }
3017         case COLTYPE_REAL: {
3018           testcase( (pIn1->flags & (MEM_Real|MEM_IntReal))==MEM_Real );
3019           testcase( (pIn1->flags & (MEM_Real|MEM_IntReal))==MEM_IntReal );
3020           if( pIn1->flags & MEM_Int ){
3021             /* When applying REAL affinity, if the result is still an MEM_Int
3022             ** that will fit in 6 bytes, then change the type to MEM_IntReal
3023             ** so that we keep the high-resolution integer value but know that
3024             ** the type really wants to be REAL. */
3025             testcase( pIn1->u.i==140737488355328LL );
3026             testcase( pIn1->u.i==140737488355327LL );
3027             testcase( pIn1->u.i==-140737488355328LL );
3028             testcase( pIn1->u.i==-140737488355329LL );
3029             if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL){
3030               pIn1->flags |= MEM_IntReal;
3031               pIn1->flags &= ~MEM_Int;
3032             }else{
3033               pIn1->u.r = (double)pIn1->u.i;
3034               pIn1->flags |= MEM_Real;
3035               pIn1->flags &= ~MEM_Int;
3036             }
3037           }else if( (pIn1->flags & (MEM_Real|MEM_IntReal))==0 ){
3038             goto vdbe_type_error;
3039           }
3040           break;
3041         }
3042         default: {
3043           /* COLTYPE_ANY.  Accept anything. */
3044           break;
3045         }
3046       }
3047     }
3048     REGISTER_TRACE((int)(pIn1-aMem), pIn1);
3049     pIn1++;
3050   }
3051   assert( pIn1 == &aMem[pOp->p1+pOp->p2] );
3052   break;
3053 
3054 vdbe_type_error:
3055   sqlite3VdbeError(p, "cannot store %s value in %s column %s.%s",
3056      vdbeMemTypeName(pIn1), sqlite3StdType[aCol[i].eCType-1],
3057      pTab->zName, aCol[i].zCnName);
3058   rc = SQLITE_CONSTRAINT_DATATYPE;
3059   goto abort_due_to_error;
3060 }
3061 
3062 /* Opcode: Affinity P1 P2 * P4 *
3063 ** Synopsis: affinity(r[P1@P2])
3064 **
3065 ** Apply affinities to a range of P2 registers starting with P1.
3066 **
3067 ** P4 is a string that is P2 characters long. The N-th character of the
3068 ** string indicates the column affinity that should be used for the N-th
3069 ** memory cell in the range.
3070 */
3071 case OP_Affinity: {
3072   const char *zAffinity;   /* The affinity to be applied */
3073 
3074   zAffinity = pOp->p4.z;
3075   assert( zAffinity!=0 );
3076   assert( pOp->p2>0 );
3077   assert( zAffinity[pOp->p2]==0 );
3078   pIn1 = &aMem[pOp->p1];
3079   while( 1 /*exit-by-break*/ ){
3080     assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
3081     assert( zAffinity[0]==SQLITE_AFF_NONE || memIsValid(pIn1) );
3082     applyAffinity(pIn1, zAffinity[0], encoding);
3083     if( zAffinity[0]==SQLITE_AFF_REAL && (pIn1->flags & MEM_Int)!=0 ){
3084       /* When applying REAL affinity, if the result is still an MEM_Int
3085       ** that will fit in 6 bytes, then change the type to MEM_IntReal
3086       ** so that we keep the high-resolution integer value but know that
3087       ** the type really wants to be REAL. */
3088       testcase( pIn1->u.i==140737488355328LL );
3089       testcase( pIn1->u.i==140737488355327LL );
3090       testcase( pIn1->u.i==-140737488355328LL );
3091       testcase( pIn1->u.i==-140737488355329LL );
3092       if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL ){
3093         pIn1->flags |= MEM_IntReal;
3094         pIn1->flags &= ~MEM_Int;
3095       }else{
3096         pIn1->u.r = (double)pIn1->u.i;
3097         pIn1->flags |= MEM_Real;
3098         pIn1->flags &= ~MEM_Int;
3099       }
3100     }
3101     REGISTER_TRACE((int)(pIn1-aMem), pIn1);
3102     zAffinity++;
3103     if( zAffinity[0]==0 ) break;
3104     pIn1++;
3105   }
3106   break;
3107 }
3108 
3109 /* Opcode: MakeRecord P1 P2 P3 P4 *
3110 ** Synopsis: r[P3]=mkrec(r[P1@P2])
3111 **
3112 ** Convert P2 registers beginning with P1 into the [record format]
3113 ** use as a data record in a database table or as a key
3114 ** in an index.  The OP_Column opcode can decode the record later.
3115 **
3116 ** P4 may be a string that is P2 characters long.  The N-th character of the
3117 ** string indicates the column affinity that should be used for the N-th
3118 ** field of the index key.
3119 **
3120 ** The mapping from character to affinity is given by the SQLITE_AFF_
3121 ** macros defined in sqliteInt.h.
3122 **
3123 ** If P4 is NULL then all index fields have the affinity BLOB.
3124 **
3125 ** The meaning of P5 depends on whether or not the SQLITE_ENABLE_NULL_TRIM
3126 ** compile-time option is enabled:
3127 **
3128 **   * If SQLITE_ENABLE_NULL_TRIM is enabled, then the P5 is the index
3129 **     of the right-most table that can be null-trimmed.
3130 **
3131 **   * If SQLITE_ENABLE_NULL_TRIM is omitted, then P5 has the value
3132 **     OPFLAG_NOCHNG_MAGIC if the OP_MakeRecord opcode is allowed to
3133 **     accept no-change records with serial_type 10.  This value is
3134 **     only used inside an assert() and does not affect the end result.
3135 */
3136 case OP_MakeRecord: {
3137   Mem *pRec;             /* The new record */
3138   u64 nData;             /* Number of bytes of data space */
3139   int nHdr;              /* Number of bytes of header space */
3140   i64 nByte;             /* Data space required for this record */
3141   i64 nZero;             /* Number of zero bytes at the end of the record */
3142   int nVarint;           /* Number of bytes in a varint */
3143   u32 serial_type;       /* Type field */
3144   Mem *pData0;           /* First field to be combined into the record */
3145   Mem *pLast;            /* Last field of the record */
3146   int nField;            /* Number of fields in the record */
3147   char *zAffinity;       /* The affinity string for the record */
3148   u32 len;               /* Length of a field */
3149   u8 *zHdr;              /* Where to write next byte of the header */
3150   u8 *zPayload;          /* Where to write next byte of the payload */
3151 
3152   /* Assuming the record contains N fields, the record format looks
3153   ** like this:
3154   **
3155   ** ------------------------------------------------------------------------
3156   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
3157   ** ------------------------------------------------------------------------
3158   **
3159   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
3160   ** and so forth.
3161   **
3162   ** Each type field is a varint representing the serial type of the
3163   ** corresponding data element (see sqlite3VdbeSerialType()). The
3164   ** hdr-size field is also a varint which is the offset from the beginning
3165   ** of the record to data0.
3166   */
3167   nData = 0;         /* Number of bytes of data space */
3168   nHdr = 0;          /* Number of bytes of header space */
3169   nZero = 0;         /* Number of zero bytes at the end of the record */
3170   nField = pOp->p1;
3171   zAffinity = pOp->p4.z;
3172   assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
3173   pData0 = &aMem[nField];
3174   nField = pOp->p2;
3175   pLast = &pData0[nField-1];
3176 
3177   /* Identify the output register */
3178   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
3179   pOut = &aMem[pOp->p3];
3180   memAboutToChange(p, pOut);
3181 
3182   /* Apply the requested affinity to all inputs
3183   */
3184   assert( pData0<=pLast );
3185   if( zAffinity ){
3186     pRec = pData0;
3187     do{
3188       applyAffinity(pRec, zAffinity[0], encoding);
3189       if( zAffinity[0]==SQLITE_AFF_REAL && (pRec->flags & MEM_Int) ){
3190         pRec->flags |= MEM_IntReal;
3191         pRec->flags &= ~(MEM_Int);
3192       }
3193       REGISTER_TRACE((int)(pRec-aMem), pRec);
3194       zAffinity++;
3195       pRec++;
3196       assert( zAffinity[0]==0 || pRec<=pLast );
3197     }while( zAffinity[0] );
3198   }
3199 
3200 #ifdef SQLITE_ENABLE_NULL_TRIM
3201   /* NULLs can be safely trimmed from the end of the record, as long as
3202   ** as the schema format is 2 or more and none of the omitted columns
3203   ** have a non-NULL default value.  Also, the record must be left with
3204   ** at least one field.  If P5>0 then it will be one more than the
3205   ** index of the right-most column with a non-NULL default value */
3206   if( pOp->p5 ){
3207     while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
3208       pLast--;
3209       nField--;
3210     }
3211   }
3212 #endif
3213 
3214   /* Loop through the elements that will make up the record to figure
3215   ** out how much space is required for the new record.  After this loop,
3216   ** the Mem.uTemp field of each term should hold the serial-type that will
3217   ** be used for that term in the generated record:
3218   **
3219   **   Mem.uTemp value    type
3220   **   ---------------    ---------------
3221   **      0               NULL
3222   **      1               1-byte signed integer
3223   **      2               2-byte signed integer
3224   **      3               3-byte signed integer
3225   **      4               4-byte signed integer
3226   **      5               6-byte signed integer
3227   **      6               8-byte signed integer
3228   **      7               IEEE float
3229   **      8               Integer constant 0
3230   **      9               Integer constant 1
3231   **     10,11            reserved for expansion
3232   **    N>=12 and even    BLOB
3233   **    N>=13 and odd     text
3234   **
3235   ** The following additional values are computed:
3236   **     nHdr        Number of bytes needed for the record header
3237   **     nData       Number of bytes of data space needed for the record
3238   **     nZero       Zero bytes at the end of the record
3239   */
3240   pRec = pLast;
3241   do{
3242     assert( memIsValid(pRec) );
3243     if( pRec->flags & MEM_Null ){
3244       if( pRec->flags & MEM_Zero ){
3245         /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
3246         ** table methods that never invoke sqlite3_result_xxxxx() while
3247         ** computing an unchanging column value in an UPDATE statement.
3248         ** Give such values a special internal-use-only serial-type of 10
3249         ** so that they can be passed through to xUpdate and have
3250         ** a true sqlite3_value_nochange(). */
3251 #ifndef SQLITE_ENABLE_NULL_TRIM
3252         assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
3253 #endif
3254         pRec->uTemp = 10;
3255       }else{
3256         pRec->uTemp = 0;
3257       }
3258       nHdr++;
3259     }else if( pRec->flags & (MEM_Int|MEM_IntReal) ){
3260       /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
3261       i64 i = pRec->u.i;
3262       u64 uu;
3263       testcase( pRec->flags & MEM_Int );
3264       testcase( pRec->flags & MEM_IntReal );
3265       if( i<0 ){
3266         uu = ~i;
3267       }else{
3268         uu = i;
3269       }
3270       nHdr++;
3271       testcase( uu==127 );               testcase( uu==128 );
3272       testcase( uu==32767 );             testcase( uu==32768 );
3273       testcase( uu==8388607 );           testcase( uu==8388608 );
3274       testcase( uu==2147483647 );        testcase( uu==2147483648LL );
3275       testcase( uu==140737488355327LL ); testcase( uu==140737488355328LL );
3276       if( uu<=127 ){
3277         if( (i&1)==i && p->minWriteFileFormat>=4 ){
3278           pRec->uTemp = 8+(u32)uu;
3279         }else{
3280           nData++;
3281           pRec->uTemp = 1;
3282         }
3283       }else if( uu<=32767 ){
3284         nData += 2;
3285         pRec->uTemp = 2;
3286       }else if( uu<=8388607 ){
3287         nData += 3;
3288         pRec->uTemp = 3;
3289       }else if( uu<=2147483647 ){
3290         nData += 4;
3291         pRec->uTemp = 4;
3292       }else if( uu<=140737488355327LL ){
3293         nData += 6;
3294         pRec->uTemp = 5;
3295       }else{
3296         nData += 8;
3297         if( pRec->flags & MEM_IntReal ){
3298           /* If the value is IntReal and is going to take up 8 bytes to store
3299           ** as an integer, then we might as well make it an 8-byte floating
3300           ** point value */
3301           pRec->u.r = (double)pRec->u.i;
3302           pRec->flags &= ~MEM_IntReal;
3303           pRec->flags |= MEM_Real;
3304           pRec->uTemp = 7;
3305         }else{
3306           pRec->uTemp = 6;
3307         }
3308       }
3309     }else if( pRec->flags & MEM_Real ){
3310       nHdr++;
3311       nData += 8;
3312       pRec->uTemp = 7;
3313     }else{
3314       assert( db->mallocFailed || pRec->flags&(MEM_Str|MEM_Blob) );
3315       assert( pRec->n>=0 );
3316       len = (u32)pRec->n;
3317       serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0);
3318       if( pRec->flags & MEM_Zero ){
3319         serial_type += pRec->u.nZero*2;
3320         if( nData ){
3321           if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
3322           len += pRec->u.nZero;
3323         }else{
3324           nZero += pRec->u.nZero;
3325         }
3326       }
3327       nData += len;
3328       nHdr += sqlite3VarintLen(serial_type);
3329       pRec->uTemp = serial_type;
3330     }
3331     if( pRec==pData0 ) break;
3332     pRec--;
3333   }while(1);
3334 
3335   /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
3336   ** which determines the total number of bytes in the header. The varint
3337   ** value is the size of the header in bytes including the size varint
3338   ** itself. */
3339   testcase( nHdr==126 );
3340   testcase( nHdr==127 );
3341   if( nHdr<=126 ){
3342     /* The common case */
3343     nHdr += 1;
3344   }else{
3345     /* Rare case of a really large header */
3346     nVarint = sqlite3VarintLen(nHdr);
3347     nHdr += nVarint;
3348     if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
3349   }
3350   nByte = nHdr+nData;
3351 
3352   /* Make sure the output register has a buffer large enough to store
3353   ** the new record. The output register (pOp->p3) is not allowed to
3354   ** be one of the input registers (because the following call to
3355   ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
3356   */
3357   if( nByte+nZero<=pOut->szMalloc ){
3358     /* The output register is already large enough to hold the record.
3359     ** No error checks or buffer enlargement is required */
3360     pOut->z = pOut->zMalloc;
3361   }else{
3362     /* Need to make sure that the output is not too big and then enlarge
3363     ** the output register to hold the full result */
3364     if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
3365       goto too_big;
3366     }
3367     if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
3368       goto no_mem;
3369     }
3370   }
3371   pOut->n = (int)nByte;
3372   pOut->flags = MEM_Blob;
3373   if( nZero ){
3374     pOut->u.nZero = nZero;
3375     pOut->flags |= MEM_Zero;
3376   }
3377   UPDATE_MAX_BLOBSIZE(pOut);
3378   zHdr = (u8 *)pOut->z;
3379   zPayload = zHdr + nHdr;
3380 
3381   /* Write the record */
3382   zHdr += putVarint32(zHdr, nHdr);
3383   assert( pData0<=pLast );
3384   pRec = pData0;
3385   do{
3386     serial_type = pRec->uTemp;
3387     /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
3388     ** additional varints, one per column. */
3389     zHdr += putVarint32(zHdr, serial_type);            /* serial type */
3390     /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
3391     ** immediately follow the header. */
3392     zPayload += sqlite3VdbeSerialPut(zPayload, pRec, serial_type); /* content */
3393   }while( (++pRec)<=pLast );
3394   assert( nHdr==(int)(zHdr - (u8*)pOut->z) );
3395   assert( nByte==(int)(zPayload - (u8*)pOut->z) );
3396 
3397   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
3398   REGISTER_TRACE(pOp->p3, pOut);
3399   break;
3400 }
3401 
3402 /* Opcode: Count P1 P2 P3 * *
3403 ** Synopsis: r[P2]=count()
3404 **
3405 ** Store the number of entries (an integer value) in the table or index
3406 ** opened by cursor P1 in register P2.
3407 **
3408 ** If P3==0, then an exact count is obtained, which involves visiting
3409 ** every btree page of the table.  But if P3 is non-zero, an estimate
3410 ** is returned based on the current cursor position.
3411 */
3412 case OP_Count: {         /* out2 */
3413   i64 nEntry;
3414   BtCursor *pCrsr;
3415 
3416   assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
3417   pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
3418   assert( pCrsr );
3419   if( pOp->p3 ){
3420     nEntry = sqlite3BtreeRowCountEst(pCrsr);
3421   }else{
3422     nEntry = 0;  /* Not needed.  Only used to silence a warning. */
3423     rc = sqlite3BtreeCount(db, pCrsr, &nEntry);
3424     if( rc ) goto abort_due_to_error;
3425   }
3426   pOut = out2Prerelease(p, pOp);
3427   pOut->u.i = nEntry;
3428   goto check_for_interrupt;
3429 }
3430 
3431 /* Opcode: Savepoint P1 * * P4 *
3432 **
3433 ** Open, release or rollback the savepoint named by parameter P4, depending
3434 ** on the value of P1. To open a new savepoint set P1==0 (SAVEPOINT_BEGIN).
3435 ** To release (commit) an existing savepoint set P1==1 (SAVEPOINT_RELEASE).
3436 ** To rollback an existing savepoint set P1==2 (SAVEPOINT_ROLLBACK).
3437 */
3438 case OP_Savepoint: {
3439   int p1;                         /* Value of P1 operand */
3440   char *zName;                    /* Name of savepoint */
3441   int nName;
3442   Savepoint *pNew;
3443   Savepoint *pSavepoint;
3444   Savepoint *pTmp;
3445   int iSavepoint;
3446   int ii;
3447 
3448   p1 = pOp->p1;
3449   zName = pOp->p4.z;
3450 
3451   /* Assert that the p1 parameter is valid. Also that if there is no open
3452   ** transaction, then there cannot be any savepoints.
3453   */
3454   assert( db->pSavepoint==0 || db->autoCommit==0 );
3455   assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
3456   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
3457   assert( checkSavepointCount(db) );
3458   assert( p->bIsReader );
3459 
3460   if( p1==SAVEPOINT_BEGIN ){
3461     if( db->nVdbeWrite>0 ){
3462       /* A new savepoint cannot be created if there are active write
3463       ** statements (i.e. open read/write incremental blob handles).
3464       */
3465       sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
3466       rc = SQLITE_BUSY;
3467     }else{
3468       nName = sqlite3Strlen30(zName);
3469 
3470 #ifndef SQLITE_OMIT_VIRTUALTABLE
3471       /* This call is Ok even if this savepoint is actually a transaction
3472       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
3473       ** If this is a transaction savepoint being opened, it is guaranteed
3474       ** that the db->aVTrans[] array is empty.  */
3475       assert( db->autoCommit==0 || db->nVTrans==0 );
3476       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
3477                                 db->nStatement+db->nSavepoint);
3478       if( rc!=SQLITE_OK ) goto abort_due_to_error;
3479 #endif
3480 
3481       /* Create a new savepoint structure. */
3482       pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
3483       if( pNew ){
3484         pNew->zName = (char *)&pNew[1];
3485         memcpy(pNew->zName, zName, nName+1);
3486 
3487         /* If there is no open transaction, then mark this as a special
3488         ** "transaction savepoint". */
3489         if( db->autoCommit ){
3490           db->autoCommit = 0;
3491           db->isTransactionSavepoint = 1;
3492         }else{
3493           db->nSavepoint++;
3494         }
3495 
3496         /* Link the new savepoint into the database handle's list. */
3497         pNew->pNext = db->pSavepoint;
3498         db->pSavepoint = pNew;
3499         pNew->nDeferredCons = db->nDeferredCons;
3500         pNew->nDeferredImmCons = db->nDeferredImmCons;
3501       }
3502     }
3503   }else{
3504     assert( p1==SAVEPOINT_RELEASE || p1==SAVEPOINT_ROLLBACK );
3505     iSavepoint = 0;
3506 
3507     /* Find the named savepoint. If there is no such savepoint, then an
3508     ** an error is returned to the user.  */
3509     for(
3510       pSavepoint = db->pSavepoint;
3511       pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
3512       pSavepoint = pSavepoint->pNext
3513     ){
3514       iSavepoint++;
3515     }
3516     if( !pSavepoint ){
3517       sqlite3VdbeError(p, "no such savepoint: %s", zName);
3518       rc = SQLITE_ERROR;
3519     }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
3520       /* It is not possible to release (commit) a savepoint if there are
3521       ** active write statements.
3522       */
3523       sqlite3VdbeError(p, "cannot release savepoint - "
3524                           "SQL statements in progress");
3525       rc = SQLITE_BUSY;
3526     }else{
3527 
3528       /* Determine whether or not this is a transaction savepoint. If so,
3529       ** and this is a RELEASE command, then the current transaction
3530       ** is committed.
3531       */
3532       int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
3533       if( isTransaction && p1==SAVEPOINT_RELEASE ){
3534         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3535           goto vdbe_return;
3536         }
3537         db->autoCommit = 1;
3538         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3539           p->pc = (int)(pOp - aOp);
3540           db->autoCommit = 0;
3541           p->rc = rc = SQLITE_BUSY;
3542           goto vdbe_return;
3543         }
3544         rc = p->rc;
3545         if( rc ){
3546           db->autoCommit = 0;
3547         }else{
3548           db->isTransactionSavepoint = 0;
3549         }
3550       }else{
3551         int isSchemaChange;
3552         iSavepoint = db->nSavepoint - iSavepoint - 1;
3553         if( p1==SAVEPOINT_ROLLBACK ){
3554           isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
3555           for(ii=0; ii<db->nDb; ii++){
3556             rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
3557                                        SQLITE_ABORT_ROLLBACK,
3558                                        isSchemaChange==0);
3559             if( rc!=SQLITE_OK ) goto abort_due_to_error;
3560           }
3561         }else{
3562           assert( p1==SAVEPOINT_RELEASE );
3563           isSchemaChange = 0;
3564         }
3565         for(ii=0; ii<db->nDb; ii++){
3566           rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
3567           if( rc!=SQLITE_OK ){
3568             goto abort_due_to_error;
3569           }
3570         }
3571         if( isSchemaChange ){
3572           sqlite3ExpirePreparedStatements(db, 0);
3573           sqlite3ResetAllSchemasOfConnection(db);
3574           db->mDbFlags |= DBFLAG_SchemaChange;
3575         }
3576       }
3577       if( rc ) goto abort_due_to_error;
3578 
3579       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
3580       ** savepoints nested inside of the savepoint being operated on. */
3581       while( db->pSavepoint!=pSavepoint ){
3582         pTmp = db->pSavepoint;
3583         db->pSavepoint = pTmp->pNext;
3584         sqlite3DbFree(db, pTmp);
3585         db->nSavepoint--;
3586       }
3587 
3588       /* If it is a RELEASE, then destroy the savepoint being operated on
3589       ** too. If it is a ROLLBACK TO, then set the number of deferred
3590       ** constraint violations present in the database to the value stored
3591       ** when the savepoint was created.  */
3592       if( p1==SAVEPOINT_RELEASE ){
3593         assert( pSavepoint==db->pSavepoint );
3594         db->pSavepoint = pSavepoint->pNext;
3595         sqlite3DbFree(db, pSavepoint);
3596         if( !isTransaction ){
3597           db->nSavepoint--;
3598         }
3599       }else{
3600         assert( p1==SAVEPOINT_ROLLBACK );
3601         db->nDeferredCons = pSavepoint->nDeferredCons;
3602         db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
3603       }
3604 
3605       if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
3606         rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
3607         if( rc!=SQLITE_OK ) goto abort_due_to_error;
3608       }
3609     }
3610   }
3611   if( rc ) goto abort_due_to_error;
3612 
3613   break;
3614 }
3615 
3616 /* Opcode: AutoCommit P1 P2 * * *
3617 **
3618 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
3619 ** back any currently active btree transactions. If there are any active
3620 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
3621 ** there are active writing VMs or active VMs that use shared cache.
3622 **
3623 ** This instruction causes the VM to halt.
3624 */
3625 case OP_AutoCommit: {
3626   int desiredAutoCommit;
3627   int iRollback;
3628 
3629   desiredAutoCommit = pOp->p1;
3630   iRollback = pOp->p2;
3631   assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
3632   assert( desiredAutoCommit==1 || iRollback==0 );
3633   assert( db->nVdbeActive>0 );  /* At least this one VM is active */
3634   assert( p->bIsReader );
3635 
3636   if( desiredAutoCommit!=db->autoCommit ){
3637     if( iRollback ){
3638       assert( desiredAutoCommit==1 );
3639       sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
3640       db->autoCommit = 1;
3641     }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
3642       /* If this instruction implements a COMMIT and other VMs are writing
3643       ** return an error indicating that the other VMs must complete first.
3644       */
3645       sqlite3VdbeError(p, "cannot commit transaction - "
3646                           "SQL statements in progress");
3647       rc = SQLITE_BUSY;
3648       goto abort_due_to_error;
3649     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3650       goto vdbe_return;
3651     }else{
3652       db->autoCommit = (u8)desiredAutoCommit;
3653     }
3654     if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3655       p->pc = (int)(pOp - aOp);
3656       db->autoCommit = (u8)(1-desiredAutoCommit);
3657       p->rc = rc = SQLITE_BUSY;
3658       goto vdbe_return;
3659     }
3660     sqlite3CloseSavepoints(db);
3661     if( p->rc==SQLITE_OK ){
3662       rc = SQLITE_DONE;
3663     }else{
3664       rc = SQLITE_ERROR;
3665     }
3666     goto vdbe_return;
3667   }else{
3668     sqlite3VdbeError(p,
3669         (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
3670         (iRollback)?"cannot rollback - no transaction is active":
3671                    "cannot commit - no transaction is active"));
3672 
3673     rc = SQLITE_ERROR;
3674     goto abort_due_to_error;
3675   }
3676   /*NOTREACHED*/ assert(0);
3677 }
3678 
3679 /* Opcode: Transaction P1 P2 P3 P4 P5
3680 **
3681 ** Begin a transaction on database P1 if a transaction is not already
3682 ** active.
3683 ** If P2 is non-zero, then a write-transaction is started, or if a
3684 ** read-transaction is already active, it is upgraded to a write-transaction.
3685 ** If P2 is zero, then a read-transaction is started.  If P2 is 2 or more
3686 ** then an exclusive transaction is started.
3687 **
3688 ** P1 is the index of the database file on which the transaction is
3689 ** started.  Index 0 is the main database file and index 1 is the
3690 ** file used for temporary tables.  Indices of 2 or more are used for
3691 ** attached databases.
3692 **
3693 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
3694 ** true (this flag is set if the Vdbe may modify more than one row and may
3695 ** throw an ABORT exception), a statement transaction may also be opened.
3696 ** More specifically, a statement transaction is opened iff the database
3697 ** connection is currently not in autocommit mode, or if there are other
3698 ** active statements. A statement transaction allows the changes made by this
3699 ** VDBE to be rolled back after an error without having to roll back the
3700 ** entire transaction. If no error is encountered, the statement transaction
3701 ** will automatically commit when the VDBE halts.
3702 **
3703 ** If P5!=0 then this opcode also checks the schema cookie against P3
3704 ** and the schema generation counter against P4.
3705 ** The cookie changes its value whenever the database schema changes.
3706 ** This operation is used to detect when that the cookie has changed
3707 ** and that the current process needs to reread the schema.  If the schema
3708 ** cookie in P3 differs from the schema cookie in the database header or
3709 ** if the schema generation counter in P4 differs from the current
3710 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
3711 ** halts.  The sqlite3_step() wrapper function might then reprepare the
3712 ** statement and rerun it from the beginning.
3713 */
3714 case OP_Transaction: {
3715   Btree *pBt;
3716   int iMeta = 0;
3717 
3718   assert( p->bIsReader );
3719   assert( p->readOnly==0 || pOp->p2==0 );
3720   assert( pOp->p2>=0 && pOp->p2<=2 );
3721   assert( pOp->p1>=0 && pOp->p1<db->nDb );
3722   assert( DbMaskTest(p->btreeMask, pOp->p1) );
3723   assert( rc==SQLITE_OK );
3724   if( pOp->p2 && (db->flags & (SQLITE_QueryOnly|SQLITE_CorruptRdOnly))!=0 ){
3725     if( db->flags & SQLITE_QueryOnly ){
3726       /* Writes prohibited by the "PRAGMA query_only=TRUE" statement */
3727       rc = SQLITE_READONLY;
3728     }else{
3729       /* Writes prohibited due to a prior SQLITE_CORRUPT in the current
3730       ** transaction */
3731       rc = SQLITE_CORRUPT;
3732     }
3733     goto abort_due_to_error;
3734   }
3735   pBt = db->aDb[pOp->p1].pBt;
3736 
3737   if( pBt ){
3738     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta);
3739     testcase( rc==SQLITE_BUSY_SNAPSHOT );
3740     testcase( rc==SQLITE_BUSY_RECOVERY );
3741     if( rc!=SQLITE_OK ){
3742       if( (rc&0xff)==SQLITE_BUSY ){
3743         p->pc = (int)(pOp - aOp);
3744         p->rc = rc;
3745         goto vdbe_return;
3746       }
3747       goto abort_due_to_error;
3748     }
3749 
3750     if( p->usesStmtJournal
3751      && pOp->p2
3752      && (db->autoCommit==0 || db->nVdbeRead>1)
3753     ){
3754       assert( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE );
3755       if( p->iStatement==0 ){
3756         assert( db->nStatement>=0 && db->nSavepoint>=0 );
3757         db->nStatement++;
3758         p->iStatement = db->nSavepoint + db->nStatement;
3759       }
3760 
3761       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
3762       if( rc==SQLITE_OK ){
3763         rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
3764       }
3765 
3766       /* Store the current value of the database handles deferred constraint
3767       ** counter. If the statement transaction needs to be rolled back,
3768       ** the value of this counter needs to be restored too.  */
3769       p->nStmtDefCons = db->nDeferredCons;
3770       p->nStmtDefImmCons = db->nDeferredImmCons;
3771     }
3772   }
3773   assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
3774   if( rc==SQLITE_OK
3775    && pOp->p5
3776    && (iMeta!=pOp->p3
3777       || db->aDb[pOp->p1].pSchema->iGeneration!=pOp->p4.i)
3778   ){
3779     /*
3780     ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
3781     ** version is checked to ensure that the schema has not changed since the
3782     ** SQL statement was prepared.
3783     */
3784     sqlite3DbFree(db, p->zErrMsg);
3785     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
3786     /* If the schema-cookie from the database file matches the cookie
3787     ** stored with the in-memory representation of the schema, do
3788     ** not reload the schema from the database file.
3789     **
3790     ** If virtual-tables are in use, this is not just an optimization.
3791     ** Often, v-tables store their data in other SQLite tables, which
3792     ** are queried from within xNext() and other v-table methods using
3793     ** prepared queries. If such a query is out-of-date, we do not want to
3794     ** discard the database schema, as the user code implementing the
3795     ** v-table would have to be ready for the sqlite3_vtab structure itself
3796     ** to be invalidated whenever sqlite3_step() is called from within
3797     ** a v-table method.
3798     */
3799     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
3800       sqlite3ResetOneSchema(db, pOp->p1);
3801     }
3802     p->expired = 1;
3803     rc = SQLITE_SCHEMA;
3804   }
3805   if( rc ) goto abort_due_to_error;
3806   break;
3807 }
3808 
3809 /* Opcode: ReadCookie P1 P2 P3 * *
3810 **
3811 ** Read cookie number P3 from database P1 and write it into register P2.
3812 ** P3==1 is the schema version.  P3==2 is the database format.
3813 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
3814 ** the main database file and P1==1 is the database file used to store
3815 ** temporary tables.
3816 **
3817 ** There must be a read-lock on the database (either a transaction
3818 ** must be started or there must be an open cursor) before
3819 ** executing this instruction.
3820 */
3821 case OP_ReadCookie: {               /* out2 */
3822   int iMeta;
3823   int iDb;
3824   int iCookie;
3825 
3826   assert( p->bIsReader );
3827   iDb = pOp->p1;
3828   iCookie = pOp->p3;
3829   assert( pOp->p3<SQLITE_N_BTREE_META );
3830   assert( iDb>=0 && iDb<db->nDb );
3831   assert( db->aDb[iDb].pBt!=0 );
3832   assert( DbMaskTest(p->btreeMask, iDb) );
3833 
3834   sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
3835   pOut = out2Prerelease(p, pOp);
3836   pOut->u.i = iMeta;
3837   break;
3838 }
3839 
3840 /* Opcode: SetCookie P1 P2 P3 * P5
3841 **
3842 ** Write the integer value P3 into cookie number P2 of database P1.
3843 ** P2==1 is the schema version.  P2==2 is the database format.
3844 ** P2==3 is the recommended pager cache
3845 ** size, and so forth.  P1==0 is the main database file and P1==1 is the
3846 ** database file used to store temporary tables.
3847 **
3848 ** A transaction must be started before executing this opcode.
3849 **
3850 ** If P2 is the SCHEMA_VERSION cookie (cookie number 1) then the internal
3851 ** schema version is set to P3-P5.  The "PRAGMA schema_version=N" statement
3852 ** has P5 set to 1, so that the internal schema version will be different
3853 ** from the database schema version, resulting in a schema reset.
3854 */
3855 case OP_SetCookie: {
3856   Db *pDb;
3857 
3858   sqlite3VdbeIncrWriteCounter(p, 0);
3859   assert( pOp->p2<SQLITE_N_BTREE_META );
3860   assert( pOp->p1>=0 && pOp->p1<db->nDb );
3861   assert( DbMaskTest(p->btreeMask, pOp->p1) );
3862   assert( p->readOnly==0 );
3863   pDb = &db->aDb[pOp->p1];
3864   assert( pDb->pBt!=0 );
3865   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
3866   /* See note about index shifting on OP_ReadCookie */
3867   rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
3868   if( pOp->p2==BTREE_SCHEMA_VERSION ){
3869     /* When the schema cookie changes, record the new cookie internally */
3870     pDb->pSchema->schema_cookie = pOp->p3 - pOp->p5;
3871     db->mDbFlags |= DBFLAG_SchemaChange;
3872     sqlite3FkClearTriggerCache(db, pOp->p1);
3873   }else if( pOp->p2==BTREE_FILE_FORMAT ){
3874     /* Record changes in the file format */
3875     pDb->pSchema->file_format = pOp->p3;
3876   }
3877   if( pOp->p1==1 ){
3878     /* Invalidate all prepared statements whenever the TEMP database
3879     ** schema is changed.  Ticket #1644 */
3880     sqlite3ExpirePreparedStatements(db, 0);
3881     p->expired = 0;
3882   }
3883   if( rc ) goto abort_due_to_error;
3884   break;
3885 }
3886 
3887 /* Opcode: OpenRead P1 P2 P3 P4 P5
3888 ** Synopsis: root=P2 iDb=P3
3889 **
3890 ** Open a read-only cursor for the database table whose root page is
3891 ** P2 in a database file.  The database file is determined by P3.
3892 ** P3==0 means the main database, P3==1 means the database used for
3893 ** temporary tables, and P3>1 means used the corresponding attached
3894 ** database.  Give the new cursor an identifier of P1.  The P1
3895 ** values need not be contiguous but all P1 values should be small integers.
3896 ** It is an error for P1 to be negative.
3897 **
3898 ** Allowed P5 bits:
3899 ** <ul>
3900 ** <li>  <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
3901 **       equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
3902 **       of OP_SeekLE/OP_IdxLT)
3903 ** </ul>
3904 **
3905 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3906 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3907 ** object, then table being opened must be an [index b-tree] where the
3908 ** KeyInfo object defines the content and collating
3909 ** sequence of that index b-tree. Otherwise, if P4 is an integer
3910 ** value, then the table being opened must be a [table b-tree] with a
3911 ** number of columns no less than the value of P4.
3912 **
3913 ** See also: OpenWrite, ReopenIdx
3914 */
3915 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
3916 ** Synopsis: root=P2 iDb=P3
3917 **
3918 ** The ReopenIdx opcode works like OP_OpenRead except that it first
3919 ** checks to see if the cursor on P1 is already open on the same
3920 ** b-tree and if it is this opcode becomes a no-op.  In other words,
3921 ** if the cursor is already open, do not reopen it.
3922 **
3923 ** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ
3924 ** and with P4 being a P4_KEYINFO object.  Furthermore, the P3 value must
3925 ** be the same as every other ReopenIdx or OpenRead for the same cursor
3926 ** number.
3927 **
3928 ** Allowed P5 bits:
3929 ** <ul>
3930 ** <li>  <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
3931 **       equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
3932 **       of OP_SeekLE/OP_IdxLT)
3933 ** </ul>
3934 **
3935 ** See also: OP_OpenRead, OP_OpenWrite
3936 */
3937 /* Opcode: OpenWrite P1 P2 P3 P4 P5
3938 ** Synopsis: root=P2 iDb=P3
3939 **
3940 ** Open a read/write cursor named P1 on the table or index whose root
3941 ** page is P2 (or whose root page is held in register P2 if the
3942 ** OPFLAG_P2ISREG bit is set in P5 - see below).
3943 **
3944 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3945 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3946 ** object, then table being opened must be an [index b-tree] where the
3947 ** KeyInfo object defines the content and collating
3948 ** sequence of that index b-tree. Otherwise, if P4 is an integer
3949 ** value, then the table being opened must be a [table b-tree] with a
3950 ** number of columns no less than the value of P4.
3951 **
3952 ** Allowed P5 bits:
3953 ** <ul>
3954 ** <li>  <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
3955 **       equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
3956 **       of OP_SeekLE/OP_IdxLT)
3957 ** <li>  <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek
3958 **       and subsequently delete entries in an index btree.  This is a
3959 **       hint to the storage engine that the storage engine is allowed to
3960 **       ignore.  The hint is not used by the official SQLite b*tree storage
3961 **       engine, but is used by COMDB2.
3962 ** <li>  <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2
3963 **       as the root page, not the value of P2 itself.
3964 ** </ul>
3965 **
3966 ** This instruction works like OpenRead except that it opens the cursor
3967 ** in read/write mode.
3968 **
3969 ** See also: OP_OpenRead, OP_ReopenIdx
3970 */
3971 case OP_ReopenIdx: {
3972   int nField;
3973   KeyInfo *pKeyInfo;
3974   u32 p2;
3975   int iDb;
3976   int wrFlag;
3977   Btree *pX;
3978   VdbeCursor *pCur;
3979   Db *pDb;
3980 
3981   assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
3982   assert( pOp->p4type==P4_KEYINFO );
3983   pCur = p->apCsr[pOp->p1];
3984   if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
3985     assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
3986     assert( pCur->eCurType==CURTYPE_BTREE );
3987     sqlite3BtreeClearCursor(pCur->uc.pCursor);
3988     goto open_cursor_set_hints;
3989   }
3990   /* If the cursor is not currently open or is open on a different
3991   ** index, then fall through into OP_OpenRead to force a reopen */
3992 case OP_OpenRead:
3993 case OP_OpenWrite:
3994 
3995   assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
3996   assert( p->bIsReader );
3997   assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
3998           || p->readOnly==0 );
3999 
4000   if( p->expired==1 ){
4001     rc = SQLITE_ABORT_ROLLBACK;
4002     goto abort_due_to_error;
4003   }
4004 
4005   nField = 0;
4006   pKeyInfo = 0;
4007   p2 = (u32)pOp->p2;
4008   iDb = pOp->p3;
4009   assert( iDb>=0 && iDb<db->nDb );
4010   assert( DbMaskTest(p->btreeMask, iDb) );
4011   pDb = &db->aDb[iDb];
4012   pX = pDb->pBt;
4013   assert( pX!=0 );
4014   if( pOp->opcode==OP_OpenWrite ){
4015     assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
4016     wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
4017     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
4018     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
4019       p->minWriteFileFormat = pDb->pSchema->file_format;
4020     }
4021   }else{
4022     wrFlag = 0;
4023   }
4024   if( pOp->p5 & OPFLAG_P2ISREG ){
4025     assert( p2>0 );
4026     assert( p2<=(u32)(p->nMem+1 - p->nCursor) );
4027     assert( pOp->opcode==OP_OpenWrite );
4028     pIn2 = &aMem[p2];
4029     assert( memIsValid(pIn2) );
4030     assert( (pIn2->flags & MEM_Int)!=0 );
4031     sqlite3VdbeMemIntegerify(pIn2);
4032     p2 = (int)pIn2->u.i;
4033     /* The p2 value always comes from a prior OP_CreateBtree opcode and
4034     ** that opcode will always set the p2 value to 2 or more or else fail.
4035     ** If there were a failure, the prepared statement would have halted
4036     ** before reaching this instruction. */
4037     assert( p2>=2 );
4038   }
4039   if( pOp->p4type==P4_KEYINFO ){
4040     pKeyInfo = pOp->p4.pKeyInfo;
4041     assert( pKeyInfo->enc==ENC(db) );
4042     assert( pKeyInfo->db==db );
4043     nField = pKeyInfo->nAllField;
4044   }else if( pOp->p4type==P4_INT32 ){
4045     nField = pOp->p4.i;
4046   }
4047   assert( pOp->p1>=0 );
4048   assert( nField>=0 );
4049   testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
4050   pCur = allocateCursor(p, pOp->p1, nField, CURTYPE_BTREE);
4051   if( pCur==0 ) goto no_mem;
4052   pCur->iDb = iDb;
4053   pCur->nullRow = 1;
4054   pCur->isOrdered = 1;
4055   pCur->pgnoRoot = p2;
4056 #ifdef SQLITE_DEBUG
4057   pCur->wrFlag = wrFlag;
4058 #endif
4059   rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
4060   pCur->pKeyInfo = pKeyInfo;
4061   /* Set the VdbeCursor.isTable variable. Previous versions of
4062   ** SQLite used to check if the root-page flags were sane at this point
4063   ** and report database corruption if they were not, but this check has
4064   ** since moved into the btree layer.  */
4065   pCur->isTable = pOp->p4type!=P4_KEYINFO;
4066 
4067 open_cursor_set_hints:
4068   assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
4069   assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
4070   testcase( pOp->p5 & OPFLAG_BULKCSR );
4071   testcase( pOp->p2 & OPFLAG_SEEKEQ );
4072   sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
4073                                (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
4074   if( rc ) goto abort_due_to_error;
4075   break;
4076 }
4077 
4078 /* Opcode: OpenDup P1 P2 * * *
4079 **
4080 ** Open a new cursor P1 that points to the same ephemeral table as
4081 ** cursor P2.  The P2 cursor must have been opened by a prior OP_OpenEphemeral
4082 ** opcode.  Only ephemeral cursors may be duplicated.
4083 **
4084 ** Duplicate ephemeral cursors are used for self-joins of materialized views.
4085 */
4086 case OP_OpenDup: {
4087   VdbeCursor *pOrig;    /* The original cursor to be duplicated */
4088   VdbeCursor *pCx;      /* The new cursor */
4089 
4090   pOrig = p->apCsr[pOp->p2];
4091   assert( pOrig );
4092   assert( pOrig->isEphemeral );  /* Only ephemeral cursors can be duplicated */
4093 
4094   pCx = allocateCursor(p, pOp->p1, pOrig->nField, CURTYPE_BTREE);
4095   if( pCx==0 ) goto no_mem;
4096   pCx->nullRow = 1;
4097   pCx->isEphemeral = 1;
4098   pCx->pKeyInfo = pOrig->pKeyInfo;
4099   pCx->isTable = pOrig->isTable;
4100   pCx->pgnoRoot = pOrig->pgnoRoot;
4101   pCx->isOrdered = pOrig->isOrdered;
4102   pCx->ub.pBtx = pOrig->ub.pBtx;
4103   pCx->hasBeenDuped = 1;
4104   pOrig->hasBeenDuped = 1;
4105   rc = sqlite3BtreeCursor(pCx->ub.pBtx, pCx->pgnoRoot, BTREE_WRCSR,
4106                           pCx->pKeyInfo, pCx->uc.pCursor);
4107   /* The sqlite3BtreeCursor() routine can only fail for the first cursor
4108   ** opened for a database.  Since there is already an open cursor when this
4109   ** opcode is run, the sqlite3BtreeCursor() cannot fail */
4110   assert( rc==SQLITE_OK );
4111   break;
4112 }
4113 
4114 
4115 /* Opcode: OpenEphemeral P1 P2 P3 P4 P5
4116 ** Synopsis: nColumn=P2
4117 **
4118 ** Open a new cursor P1 to a transient table.
4119 ** The cursor is always opened read/write even if
4120 ** the main database is read-only.  The ephemeral
4121 ** table is deleted automatically when the cursor is closed.
4122 **
4123 ** If the cursor P1 is already opened on an ephemeral table, the table
4124 ** is cleared (all content is erased).
4125 **
4126 ** P2 is the number of columns in the ephemeral table.
4127 ** The cursor points to a BTree table if P4==0 and to a BTree index
4128 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
4129 ** that defines the format of keys in the index.
4130 **
4131 ** The P5 parameter can be a mask of the BTREE_* flags defined
4132 ** in btree.h.  These flags control aspects of the operation of
4133 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
4134 ** added automatically.
4135 **
4136 ** If P3 is positive, then reg[P3] is modified slightly so that it
4137 ** can be used as zero-length data for OP_Insert.  This is an optimization
4138 ** that avoids an extra OP_Blob opcode to initialize that register.
4139 */
4140 /* Opcode: OpenAutoindex P1 P2 * P4 *
4141 ** Synopsis: nColumn=P2
4142 **
4143 ** This opcode works the same as OP_OpenEphemeral.  It has a
4144 ** different name to distinguish its use.  Tables created using
4145 ** by this opcode will be used for automatically created transient
4146 ** indices in joins.
4147 */
4148 case OP_OpenAutoindex:
4149 case OP_OpenEphemeral: {
4150   VdbeCursor *pCx;
4151   KeyInfo *pKeyInfo;
4152 
4153   static const int vfsFlags =
4154       SQLITE_OPEN_READWRITE |
4155       SQLITE_OPEN_CREATE |
4156       SQLITE_OPEN_EXCLUSIVE |
4157       SQLITE_OPEN_DELETEONCLOSE |
4158       SQLITE_OPEN_TRANSIENT_DB;
4159   assert( pOp->p1>=0 );
4160   assert( pOp->p2>=0 );
4161   if( pOp->p3>0 ){
4162     /* Make register reg[P3] into a value that can be used as the data
4163     ** form sqlite3BtreeInsert() where the length of the data is zero. */
4164     assert( pOp->p2==0 ); /* Only used when number of columns is zero */
4165     assert( pOp->opcode==OP_OpenEphemeral );
4166     assert( aMem[pOp->p3].flags & MEM_Null );
4167     aMem[pOp->p3].n = 0;
4168     aMem[pOp->p3].z = "";
4169   }
4170   pCx = p->apCsr[pOp->p1];
4171   if( pCx && !pCx->hasBeenDuped &&  ALWAYS(pOp->p2<=pCx->nField) ){
4172     /* If the ephermeral table is already open and has no duplicates from
4173     ** OP_OpenDup, then erase all existing content so that the table is
4174     ** empty again, rather than creating a new table. */
4175     assert( pCx->isEphemeral );
4176     pCx->seqCount = 0;
4177     pCx->cacheStatus = CACHE_STALE;
4178     rc = sqlite3BtreeClearTable(pCx->ub.pBtx, pCx->pgnoRoot, 0);
4179   }else{
4180     pCx = allocateCursor(p, pOp->p1, pOp->p2, CURTYPE_BTREE);
4181     if( pCx==0 ) goto no_mem;
4182     pCx->isEphemeral = 1;
4183     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->ub.pBtx,
4184                           BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5,
4185                           vfsFlags);
4186     if( rc==SQLITE_OK ){
4187       rc = sqlite3BtreeBeginTrans(pCx->ub.pBtx, 1, 0);
4188       if( rc==SQLITE_OK ){
4189         /* If a transient index is required, create it by calling
4190         ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
4191         ** opening it. If a transient table is required, just use the
4192         ** automatically created table with root-page 1 (an BLOB_INTKEY table).
4193         */
4194         if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
4195           assert( pOp->p4type==P4_KEYINFO );
4196           rc = sqlite3BtreeCreateTable(pCx->ub.pBtx, &pCx->pgnoRoot,
4197               BTREE_BLOBKEY | pOp->p5);
4198           if( rc==SQLITE_OK ){
4199             assert( pCx->pgnoRoot==SCHEMA_ROOT+1 );
4200             assert( pKeyInfo->db==db );
4201             assert( pKeyInfo->enc==ENC(db) );
4202             rc = sqlite3BtreeCursor(pCx->ub.pBtx, pCx->pgnoRoot, BTREE_WRCSR,
4203                 pKeyInfo, pCx->uc.pCursor);
4204           }
4205           pCx->isTable = 0;
4206         }else{
4207           pCx->pgnoRoot = SCHEMA_ROOT;
4208           rc = sqlite3BtreeCursor(pCx->ub.pBtx, SCHEMA_ROOT, BTREE_WRCSR,
4209               0, pCx->uc.pCursor);
4210           pCx->isTable = 1;
4211         }
4212       }
4213       pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
4214       if( rc ){
4215         sqlite3BtreeClose(pCx->ub.pBtx);
4216       }
4217     }
4218   }
4219   if( rc ) goto abort_due_to_error;
4220   pCx->nullRow = 1;
4221   break;
4222 }
4223 
4224 /* Opcode: SorterOpen P1 P2 P3 P4 *
4225 **
4226 ** This opcode works like OP_OpenEphemeral except that it opens
4227 ** a transient index that is specifically designed to sort large
4228 ** tables using an external merge-sort algorithm.
4229 **
4230 ** If argument P3 is non-zero, then it indicates that the sorter may
4231 ** assume that a stable sort considering the first P3 fields of each
4232 ** key is sufficient to produce the required results.
4233 */
4234 case OP_SorterOpen: {
4235   VdbeCursor *pCx;
4236 
4237   assert( pOp->p1>=0 );
4238   assert( pOp->p2>=0 );
4239   pCx = allocateCursor(p, pOp->p1, pOp->p2, CURTYPE_SORTER);
4240   if( pCx==0 ) goto no_mem;
4241   pCx->pKeyInfo = pOp->p4.pKeyInfo;
4242   assert( pCx->pKeyInfo->db==db );
4243   assert( pCx->pKeyInfo->enc==ENC(db) );
4244   rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
4245   if( rc ) goto abort_due_to_error;
4246   break;
4247 }
4248 
4249 /* Opcode: SequenceTest P1 P2 * * *
4250 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
4251 **
4252 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
4253 ** to P2. Regardless of whether or not the jump is taken, increment the
4254 ** the sequence value.
4255 */
4256 case OP_SequenceTest: {
4257   VdbeCursor *pC;
4258   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4259   pC = p->apCsr[pOp->p1];
4260   assert( isSorter(pC) );
4261   if( (pC->seqCount++)==0 ){
4262     goto jump_to_p2;
4263   }
4264   break;
4265 }
4266 
4267 /* Opcode: OpenPseudo P1 P2 P3 * *
4268 ** Synopsis: P3 columns in r[P2]
4269 **
4270 ** Open a new cursor that points to a fake table that contains a single
4271 ** row of data.  The content of that one row is the content of memory
4272 ** register P2.  In other words, cursor P1 becomes an alias for the
4273 ** MEM_Blob content contained in register P2.
4274 **
4275 ** A pseudo-table created by this opcode is used to hold a single
4276 ** row output from the sorter so that the row can be decomposed into
4277 ** individual columns using the OP_Column opcode.  The OP_Column opcode
4278 ** is the only cursor opcode that works with a pseudo-table.
4279 **
4280 ** P3 is the number of fields in the records that will be stored by
4281 ** the pseudo-table.
4282 */
4283 case OP_OpenPseudo: {
4284   VdbeCursor *pCx;
4285 
4286   assert( pOp->p1>=0 );
4287   assert( pOp->p3>=0 );
4288   pCx = allocateCursor(p, pOp->p1, pOp->p3, CURTYPE_PSEUDO);
4289   if( pCx==0 ) goto no_mem;
4290   pCx->nullRow = 1;
4291   pCx->seekResult = pOp->p2;
4292   pCx->isTable = 1;
4293   /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
4294   ** can be safely passed to sqlite3VdbeCursorMoveto().  This avoids a test
4295   ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
4296   ** which is a performance optimization */
4297   pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
4298   assert( pOp->p5==0 );
4299   break;
4300 }
4301 
4302 /* Opcode: Close P1 * * * *
4303 **
4304 ** Close a cursor previously opened as P1.  If P1 is not
4305 ** currently open, this instruction is a no-op.
4306 */
4307 case OP_Close: {
4308   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4309   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
4310   p->apCsr[pOp->p1] = 0;
4311   break;
4312 }
4313 
4314 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
4315 /* Opcode: ColumnsUsed P1 * * P4 *
4316 **
4317 ** This opcode (which only exists if SQLite was compiled with
4318 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
4319 ** table or index for cursor P1 are used.  P4 is a 64-bit integer
4320 ** (P4_INT64) in which the first 63 bits are one for each of the
4321 ** first 63 columns of the table or index that are actually used
4322 ** by the cursor.  The high-order bit is set if any column after
4323 ** the 64th is used.
4324 */
4325 case OP_ColumnsUsed: {
4326   VdbeCursor *pC;
4327   pC = p->apCsr[pOp->p1];
4328   assert( pC->eCurType==CURTYPE_BTREE );
4329   pC->maskUsed = *(u64*)pOp->p4.pI64;
4330   break;
4331 }
4332 #endif
4333 
4334 /* Opcode: SeekGE P1 P2 P3 P4 *
4335 ** Synopsis: key=r[P3@P4]
4336 **
4337 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4338 ** use the value in register P3 as the key.  If cursor P1 refers
4339 ** to an SQL index, then P3 is the first in an array of P4 registers
4340 ** that are used as an unpacked index key.
4341 **
4342 ** Reposition cursor P1 so that  it points to the smallest entry that
4343 ** is greater than or equal to the key value. If there are no records
4344 ** greater than or equal to the key and P2 is not zero, then jump to P2.
4345 **
4346 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
4347 ** opcode will either land on a record that exactly matches the key, or
4348 ** else it will cause a jump to P2.  When the cursor is OPFLAG_SEEKEQ,
4349 ** this opcode must be followed by an IdxLE opcode with the same arguments.
4350 ** The IdxGT opcode will be skipped if this opcode succeeds, but the
4351 ** IdxGT opcode will be used on subsequent loop iterations.  The
4352 ** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
4353 ** is an equality search.
4354 **
4355 ** This opcode leaves the cursor configured to move in forward order,
4356 ** from the beginning toward the end.  In other words, the cursor is
4357 ** configured to use Next, not Prev.
4358 **
4359 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
4360 */
4361 /* Opcode: SeekGT P1 P2 P3 P4 *
4362 ** Synopsis: key=r[P3@P4]
4363 **
4364 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4365 ** use the value in register P3 as a key. If cursor P1 refers
4366 ** to an SQL index, then P3 is the first in an array of P4 registers
4367 ** that are used as an unpacked index key.
4368 **
4369 ** Reposition cursor P1 so that it points to the smallest entry that
4370 ** is greater than the key value. If there are no records greater than
4371 ** the key and P2 is not zero, then jump to P2.
4372 **
4373 ** This opcode leaves the cursor configured to move in forward order,
4374 ** from the beginning toward the end.  In other words, the cursor is
4375 ** configured to use Next, not Prev.
4376 **
4377 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
4378 */
4379 /* Opcode: SeekLT P1 P2 P3 P4 *
4380 ** Synopsis: key=r[P3@P4]
4381 **
4382 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4383 ** use the value in register P3 as a key. If cursor P1 refers
4384 ** to an SQL index, then P3 is the first in an array of P4 registers
4385 ** that are used as an unpacked index key.
4386 **
4387 ** Reposition cursor P1 so that  it points to the largest entry that
4388 ** is less than the key value. If there are no records less than
4389 ** the key and P2 is not zero, then jump to P2.
4390 **
4391 ** This opcode leaves the cursor configured to move in reverse order,
4392 ** from the end toward the beginning.  In other words, the cursor is
4393 ** configured to use Prev, not Next.
4394 **
4395 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
4396 */
4397 /* Opcode: SeekLE P1 P2 P3 P4 *
4398 ** Synopsis: key=r[P3@P4]
4399 **
4400 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4401 ** use the value in register P3 as a key. If cursor P1 refers
4402 ** to an SQL index, then P3 is the first in an array of P4 registers
4403 ** that are used as an unpacked index key.
4404 **
4405 ** Reposition cursor P1 so that it points to the largest entry that
4406 ** is less than or equal to the key value. If there are no records
4407 ** less than or equal to the key and P2 is not zero, then jump to P2.
4408 **
4409 ** This opcode leaves the cursor configured to move in reverse order,
4410 ** from the end toward the beginning.  In other words, the cursor is
4411 ** configured to use Prev, not Next.
4412 **
4413 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
4414 ** opcode will either land on a record that exactly matches the key, or
4415 ** else it will cause a jump to P2.  When the cursor is OPFLAG_SEEKEQ,
4416 ** this opcode must be followed by an IdxLE opcode with the same arguments.
4417 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
4418 ** IdxGE opcode will be used on subsequent loop iterations.  The
4419 ** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
4420 ** is an equality search.
4421 **
4422 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
4423 */
4424 case OP_SeekLT:         /* jump, in3, group */
4425 case OP_SeekLE:         /* jump, in3, group */
4426 case OP_SeekGE:         /* jump, in3, group */
4427 case OP_SeekGT: {       /* jump, in3, group */
4428   int res;           /* Comparison result */
4429   int oc;            /* Opcode */
4430   VdbeCursor *pC;    /* The cursor to seek */
4431   UnpackedRecord r;  /* The key to seek for */
4432   int nField;        /* Number of columns or fields in the key */
4433   i64 iKey;          /* The rowid we are to seek to */
4434   int eqOnly;        /* Only interested in == results */
4435 
4436   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4437   assert( pOp->p2!=0 );
4438   pC = p->apCsr[pOp->p1];
4439   assert( pC!=0 );
4440   assert( pC->eCurType==CURTYPE_BTREE );
4441   assert( OP_SeekLE == OP_SeekLT+1 );
4442   assert( OP_SeekGE == OP_SeekLT+2 );
4443   assert( OP_SeekGT == OP_SeekLT+3 );
4444   assert( pC->isOrdered );
4445   assert( pC->uc.pCursor!=0 );
4446   oc = pOp->opcode;
4447   eqOnly = 0;
4448   pC->nullRow = 0;
4449 #ifdef SQLITE_DEBUG
4450   pC->seekOp = pOp->opcode;
4451 #endif
4452 
4453   pC->deferredMoveto = 0;
4454   pC->cacheStatus = CACHE_STALE;
4455   if( pC->isTable ){
4456     u16 flags3, newType;
4457     /* The OPFLAG_SEEKEQ/BTREE_SEEK_EQ flag is only set on index cursors */
4458     assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
4459               || CORRUPT_DB );
4460 
4461     /* The input value in P3 might be of any type: integer, real, string,
4462     ** blob, or NULL.  But it needs to be an integer before we can do
4463     ** the seek, so convert it. */
4464     pIn3 = &aMem[pOp->p3];
4465     flags3 = pIn3->flags;
4466     if( (flags3 & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Str))==MEM_Str ){
4467       applyNumericAffinity(pIn3, 0);
4468     }
4469     iKey = sqlite3VdbeIntValue(pIn3); /* Get the integer key value */
4470     newType = pIn3->flags; /* Record the type after applying numeric affinity */
4471     pIn3->flags = flags3;  /* But convert the type back to its original */
4472 
4473     /* If the P3 value could not be converted into an integer without
4474     ** loss of information, then special processing is required... */
4475     if( (newType & (MEM_Int|MEM_IntReal))==0 ){
4476       int c;
4477       if( (newType & MEM_Real)==0 ){
4478         if( (newType & MEM_Null) || oc>=OP_SeekGE ){
4479           VdbeBranchTaken(1,2);
4480           goto jump_to_p2;
4481         }else{
4482           rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
4483           if( rc!=SQLITE_OK ) goto abort_due_to_error;
4484           goto seek_not_found;
4485         }
4486       }
4487       c = sqlite3IntFloatCompare(iKey, pIn3->u.r);
4488 
4489       /* If the approximation iKey is larger than the actual real search
4490       ** term, substitute >= for > and < for <=. e.g. if the search term
4491       ** is 4.9 and the integer approximation 5:
4492       **
4493       **        (x >  4.9)    ->     (x >= 5)
4494       **        (x <= 4.9)    ->     (x <  5)
4495       */
4496       if( c>0 ){
4497         assert( OP_SeekGE==(OP_SeekGT-1) );
4498         assert( OP_SeekLT==(OP_SeekLE-1) );
4499         assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
4500         if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
4501       }
4502 
4503       /* If the approximation iKey is smaller than the actual real search
4504       ** term, substitute <= for < and > for >=.  */
4505       else if( c<0 ){
4506         assert( OP_SeekLE==(OP_SeekLT+1) );
4507         assert( OP_SeekGT==(OP_SeekGE+1) );
4508         assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
4509         if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
4510       }
4511     }
4512     rc = sqlite3BtreeTableMoveto(pC->uc.pCursor, (u64)iKey, 0, &res);
4513     pC->movetoTarget = iKey;  /* Used by OP_Delete */
4514     if( rc!=SQLITE_OK ){
4515       goto abort_due_to_error;
4516     }
4517   }else{
4518     /* For a cursor with the OPFLAG_SEEKEQ/BTREE_SEEK_EQ hint, only the
4519     ** OP_SeekGE and OP_SeekLE opcodes are allowed, and these must be
4520     ** immediately followed by an OP_IdxGT or OP_IdxLT opcode, respectively,
4521     ** with the same key.
4522     */
4523     if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
4524       eqOnly = 1;
4525       assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
4526       assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
4527       assert( pOp->opcode==OP_SeekGE || pOp[1].opcode==OP_IdxLT );
4528       assert( pOp->opcode==OP_SeekLE || pOp[1].opcode==OP_IdxGT );
4529       assert( pOp[1].p1==pOp[0].p1 );
4530       assert( pOp[1].p2==pOp[0].p2 );
4531       assert( pOp[1].p3==pOp[0].p3 );
4532       assert( pOp[1].p4.i==pOp[0].p4.i );
4533     }
4534 
4535     nField = pOp->p4.i;
4536     assert( pOp->p4type==P4_INT32 );
4537     assert( nField>0 );
4538     r.pKeyInfo = pC->pKeyInfo;
4539     r.nField = (u16)nField;
4540 
4541     /* The next line of code computes as follows, only faster:
4542     **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
4543     **     r.default_rc = -1;
4544     **   }else{
4545     **     r.default_rc = +1;
4546     **   }
4547     */
4548     r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
4549     assert( oc!=OP_SeekGT || r.default_rc==-1 );
4550     assert( oc!=OP_SeekLE || r.default_rc==-1 );
4551     assert( oc!=OP_SeekGE || r.default_rc==+1 );
4552     assert( oc!=OP_SeekLT || r.default_rc==+1 );
4553 
4554     r.aMem = &aMem[pOp->p3];
4555 #ifdef SQLITE_DEBUG
4556     { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
4557 #endif
4558     r.eqSeen = 0;
4559     rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, &r, &res);
4560     if( rc!=SQLITE_OK ){
4561       goto abort_due_to_error;
4562     }
4563     if( eqOnly && r.eqSeen==0 ){
4564       assert( res!=0 );
4565       goto seek_not_found;
4566     }
4567   }
4568 #ifdef SQLITE_TEST
4569   sqlite3_search_count++;
4570 #endif
4571   if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
4572     if( res<0 || (res==0 && oc==OP_SeekGT) ){
4573       res = 0;
4574       rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
4575       if( rc!=SQLITE_OK ){
4576         if( rc==SQLITE_DONE ){
4577           rc = SQLITE_OK;
4578           res = 1;
4579         }else{
4580           goto abort_due_to_error;
4581         }
4582       }
4583     }else{
4584       res = 0;
4585     }
4586   }else{
4587     assert( oc==OP_SeekLT || oc==OP_SeekLE );
4588     if( res>0 || (res==0 && oc==OP_SeekLT) ){
4589       res = 0;
4590       rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
4591       if( rc!=SQLITE_OK ){
4592         if( rc==SQLITE_DONE ){
4593           rc = SQLITE_OK;
4594           res = 1;
4595         }else{
4596           goto abort_due_to_error;
4597         }
4598       }
4599     }else{
4600       /* res might be negative because the table is empty.  Check to
4601       ** see if this is the case.
4602       */
4603       res = sqlite3BtreeEof(pC->uc.pCursor);
4604     }
4605   }
4606 seek_not_found:
4607   assert( pOp->p2>0 );
4608   VdbeBranchTaken(res!=0,2);
4609   if( res ){
4610     goto jump_to_p2;
4611   }else if( eqOnly ){
4612     assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
4613     pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
4614   }
4615   break;
4616 }
4617 
4618 
4619 /* Opcode: SeekScan  P1 P2 * * *
4620 ** Synopsis: Scan-ahead up to P1 rows
4621 **
4622 ** This opcode is a prefix opcode to OP_SeekGE.  In other words, this
4623 ** opcode must be immediately followed by OP_SeekGE. This constraint is
4624 ** checked by assert() statements.
4625 **
4626 ** This opcode uses the P1 through P4 operands of the subsequent
4627 ** OP_SeekGE.  In the text that follows, the operands of the subsequent
4628 ** OP_SeekGE opcode are denoted as SeekOP.P1 through SeekOP.P4.   Only
4629 ** the P1 and P2 operands of this opcode are also used, and  are called
4630 ** This.P1 and This.P2.
4631 **
4632 ** This opcode helps to optimize IN operators on a multi-column index
4633 ** where the IN operator is on the later terms of the index by avoiding
4634 ** unnecessary seeks on the btree, substituting steps to the next row
4635 ** of the b-tree instead.  A correct answer is obtained if this opcode
4636 ** is omitted or is a no-op.
4637 **
4638 ** The SeekGE.P3 and SeekGE.P4 operands identify an unpacked key which
4639 ** is the desired entry that we want the cursor SeekGE.P1 to be pointing
4640 ** to.  Call this SeekGE.P4/P5 row the "target".
4641 **
4642 ** If the SeekGE.P1 cursor is not currently pointing to a valid row,
4643 ** then this opcode is a no-op and control passes through into the OP_SeekGE.
4644 **
4645 ** If the SeekGE.P1 cursor is pointing to a valid row, then that row
4646 ** might be the target row, or it might be near and slightly before the
4647 ** target row.  This opcode attempts to position the cursor on the target
4648 ** row by, perhaps by invoking sqlite3BtreeStep() on the cursor
4649 ** between 0 and This.P1 times.
4650 **
4651 ** There are three possible outcomes from this opcode:<ol>
4652 **
4653 ** <li> If after This.P1 steps, the cursor is still pointing to a place that
4654 **      is earlier in the btree than the target row, then fall through
4655 **      into the subsquence OP_SeekGE opcode.
4656 **
4657 ** <li> If the cursor is successfully moved to the target row by 0 or more
4658 **      sqlite3BtreeNext() calls, then jump to This.P2, which will land just
4659 **      past the OP_IdxGT or OP_IdxGE opcode that follows the OP_SeekGE.
4660 **
4661 ** <li> If the cursor ends up past the target row (indicating the the target
4662 **      row does not exist in the btree) then jump to SeekOP.P2.
4663 ** </ol>
4664 */
4665 case OP_SeekScan: {
4666   VdbeCursor *pC;
4667   int res;
4668   int nStep;
4669   UnpackedRecord r;
4670 
4671   assert( pOp[1].opcode==OP_SeekGE );
4672 
4673   /* pOp->p2 points to the first instruction past the OP_IdxGT that
4674   ** follows the OP_SeekGE.  */
4675   assert( pOp->p2>=(int)(pOp-aOp)+2 );
4676   assert( aOp[pOp->p2-1].opcode==OP_IdxGT || aOp[pOp->p2-1].opcode==OP_IdxGE );
4677   testcase( aOp[pOp->p2-1].opcode==OP_IdxGE );
4678   assert( pOp[1].p1==aOp[pOp->p2-1].p1 );
4679   assert( pOp[1].p2==aOp[pOp->p2-1].p2 );
4680   assert( pOp[1].p3==aOp[pOp->p2-1].p3 );
4681 
4682   assert( pOp->p1>0 );
4683   pC = p->apCsr[pOp[1].p1];
4684   assert( pC!=0 );
4685   assert( pC->eCurType==CURTYPE_BTREE );
4686   assert( !pC->isTable );
4687   if( !sqlite3BtreeCursorIsValidNN(pC->uc.pCursor) ){
4688 #ifdef SQLITE_DEBUG
4689      if( db->flags&SQLITE_VdbeTrace ){
4690        printf("... cursor not valid - fall through\n");
4691      }
4692 #endif
4693     break;
4694   }
4695   nStep = pOp->p1;
4696   assert( nStep>=1 );
4697   r.pKeyInfo = pC->pKeyInfo;
4698   r.nField = (u16)pOp[1].p4.i;
4699   r.default_rc = 0;
4700   r.aMem = &aMem[pOp[1].p3];
4701 #ifdef SQLITE_DEBUG
4702   {
4703     int i;
4704     for(i=0; i<r.nField; i++){
4705       assert( memIsValid(&r.aMem[i]) );
4706       REGISTER_TRACE(pOp[1].p3+i, &aMem[pOp[1].p3+i]);
4707     }
4708   }
4709 #endif
4710   res = 0;  /* Not needed.  Only used to silence a warning. */
4711   while(1){
4712     rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
4713     if( rc ) goto abort_due_to_error;
4714     if( res>0 ){
4715       seekscan_search_fail:
4716 #ifdef SQLITE_DEBUG
4717       if( db->flags&SQLITE_VdbeTrace ){
4718         printf("... %d steps and then skip\n", pOp->p1 - nStep);
4719       }
4720 #endif
4721       VdbeBranchTaken(1,3);
4722       pOp++;
4723       goto jump_to_p2;
4724     }
4725     if( res==0 ){
4726 #ifdef SQLITE_DEBUG
4727       if( db->flags&SQLITE_VdbeTrace ){
4728         printf("... %d steps and then success\n", pOp->p1 - nStep);
4729       }
4730 #endif
4731       VdbeBranchTaken(2,3);
4732       goto jump_to_p2;
4733       break;
4734     }
4735     if( nStep<=0 ){
4736 #ifdef SQLITE_DEBUG
4737       if( db->flags&SQLITE_VdbeTrace ){
4738         printf("... fall through after %d steps\n", pOp->p1);
4739       }
4740 #endif
4741       VdbeBranchTaken(0,3);
4742       break;
4743     }
4744     nStep--;
4745     rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
4746     if( rc ){
4747       if( rc==SQLITE_DONE ){
4748         rc = SQLITE_OK;
4749         goto seekscan_search_fail;
4750       }else{
4751         goto abort_due_to_error;
4752       }
4753     }
4754   }
4755 
4756   break;
4757 }
4758 
4759 
4760 /* Opcode: SeekHit P1 P2 P3 * *
4761 ** Synopsis: set P2<=seekHit<=P3
4762 **
4763 ** Increase or decrease the seekHit value for cursor P1, if necessary,
4764 ** so that it is no less than P2 and no greater than P3.
4765 **
4766 ** The seekHit integer represents the maximum of terms in an index for which
4767 ** there is known to be at least one match.  If the seekHit value is smaller
4768 ** than the total number of equality terms in an index lookup, then the
4769 ** OP_IfNoHope opcode might run to see if the IN loop can be abandoned
4770 ** early, thus saving work.  This is part of the IN-early-out optimization.
4771 **
4772 ** P1 must be a valid b-tree cursor.
4773 */
4774 case OP_SeekHit: {
4775   VdbeCursor *pC;
4776   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4777   pC = p->apCsr[pOp->p1];
4778   assert( pC!=0 );
4779   assert( pOp->p3>=pOp->p2 );
4780   if( pC->seekHit<pOp->p2 ){
4781 #ifdef SQLITE_DEBUG
4782     if( db->flags&SQLITE_VdbeTrace ){
4783       printf("seekHit changes from %d to %d\n", pC->seekHit, pOp->p2);
4784     }
4785 #endif
4786     pC->seekHit = pOp->p2;
4787   }else if( pC->seekHit>pOp->p3 ){
4788 #ifdef SQLITE_DEBUG
4789     if( db->flags&SQLITE_VdbeTrace ){
4790       printf("seekHit changes from %d to %d\n", pC->seekHit, pOp->p3);
4791     }
4792 #endif
4793     pC->seekHit = pOp->p3;
4794   }
4795   break;
4796 }
4797 
4798 /* Opcode: IfNotOpen P1 P2 * * *
4799 ** Synopsis: if( !csr[P1] ) goto P2
4800 **
4801 ** If cursor P1 is not open, jump to instruction P2. Otherwise, fall through.
4802 */
4803 case OP_IfNotOpen: {        /* jump */
4804   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4805   VdbeBranchTaken(p->apCsr[pOp->p1]==0, 2);
4806   if( !p->apCsr[pOp->p1] ){
4807     goto jump_to_p2_and_check_for_interrupt;
4808   }
4809   break;
4810 }
4811 
4812 /* Opcode: Found P1 P2 P3 P4 *
4813 ** Synopsis: key=r[P3@P4]
4814 **
4815 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
4816 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4817 ** record.
4818 **
4819 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
4820 ** is a prefix of any entry in P1 then a jump is made to P2 and
4821 ** P1 is left pointing at the matching entry.
4822 **
4823 ** This operation leaves the cursor in a state where it can be
4824 ** advanced in the forward direction.  The Next instruction will work,
4825 ** but not the Prev instruction.
4826 **
4827 ** See also: NotFound, NoConflict, NotExists. SeekGe
4828 */
4829 /* Opcode: NotFound P1 P2 P3 P4 *
4830 ** Synopsis: key=r[P3@P4]
4831 **
4832 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
4833 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4834 ** record.
4835 **
4836 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
4837 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
4838 ** does contain an entry whose prefix matches the P3/P4 record then control
4839 ** falls through to the next instruction and P1 is left pointing at the
4840 ** matching entry.
4841 **
4842 ** This operation leaves the cursor in a state where it cannot be
4843 ** advanced in either direction.  In other words, the Next and Prev
4844 ** opcodes do not work after this operation.
4845 **
4846 ** See also: Found, NotExists, NoConflict, IfNoHope
4847 */
4848 /* Opcode: IfNoHope P1 P2 P3 P4 *
4849 ** Synopsis: key=r[P3@P4]
4850 **
4851 ** Register P3 is the first of P4 registers that form an unpacked
4852 ** record.  Cursor P1 is an index btree.  P2 is a jump destination.
4853 ** In other words, the operands to this opcode are the same as the
4854 ** operands to OP_NotFound and OP_IdxGT.
4855 **
4856 ** This opcode is an optimization attempt only.  If this opcode always
4857 ** falls through, the correct answer is still obtained, but extra works
4858 ** is performed.
4859 **
4860 ** A value of N in the seekHit flag of cursor P1 means that there exists
4861 ** a key P3:N that will match some record in the index.  We want to know
4862 ** if it is possible for a record P3:P4 to match some record in the
4863 ** index.  If it is not possible, we can skips some work.  So if seekHit
4864 ** is less than P4, attempt to find out if a match is possible by running
4865 ** OP_NotFound.
4866 **
4867 ** This opcode is used in IN clause processing for a multi-column key.
4868 ** If an IN clause is attached to an element of the key other than the
4869 ** left-most element, and if there are no matches on the most recent
4870 ** seek over the whole key, then it might be that one of the key element
4871 ** to the left is prohibiting a match, and hence there is "no hope" of
4872 ** any match regardless of how many IN clause elements are checked.
4873 ** In such a case, we abandon the IN clause search early, using this
4874 ** opcode.  The opcode name comes from the fact that the
4875 ** jump is taken if there is "no hope" of achieving a match.
4876 **
4877 ** See also: NotFound, SeekHit
4878 */
4879 /* Opcode: NoConflict P1 P2 P3 P4 *
4880 ** Synopsis: key=r[P3@P4]
4881 **
4882 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
4883 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4884 ** record.
4885 **
4886 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
4887 ** contains any NULL value, jump immediately to P2.  If all terms of the
4888 ** record are not-NULL then a check is done to determine if any row in the
4889 ** P1 index btree has a matching key prefix.  If there are no matches, jump
4890 ** immediately to P2.  If there is a match, fall through and leave the P1
4891 ** cursor pointing to the matching row.
4892 **
4893 ** This opcode is similar to OP_NotFound with the exceptions that the
4894 ** branch is always taken if any part of the search key input is NULL.
4895 **
4896 ** This operation leaves the cursor in a state where it cannot be
4897 ** advanced in either direction.  In other words, the Next and Prev
4898 ** opcodes do not work after this operation.
4899 **
4900 ** See also: NotFound, Found, NotExists
4901 */
4902 case OP_IfNoHope: {     /* jump, in3 */
4903   VdbeCursor *pC;
4904   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4905   pC = p->apCsr[pOp->p1];
4906   assert( pC!=0 );
4907 #ifdef SQLITE_DEBUG
4908   if( db->flags&SQLITE_VdbeTrace ){
4909     printf("seekHit is %d\n", pC->seekHit);
4910   }
4911 #endif
4912   if( pC->seekHit>=pOp->p4.i ) break;
4913   /* Fall through into OP_NotFound */
4914   /* no break */ deliberate_fall_through
4915 }
4916 case OP_NoConflict:     /* jump, in3 */
4917 case OP_NotFound:       /* jump, in3 */
4918 case OP_Found: {        /* jump, in3 */
4919   int alreadyExists;
4920   int takeJump;
4921   int ii;
4922   VdbeCursor *pC;
4923   int res;
4924   UnpackedRecord *pFree;
4925   UnpackedRecord *pIdxKey;
4926   UnpackedRecord r;
4927 
4928 #ifdef SQLITE_TEST
4929   if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
4930 #endif
4931 
4932   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4933   assert( pOp->p4type==P4_INT32 );
4934   pC = p->apCsr[pOp->p1];
4935   assert( pC!=0 );
4936 #ifdef SQLITE_DEBUG
4937   pC->seekOp = pOp->opcode;
4938 #endif
4939   pIn3 = &aMem[pOp->p3];
4940   assert( pC->eCurType==CURTYPE_BTREE );
4941   assert( pC->uc.pCursor!=0 );
4942   assert( pC->isTable==0 );
4943   if( pOp->p4.i>0 ){
4944     r.pKeyInfo = pC->pKeyInfo;
4945     r.nField = (u16)pOp->p4.i;
4946     r.aMem = pIn3;
4947 #ifdef SQLITE_DEBUG
4948     for(ii=0; ii<r.nField; ii++){
4949       assert( memIsValid(&r.aMem[ii]) );
4950       assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
4951       if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
4952     }
4953 #endif
4954     pIdxKey = &r;
4955     pFree = 0;
4956   }else{
4957     assert( pIn3->flags & MEM_Blob );
4958     rc = ExpandBlob(pIn3);
4959     assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
4960     if( rc ) goto no_mem;
4961     pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
4962     if( pIdxKey==0 ) goto no_mem;
4963     sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
4964   }
4965   pIdxKey->default_rc = 0;
4966   takeJump = 0;
4967   if( pOp->opcode==OP_NoConflict ){
4968     /* For the OP_NoConflict opcode, take the jump if any of the
4969     ** input fields are NULL, since any key with a NULL will not
4970     ** conflict */
4971     for(ii=0; ii<pIdxKey->nField; ii++){
4972       if( pIdxKey->aMem[ii].flags & MEM_Null ){
4973         takeJump = 1;
4974         break;
4975       }
4976     }
4977   }
4978   rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, pIdxKey, &res);
4979   if( pFree ) sqlite3DbFreeNN(db, pFree);
4980   if( rc!=SQLITE_OK ){
4981     goto abort_due_to_error;
4982   }
4983   pC->seekResult = res;
4984   alreadyExists = (res==0);
4985   pC->nullRow = 1-alreadyExists;
4986   pC->deferredMoveto = 0;
4987   pC->cacheStatus = CACHE_STALE;
4988   if( pOp->opcode==OP_Found ){
4989     VdbeBranchTaken(alreadyExists!=0,2);
4990     if( alreadyExists ) goto jump_to_p2;
4991   }else{
4992     VdbeBranchTaken(takeJump||alreadyExists==0,2);
4993     if( takeJump || !alreadyExists ) goto jump_to_p2;
4994     if( pOp->opcode==OP_IfNoHope ) pC->seekHit = pOp->p4.i;
4995   }
4996   break;
4997 }
4998 
4999 /* Opcode: SeekRowid P1 P2 P3 * *
5000 ** Synopsis: intkey=r[P3]
5001 **
5002 ** P1 is the index of a cursor open on an SQL table btree (with integer
5003 ** keys).  If register P3 does not contain an integer or if P1 does not
5004 ** contain a record with rowid P3 then jump immediately to P2.
5005 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
5006 ** a record with rowid P3 then
5007 ** leave the cursor pointing at that record and fall through to the next
5008 ** instruction.
5009 **
5010 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
5011 ** the P3 register must be guaranteed to contain an integer value.  With this
5012 ** opcode, register P3 might not contain an integer.
5013 **
5014 ** The OP_NotFound opcode performs the same operation on index btrees
5015 ** (with arbitrary multi-value keys).
5016 **
5017 ** This opcode leaves the cursor in a state where it cannot be advanced
5018 ** in either direction.  In other words, the Next and Prev opcodes will
5019 ** not work following this opcode.
5020 **
5021 ** See also: Found, NotFound, NoConflict, SeekRowid
5022 */
5023 /* Opcode: NotExists P1 P2 P3 * *
5024 ** Synopsis: intkey=r[P3]
5025 **
5026 ** P1 is the index of a cursor open on an SQL table btree (with integer
5027 ** keys).  P3 is an integer rowid.  If P1 does not contain a record with
5028 ** rowid P3 then jump immediately to P2.  Or, if P2 is 0, raise an
5029 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
5030 ** leave the cursor pointing at that record and fall through to the next
5031 ** instruction.
5032 **
5033 ** The OP_SeekRowid opcode performs the same operation but also allows the
5034 ** P3 register to contain a non-integer value, in which case the jump is
5035 ** always taken.  This opcode requires that P3 always contain an integer.
5036 **
5037 ** The OP_NotFound opcode performs the same operation on index btrees
5038 ** (with arbitrary multi-value keys).
5039 **
5040 ** This opcode leaves the cursor in a state where it cannot be advanced
5041 ** in either direction.  In other words, the Next and Prev opcodes will
5042 ** not work following this opcode.
5043 **
5044 ** See also: Found, NotFound, NoConflict, SeekRowid
5045 */
5046 case OP_SeekRowid: {        /* jump, in3 */
5047   VdbeCursor *pC;
5048   BtCursor *pCrsr;
5049   int res;
5050   u64 iKey;
5051 
5052   pIn3 = &aMem[pOp->p3];
5053   testcase( pIn3->flags & MEM_Int );
5054   testcase( pIn3->flags & MEM_IntReal );
5055   testcase( pIn3->flags & MEM_Real );
5056   testcase( (pIn3->flags & (MEM_Str|MEM_Int))==MEM_Str );
5057   if( (pIn3->flags & (MEM_Int|MEM_IntReal))==0 ){
5058     /* If pIn3->u.i does not contain an integer, compute iKey as the
5059     ** integer value of pIn3.  Jump to P2 if pIn3 cannot be converted
5060     ** into an integer without loss of information.  Take care to avoid
5061     ** changing the datatype of pIn3, however, as it is used by other
5062     ** parts of the prepared statement. */
5063     Mem x = pIn3[0];
5064     applyAffinity(&x, SQLITE_AFF_NUMERIC, encoding);
5065     if( (x.flags & MEM_Int)==0 ) goto jump_to_p2;
5066     iKey = x.u.i;
5067     goto notExistsWithKey;
5068   }
5069   /* Fall through into OP_NotExists */
5070   /* no break */ deliberate_fall_through
5071 case OP_NotExists:          /* jump, in3 */
5072   pIn3 = &aMem[pOp->p3];
5073   assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid );
5074   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5075   iKey = pIn3->u.i;
5076 notExistsWithKey:
5077   pC = p->apCsr[pOp->p1];
5078   assert( pC!=0 );
5079 #ifdef SQLITE_DEBUG
5080   if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid;
5081 #endif
5082   assert( pC->isTable );
5083   assert( pC->eCurType==CURTYPE_BTREE );
5084   pCrsr = pC->uc.pCursor;
5085   assert( pCrsr!=0 );
5086   res = 0;
5087   rc = sqlite3BtreeTableMoveto(pCrsr, iKey, 0, &res);
5088   assert( rc==SQLITE_OK || res==0 );
5089   pC->movetoTarget = iKey;  /* Used by OP_Delete */
5090   pC->nullRow = 0;
5091   pC->cacheStatus = CACHE_STALE;
5092   pC->deferredMoveto = 0;
5093   VdbeBranchTaken(res!=0,2);
5094   pC->seekResult = res;
5095   if( res!=0 ){
5096     assert( rc==SQLITE_OK );
5097     if( pOp->p2==0 ){
5098       rc = SQLITE_CORRUPT_BKPT;
5099     }else{
5100       goto jump_to_p2;
5101     }
5102   }
5103   if( rc ) goto abort_due_to_error;
5104   break;
5105 }
5106 
5107 /* Opcode: Sequence P1 P2 * * *
5108 ** Synopsis: r[P2]=cursor[P1].ctr++
5109 **
5110 ** Find the next available sequence number for cursor P1.
5111 ** Write the sequence number into register P2.
5112 ** The sequence number on the cursor is incremented after this
5113 ** instruction.
5114 */
5115 case OP_Sequence: {           /* out2 */
5116   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5117   assert( p->apCsr[pOp->p1]!=0 );
5118   assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
5119   pOut = out2Prerelease(p, pOp);
5120   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
5121   break;
5122 }
5123 
5124 
5125 /* Opcode: NewRowid P1 P2 P3 * *
5126 ** Synopsis: r[P2]=rowid
5127 **
5128 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
5129 ** The record number is not previously used as a key in the database
5130 ** table that cursor P1 points to.  The new record number is written
5131 ** written to register P2.
5132 **
5133 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
5134 ** the largest previously generated record number. No new record numbers are
5135 ** allowed to be less than this value. When this value reaches its maximum,
5136 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
5137 ** generated record number. This P3 mechanism is used to help implement the
5138 ** AUTOINCREMENT feature.
5139 */
5140 case OP_NewRowid: {           /* out2 */
5141   i64 v;                 /* The new rowid */
5142   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
5143   int res;               /* Result of an sqlite3BtreeLast() */
5144   int cnt;               /* Counter to limit the number of searches */
5145 #ifndef SQLITE_OMIT_AUTOINCREMENT
5146   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
5147   VdbeFrame *pFrame;     /* Root frame of VDBE */
5148 #endif
5149 
5150   v = 0;
5151   res = 0;
5152   pOut = out2Prerelease(p, pOp);
5153   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5154   pC = p->apCsr[pOp->p1];
5155   assert( pC!=0 );
5156   assert( pC->isTable );
5157   assert( pC->eCurType==CURTYPE_BTREE );
5158   assert( pC->uc.pCursor!=0 );
5159   {
5160     /* The next rowid or record number (different terms for the same
5161     ** thing) is obtained in a two-step algorithm.
5162     **
5163     ** First we attempt to find the largest existing rowid and add one
5164     ** to that.  But if the largest existing rowid is already the maximum
5165     ** positive integer, we have to fall through to the second
5166     ** probabilistic algorithm
5167     **
5168     ** The second algorithm is to select a rowid at random and see if
5169     ** it already exists in the table.  If it does not exist, we have
5170     ** succeeded.  If the random rowid does exist, we select a new one
5171     ** and try again, up to 100 times.
5172     */
5173     assert( pC->isTable );
5174 
5175 #ifdef SQLITE_32BIT_ROWID
5176 #   define MAX_ROWID 0x7fffffff
5177 #else
5178     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
5179     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
5180     ** to provide the constant while making all compilers happy.
5181     */
5182 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
5183 #endif
5184 
5185     if( !pC->useRandomRowid ){
5186       rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
5187       if( rc!=SQLITE_OK ){
5188         goto abort_due_to_error;
5189       }
5190       if( res ){
5191         v = 1;   /* IMP: R-61914-48074 */
5192       }else{
5193         assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
5194         v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5195         if( v>=MAX_ROWID ){
5196           pC->useRandomRowid = 1;
5197         }else{
5198           v++;   /* IMP: R-29538-34987 */
5199         }
5200       }
5201     }
5202 
5203 #ifndef SQLITE_OMIT_AUTOINCREMENT
5204     if( pOp->p3 ){
5205       /* Assert that P3 is a valid memory cell. */
5206       assert( pOp->p3>0 );
5207       if( p->pFrame ){
5208         for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
5209         /* Assert that P3 is a valid memory cell. */
5210         assert( pOp->p3<=pFrame->nMem );
5211         pMem = &pFrame->aMem[pOp->p3];
5212       }else{
5213         /* Assert that P3 is a valid memory cell. */
5214         assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
5215         pMem = &aMem[pOp->p3];
5216         memAboutToChange(p, pMem);
5217       }
5218       assert( memIsValid(pMem) );
5219 
5220       REGISTER_TRACE(pOp->p3, pMem);
5221       sqlite3VdbeMemIntegerify(pMem);
5222       assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
5223       if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
5224         rc = SQLITE_FULL;   /* IMP: R-17817-00630 */
5225         goto abort_due_to_error;
5226       }
5227       if( v<pMem->u.i+1 ){
5228         v = pMem->u.i + 1;
5229       }
5230       pMem->u.i = v;
5231     }
5232 #endif
5233     if( pC->useRandomRowid ){
5234       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
5235       ** largest possible integer (9223372036854775807) then the database
5236       ** engine starts picking positive candidate ROWIDs at random until
5237       ** it finds one that is not previously used. */
5238       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
5239                              ** an AUTOINCREMENT table. */
5240       cnt = 0;
5241       do{
5242         sqlite3_randomness(sizeof(v), &v);
5243         v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */
5244       }while(  ((rc = sqlite3BtreeTableMoveto(pC->uc.pCursor, (u64)v,
5245                                                  0, &res))==SQLITE_OK)
5246             && (res==0)
5247             && (++cnt<100));
5248       if( rc ) goto abort_due_to_error;
5249       if( res==0 ){
5250         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
5251         goto abort_due_to_error;
5252       }
5253       assert( v>0 );  /* EV: R-40812-03570 */
5254     }
5255     pC->deferredMoveto = 0;
5256     pC->cacheStatus = CACHE_STALE;
5257   }
5258   pOut->u.i = v;
5259   break;
5260 }
5261 
5262 /* Opcode: Insert P1 P2 P3 P4 P5
5263 ** Synopsis: intkey=r[P3] data=r[P2]
5264 **
5265 ** Write an entry into the table of cursor P1.  A new entry is
5266 ** created if it doesn't already exist or the data for an existing
5267 ** entry is overwritten.  The data is the value MEM_Blob stored in register
5268 ** number P2. The key is stored in register P3. The key must
5269 ** be a MEM_Int.
5270 **
5271 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
5272 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
5273 ** then rowid is stored for subsequent return by the
5274 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
5275 **
5276 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
5277 ** run faster by avoiding an unnecessary seek on cursor P1.  However,
5278 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
5279 ** seeks on the cursor or if the most recent seek used a key equal to P3.
5280 **
5281 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
5282 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
5283 ** is part of an INSERT operation.  The difference is only important to
5284 ** the update hook.
5285 **
5286 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
5287 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
5288 ** following a successful insert.
5289 **
5290 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
5291 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
5292 ** and register P2 becomes ephemeral.  If the cursor is changed, the
5293 ** value of register P2 will then change.  Make sure this does not
5294 ** cause any problems.)
5295 **
5296 ** This instruction only works on tables.  The equivalent instruction
5297 ** for indices is OP_IdxInsert.
5298 */
5299 case OP_Insert: {
5300   Mem *pData;       /* MEM cell holding data for the record to be inserted */
5301   Mem *pKey;        /* MEM cell holding key  for the record */
5302   VdbeCursor *pC;   /* Cursor to table into which insert is written */
5303   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
5304   const char *zDb;  /* database name - used by the update hook */
5305   Table *pTab;      /* Table structure - used by update and pre-update hooks */
5306   BtreePayload x;   /* Payload to be inserted */
5307 
5308   pData = &aMem[pOp->p2];
5309   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5310   assert( memIsValid(pData) );
5311   pC = p->apCsr[pOp->p1];
5312   assert( pC!=0 );
5313   assert( pC->eCurType==CURTYPE_BTREE );
5314   assert( pC->deferredMoveto==0 );
5315   assert( pC->uc.pCursor!=0 );
5316   assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
5317   assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
5318   REGISTER_TRACE(pOp->p2, pData);
5319   sqlite3VdbeIncrWriteCounter(p, pC);
5320 
5321   pKey = &aMem[pOp->p3];
5322   assert( pKey->flags & MEM_Int );
5323   assert( memIsValid(pKey) );
5324   REGISTER_TRACE(pOp->p3, pKey);
5325   x.nKey = pKey->u.i;
5326 
5327   if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
5328     assert( pC->iDb>=0 );
5329     zDb = db->aDb[pC->iDb].zDbSName;
5330     pTab = pOp->p4.pTab;
5331     assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
5332   }else{
5333     pTab = 0;
5334     zDb = 0;
5335   }
5336 
5337 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
5338   /* Invoke the pre-update hook, if any */
5339   if( pTab ){
5340     if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
5341       sqlite3VdbePreUpdateHook(p,pC,SQLITE_INSERT,zDb,pTab,x.nKey,pOp->p2,-1);
5342     }
5343     if( db->xUpdateCallback==0 || pTab->aCol==0 ){
5344       /* Prevent post-update hook from running in cases when it should not */
5345       pTab = 0;
5346     }
5347   }
5348   if( pOp->p5 & OPFLAG_ISNOOP ) break;
5349 #endif
5350 
5351   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
5352   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
5353   assert( (pData->flags & (MEM_Blob|MEM_Str))!=0 || pData->n==0 );
5354   x.pData = pData->z;
5355   x.nData = pData->n;
5356   seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
5357   if( pData->flags & MEM_Zero ){
5358     x.nZero = pData->u.nZero;
5359   }else{
5360     x.nZero = 0;
5361   }
5362   x.pKey = 0;
5363   rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
5364       (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
5365       seekResult
5366   );
5367   pC->deferredMoveto = 0;
5368   pC->cacheStatus = CACHE_STALE;
5369 
5370   /* Invoke the update-hook if required. */
5371   if( rc ) goto abort_due_to_error;
5372   if( pTab ){
5373     assert( db->xUpdateCallback!=0 );
5374     assert( pTab->aCol!=0 );
5375     db->xUpdateCallback(db->pUpdateArg,
5376            (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
5377            zDb, pTab->zName, x.nKey);
5378   }
5379   break;
5380 }
5381 
5382 /* Opcode: RowCell P1 P2 P3 * *
5383 **
5384 ** P1 and P2 are both open cursors. Both must be opened on the same type
5385 ** of table - intkey or index. This opcode is used as part of copying
5386 ** the current row from P2 into P1. If the cursors are opened on intkey
5387 ** tables, register P3 contains the rowid to use with the new record in
5388 ** P1. If they are opened on index tables, P3 is not used.
5389 **
5390 ** This opcode must be followed by either an Insert or InsertIdx opcode
5391 ** with the OPFLAG_PREFORMAT flag set to complete the insert operation.
5392 */
5393 case OP_RowCell: {
5394   VdbeCursor *pDest;              /* Cursor to write to */
5395   VdbeCursor *pSrc;               /* Cursor to read from */
5396   i64 iKey;                       /* Rowid value to insert with */
5397   assert( pOp[1].opcode==OP_Insert || pOp[1].opcode==OP_IdxInsert );
5398   assert( pOp[1].opcode==OP_Insert    || pOp->p3==0 );
5399   assert( pOp[1].opcode==OP_IdxInsert || pOp->p3>0 );
5400   assert( pOp[1].p5 & OPFLAG_PREFORMAT );
5401   pDest = p->apCsr[pOp->p1];
5402   pSrc = p->apCsr[pOp->p2];
5403   iKey = pOp->p3 ? aMem[pOp->p3].u.i : 0;
5404   rc = sqlite3BtreeTransferRow(pDest->uc.pCursor, pSrc->uc.pCursor, iKey);
5405   if( rc!=SQLITE_OK ) goto abort_due_to_error;
5406   break;
5407 };
5408 
5409 /* Opcode: Delete P1 P2 P3 P4 P5
5410 **
5411 ** Delete the record at which the P1 cursor is currently pointing.
5412 **
5413 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
5414 ** the cursor will be left pointing at  either the next or the previous
5415 ** record in the table. If it is left pointing at the next record, then
5416 ** the next Next instruction will be a no-op. As a result, in this case
5417 ** it is ok to delete a record from within a Next loop. If
5418 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
5419 ** left in an undefined state.
5420 **
5421 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
5422 ** delete one of several associated with deleting a table row and all its
5423 ** associated index entries.  Exactly one of those deletes is the "primary"
5424 ** delete.  The others are all on OPFLAG_FORDELETE cursors or else are
5425 ** marked with the AUXDELETE flag.
5426 **
5427 ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
5428 ** change count is incremented (otherwise not).
5429 **
5430 ** P1 must not be pseudo-table.  It has to be a real table with
5431 ** multiple rows.
5432 **
5433 ** If P4 is not NULL then it points to a Table object. In this case either
5434 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
5435 ** have been positioned using OP_NotFound prior to invoking this opcode in
5436 ** this case. Specifically, if one is configured, the pre-update hook is
5437 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
5438 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
5439 **
5440 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
5441 ** of the memory cell that contains the value that the rowid of the row will
5442 ** be set to by the update.
5443 */
5444 case OP_Delete: {
5445   VdbeCursor *pC;
5446   const char *zDb;
5447   Table *pTab;
5448   int opflags;
5449 
5450   opflags = pOp->p2;
5451   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5452   pC = p->apCsr[pOp->p1];
5453   assert( pC!=0 );
5454   assert( pC->eCurType==CURTYPE_BTREE );
5455   assert( pC->uc.pCursor!=0 );
5456   assert( pC->deferredMoveto==0 );
5457   sqlite3VdbeIncrWriteCounter(p, pC);
5458 
5459 #ifdef SQLITE_DEBUG
5460   if( pOp->p4type==P4_TABLE
5461    && HasRowid(pOp->p4.pTab)
5462    && pOp->p5==0
5463    && sqlite3BtreeCursorIsValidNN(pC->uc.pCursor)
5464   ){
5465     /* If p5 is zero, the seek operation that positioned the cursor prior to
5466     ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
5467     ** the row that is being deleted */
5468     i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5469     assert( CORRUPT_DB || pC->movetoTarget==iKey );
5470   }
5471 #endif
5472 
5473   /* If the update-hook or pre-update-hook will be invoked, set zDb to
5474   ** the name of the db to pass as to it. Also set local pTab to a copy
5475   ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
5476   ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
5477   ** VdbeCursor.movetoTarget to the current rowid.  */
5478   if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
5479     assert( pC->iDb>=0 );
5480     assert( pOp->p4.pTab!=0 );
5481     zDb = db->aDb[pC->iDb].zDbSName;
5482     pTab = pOp->p4.pTab;
5483     if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
5484       pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5485     }
5486   }else{
5487     zDb = 0;
5488     pTab = 0;
5489   }
5490 
5491 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
5492   /* Invoke the pre-update-hook if required. */
5493   assert( db->xPreUpdateCallback==0 || pTab==pOp->p4.pTab );
5494   if( db->xPreUpdateCallback && pTab ){
5495     assert( !(opflags & OPFLAG_ISUPDATE)
5496          || HasRowid(pTab)==0
5497          || (aMem[pOp->p3].flags & MEM_Int)
5498     );
5499     sqlite3VdbePreUpdateHook(p, pC,
5500         (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
5501         zDb, pTab, pC->movetoTarget,
5502         pOp->p3, -1
5503     );
5504   }
5505   if( opflags & OPFLAG_ISNOOP ) break;
5506 #endif
5507 
5508   /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
5509   assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
5510   assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
5511   assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
5512 
5513 #ifdef SQLITE_DEBUG
5514   if( p->pFrame==0 ){
5515     if( pC->isEphemeral==0
5516         && (pOp->p5 & OPFLAG_AUXDELETE)==0
5517         && (pC->wrFlag & OPFLAG_FORDELETE)==0
5518       ){
5519       nExtraDelete++;
5520     }
5521     if( pOp->p2 & OPFLAG_NCHANGE ){
5522       nExtraDelete--;
5523     }
5524   }
5525 #endif
5526 
5527   rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
5528   pC->cacheStatus = CACHE_STALE;
5529   pC->seekResult = 0;
5530   if( rc ) goto abort_due_to_error;
5531 
5532   /* Invoke the update-hook if required. */
5533   if( opflags & OPFLAG_NCHANGE ){
5534     p->nChange++;
5535     if( db->xUpdateCallback && ALWAYS(pTab!=0) && HasRowid(pTab) ){
5536       db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
5537           pC->movetoTarget);
5538       assert( pC->iDb>=0 );
5539     }
5540   }
5541 
5542   break;
5543 }
5544 /* Opcode: ResetCount * * * * *
5545 **
5546 ** The value of the change counter is copied to the database handle
5547 ** change counter (returned by subsequent calls to sqlite3_changes()).
5548 ** Then the VMs internal change counter resets to 0.
5549 ** This is used by trigger programs.
5550 */
5551 case OP_ResetCount: {
5552   sqlite3VdbeSetChanges(db, p->nChange);
5553   p->nChange = 0;
5554   break;
5555 }
5556 
5557 /* Opcode: SorterCompare P1 P2 P3 P4
5558 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
5559 **
5560 ** P1 is a sorter cursor. This instruction compares a prefix of the
5561 ** record blob in register P3 against a prefix of the entry that
5562 ** the sorter cursor currently points to.  Only the first P4 fields
5563 ** of r[P3] and the sorter record are compared.
5564 **
5565 ** If either P3 or the sorter contains a NULL in one of their significant
5566 ** fields (not counting the P4 fields at the end which are ignored) then
5567 ** the comparison is assumed to be equal.
5568 **
5569 ** Fall through to next instruction if the two records compare equal to
5570 ** each other.  Jump to P2 if they are different.
5571 */
5572 case OP_SorterCompare: {
5573   VdbeCursor *pC;
5574   int res;
5575   int nKeyCol;
5576 
5577   pC = p->apCsr[pOp->p1];
5578   assert( isSorter(pC) );
5579   assert( pOp->p4type==P4_INT32 );
5580   pIn3 = &aMem[pOp->p3];
5581   nKeyCol = pOp->p4.i;
5582   res = 0;
5583   rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
5584   VdbeBranchTaken(res!=0,2);
5585   if( rc ) goto abort_due_to_error;
5586   if( res ) goto jump_to_p2;
5587   break;
5588 };
5589 
5590 /* Opcode: SorterData P1 P2 P3 * *
5591 ** Synopsis: r[P2]=data
5592 **
5593 ** Write into register P2 the current sorter data for sorter cursor P1.
5594 ** Then clear the column header cache on cursor P3.
5595 **
5596 ** This opcode is normally use to move a record out of the sorter and into
5597 ** a register that is the source for a pseudo-table cursor created using
5598 ** OpenPseudo.  That pseudo-table cursor is the one that is identified by
5599 ** parameter P3.  Clearing the P3 column cache as part of this opcode saves
5600 ** us from having to issue a separate NullRow instruction to clear that cache.
5601 */
5602 case OP_SorterData: {
5603   VdbeCursor *pC;
5604 
5605   pOut = &aMem[pOp->p2];
5606   pC = p->apCsr[pOp->p1];
5607   assert( isSorter(pC) );
5608   rc = sqlite3VdbeSorterRowkey(pC, pOut);
5609   assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
5610   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5611   if( rc ) goto abort_due_to_error;
5612   p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
5613   break;
5614 }
5615 
5616 /* Opcode: RowData P1 P2 P3 * *
5617 ** Synopsis: r[P2]=data
5618 **
5619 ** Write into register P2 the complete row content for the row at
5620 ** which cursor P1 is currently pointing.
5621 ** There is no interpretation of the data.
5622 ** It is just copied onto the P2 register exactly as
5623 ** it is found in the database file.
5624 **
5625 ** If cursor P1 is an index, then the content is the key of the row.
5626 ** If cursor P2 is a table, then the content extracted is the data.
5627 **
5628 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
5629 ** of a real table, not a pseudo-table.
5630 **
5631 ** If P3!=0 then this opcode is allowed to make an ephemeral pointer
5632 ** into the database page.  That means that the content of the output
5633 ** register will be invalidated as soon as the cursor moves - including
5634 ** moves caused by other cursors that "save" the current cursors
5635 ** position in order that they can write to the same table.  If P3==0
5636 ** then a copy of the data is made into memory.  P3!=0 is faster, but
5637 ** P3==0 is safer.
5638 **
5639 ** If P3!=0 then the content of the P2 register is unsuitable for use
5640 ** in OP_Result and any OP_Result will invalidate the P2 register content.
5641 ** The P2 register content is invalidated by opcodes like OP_Function or
5642 ** by any use of another cursor pointing to the same table.
5643 */
5644 case OP_RowData: {
5645   VdbeCursor *pC;
5646   BtCursor *pCrsr;
5647   u32 n;
5648 
5649   pOut = out2Prerelease(p, pOp);
5650 
5651   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5652   pC = p->apCsr[pOp->p1];
5653   assert( pC!=0 );
5654   assert( pC->eCurType==CURTYPE_BTREE );
5655   assert( isSorter(pC)==0 );
5656   assert( pC->nullRow==0 );
5657   assert( pC->uc.pCursor!=0 );
5658   pCrsr = pC->uc.pCursor;
5659 
5660   /* The OP_RowData opcodes always follow OP_NotExists or
5661   ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
5662   ** that might invalidate the cursor.
5663   ** If this where not the case, on of the following assert()s
5664   ** would fail.  Should this ever change (because of changes in the code
5665   ** generator) then the fix would be to insert a call to
5666   ** sqlite3VdbeCursorMoveto().
5667   */
5668   assert( pC->deferredMoveto==0 );
5669   assert( sqlite3BtreeCursorIsValid(pCrsr) );
5670 
5671   n = sqlite3BtreePayloadSize(pCrsr);
5672   if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
5673     goto too_big;
5674   }
5675   testcase( n==0 );
5676   rc = sqlite3VdbeMemFromBtreeZeroOffset(pCrsr, n, pOut);
5677   if( rc ) goto abort_due_to_error;
5678   if( !pOp->p3 ) Deephemeralize(pOut);
5679   UPDATE_MAX_BLOBSIZE(pOut);
5680   REGISTER_TRACE(pOp->p2, pOut);
5681   break;
5682 }
5683 
5684 /* Opcode: Rowid P1 P2 * * *
5685 ** Synopsis: r[P2]=rowid
5686 **
5687 ** Store in register P2 an integer which is the key of the table entry that
5688 ** P1 is currently point to.
5689 **
5690 ** P1 can be either an ordinary table or a virtual table.  There used to
5691 ** be a separate OP_VRowid opcode for use with virtual tables, but this
5692 ** one opcode now works for both table types.
5693 */
5694 case OP_Rowid: {                 /* out2 */
5695   VdbeCursor *pC;
5696   i64 v;
5697   sqlite3_vtab *pVtab;
5698   const sqlite3_module *pModule;
5699 
5700   pOut = out2Prerelease(p, pOp);
5701   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5702   pC = p->apCsr[pOp->p1];
5703   assert( pC!=0 );
5704   assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
5705   if( pC->nullRow ){
5706     pOut->flags = MEM_Null;
5707     break;
5708   }else if( pC->deferredMoveto ){
5709     v = pC->movetoTarget;
5710 #ifndef SQLITE_OMIT_VIRTUALTABLE
5711   }else if( pC->eCurType==CURTYPE_VTAB ){
5712     assert( pC->uc.pVCur!=0 );
5713     pVtab = pC->uc.pVCur->pVtab;
5714     pModule = pVtab->pModule;
5715     assert( pModule->xRowid );
5716     rc = pModule->xRowid(pC->uc.pVCur, &v);
5717     sqlite3VtabImportErrmsg(p, pVtab);
5718     if( rc ) goto abort_due_to_error;
5719 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5720   }else{
5721     assert( pC->eCurType==CURTYPE_BTREE );
5722     assert( pC->uc.pCursor!=0 );
5723     rc = sqlite3VdbeCursorRestore(pC);
5724     if( rc ) goto abort_due_to_error;
5725     if( pC->nullRow ){
5726       pOut->flags = MEM_Null;
5727       break;
5728     }
5729     v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5730   }
5731   pOut->u.i = v;
5732   break;
5733 }
5734 
5735 /* Opcode: NullRow P1 * * * *
5736 **
5737 ** Move the cursor P1 to a null row.  Any OP_Column operations
5738 ** that occur while the cursor is on the null row will always
5739 ** write a NULL.
5740 **
5741 ** Or, if P1 is a Pseudo-Cursor (a cursor opened using OP_OpenPseudo)
5742 ** just reset the cache for that cursor.  This causes the row of
5743 ** content held by the pseudo-cursor to be reparsed.
5744 */
5745 case OP_NullRow: {
5746   VdbeCursor *pC;
5747 
5748   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5749   pC = p->apCsr[pOp->p1];
5750   assert( pC!=0 );
5751   pC->nullRow = 1;
5752   pC->cacheStatus = CACHE_STALE;
5753   if( pC->eCurType==CURTYPE_BTREE ){
5754     assert( pC->uc.pCursor!=0 );
5755     sqlite3BtreeClearCursor(pC->uc.pCursor);
5756   }
5757 #ifdef SQLITE_DEBUG
5758   if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
5759 #endif
5760   break;
5761 }
5762 
5763 /* Opcode: SeekEnd P1 * * * *
5764 **
5765 ** Position cursor P1 at the end of the btree for the purpose of
5766 ** appending a new entry onto the btree.
5767 **
5768 ** It is assumed that the cursor is used only for appending and so
5769 ** if the cursor is valid, then the cursor must already be pointing
5770 ** at the end of the btree and so no changes are made to
5771 ** the cursor.
5772 */
5773 /* Opcode: Last P1 P2 * * *
5774 **
5775 ** The next use of the Rowid or Column or Prev instruction for P1
5776 ** will refer to the last entry in the database table or index.
5777 ** If the table or index is empty and P2>0, then jump immediately to P2.
5778 ** If P2 is 0 or if the table or index is not empty, fall through
5779 ** to the following instruction.
5780 **
5781 ** This opcode leaves the cursor configured to move in reverse order,
5782 ** from the end toward the beginning.  In other words, the cursor is
5783 ** configured to use Prev, not Next.
5784 */
5785 case OP_SeekEnd:
5786 case OP_Last: {        /* jump */
5787   VdbeCursor *pC;
5788   BtCursor *pCrsr;
5789   int res;
5790 
5791   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5792   pC = p->apCsr[pOp->p1];
5793   assert( pC!=0 );
5794   assert( pC->eCurType==CURTYPE_BTREE );
5795   pCrsr = pC->uc.pCursor;
5796   res = 0;
5797   assert( pCrsr!=0 );
5798 #ifdef SQLITE_DEBUG
5799   pC->seekOp = pOp->opcode;
5800 #endif
5801   if( pOp->opcode==OP_SeekEnd ){
5802     assert( pOp->p2==0 );
5803     pC->seekResult = -1;
5804     if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
5805       break;
5806     }
5807   }
5808   rc = sqlite3BtreeLast(pCrsr, &res);
5809   pC->nullRow = (u8)res;
5810   pC->deferredMoveto = 0;
5811   pC->cacheStatus = CACHE_STALE;
5812   if( rc ) goto abort_due_to_error;
5813   if( pOp->p2>0 ){
5814     VdbeBranchTaken(res!=0,2);
5815     if( res ) goto jump_to_p2;
5816   }
5817   break;
5818 }
5819 
5820 /* Opcode: IfSmaller P1 P2 P3 * *
5821 **
5822 ** Estimate the number of rows in the table P1.  Jump to P2 if that
5823 ** estimate is less than approximately 2**(0.1*P3).
5824 */
5825 case OP_IfSmaller: {        /* jump */
5826   VdbeCursor *pC;
5827   BtCursor *pCrsr;
5828   int res;
5829   i64 sz;
5830 
5831   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5832   pC = p->apCsr[pOp->p1];
5833   assert( pC!=0 );
5834   pCrsr = pC->uc.pCursor;
5835   assert( pCrsr );
5836   rc = sqlite3BtreeFirst(pCrsr, &res);
5837   if( rc ) goto abort_due_to_error;
5838   if( res==0 ){
5839     sz = sqlite3BtreeRowCountEst(pCrsr);
5840     if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
5841   }
5842   VdbeBranchTaken(res!=0,2);
5843   if( res ) goto jump_to_p2;
5844   break;
5845 }
5846 
5847 
5848 /* Opcode: SorterSort P1 P2 * * *
5849 **
5850 ** After all records have been inserted into the Sorter object
5851 ** identified by P1, invoke this opcode to actually do the sorting.
5852 ** Jump to P2 if there are no records to be sorted.
5853 **
5854 ** This opcode is an alias for OP_Sort and OP_Rewind that is used
5855 ** for Sorter objects.
5856 */
5857 /* Opcode: Sort P1 P2 * * *
5858 **
5859 ** This opcode does exactly the same thing as OP_Rewind except that
5860 ** it increments an undocumented global variable used for testing.
5861 **
5862 ** Sorting is accomplished by writing records into a sorting index,
5863 ** then rewinding that index and playing it back from beginning to
5864 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
5865 ** rewinding so that the global variable will be incremented and
5866 ** regression tests can determine whether or not the optimizer is
5867 ** correctly optimizing out sorts.
5868 */
5869 case OP_SorterSort:    /* jump */
5870 case OP_Sort: {        /* jump */
5871 #ifdef SQLITE_TEST
5872   sqlite3_sort_count++;
5873   sqlite3_search_count--;
5874 #endif
5875   p->aCounter[SQLITE_STMTSTATUS_SORT]++;
5876   /* Fall through into OP_Rewind */
5877   /* no break */ deliberate_fall_through
5878 }
5879 /* Opcode: Rewind P1 P2 * * *
5880 **
5881 ** The next use of the Rowid or Column or Next instruction for P1
5882 ** will refer to the first entry in the database table or index.
5883 ** If the table or index is empty, jump immediately to P2.
5884 ** If the table or index is not empty, fall through to the following
5885 ** instruction.
5886 **
5887 ** This opcode leaves the cursor configured to move in forward order,
5888 ** from the beginning toward the end.  In other words, the cursor is
5889 ** configured to use Next, not Prev.
5890 */
5891 case OP_Rewind: {        /* jump */
5892   VdbeCursor *pC;
5893   BtCursor *pCrsr;
5894   int res;
5895 
5896   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5897   assert( pOp->p5==0 );
5898   pC = p->apCsr[pOp->p1];
5899   assert( pC!=0 );
5900   assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
5901   res = 1;
5902 #ifdef SQLITE_DEBUG
5903   pC->seekOp = OP_Rewind;
5904 #endif
5905   if( isSorter(pC) ){
5906     rc = sqlite3VdbeSorterRewind(pC, &res);
5907   }else{
5908     assert( pC->eCurType==CURTYPE_BTREE );
5909     pCrsr = pC->uc.pCursor;
5910     assert( pCrsr );
5911     rc = sqlite3BtreeFirst(pCrsr, &res);
5912     pC->deferredMoveto = 0;
5913     pC->cacheStatus = CACHE_STALE;
5914   }
5915   if( rc ) goto abort_due_to_error;
5916   pC->nullRow = (u8)res;
5917   assert( pOp->p2>0 && pOp->p2<p->nOp );
5918   VdbeBranchTaken(res!=0,2);
5919   if( res ) goto jump_to_p2;
5920   break;
5921 }
5922 
5923 /* Opcode: Next P1 P2 P3 * P5
5924 **
5925 ** Advance cursor P1 so that it points to the next key/data pair in its
5926 ** table or index.  If there are no more key/value pairs then fall through
5927 ** to the following instruction.  But if the cursor advance was successful,
5928 ** jump immediately to P2.
5929 **
5930 ** The Next opcode is only valid following an SeekGT, SeekGE, or
5931 ** OP_Rewind opcode used to position the cursor.  Next is not allowed
5932 ** to follow SeekLT, SeekLE, or OP_Last.
5933 **
5934 ** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
5935 ** been opened prior to this opcode or the program will segfault.
5936 **
5937 ** The P3 value is a hint to the btree implementation. If P3==1, that
5938 ** means P1 is an SQL index and that this instruction could have been
5939 ** omitted if that index had been unique.  P3 is usually 0.  P3 is
5940 ** always either 0 or 1.
5941 **
5942 ** If P5 is positive and the jump is taken, then event counter
5943 ** number P5-1 in the prepared statement is incremented.
5944 **
5945 ** See also: Prev
5946 */
5947 /* Opcode: Prev P1 P2 P3 * P5
5948 **
5949 ** Back up cursor P1 so that it points to the previous key/data pair in its
5950 ** table or index.  If there is no previous key/value pairs then fall through
5951 ** to the following instruction.  But if the cursor backup was successful,
5952 ** jump immediately to P2.
5953 **
5954 **
5955 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
5956 ** OP_Last opcode used to position the cursor.  Prev is not allowed
5957 ** to follow SeekGT, SeekGE, or OP_Rewind.
5958 **
5959 ** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
5960 ** not open then the behavior is undefined.
5961 **
5962 ** The P3 value is a hint to the btree implementation. If P3==1, that
5963 ** means P1 is an SQL index and that this instruction could have been
5964 ** omitted if that index had been unique.  P3 is usually 0.  P3 is
5965 ** always either 0 or 1.
5966 **
5967 ** If P5 is positive and the jump is taken, then event counter
5968 ** number P5-1 in the prepared statement is incremented.
5969 */
5970 /* Opcode: SorterNext P1 P2 * * P5
5971 **
5972 ** This opcode works just like OP_Next except that P1 must be a
5973 ** sorter object for which the OP_SorterSort opcode has been
5974 ** invoked.  This opcode advances the cursor to the next sorted
5975 ** record, or jumps to P2 if there are no more sorted records.
5976 */
5977 case OP_SorterNext: {  /* jump */
5978   VdbeCursor *pC;
5979 
5980   pC = p->apCsr[pOp->p1];
5981   assert( isSorter(pC) );
5982   rc = sqlite3VdbeSorterNext(db, pC);
5983   goto next_tail;
5984 
5985 case OP_Prev:          /* jump */
5986   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5987   assert( pOp->p5<ArraySize(p->aCounter) );
5988   pC = p->apCsr[pOp->p1];
5989   assert( pC!=0 );
5990   assert( pC->deferredMoveto==0 );
5991   assert( pC->eCurType==CURTYPE_BTREE );
5992   assert( pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
5993        || pC->seekOp==OP_Last   || pC->seekOp==OP_IfNoHope
5994        || pC->seekOp==OP_NullRow);
5995   rc = sqlite3BtreePrevious(pC->uc.pCursor, pOp->p3);
5996   goto next_tail;
5997 
5998 case OP_Next:          /* jump */
5999   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6000   assert( pOp->p5<ArraySize(p->aCounter) );
6001   pC = p->apCsr[pOp->p1];
6002   assert( pC!=0 );
6003   assert( pC->deferredMoveto==0 );
6004   assert( pC->eCurType==CURTYPE_BTREE );
6005   assert( pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
6006        || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found
6007        || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid
6008        || pC->seekOp==OP_IfNoHope);
6009   rc = sqlite3BtreeNext(pC->uc.pCursor, pOp->p3);
6010 
6011 next_tail:
6012   pC->cacheStatus = CACHE_STALE;
6013   VdbeBranchTaken(rc==SQLITE_OK,2);
6014   if( rc==SQLITE_OK ){
6015     pC->nullRow = 0;
6016     p->aCounter[pOp->p5]++;
6017 #ifdef SQLITE_TEST
6018     sqlite3_search_count++;
6019 #endif
6020     goto jump_to_p2_and_check_for_interrupt;
6021   }
6022   if( rc!=SQLITE_DONE ) goto abort_due_to_error;
6023   rc = SQLITE_OK;
6024   pC->nullRow = 1;
6025   goto check_for_interrupt;
6026 }
6027 
6028 /* Opcode: IdxInsert P1 P2 P3 P4 P5
6029 ** Synopsis: key=r[P2]
6030 **
6031 ** Register P2 holds an SQL index key made using the
6032 ** MakeRecord instructions.  This opcode writes that key
6033 ** into the index P1.  Data for the entry is nil.
6034 **
6035 ** If P4 is not zero, then it is the number of values in the unpacked
6036 ** key of reg(P2).  In that case, P3 is the index of the first register
6037 ** for the unpacked key.  The availability of the unpacked key can sometimes
6038 ** be an optimization.
6039 **
6040 ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
6041 ** that this insert is likely to be an append.
6042 **
6043 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
6044 ** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
6045 ** then the change counter is unchanged.
6046 **
6047 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
6048 ** run faster by avoiding an unnecessary seek on cursor P1.  However,
6049 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
6050 ** seeks on the cursor or if the most recent seek used a key equivalent
6051 ** to P2.
6052 **
6053 ** This instruction only works for indices.  The equivalent instruction
6054 ** for tables is OP_Insert.
6055 */
6056 case OP_IdxInsert: {        /* in2 */
6057   VdbeCursor *pC;
6058   BtreePayload x;
6059 
6060   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6061   pC = p->apCsr[pOp->p1];
6062   sqlite3VdbeIncrWriteCounter(p, pC);
6063   assert( pC!=0 );
6064   assert( !isSorter(pC) );
6065   pIn2 = &aMem[pOp->p2];
6066   assert( (pIn2->flags & MEM_Blob) || (pOp->p5 & OPFLAG_PREFORMAT) );
6067   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
6068   assert( pC->eCurType==CURTYPE_BTREE );
6069   assert( pC->isTable==0 );
6070   rc = ExpandBlob(pIn2);
6071   if( rc ) goto abort_due_to_error;
6072   x.nKey = pIn2->n;
6073   x.pKey = pIn2->z;
6074   x.aMem = aMem + pOp->p3;
6075   x.nMem = (u16)pOp->p4.i;
6076   rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
6077        (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
6078       ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
6079       );
6080   assert( pC->deferredMoveto==0 );
6081   pC->cacheStatus = CACHE_STALE;
6082   if( rc) goto abort_due_to_error;
6083   break;
6084 }
6085 
6086 /* Opcode: SorterInsert P1 P2 * * *
6087 ** Synopsis: key=r[P2]
6088 **
6089 ** Register P2 holds an SQL index key made using the
6090 ** MakeRecord instructions.  This opcode writes that key
6091 ** into the sorter P1.  Data for the entry is nil.
6092 */
6093 case OP_SorterInsert: {     /* in2 */
6094   VdbeCursor *pC;
6095 
6096   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6097   pC = p->apCsr[pOp->p1];
6098   sqlite3VdbeIncrWriteCounter(p, pC);
6099   assert( pC!=0 );
6100   assert( isSorter(pC) );
6101   pIn2 = &aMem[pOp->p2];
6102   assert( pIn2->flags & MEM_Blob );
6103   assert( pC->isTable==0 );
6104   rc = ExpandBlob(pIn2);
6105   if( rc ) goto abort_due_to_error;
6106   rc = sqlite3VdbeSorterWrite(pC, pIn2);
6107   if( rc) goto abort_due_to_error;
6108   break;
6109 }
6110 
6111 /* Opcode: IdxDelete P1 P2 P3 * P5
6112 ** Synopsis: key=r[P2@P3]
6113 **
6114 ** The content of P3 registers starting at register P2 form
6115 ** an unpacked index key. This opcode removes that entry from the
6116 ** index opened by cursor P1.
6117 **
6118 ** If P5 is not zero, then raise an SQLITE_CORRUPT_INDEX error
6119 ** if no matching index entry is found.  This happens when running
6120 ** an UPDATE or DELETE statement and the index entry to be updated
6121 ** or deleted is not found.  For some uses of IdxDelete
6122 ** (example:  the EXCEPT operator) it does not matter that no matching
6123 ** entry is found.  For those cases, P5 is zero.  Also, do not raise
6124 ** this (self-correcting and non-critical) error if in writable_schema mode.
6125 */
6126 case OP_IdxDelete: {
6127   VdbeCursor *pC;
6128   BtCursor *pCrsr;
6129   int res;
6130   UnpackedRecord r;
6131 
6132   assert( pOp->p3>0 );
6133   assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
6134   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6135   pC = p->apCsr[pOp->p1];
6136   assert( pC!=0 );
6137   assert( pC->eCurType==CURTYPE_BTREE );
6138   sqlite3VdbeIncrWriteCounter(p, pC);
6139   pCrsr = pC->uc.pCursor;
6140   assert( pCrsr!=0 );
6141   r.pKeyInfo = pC->pKeyInfo;
6142   r.nField = (u16)pOp->p3;
6143   r.default_rc = 0;
6144   r.aMem = &aMem[pOp->p2];
6145   rc = sqlite3BtreeIndexMoveto(pCrsr, &r, &res);
6146   if( rc ) goto abort_due_to_error;
6147   if( res==0 ){
6148     rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
6149     if( rc ) goto abort_due_to_error;
6150   }else if( pOp->p5 && !sqlite3WritableSchema(db) ){
6151     rc = sqlite3ReportError(SQLITE_CORRUPT_INDEX, __LINE__, "index corruption");
6152     goto abort_due_to_error;
6153   }
6154   assert( pC->deferredMoveto==0 );
6155   pC->cacheStatus = CACHE_STALE;
6156   pC->seekResult = 0;
6157   break;
6158 }
6159 
6160 /* Opcode: DeferredSeek P1 * P3 P4 *
6161 ** Synopsis: Move P3 to P1.rowid if needed
6162 **
6163 ** P1 is an open index cursor and P3 is a cursor on the corresponding
6164 ** table.  This opcode does a deferred seek of the P3 table cursor
6165 ** to the row that corresponds to the current row of P1.
6166 **
6167 ** This is a deferred seek.  Nothing actually happens until
6168 ** the cursor is used to read a record.  That way, if no reads
6169 ** occur, no unnecessary I/O happens.
6170 **
6171 ** P4 may be an array of integers (type P4_INTARRAY) containing
6172 ** one entry for each column in the P3 table.  If array entry a(i)
6173 ** is non-zero, then reading column a(i)-1 from cursor P3 is
6174 ** equivalent to performing the deferred seek and then reading column i
6175 ** from P1.  This information is stored in P3 and used to redirect
6176 ** reads against P3 over to P1, thus possibly avoiding the need to
6177 ** seek and read cursor P3.
6178 */
6179 /* Opcode: IdxRowid P1 P2 * * *
6180 ** Synopsis: r[P2]=rowid
6181 **
6182 ** Write into register P2 an integer which is the last entry in the record at
6183 ** the end of the index key pointed to by cursor P1.  This integer should be
6184 ** the rowid of the table entry to which this index entry points.
6185 **
6186 ** See also: Rowid, MakeRecord.
6187 */
6188 case OP_DeferredSeek:
6189 case OP_IdxRowid: {           /* out2 */
6190   VdbeCursor *pC;             /* The P1 index cursor */
6191   VdbeCursor *pTabCur;        /* The P2 table cursor (OP_DeferredSeek only) */
6192   i64 rowid;                  /* Rowid that P1 current points to */
6193 
6194   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6195   pC = p->apCsr[pOp->p1];
6196   assert( pC!=0 );
6197   assert( pC->eCurType==CURTYPE_BTREE );
6198   assert( pC->uc.pCursor!=0 );
6199   assert( pC->isTable==0 );
6200   assert( pC->deferredMoveto==0 );
6201   assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
6202 
6203   /* The IdxRowid and Seek opcodes are combined because of the commonality
6204   ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
6205   rc = sqlite3VdbeCursorRestore(pC);
6206 
6207   /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
6208   ** out from under the cursor.  That will never happens for an IdxRowid
6209   ** or Seek opcode */
6210   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
6211 
6212   if( !pC->nullRow ){
6213     rowid = 0;  /* Not needed.  Only used to silence a warning. */
6214     rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
6215     if( rc!=SQLITE_OK ){
6216       goto abort_due_to_error;
6217     }
6218     if( pOp->opcode==OP_DeferredSeek ){
6219       assert( pOp->p3>=0 && pOp->p3<p->nCursor );
6220       pTabCur = p->apCsr[pOp->p3];
6221       assert( pTabCur!=0 );
6222       assert( pTabCur->eCurType==CURTYPE_BTREE );
6223       assert( pTabCur->uc.pCursor!=0 );
6224       assert( pTabCur->isTable );
6225       pTabCur->nullRow = 0;
6226       pTabCur->movetoTarget = rowid;
6227       pTabCur->deferredMoveto = 1;
6228       pTabCur->cacheStatus = CACHE_STALE;
6229       assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
6230       assert( !pTabCur->isEphemeral );
6231       pTabCur->ub.aAltMap = pOp->p4.ai;
6232       assert( !pC->isEphemeral );
6233       pTabCur->pAltCursor = pC;
6234     }else{
6235       pOut = out2Prerelease(p, pOp);
6236       pOut->u.i = rowid;
6237     }
6238   }else{
6239     assert( pOp->opcode==OP_IdxRowid );
6240     sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
6241   }
6242   break;
6243 }
6244 
6245 /* Opcode: FinishSeek P1 * * * *
6246 **
6247 ** If cursor P1 was previously moved via OP_DeferredSeek, complete that
6248 ** seek operation now, without further delay.  If the cursor seek has
6249 ** already occurred, this instruction is a no-op.
6250 */
6251 case OP_FinishSeek: {
6252   VdbeCursor *pC;             /* The P1 index cursor */
6253 
6254   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6255   pC = p->apCsr[pOp->p1];
6256   if( pC->deferredMoveto ){
6257     rc = sqlite3VdbeFinishMoveto(pC);
6258     if( rc ) goto abort_due_to_error;
6259   }
6260   break;
6261 }
6262 
6263 /* Opcode: IdxGE P1 P2 P3 P4 *
6264 ** Synopsis: key=r[P3@P4]
6265 **
6266 ** The P4 register values beginning with P3 form an unpacked index
6267 ** key that omits the PRIMARY KEY.  Compare this key value against the index
6268 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
6269 ** fields at the end.
6270 **
6271 ** If the P1 index entry is greater than or equal to the key value
6272 ** then jump to P2.  Otherwise fall through to the next instruction.
6273 */
6274 /* Opcode: IdxGT P1 P2 P3 P4 *
6275 ** Synopsis: key=r[P3@P4]
6276 **
6277 ** The P4 register values beginning with P3 form an unpacked index
6278 ** key that omits the PRIMARY KEY.  Compare this key value against the index
6279 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
6280 ** fields at the end.
6281 **
6282 ** If the P1 index entry is greater than the key value
6283 ** then jump to P2.  Otherwise fall through to the next instruction.
6284 */
6285 /* Opcode: IdxLT P1 P2 P3 P4 *
6286 ** Synopsis: key=r[P3@P4]
6287 **
6288 ** The P4 register values beginning with P3 form an unpacked index
6289 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
6290 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
6291 ** ROWID on the P1 index.
6292 **
6293 ** If the P1 index entry is less than the key value then jump to P2.
6294 ** Otherwise fall through to the next instruction.
6295 */
6296 /* Opcode: IdxLE P1 P2 P3 P4 *
6297 ** Synopsis: key=r[P3@P4]
6298 **
6299 ** The P4 register values beginning with P3 form an unpacked index
6300 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
6301 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
6302 ** ROWID on the P1 index.
6303 **
6304 ** If the P1 index entry is less than or equal to the key value then jump
6305 ** to P2. Otherwise fall through to the next instruction.
6306 */
6307 case OP_IdxLE:          /* jump */
6308 case OP_IdxGT:          /* jump */
6309 case OP_IdxLT:          /* jump */
6310 case OP_IdxGE:  {       /* jump */
6311   VdbeCursor *pC;
6312   int res;
6313   UnpackedRecord r;
6314 
6315   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6316   pC = p->apCsr[pOp->p1];
6317   assert( pC!=0 );
6318   assert( pC->isOrdered );
6319   assert( pC->eCurType==CURTYPE_BTREE );
6320   assert( pC->uc.pCursor!=0);
6321   assert( pC->deferredMoveto==0 );
6322   assert( pOp->p4type==P4_INT32 );
6323   r.pKeyInfo = pC->pKeyInfo;
6324   r.nField = (u16)pOp->p4.i;
6325   if( pOp->opcode<OP_IdxLT ){
6326     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
6327     r.default_rc = -1;
6328   }else{
6329     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
6330     r.default_rc = 0;
6331   }
6332   r.aMem = &aMem[pOp->p3];
6333 #ifdef SQLITE_DEBUG
6334   {
6335     int i;
6336     for(i=0; i<r.nField; i++){
6337       assert( memIsValid(&r.aMem[i]) );
6338       REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]);
6339     }
6340   }
6341 #endif
6342 
6343   /* Inlined version of sqlite3VdbeIdxKeyCompare() */
6344   {
6345     i64 nCellKey = 0;
6346     BtCursor *pCur;
6347     Mem m;
6348 
6349     assert( pC->eCurType==CURTYPE_BTREE );
6350     pCur = pC->uc.pCursor;
6351     assert( sqlite3BtreeCursorIsValid(pCur) );
6352     nCellKey = sqlite3BtreePayloadSize(pCur);
6353     /* nCellKey will always be between 0 and 0xffffffff because of the way
6354     ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
6355     if( nCellKey<=0 || nCellKey>0x7fffffff ){
6356       rc = SQLITE_CORRUPT_BKPT;
6357       goto abort_due_to_error;
6358     }
6359     sqlite3VdbeMemInit(&m, db, 0);
6360     rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
6361     if( rc ) goto abort_due_to_error;
6362     res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, &r, 0);
6363     sqlite3VdbeMemReleaseMalloc(&m);
6364   }
6365   /* End of inlined sqlite3VdbeIdxKeyCompare() */
6366 
6367   assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
6368   if( (pOp->opcode&1)==(OP_IdxLT&1) ){
6369     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
6370     res = -res;
6371   }else{
6372     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
6373     res++;
6374   }
6375   VdbeBranchTaken(res>0,2);
6376   assert( rc==SQLITE_OK );
6377   if( res>0 ) goto jump_to_p2;
6378   break;
6379 }
6380 
6381 /* Opcode: Destroy P1 P2 P3 * *
6382 **
6383 ** Delete an entire database table or index whose root page in the database
6384 ** file is given by P1.
6385 **
6386 ** The table being destroyed is in the main database file if P3==0.  If
6387 ** P3==1 then the table to be clear is in the auxiliary database file
6388 ** that is used to store tables create using CREATE TEMPORARY TABLE.
6389 **
6390 ** If AUTOVACUUM is enabled then it is possible that another root page
6391 ** might be moved into the newly deleted root page in order to keep all
6392 ** root pages contiguous at the beginning of the database.  The former
6393 ** value of the root page that moved - its value before the move occurred -
6394 ** is stored in register P2. If no page movement was required (because the
6395 ** table being dropped was already the last one in the database) then a
6396 ** zero is stored in register P2.  If AUTOVACUUM is disabled then a zero
6397 ** is stored in register P2.
6398 **
6399 ** This opcode throws an error if there are any active reader VMs when
6400 ** it is invoked. This is done to avoid the difficulty associated with
6401 ** updating existing cursors when a root page is moved in an AUTOVACUUM
6402 ** database. This error is thrown even if the database is not an AUTOVACUUM
6403 ** db in order to avoid introducing an incompatibility between autovacuum
6404 ** and non-autovacuum modes.
6405 **
6406 ** See also: Clear
6407 */
6408 case OP_Destroy: {     /* out2 */
6409   int iMoved;
6410   int iDb;
6411 
6412   sqlite3VdbeIncrWriteCounter(p, 0);
6413   assert( p->readOnly==0 );
6414   assert( pOp->p1>1 );
6415   pOut = out2Prerelease(p, pOp);
6416   pOut->flags = MEM_Null;
6417   if( db->nVdbeRead > db->nVDestroy+1 ){
6418     rc = SQLITE_LOCKED;
6419     p->errorAction = OE_Abort;
6420     goto abort_due_to_error;
6421   }else{
6422     iDb = pOp->p3;
6423     assert( DbMaskTest(p->btreeMask, iDb) );
6424     iMoved = 0;  /* Not needed.  Only to silence a warning. */
6425     rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
6426     pOut->flags = MEM_Int;
6427     pOut->u.i = iMoved;
6428     if( rc ) goto abort_due_to_error;
6429 #ifndef SQLITE_OMIT_AUTOVACUUM
6430     if( iMoved!=0 ){
6431       sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
6432       /* All OP_Destroy operations occur on the same btree */
6433       assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
6434       resetSchemaOnFault = iDb+1;
6435     }
6436 #endif
6437   }
6438   break;
6439 }
6440 
6441 /* Opcode: Clear P1 P2 P3
6442 **
6443 ** Delete all contents of the database table or index whose root page
6444 ** in the database file is given by P1.  But, unlike Destroy, do not
6445 ** remove the table or index from the database file.
6446 **
6447 ** The table being clear is in the main database file if P2==0.  If
6448 ** P2==1 then the table to be clear is in the auxiliary database file
6449 ** that is used to store tables create using CREATE TEMPORARY TABLE.
6450 **
6451 ** If the P3 value is non-zero, then the row change count is incremented
6452 ** by the number of rows in the table being cleared. If P3 is greater
6453 ** than zero, then the value stored in register P3 is also incremented
6454 ** by the number of rows in the table being cleared.
6455 **
6456 ** See also: Destroy
6457 */
6458 case OP_Clear: {
6459   i64 nChange;
6460 
6461   sqlite3VdbeIncrWriteCounter(p, 0);
6462   nChange = 0;
6463   assert( p->readOnly==0 );
6464   assert( DbMaskTest(p->btreeMask, pOp->p2) );
6465   rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, (u32)pOp->p1, &nChange);
6466   if( pOp->p3 ){
6467     p->nChange += nChange;
6468     if( pOp->p3>0 ){
6469       assert( memIsValid(&aMem[pOp->p3]) );
6470       memAboutToChange(p, &aMem[pOp->p3]);
6471       aMem[pOp->p3].u.i += nChange;
6472     }
6473   }
6474   if( rc ) goto abort_due_to_error;
6475   break;
6476 }
6477 
6478 /* Opcode: ResetSorter P1 * * * *
6479 **
6480 ** Delete all contents from the ephemeral table or sorter
6481 ** that is open on cursor P1.
6482 **
6483 ** This opcode only works for cursors used for sorting and
6484 ** opened with OP_OpenEphemeral or OP_SorterOpen.
6485 */
6486 case OP_ResetSorter: {
6487   VdbeCursor *pC;
6488 
6489   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6490   pC = p->apCsr[pOp->p1];
6491   assert( pC!=0 );
6492   if( isSorter(pC) ){
6493     sqlite3VdbeSorterReset(db, pC->uc.pSorter);
6494   }else{
6495     assert( pC->eCurType==CURTYPE_BTREE );
6496     assert( pC->isEphemeral );
6497     rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
6498     if( rc ) goto abort_due_to_error;
6499   }
6500   break;
6501 }
6502 
6503 /* Opcode: CreateBtree P1 P2 P3 * *
6504 ** Synopsis: r[P2]=root iDb=P1 flags=P3
6505 **
6506 ** Allocate a new b-tree in the main database file if P1==0 or in the
6507 ** TEMP database file if P1==1 or in an attached database if
6508 ** P1>1.  The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
6509 ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
6510 ** The root page number of the new b-tree is stored in register P2.
6511 */
6512 case OP_CreateBtree: {          /* out2 */
6513   Pgno pgno;
6514   Db *pDb;
6515 
6516   sqlite3VdbeIncrWriteCounter(p, 0);
6517   pOut = out2Prerelease(p, pOp);
6518   pgno = 0;
6519   assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
6520   assert( pOp->p1>=0 && pOp->p1<db->nDb );
6521   assert( DbMaskTest(p->btreeMask, pOp->p1) );
6522   assert( p->readOnly==0 );
6523   pDb = &db->aDb[pOp->p1];
6524   assert( pDb->pBt!=0 );
6525   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
6526   if( rc ) goto abort_due_to_error;
6527   pOut->u.i = pgno;
6528   break;
6529 }
6530 
6531 /* Opcode: SqlExec * * * P4 *
6532 **
6533 ** Run the SQL statement or statements specified in the P4 string.
6534 */
6535 case OP_SqlExec: {
6536   sqlite3VdbeIncrWriteCounter(p, 0);
6537   db->nSqlExec++;
6538   rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
6539   db->nSqlExec--;
6540   if( rc ) goto abort_due_to_error;
6541   break;
6542 }
6543 
6544 /* Opcode: ParseSchema P1 * * P4 *
6545 **
6546 ** Read and parse all entries from the schema table of database P1
6547 ** that match the WHERE clause P4.  If P4 is a NULL pointer, then the
6548 ** entire schema for P1 is reparsed.
6549 **
6550 ** This opcode invokes the parser to create a new virtual machine,
6551 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
6552 */
6553 case OP_ParseSchema: {
6554   int iDb;
6555   const char *zSchema;
6556   char *zSql;
6557   InitData initData;
6558 
6559   /* Any prepared statement that invokes this opcode will hold mutexes
6560   ** on every btree.  This is a prerequisite for invoking
6561   ** sqlite3InitCallback().
6562   */
6563 #ifdef SQLITE_DEBUG
6564   for(iDb=0; iDb<db->nDb; iDb++){
6565     assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
6566   }
6567 #endif
6568 
6569   iDb = pOp->p1;
6570   assert( iDb>=0 && iDb<db->nDb );
6571   assert( DbHasProperty(db, iDb, DB_SchemaLoaded)
6572            || db->mallocFailed
6573            || (CORRUPT_DB && (db->flags & SQLITE_NoSchemaError)!=0) );
6574 
6575 #ifndef SQLITE_OMIT_ALTERTABLE
6576   if( pOp->p4.z==0 ){
6577     sqlite3SchemaClear(db->aDb[iDb].pSchema);
6578     db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
6579     rc = sqlite3InitOne(db, iDb, &p->zErrMsg, pOp->p5);
6580     db->mDbFlags |= DBFLAG_SchemaChange;
6581     p->expired = 0;
6582   }else
6583 #endif
6584   {
6585     zSchema = LEGACY_SCHEMA_TABLE;
6586     initData.db = db;
6587     initData.iDb = iDb;
6588     initData.pzErrMsg = &p->zErrMsg;
6589     initData.mInitFlags = 0;
6590     initData.mxPage = sqlite3BtreeLastPage(db->aDb[iDb].pBt);
6591     zSql = sqlite3MPrintf(db,
6592        "SELECT*FROM\"%w\".%s WHERE %s ORDER BY rowid",
6593        db->aDb[iDb].zDbSName, zSchema, pOp->p4.z);
6594     if( zSql==0 ){
6595       rc = SQLITE_NOMEM_BKPT;
6596     }else{
6597       assert( db->init.busy==0 );
6598       db->init.busy = 1;
6599       initData.rc = SQLITE_OK;
6600       initData.nInitRow = 0;
6601       assert( !db->mallocFailed );
6602       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
6603       if( rc==SQLITE_OK ) rc = initData.rc;
6604       if( rc==SQLITE_OK && initData.nInitRow==0 ){
6605         /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse
6606         ** at least one SQL statement. Any less than that indicates that
6607         ** the sqlite_schema table is corrupt. */
6608         rc = SQLITE_CORRUPT_BKPT;
6609       }
6610       sqlite3DbFreeNN(db, zSql);
6611       db->init.busy = 0;
6612     }
6613   }
6614   if( rc ){
6615     sqlite3ResetAllSchemasOfConnection(db);
6616     if( rc==SQLITE_NOMEM ){
6617       goto no_mem;
6618     }
6619     goto abort_due_to_error;
6620   }
6621   break;
6622 }
6623 
6624 #if !defined(SQLITE_OMIT_ANALYZE)
6625 /* Opcode: LoadAnalysis P1 * * * *
6626 **
6627 ** Read the sqlite_stat1 table for database P1 and load the content
6628 ** of that table into the internal index hash table.  This will cause
6629 ** the analysis to be used when preparing all subsequent queries.
6630 */
6631 case OP_LoadAnalysis: {
6632   assert( pOp->p1>=0 && pOp->p1<db->nDb );
6633   rc = sqlite3AnalysisLoad(db, pOp->p1);
6634   if( rc ) goto abort_due_to_error;
6635   break;
6636 }
6637 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
6638 
6639 /* Opcode: DropTable P1 * * P4 *
6640 **
6641 ** Remove the internal (in-memory) data structures that describe
6642 ** the table named P4 in database P1.  This is called after a table
6643 ** is dropped from disk (using the Destroy opcode) in order to keep
6644 ** the internal representation of the
6645 ** schema consistent with what is on disk.
6646 */
6647 case OP_DropTable: {
6648   sqlite3VdbeIncrWriteCounter(p, 0);
6649   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
6650   break;
6651 }
6652 
6653 /* Opcode: DropIndex P1 * * P4 *
6654 **
6655 ** Remove the internal (in-memory) data structures that describe
6656 ** the index named P4 in database P1.  This is called after an index
6657 ** is dropped from disk (using the Destroy opcode)
6658 ** in order to keep the internal representation of the
6659 ** schema consistent with what is on disk.
6660 */
6661 case OP_DropIndex: {
6662   sqlite3VdbeIncrWriteCounter(p, 0);
6663   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
6664   break;
6665 }
6666 
6667 /* Opcode: DropTrigger P1 * * P4 *
6668 **
6669 ** Remove the internal (in-memory) data structures that describe
6670 ** the trigger named P4 in database P1.  This is called after a trigger
6671 ** is dropped from disk (using the Destroy opcode) in order to keep
6672 ** the internal representation of the
6673 ** schema consistent with what is on disk.
6674 */
6675 case OP_DropTrigger: {
6676   sqlite3VdbeIncrWriteCounter(p, 0);
6677   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
6678   break;
6679 }
6680 
6681 
6682 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
6683 /* Opcode: IntegrityCk P1 P2 P3 P4 P5
6684 **
6685 ** Do an analysis of the currently open database.  Store in
6686 ** register P1 the text of an error message describing any problems.
6687 ** If no problems are found, store a NULL in register P1.
6688 **
6689 ** The register P3 contains one less than the maximum number of allowed errors.
6690 ** At most reg(P3) errors will be reported.
6691 ** In other words, the analysis stops as soon as reg(P1) errors are
6692 ** seen.  Reg(P1) is updated with the number of errors remaining.
6693 **
6694 ** The root page numbers of all tables in the database are integers
6695 ** stored in P4_INTARRAY argument.
6696 **
6697 ** If P5 is not zero, the check is done on the auxiliary database
6698 ** file, not the main database file.
6699 **
6700 ** This opcode is used to implement the integrity_check pragma.
6701 */
6702 case OP_IntegrityCk: {
6703   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
6704   Pgno *aRoot;    /* Array of rootpage numbers for tables to be checked */
6705   int nErr;       /* Number of errors reported */
6706   char *z;        /* Text of the error report */
6707   Mem *pnErr;     /* Register keeping track of errors remaining */
6708 
6709   assert( p->bIsReader );
6710   nRoot = pOp->p2;
6711   aRoot = pOp->p4.ai;
6712   assert( nRoot>0 );
6713   assert( aRoot[0]==(Pgno)nRoot );
6714   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
6715   pnErr = &aMem[pOp->p3];
6716   assert( (pnErr->flags & MEM_Int)!=0 );
6717   assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
6718   pIn1 = &aMem[pOp->p1];
6719   assert( pOp->p5<db->nDb );
6720   assert( DbMaskTest(p->btreeMask, pOp->p5) );
6721   z = sqlite3BtreeIntegrityCheck(db, db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
6722                                  (int)pnErr->u.i+1, &nErr);
6723   sqlite3VdbeMemSetNull(pIn1);
6724   if( nErr==0 ){
6725     assert( z==0 );
6726   }else if( z==0 ){
6727     goto no_mem;
6728   }else{
6729     pnErr->u.i -= nErr-1;
6730     sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
6731   }
6732   UPDATE_MAX_BLOBSIZE(pIn1);
6733   sqlite3VdbeChangeEncoding(pIn1, encoding);
6734   goto check_for_interrupt;
6735 }
6736 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
6737 
6738 /* Opcode: RowSetAdd P1 P2 * * *
6739 ** Synopsis: rowset(P1)=r[P2]
6740 **
6741 ** Insert the integer value held by register P2 into a RowSet object
6742 ** held in register P1.
6743 **
6744 ** An assertion fails if P2 is not an integer.
6745 */
6746 case OP_RowSetAdd: {       /* in1, in2 */
6747   pIn1 = &aMem[pOp->p1];
6748   pIn2 = &aMem[pOp->p2];
6749   assert( (pIn2->flags & MEM_Int)!=0 );
6750   if( (pIn1->flags & MEM_Blob)==0 ){
6751     if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
6752   }
6753   assert( sqlite3VdbeMemIsRowSet(pIn1) );
6754   sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i);
6755   break;
6756 }
6757 
6758 /* Opcode: RowSetRead P1 P2 P3 * *
6759 ** Synopsis: r[P3]=rowset(P1)
6760 **
6761 ** Extract the smallest value from the RowSet object in P1
6762 ** and put that value into register P3.
6763 ** Or, if RowSet object P1 is initially empty, leave P3
6764 ** unchanged and jump to instruction P2.
6765 */
6766 case OP_RowSetRead: {       /* jump, in1, out3 */
6767   i64 val;
6768 
6769   pIn1 = &aMem[pOp->p1];
6770   assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) );
6771   if( (pIn1->flags & MEM_Blob)==0
6772    || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0
6773   ){
6774     /* The boolean index is empty */
6775     sqlite3VdbeMemSetNull(pIn1);
6776     VdbeBranchTaken(1,2);
6777     goto jump_to_p2_and_check_for_interrupt;
6778   }else{
6779     /* A value was pulled from the index */
6780     VdbeBranchTaken(0,2);
6781     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
6782   }
6783   goto check_for_interrupt;
6784 }
6785 
6786 /* Opcode: RowSetTest P1 P2 P3 P4
6787 ** Synopsis: if r[P3] in rowset(P1) goto P2
6788 **
6789 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
6790 ** contains a RowSet object and that RowSet object contains
6791 ** the value held in P3, jump to register P2. Otherwise, insert the
6792 ** integer in P3 into the RowSet and continue on to the
6793 ** next opcode.
6794 **
6795 ** The RowSet object is optimized for the case where sets of integers
6796 ** are inserted in distinct phases, which each set contains no duplicates.
6797 ** Each set is identified by a unique P4 value. The first set
6798 ** must have P4==0, the final set must have P4==-1, and for all other sets
6799 ** must have P4>0.
6800 **
6801 ** This allows optimizations: (a) when P4==0 there is no need to test
6802 ** the RowSet object for P3, as it is guaranteed not to contain it,
6803 ** (b) when P4==-1 there is no need to insert the value, as it will
6804 ** never be tested for, and (c) when a value that is part of set X is
6805 ** inserted, there is no need to search to see if the same value was
6806 ** previously inserted as part of set X (only if it was previously
6807 ** inserted as part of some other set).
6808 */
6809 case OP_RowSetTest: {                     /* jump, in1, in3 */
6810   int iSet;
6811   int exists;
6812 
6813   pIn1 = &aMem[pOp->p1];
6814   pIn3 = &aMem[pOp->p3];
6815   iSet = pOp->p4.i;
6816   assert( pIn3->flags&MEM_Int );
6817 
6818   /* If there is anything other than a rowset object in memory cell P1,
6819   ** delete it now and initialize P1 with an empty rowset
6820   */
6821   if( (pIn1->flags & MEM_Blob)==0 ){
6822     if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
6823   }
6824   assert( sqlite3VdbeMemIsRowSet(pIn1) );
6825   assert( pOp->p4type==P4_INT32 );
6826   assert( iSet==-1 || iSet>=0 );
6827   if( iSet ){
6828     exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i);
6829     VdbeBranchTaken(exists!=0,2);
6830     if( exists ) goto jump_to_p2;
6831   }
6832   if( iSet>=0 ){
6833     sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i);
6834   }
6835   break;
6836 }
6837 
6838 
6839 #ifndef SQLITE_OMIT_TRIGGER
6840 
6841 /* Opcode: Program P1 P2 P3 P4 P5
6842 **
6843 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
6844 **
6845 ** P1 contains the address of the memory cell that contains the first memory
6846 ** cell in an array of values used as arguments to the sub-program. P2
6847 ** contains the address to jump to if the sub-program throws an IGNORE
6848 ** exception using the RAISE() function. Register P3 contains the address
6849 ** of a memory cell in this (the parent) VM that is used to allocate the
6850 ** memory required by the sub-vdbe at runtime.
6851 **
6852 ** P4 is a pointer to the VM containing the trigger program.
6853 **
6854 ** If P5 is non-zero, then recursive program invocation is enabled.
6855 */
6856 case OP_Program: {        /* jump */
6857   int nMem;               /* Number of memory registers for sub-program */
6858   int nByte;              /* Bytes of runtime space required for sub-program */
6859   Mem *pRt;               /* Register to allocate runtime space */
6860   Mem *pMem;              /* Used to iterate through memory cells */
6861   Mem *pEnd;              /* Last memory cell in new array */
6862   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
6863   SubProgram *pProgram;   /* Sub-program to execute */
6864   void *t;                /* Token identifying trigger */
6865 
6866   pProgram = pOp->p4.pProgram;
6867   pRt = &aMem[pOp->p3];
6868   assert( pProgram->nOp>0 );
6869 
6870   /* If the p5 flag is clear, then recursive invocation of triggers is
6871   ** disabled for backwards compatibility (p5 is set if this sub-program
6872   ** is really a trigger, not a foreign key action, and the flag set
6873   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
6874   **
6875   ** It is recursive invocation of triggers, at the SQL level, that is
6876   ** disabled. In some cases a single trigger may generate more than one
6877   ** SubProgram (if the trigger may be executed with more than one different
6878   ** ON CONFLICT algorithm). SubProgram structures associated with a
6879   ** single trigger all have the same value for the SubProgram.token
6880   ** variable.  */
6881   if( pOp->p5 ){
6882     t = pProgram->token;
6883     for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
6884     if( pFrame ) break;
6885   }
6886 
6887   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
6888     rc = SQLITE_ERROR;
6889     sqlite3VdbeError(p, "too many levels of trigger recursion");
6890     goto abort_due_to_error;
6891   }
6892 
6893   /* Register pRt is used to store the memory required to save the state
6894   ** of the current program, and the memory required at runtime to execute
6895   ** the trigger program. If this trigger has been fired before, then pRt
6896   ** is already allocated. Otherwise, it must be initialized.  */
6897   if( (pRt->flags&MEM_Blob)==0 ){
6898     /* SubProgram.nMem is set to the number of memory cells used by the
6899     ** program stored in SubProgram.aOp. As well as these, one memory
6900     ** cell is required for each cursor used by the program. Set local
6901     ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
6902     */
6903     nMem = pProgram->nMem + pProgram->nCsr;
6904     assert( nMem>0 );
6905     if( pProgram->nCsr==0 ) nMem++;
6906     nByte = ROUND8(sizeof(VdbeFrame))
6907               + nMem * sizeof(Mem)
6908               + pProgram->nCsr * sizeof(VdbeCursor*)
6909               + (pProgram->nOp + 7)/8;
6910     pFrame = sqlite3DbMallocZero(db, nByte);
6911     if( !pFrame ){
6912       goto no_mem;
6913     }
6914     sqlite3VdbeMemRelease(pRt);
6915     pRt->flags = MEM_Blob|MEM_Dyn;
6916     pRt->z = (char*)pFrame;
6917     pRt->n = nByte;
6918     pRt->xDel = sqlite3VdbeFrameMemDel;
6919 
6920     pFrame->v = p;
6921     pFrame->nChildMem = nMem;
6922     pFrame->nChildCsr = pProgram->nCsr;
6923     pFrame->pc = (int)(pOp - aOp);
6924     pFrame->aMem = p->aMem;
6925     pFrame->nMem = p->nMem;
6926     pFrame->apCsr = p->apCsr;
6927     pFrame->nCursor = p->nCursor;
6928     pFrame->aOp = p->aOp;
6929     pFrame->nOp = p->nOp;
6930     pFrame->token = pProgram->token;
6931 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
6932     pFrame->anExec = p->anExec;
6933 #endif
6934 #ifdef SQLITE_DEBUG
6935     pFrame->iFrameMagic = SQLITE_FRAME_MAGIC;
6936 #endif
6937 
6938     pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
6939     for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
6940       pMem->flags = MEM_Undefined;
6941       pMem->db = db;
6942     }
6943   }else{
6944     pFrame = (VdbeFrame*)pRt->z;
6945     assert( pRt->xDel==sqlite3VdbeFrameMemDel );
6946     assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
6947         || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
6948     assert( pProgram->nCsr==pFrame->nChildCsr );
6949     assert( (int)(pOp - aOp)==pFrame->pc );
6950   }
6951 
6952   p->nFrame++;
6953   pFrame->pParent = p->pFrame;
6954   pFrame->lastRowid = db->lastRowid;
6955   pFrame->nChange = p->nChange;
6956   pFrame->nDbChange = p->db->nChange;
6957   assert( pFrame->pAuxData==0 );
6958   pFrame->pAuxData = p->pAuxData;
6959   p->pAuxData = 0;
6960   p->nChange = 0;
6961   p->pFrame = pFrame;
6962   p->aMem = aMem = VdbeFrameMem(pFrame);
6963   p->nMem = pFrame->nChildMem;
6964   p->nCursor = (u16)pFrame->nChildCsr;
6965   p->apCsr = (VdbeCursor **)&aMem[p->nMem];
6966   pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
6967   memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
6968   p->aOp = aOp = pProgram->aOp;
6969   p->nOp = pProgram->nOp;
6970 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
6971   p->anExec = 0;
6972 #endif
6973 #ifdef SQLITE_DEBUG
6974   /* Verify that second and subsequent executions of the same trigger do not
6975   ** try to reuse register values from the first use. */
6976   {
6977     int i;
6978     for(i=0; i<p->nMem; i++){
6979       aMem[i].pScopyFrom = 0;  /* Prevent false-positive AboutToChange() errs */
6980       MemSetTypeFlag(&aMem[i], MEM_Undefined); /* Fault if this reg is reused */
6981     }
6982   }
6983 #endif
6984   pOp = &aOp[-1];
6985   goto check_for_interrupt;
6986 }
6987 
6988 /* Opcode: Param P1 P2 * * *
6989 **
6990 ** This opcode is only ever present in sub-programs called via the
6991 ** OP_Program instruction. Copy a value currently stored in a memory
6992 ** cell of the calling (parent) frame to cell P2 in the current frames
6993 ** address space. This is used by trigger programs to access the new.*
6994 ** and old.* values.
6995 **
6996 ** The address of the cell in the parent frame is determined by adding
6997 ** the value of the P1 argument to the value of the P1 argument to the
6998 ** calling OP_Program instruction.
6999 */
7000 case OP_Param: {           /* out2 */
7001   VdbeFrame *pFrame;
7002   Mem *pIn;
7003   pOut = out2Prerelease(p, pOp);
7004   pFrame = p->pFrame;
7005   pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
7006   sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
7007   break;
7008 }
7009 
7010 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
7011 
7012 #ifndef SQLITE_OMIT_FOREIGN_KEY
7013 /* Opcode: FkCounter P1 P2 * * *
7014 ** Synopsis: fkctr[P1]+=P2
7015 **
7016 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
7017 ** If P1 is non-zero, the database constraint counter is incremented
7018 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
7019 ** statement counter is incremented (immediate foreign key constraints).
7020 */
7021 case OP_FkCounter: {
7022   if( db->flags & SQLITE_DeferFKs ){
7023     db->nDeferredImmCons += pOp->p2;
7024   }else if( pOp->p1 ){
7025     db->nDeferredCons += pOp->p2;
7026   }else{
7027     p->nFkConstraint += pOp->p2;
7028   }
7029   break;
7030 }
7031 
7032 /* Opcode: FkIfZero P1 P2 * * *
7033 ** Synopsis: if fkctr[P1]==0 goto P2
7034 **
7035 ** This opcode tests if a foreign key constraint-counter is currently zero.
7036 ** If so, jump to instruction P2. Otherwise, fall through to the next
7037 ** instruction.
7038 **
7039 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
7040 ** is zero (the one that counts deferred constraint violations). If P1 is
7041 ** zero, the jump is taken if the statement constraint-counter is zero
7042 ** (immediate foreign key constraint violations).
7043 */
7044 case OP_FkIfZero: {         /* jump */
7045   if( pOp->p1 ){
7046     VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
7047     if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
7048   }else{
7049     VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
7050     if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
7051   }
7052   break;
7053 }
7054 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
7055 
7056 #ifndef SQLITE_OMIT_AUTOINCREMENT
7057 /* Opcode: MemMax P1 P2 * * *
7058 ** Synopsis: r[P1]=max(r[P1],r[P2])
7059 **
7060 ** P1 is a register in the root frame of this VM (the root frame is
7061 ** different from the current frame if this instruction is being executed
7062 ** within a sub-program). Set the value of register P1 to the maximum of
7063 ** its current value and the value in register P2.
7064 **
7065 ** This instruction throws an error if the memory cell is not initially
7066 ** an integer.
7067 */
7068 case OP_MemMax: {        /* in2 */
7069   VdbeFrame *pFrame;
7070   if( p->pFrame ){
7071     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
7072     pIn1 = &pFrame->aMem[pOp->p1];
7073   }else{
7074     pIn1 = &aMem[pOp->p1];
7075   }
7076   assert( memIsValid(pIn1) );
7077   sqlite3VdbeMemIntegerify(pIn1);
7078   pIn2 = &aMem[pOp->p2];
7079   sqlite3VdbeMemIntegerify(pIn2);
7080   if( pIn1->u.i<pIn2->u.i){
7081     pIn1->u.i = pIn2->u.i;
7082   }
7083   break;
7084 }
7085 #endif /* SQLITE_OMIT_AUTOINCREMENT */
7086 
7087 /* Opcode: IfPos P1 P2 P3 * *
7088 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
7089 **
7090 ** Register P1 must contain an integer.
7091 ** If the value of register P1 is 1 or greater, subtract P3 from the
7092 ** value in P1 and jump to P2.
7093 **
7094 ** If the initial value of register P1 is less than 1, then the
7095 ** value is unchanged and control passes through to the next instruction.
7096 */
7097 case OP_IfPos: {        /* jump, in1 */
7098   pIn1 = &aMem[pOp->p1];
7099   assert( pIn1->flags&MEM_Int );
7100   VdbeBranchTaken( pIn1->u.i>0, 2);
7101   if( pIn1->u.i>0 ){
7102     pIn1->u.i -= pOp->p3;
7103     goto jump_to_p2;
7104   }
7105   break;
7106 }
7107 
7108 /* Opcode: OffsetLimit P1 P2 P3 * *
7109 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
7110 **
7111 ** This opcode performs a commonly used computation associated with
7112 ** LIMIT and OFFSET process.  r[P1] holds the limit counter.  r[P3]
7113 ** holds the offset counter.  The opcode computes the combined value
7114 ** of the LIMIT and OFFSET and stores that value in r[P2].  The r[P2]
7115 ** value computed is the total number of rows that will need to be
7116 ** visited in order to complete the query.
7117 **
7118 ** If r[P3] is zero or negative, that means there is no OFFSET
7119 ** and r[P2] is set to be the value of the LIMIT, r[P1].
7120 **
7121 ** if r[P1] is zero or negative, that means there is no LIMIT
7122 ** and r[P2] is set to -1.
7123 **
7124 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
7125 */
7126 case OP_OffsetLimit: {    /* in1, out2, in3 */
7127   i64 x;
7128   pIn1 = &aMem[pOp->p1];
7129   pIn3 = &aMem[pOp->p3];
7130   pOut = out2Prerelease(p, pOp);
7131   assert( pIn1->flags & MEM_Int );
7132   assert( pIn3->flags & MEM_Int );
7133   x = pIn1->u.i;
7134   if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
7135     /* If the LIMIT is less than or equal to zero, loop forever.  This
7136     ** is documented.  But also, if the LIMIT+OFFSET exceeds 2^63 then
7137     ** also loop forever.  This is undocumented.  In fact, one could argue
7138     ** that the loop should terminate.  But assuming 1 billion iterations
7139     ** per second (far exceeding the capabilities of any current hardware)
7140     ** it would take nearly 300 years to actually reach the limit.  So
7141     ** looping forever is a reasonable approximation. */
7142     pOut->u.i = -1;
7143   }else{
7144     pOut->u.i = x;
7145   }
7146   break;
7147 }
7148 
7149 /* Opcode: IfNotZero P1 P2 * * *
7150 ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
7151 **
7152 ** Register P1 must contain an integer.  If the content of register P1 is
7153 ** initially greater than zero, then decrement the value in register P1.
7154 ** If it is non-zero (negative or positive) and then also jump to P2.
7155 ** If register P1 is initially zero, leave it unchanged and fall through.
7156 */
7157 case OP_IfNotZero: {        /* jump, in1 */
7158   pIn1 = &aMem[pOp->p1];
7159   assert( pIn1->flags&MEM_Int );
7160   VdbeBranchTaken(pIn1->u.i<0, 2);
7161   if( pIn1->u.i ){
7162      if( pIn1->u.i>0 ) pIn1->u.i--;
7163      goto jump_to_p2;
7164   }
7165   break;
7166 }
7167 
7168 /* Opcode: DecrJumpZero P1 P2 * * *
7169 ** Synopsis: if (--r[P1])==0 goto P2
7170 **
7171 ** Register P1 must hold an integer.  Decrement the value in P1
7172 ** and jump to P2 if the new value is exactly zero.
7173 */
7174 case OP_DecrJumpZero: {      /* jump, in1 */
7175   pIn1 = &aMem[pOp->p1];
7176   assert( pIn1->flags&MEM_Int );
7177   if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
7178   VdbeBranchTaken(pIn1->u.i==0, 2);
7179   if( pIn1->u.i==0 ) goto jump_to_p2;
7180   break;
7181 }
7182 
7183 
7184 /* Opcode: AggStep * P2 P3 P4 P5
7185 ** Synopsis: accum=r[P3] step(r[P2@P5])
7186 **
7187 ** Execute the xStep function for an aggregate.
7188 ** The function has P5 arguments.  P4 is a pointer to the
7189 ** FuncDef structure that specifies the function.  Register P3 is the
7190 ** accumulator.
7191 **
7192 ** The P5 arguments are taken from register P2 and its
7193 ** successors.
7194 */
7195 /* Opcode: AggInverse * P2 P3 P4 P5
7196 ** Synopsis: accum=r[P3] inverse(r[P2@P5])
7197 **
7198 ** Execute the xInverse function for an aggregate.
7199 ** The function has P5 arguments.  P4 is a pointer to the
7200 ** FuncDef structure that specifies the function.  Register P3 is the
7201 ** accumulator.
7202 **
7203 ** The P5 arguments are taken from register P2 and its
7204 ** successors.
7205 */
7206 /* Opcode: AggStep1 P1 P2 P3 P4 P5
7207 ** Synopsis: accum=r[P3] step(r[P2@P5])
7208 **
7209 ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
7210 ** aggregate.  The function has P5 arguments.  P4 is a pointer to the
7211 ** FuncDef structure that specifies the function.  Register P3 is the
7212 ** accumulator.
7213 **
7214 ** The P5 arguments are taken from register P2 and its
7215 ** successors.
7216 **
7217 ** This opcode is initially coded as OP_AggStep0.  On first evaluation,
7218 ** the FuncDef stored in P4 is converted into an sqlite3_context and
7219 ** the opcode is changed.  In this way, the initialization of the
7220 ** sqlite3_context only happens once, instead of on each call to the
7221 ** step function.
7222 */
7223 case OP_AggInverse:
7224 case OP_AggStep: {
7225   int n;
7226   sqlite3_context *pCtx;
7227 
7228   assert( pOp->p4type==P4_FUNCDEF );
7229   n = pOp->p5;
7230   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
7231   assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
7232   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
7233   pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
7234                (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
7235   if( pCtx==0 ) goto no_mem;
7236   pCtx->pMem = 0;
7237   pCtx->pOut = (Mem*)&(pCtx->argv[n]);
7238   sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
7239   pCtx->pFunc = pOp->p4.pFunc;
7240   pCtx->iOp = (int)(pOp - aOp);
7241   pCtx->pVdbe = p;
7242   pCtx->skipFlag = 0;
7243   pCtx->isError = 0;
7244   pCtx->argc = n;
7245   pOp->p4type = P4_FUNCCTX;
7246   pOp->p4.pCtx = pCtx;
7247 
7248   /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */
7249   assert( pOp->p1==(pOp->opcode==OP_AggInverse) );
7250 
7251   pOp->opcode = OP_AggStep1;
7252   /* Fall through into OP_AggStep */
7253   /* no break */ deliberate_fall_through
7254 }
7255 case OP_AggStep1: {
7256   int i;
7257   sqlite3_context *pCtx;
7258   Mem *pMem;
7259 
7260   assert( pOp->p4type==P4_FUNCCTX );
7261   pCtx = pOp->p4.pCtx;
7262   pMem = &aMem[pOp->p3];
7263 
7264 #ifdef SQLITE_DEBUG
7265   if( pOp->p1 ){
7266     /* This is an OP_AggInverse call.  Verify that xStep has always
7267     ** been called at least once prior to any xInverse call. */
7268     assert( pMem->uTemp==0x1122e0e3 );
7269   }else{
7270     /* This is an OP_AggStep call.  Mark it as such. */
7271     pMem->uTemp = 0x1122e0e3;
7272   }
7273 #endif
7274 
7275   /* If this function is inside of a trigger, the register array in aMem[]
7276   ** might change from one evaluation to the next.  The next block of code
7277   ** checks to see if the register array has changed, and if so it
7278   ** reinitializes the relavant parts of the sqlite3_context object */
7279   if( pCtx->pMem != pMem ){
7280     pCtx->pMem = pMem;
7281     for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
7282   }
7283 
7284 #ifdef SQLITE_DEBUG
7285   for(i=0; i<pCtx->argc; i++){
7286     assert( memIsValid(pCtx->argv[i]) );
7287     REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
7288   }
7289 #endif
7290 
7291   pMem->n++;
7292   assert( pCtx->pOut->flags==MEM_Null );
7293   assert( pCtx->isError==0 );
7294   assert( pCtx->skipFlag==0 );
7295 #ifndef SQLITE_OMIT_WINDOWFUNC
7296   if( pOp->p1 ){
7297     (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv);
7298   }else
7299 #endif
7300   (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
7301 
7302   if( pCtx->isError ){
7303     if( pCtx->isError>0 ){
7304       sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
7305       rc = pCtx->isError;
7306     }
7307     if( pCtx->skipFlag ){
7308       assert( pOp[-1].opcode==OP_CollSeq );
7309       i = pOp[-1].p1;
7310       if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
7311       pCtx->skipFlag = 0;
7312     }
7313     sqlite3VdbeMemRelease(pCtx->pOut);
7314     pCtx->pOut->flags = MEM_Null;
7315     pCtx->isError = 0;
7316     if( rc ) goto abort_due_to_error;
7317   }
7318   assert( pCtx->pOut->flags==MEM_Null );
7319   assert( pCtx->skipFlag==0 );
7320   break;
7321 }
7322 
7323 /* Opcode: AggFinal P1 P2 * P4 *
7324 ** Synopsis: accum=r[P1] N=P2
7325 **
7326 ** P1 is the memory location that is the accumulator for an aggregate
7327 ** or window function.  Execute the finalizer function
7328 ** for an aggregate and store the result in P1.
7329 **
7330 ** P2 is the number of arguments that the step function takes and
7331 ** P4 is a pointer to the FuncDef for this function.  The P2
7332 ** argument is not used by this opcode.  It is only there to disambiguate
7333 ** functions that can take varying numbers of arguments.  The
7334 ** P4 argument is only needed for the case where
7335 ** the step function was not previously called.
7336 */
7337 /* Opcode: AggValue * P2 P3 P4 *
7338 ** Synopsis: r[P3]=value N=P2
7339 **
7340 ** Invoke the xValue() function and store the result in register P3.
7341 **
7342 ** P2 is the number of arguments that the step function takes and
7343 ** P4 is a pointer to the FuncDef for this function.  The P2
7344 ** argument is not used by this opcode.  It is only there to disambiguate
7345 ** functions that can take varying numbers of arguments.  The
7346 ** P4 argument is only needed for the case where
7347 ** the step function was not previously called.
7348 */
7349 case OP_AggValue:
7350 case OP_AggFinal: {
7351   Mem *pMem;
7352   assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
7353   assert( pOp->p3==0 || pOp->opcode==OP_AggValue );
7354   pMem = &aMem[pOp->p1];
7355   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
7356 #ifndef SQLITE_OMIT_WINDOWFUNC
7357   if( pOp->p3 ){
7358     memAboutToChange(p, &aMem[pOp->p3]);
7359     rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc);
7360     pMem = &aMem[pOp->p3];
7361   }else
7362 #endif
7363   {
7364     rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
7365   }
7366 
7367   if( rc ){
7368     sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
7369     goto abort_due_to_error;
7370   }
7371   sqlite3VdbeChangeEncoding(pMem, encoding);
7372   UPDATE_MAX_BLOBSIZE(pMem);
7373   if( sqlite3VdbeMemTooBig(pMem) ){
7374     goto too_big;
7375   }
7376   break;
7377 }
7378 
7379 #ifndef SQLITE_OMIT_WAL
7380 /* Opcode: Checkpoint P1 P2 P3 * *
7381 **
7382 ** Checkpoint database P1. This is a no-op if P1 is not currently in
7383 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
7384 ** RESTART, or TRUNCATE.  Write 1 or 0 into mem[P3] if the checkpoint returns
7385 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
7386 ** WAL after the checkpoint into mem[P3+1] and the number of pages
7387 ** in the WAL that have been checkpointed after the checkpoint
7388 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
7389 ** mem[P3+2] are initialized to -1.
7390 */
7391 case OP_Checkpoint: {
7392   int i;                          /* Loop counter */
7393   int aRes[3];                    /* Results */
7394   Mem *pMem;                      /* Write results here */
7395 
7396   assert( p->readOnly==0 );
7397   aRes[0] = 0;
7398   aRes[1] = aRes[2] = -1;
7399   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
7400        || pOp->p2==SQLITE_CHECKPOINT_FULL
7401        || pOp->p2==SQLITE_CHECKPOINT_RESTART
7402        || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
7403   );
7404   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
7405   if( rc ){
7406     if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
7407     rc = SQLITE_OK;
7408     aRes[0] = 1;
7409   }
7410   for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
7411     sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
7412   }
7413   break;
7414 };
7415 #endif
7416 
7417 #ifndef SQLITE_OMIT_PRAGMA
7418 /* Opcode: JournalMode P1 P2 P3 * *
7419 **
7420 ** Change the journal mode of database P1 to P3. P3 must be one of the
7421 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
7422 ** modes (delete, truncate, persist, off and memory), this is a simple
7423 ** operation. No IO is required.
7424 **
7425 ** If changing into or out of WAL mode the procedure is more complicated.
7426 **
7427 ** Write a string containing the final journal-mode to register P2.
7428 */
7429 case OP_JournalMode: {    /* out2 */
7430   Btree *pBt;                     /* Btree to change journal mode of */
7431   Pager *pPager;                  /* Pager associated with pBt */
7432   int eNew;                       /* New journal mode */
7433   int eOld;                       /* The old journal mode */
7434 #ifndef SQLITE_OMIT_WAL
7435   const char *zFilename;          /* Name of database file for pPager */
7436 #endif
7437 
7438   pOut = out2Prerelease(p, pOp);
7439   eNew = pOp->p3;
7440   assert( eNew==PAGER_JOURNALMODE_DELETE
7441        || eNew==PAGER_JOURNALMODE_TRUNCATE
7442        || eNew==PAGER_JOURNALMODE_PERSIST
7443        || eNew==PAGER_JOURNALMODE_OFF
7444        || eNew==PAGER_JOURNALMODE_MEMORY
7445        || eNew==PAGER_JOURNALMODE_WAL
7446        || eNew==PAGER_JOURNALMODE_QUERY
7447   );
7448   assert( pOp->p1>=0 && pOp->p1<db->nDb );
7449   assert( p->readOnly==0 );
7450 
7451   pBt = db->aDb[pOp->p1].pBt;
7452   pPager = sqlite3BtreePager(pBt);
7453   eOld = sqlite3PagerGetJournalMode(pPager);
7454   if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
7455   assert( sqlite3BtreeHoldsMutex(pBt) );
7456   if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
7457 
7458 #ifndef SQLITE_OMIT_WAL
7459   zFilename = sqlite3PagerFilename(pPager, 1);
7460 
7461   /* Do not allow a transition to journal_mode=WAL for a database
7462   ** in temporary storage or if the VFS does not support shared memory
7463   */
7464   if( eNew==PAGER_JOURNALMODE_WAL
7465    && (sqlite3Strlen30(zFilename)==0           /* Temp file */
7466        || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
7467   ){
7468     eNew = eOld;
7469   }
7470 
7471   if( (eNew!=eOld)
7472    && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
7473   ){
7474     if( !db->autoCommit || db->nVdbeRead>1 ){
7475       rc = SQLITE_ERROR;
7476       sqlite3VdbeError(p,
7477           "cannot change %s wal mode from within a transaction",
7478           (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
7479       );
7480       goto abort_due_to_error;
7481     }else{
7482 
7483       if( eOld==PAGER_JOURNALMODE_WAL ){
7484         /* If leaving WAL mode, close the log file. If successful, the call
7485         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
7486         ** file. An EXCLUSIVE lock may still be held on the database file
7487         ** after a successful return.
7488         */
7489         rc = sqlite3PagerCloseWal(pPager, db);
7490         if( rc==SQLITE_OK ){
7491           sqlite3PagerSetJournalMode(pPager, eNew);
7492         }
7493       }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
7494         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
7495         ** as an intermediate */
7496         sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
7497       }
7498 
7499       /* Open a transaction on the database file. Regardless of the journal
7500       ** mode, this transaction always uses a rollback journal.
7501       */
7502       assert( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE );
7503       if( rc==SQLITE_OK ){
7504         rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
7505       }
7506     }
7507   }
7508 #endif /* ifndef SQLITE_OMIT_WAL */
7509 
7510   if( rc ) eNew = eOld;
7511   eNew = sqlite3PagerSetJournalMode(pPager, eNew);
7512 
7513   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
7514   pOut->z = (char *)sqlite3JournalModename(eNew);
7515   pOut->n = sqlite3Strlen30(pOut->z);
7516   pOut->enc = SQLITE_UTF8;
7517   sqlite3VdbeChangeEncoding(pOut, encoding);
7518   if( rc ) goto abort_due_to_error;
7519   break;
7520 };
7521 #endif /* SQLITE_OMIT_PRAGMA */
7522 
7523 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
7524 /* Opcode: Vacuum P1 P2 * * *
7525 **
7526 ** Vacuum the entire database P1.  P1 is 0 for "main", and 2 or more
7527 ** for an attached database.  The "temp" database may not be vacuumed.
7528 **
7529 ** If P2 is not zero, then it is a register holding a string which is
7530 ** the file into which the result of vacuum should be written.  When
7531 ** P2 is zero, the vacuum overwrites the original database.
7532 */
7533 case OP_Vacuum: {
7534   assert( p->readOnly==0 );
7535   rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1,
7536                         pOp->p2 ? &aMem[pOp->p2] : 0);
7537   if( rc ) goto abort_due_to_error;
7538   break;
7539 }
7540 #endif
7541 
7542 #if !defined(SQLITE_OMIT_AUTOVACUUM)
7543 /* Opcode: IncrVacuum P1 P2 * * *
7544 **
7545 ** Perform a single step of the incremental vacuum procedure on
7546 ** the P1 database. If the vacuum has finished, jump to instruction
7547 ** P2. Otherwise, fall through to the next instruction.
7548 */
7549 case OP_IncrVacuum: {        /* jump */
7550   Btree *pBt;
7551 
7552   assert( pOp->p1>=0 && pOp->p1<db->nDb );
7553   assert( DbMaskTest(p->btreeMask, pOp->p1) );
7554   assert( p->readOnly==0 );
7555   pBt = db->aDb[pOp->p1].pBt;
7556   rc = sqlite3BtreeIncrVacuum(pBt);
7557   VdbeBranchTaken(rc==SQLITE_DONE,2);
7558   if( rc ){
7559     if( rc!=SQLITE_DONE ) goto abort_due_to_error;
7560     rc = SQLITE_OK;
7561     goto jump_to_p2;
7562   }
7563   break;
7564 }
7565 #endif
7566 
7567 /* Opcode: Expire P1 P2 * * *
7568 **
7569 ** Cause precompiled statements to expire.  When an expired statement
7570 ** is executed using sqlite3_step() it will either automatically
7571 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
7572 ** or it will fail with SQLITE_SCHEMA.
7573 **
7574 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
7575 ** then only the currently executing statement is expired.
7576 **
7577 ** If P2 is 0, then SQL statements are expired immediately.  If P2 is 1,
7578 ** then running SQL statements are allowed to continue to run to completion.
7579 ** The P2==1 case occurs when a CREATE INDEX or similar schema change happens
7580 ** that might help the statement run faster but which does not affect the
7581 ** correctness of operation.
7582 */
7583 case OP_Expire: {
7584   assert( pOp->p2==0 || pOp->p2==1 );
7585   if( !pOp->p1 ){
7586     sqlite3ExpirePreparedStatements(db, pOp->p2);
7587   }else{
7588     p->expired = pOp->p2+1;
7589   }
7590   break;
7591 }
7592 
7593 /* Opcode: CursorLock P1 * * * *
7594 **
7595 ** Lock the btree to which cursor P1 is pointing so that the btree cannot be
7596 ** written by an other cursor.
7597 */
7598 case OP_CursorLock: {
7599   VdbeCursor *pC;
7600   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
7601   pC = p->apCsr[pOp->p1];
7602   assert( pC!=0 );
7603   assert( pC->eCurType==CURTYPE_BTREE );
7604   sqlite3BtreeCursorPin(pC->uc.pCursor);
7605   break;
7606 }
7607 
7608 /* Opcode: CursorUnlock P1 * * * *
7609 **
7610 ** Unlock the btree to which cursor P1 is pointing so that it can be
7611 ** written by other cursors.
7612 */
7613 case OP_CursorUnlock: {
7614   VdbeCursor *pC;
7615   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
7616   pC = p->apCsr[pOp->p1];
7617   assert( pC!=0 );
7618   assert( pC->eCurType==CURTYPE_BTREE );
7619   sqlite3BtreeCursorUnpin(pC->uc.pCursor);
7620   break;
7621 }
7622 
7623 #ifndef SQLITE_OMIT_SHARED_CACHE
7624 /* Opcode: TableLock P1 P2 P3 P4 *
7625 ** Synopsis: iDb=P1 root=P2 write=P3
7626 **
7627 ** Obtain a lock on a particular table. This instruction is only used when
7628 ** the shared-cache feature is enabled.
7629 **
7630 ** P1 is the index of the database in sqlite3.aDb[] of the database
7631 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
7632 ** a write lock if P3==1.
7633 **
7634 ** P2 contains the root-page of the table to lock.
7635 **
7636 ** P4 contains a pointer to the name of the table being locked. This is only
7637 ** used to generate an error message if the lock cannot be obtained.
7638 */
7639 case OP_TableLock: {
7640   u8 isWriteLock = (u8)pOp->p3;
7641   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
7642     int p1 = pOp->p1;
7643     assert( p1>=0 && p1<db->nDb );
7644     assert( DbMaskTest(p->btreeMask, p1) );
7645     assert( isWriteLock==0 || isWriteLock==1 );
7646     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
7647     if( rc ){
7648       if( (rc&0xFF)==SQLITE_LOCKED ){
7649         const char *z = pOp->p4.z;
7650         sqlite3VdbeError(p, "database table is locked: %s", z);
7651       }
7652       goto abort_due_to_error;
7653     }
7654   }
7655   break;
7656 }
7657 #endif /* SQLITE_OMIT_SHARED_CACHE */
7658 
7659 #ifndef SQLITE_OMIT_VIRTUALTABLE
7660 /* Opcode: VBegin * * * P4 *
7661 **
7662 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
7663 ** xBegin method for that table.
7664 **
7665 ** Also, whether or not P4 is set, check that this is not being called from
7666 ** within a callback to a virtual table xSync() method. If it is, the error
7667 ** code will be set to SQLITE_LOCKED.
7668 */
7669 case OP_VBegin: {
7670   VTable *pVTab;
7671   pVTab = pOp->p4.pVtab;
7672   rc = sqlite3VtabBegin(db, pVTab);
7673   if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
7674   if( rc ) goto abort_due_to_error;
7675   break;
7676 }
7677 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7678 
7679 #ifndef SQLITE_OMIT_VIRTUALTABLE
7680 /* Opcode: VCreate P1 P2 * * *
7681 **
7682 ** P2 is a register that holds the name of a virtual table in database
7683 ** P1. Call the xCreate method for that table.
7684 */
7685 case OP_VCreate: {
7686   Mem sMem;          /* For storing the record being decoded */
7687   const char *zTab;  /* Name of the virtual table */
7688 
7689   memset(&sMem, 0, sizeof(sMem));
7690   sMem.db = db;
7691   /* Because P2 is always a static string, it is impossible for the
7692   ** sqlite3VdbeMemCopy() to fail */
7693   assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
7694   assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
7695   rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
7696   assert( rc==SQLITE_OK );
7697   zTab = (const char*)sqlite3_value_text(&sMem);
7698   assert( zTab || db->mallocFailed );
7699   if( zTab ){
7700     rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
7701   }
7702   sqlite3VdbeMemRelease(&sMem);
7703   if( rc ) goto abort_due_to_error;
7704   break;
7705 }
7706 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7707 
7708 #ifndef SQLITE_OMIT_VIRTUALTABLE
7709 /* Opcode: VDestroy P1 * * P4 *
7710 **
7711 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
7712 ** of that table.
7713 */
7714 case OP_VDestroy: {
7715   db->nVDestroy++;
7716   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
7717   db->nVDestroy--;
7718   assert( p->errorAction==OE_Abort && p->usesStmtJournal );
7719   if( rc ) goto abort_due_to_error;
7720   break;
7721 }
7722 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7723 
7724 #ifndef SQLITE_OMIT_VIRTUALTABLE
7725 /* Opcode: VOpen P1 * * P4 *
7726 **
7727 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
7728 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
7729 ** table and stores that cursor in P1.
7730 */
7731 case OP_VOpen: {
7732   VdbeCursor *pCur;
7733   sqlite3_vtab_cursor *pVCur;
7734   sqlite3_vtab *pVtab;
7735   const sqlite3_module *pModule;
7736 
7737   assert( p->bIsReader );
7738   pCur = 0;
7739   pVCur = 0;
7740   pVtab = pOp->p4.pVtab->pVtab;
7741   if( pVtab==0 || NEVER(pVtab->pModule==0) ){
7742     rc = SQLITE_LOCKED;
7743     goto abort_due_to_error;
7744   }
7745   pModule = pVtab->pModule;
7746   rc = pModule->xOpen(pVtab, &pVCur);
7747   sqlite3VtabImportErrmsg(p, pVtab);
7748   if( rc ) goto abort_due_to_error;
7749 
7750   /* Initialize sqlite3_vtab_cursor base class */
7751   pVCur->pVtab = pVtab;
7752 
7753   /* Initialize vdbe cursor object */
7754   pCur = allocateCursor(p, pOp->p1, 0, CURTYPE_VTAB);
7755   if( pCur ){
7756     pCur->uc.pVCur = pVCur;
7757     pVtab->nRef++;
7758   }else{
7759     assert( db->mallocFailed );
7760     pModule->xClose(pVCur);
7761     goto no_mem;
7762   }
7763   break;
7764 }
7765 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7766 
7767 #ifndef SQLITE_OMIT_VIRTUALTABLE
7768 /* Opcode: VInitIn P1 P2 P3 * *
7769 ** Synopsis: r[P2]=ValueList(P1,P3)
7770 **
7771 ** Set register P2 to be a pointer to a ValueList object for cursor P1
7772 ** with cache register P3 and output register P3+1.  This ValueList object
7773 ** can be used as the first argument to sqlite3_vtab_in_first() and
7774 ** sqlite3_vtab_in_next() to extract all of the values stored in the P1
7775 ** cursor.  Register P3 is used to hold the values returned by
7776 ** sqlite3_vtab_in_first() and sqlite3_vtab_in_next().
7777 */
7778 case OP_VInitIn: {        /* out2 */
7779   VdbeCursor *pC;         /* The cursor containing the RHS values */
7780   ValueList *pRhs;        /* New ValueList object to put in reg[P2] */
7781 
7782   pC = p->apCsr[pOp->p1];
7783   pRhs = sqlite3_malloc64( sizeof(*pRhs) );
7784   if( pRhs==0 ) goto no_mem;
7785   pRhs->pCsr = pC->uc.pCursor;
7786   pRhs->pOut = &aMem[pOp->p3];
7787   pOut = out2Prerelease(p, pOp);
7788   pOut->flags = MEM_Null;
7789   sqlite3VdbeMemSetPointer(pOut, pRhs, "ValueList", sqlite3_free);
7790   break;
7791 }
7792 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7793 
7794 
7795 #ifndef SQLITE_OMIT_VIRTUALTABLE
7796 /* Opcode: VFilter P1 P2 P3 P4 *
7797 ** Synopsis: iplan=r[P3] zplan='P4'
7798 **
7799 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
7800 ** the filtered result set is empty.
7801 **
7802 ** P4 is either NULL or a string that was generated by the xBestIndex
7803 ** method of the module.  The interpretation of the P4 string is left
7804 ** to the module implementation.
7805 **
7806 ** This opcode invokes the xFilter method on the virtual table specified
7807 ** by P1.  The integer query plan parameter to xFilter is stored in register
7808 ** P3. Register P3+1 stores the argc parameter to be passed to the
7809 ** xFilter method. Registers P3+2..P3+1+argc are the argc
7810 ** additional parameters which are passed to
7811 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
7812 **
7813 ** A jump is made to P2 if the result set after filtering would be empty.
7814 */
7815 case OP_VFilter: {   /* jump */
7816   int nArg;
7817   int iQuery;
7818   const sqlite3_module *pModule;
7819   Mem *pQuery;
7820   Mem *pArgc;
7821   sqlite3_vtab_cursor *pVCur;
7822   sqlite3_vtab *pVtab;
7823   VdbeCursor *pCur;
7824   int res;
7825   int i;
7826   Mem **apArg;
7827 
7828   pQuery = &aMem[pOp->p3];
7829   pArgc = &pQuery[1];
7830   pCur = p->apCsr[pOp->p1];
7831   assert( memIsValid(pQuery) );
7832   REGISTER_TRACE(pOp->p3, pQuery);
7833   assert( pCur!=0 );
7834   assert( pCur->eCurType==CURTYPE_VTAB );
7835   pVCur = pCur->uc.pVCur;
7836   pVtab = pVCur->pVtab;
7837   pModule = pVtab->pModule;
7838 
7839   /* Grab the index number and argc parameters */
7840   assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
7841   nArg = (int)pArgc->u.i;
7842   iQuery = (int)pQuery->u.i;
7843 
7844   /* Invoke the xFilter method */
7845   apArg = p->apArg;
7846   for(i = 0; i<nArg; i++){
7847     apArg[i] = &pArgc[i+1];
7848   }
7849   rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
7850   sqlite3VtabImportErrmsg(p, pVtab);
7851   if( rc ) goto abort_due_to_error;
7852   res = pModule->xEof(pVCur);
7853   pCur->nullRow = 0;
7854   VdbeBranchTaken(res!=0,2);
7855   if( res ) goto jump_to_p2;
7856   break;
7857 }
7858 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7859 
7860 #ifndef SQLITE_OMIT_VIRTUALTABLE
7861 /* Opcode: VColumn P1 P2 P3 * P5
7862 ** Synopsis: r[P3]=vcolumn(P2)
7863 **
7864 ** Store in register P3 the value of the P2-th column of
7865 ** the current row of the virtual-table of cursor P1.
7866 **
7867 ** If the VColumn opcode is being used to fetch the value of
7868 ** an unchanging column during an UPDATE operation, then the P5
7869 ** value is OPFLAG_NOCHNG.  This will cause the sqlite3_vtab_nochange()
7870 ** function to return true inside the xColumn method of the virtual
7871 ** table implementation.  The P5 column might also contain other
7872 ** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are
7873 ** unused by OP_VColumn.
7874 */
7875 case OP_VColumn: {
7876   sqlite3_vtab *pVtab;
7877   const sqlite3_module *pModule;
7878   Mem *pDest;
7879   sqlite3_context sContext;
7880 
7881   VdbeCursor *pCur = p->apCsr[pOp->p1];
7882   assert( pCur!=0 );
7883   assert( pCur->eCurType==CURTYPE_VTAB );
7884   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
7885   pDest = &aMem[pOp->p3];
7886   memAboutToChange(p, pDest);
7887   if( pCur->nullRow ){
7888     sqlite3VdbeMemSetNull(pDest);
7889     break;
7890   }
7891   pVtab = pCur->uc.pVCur->pVtab;
7892   pModule = pVtab->pModule;
7893   assert( pModule->xColumn );
7894   memset(&sContext, 0, sizeof(sContext));
7895   sContext.pOut = pDest;
7896   assert( pOp->p5==OPFLAG_NOCHNG || pOp->p5==0 );
7897   if( pOp->p5 & OPFLAG_NOCHNG ){
7898     sqlite3VdbeMemSetNull(pDest);
7899     pDest->flags = MEM_Null|MEM_Zero;
7900     pDest->u.nZero = 0;
7901   }else{
7902     MemSetTypeFlag(pDest, MEM_Null);
7903   }
7904   rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
7905   sqlite3VtabImportErrmsg(p, pVtab);
7906   if( sContext.isError>0 ){
7907     sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
7908     rc = sContext.isError;
7909   }
7910   sqlite3VdbeChangeEncoding(pDest, encoding);
7911   REGISTER_TRACE(pOp->p3, pDest);
7912   UPDATE_MAX_BLOBSIZE(pDest);
7913 
7914   if( sqlite3VdbeMemTooBig(pDest) ){
7915     goto too_big;
7916   }
7917   if( rc ) goto abort_due_to_error;
7918   break;
7919 }
7920 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7921 
7922 #ifndef SQLITE_OMIT_VIRTUALTABLE
7923 /* Opcode: VNext P1 P2 * * *
7924 **
7925 ** Advance virtual table P1 to the next row in its result set and
7926 ** jump to instruction P2.  Or, if the virtual table has reached
7927 ** the end of its result set, then fall through to the next instruction.
7928 */
7929 case OP_VNext: {   /* jump */
7930   sqlite3_vtab *pVtab;
7931   const sqlite3_module *pModule;
7932   int res;
7933   VdbeCursor *pCur;
7934 
7935   pCur = p->apCsr[pOp->p1];
7936   assert( pCur!=0 );
7937   assert( pCur->eCurType==CURTYPE_VTAB );
7938   if( pCur->nullRow ){
7939     break;
7940   }
7941   pVtab = pCur->uc.pVCur->pVtab;
7942   pModule = pVtab->pModule;
7943   assert( pModule->xNext );
7944 
7945   /* Invoke the xNext() method of the module. There is no way for the
7946   ** underlying implementation to return an error if one occurs during
7947   ** xNext(). Instead, if an error occurs, true is returned (indicating that
7948   ** data is available) and the error code returned when xColumn or
7949   ** some other method is next invoked on the save virtual table cursor.
7950   */
7951   rc = pModule->xNext(pCur->uc.pVCur);
7952   sqlite3VtabImportErrmsg(p, pVtab);
7953   if( rc ) goto abort_due_to_error;
7954   res = pModule->xEof(pCur->uc.pVCur);
7955   VdbeBranchTaken(!res,2);
7956   if( !res ){
7957     /* If there is data, jump to P2 */
7958     goto jump_to_p2_and_check_for_interrupt;
7959   }
7960   goto check_for_interrupt;
7961 }
7962 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7963 
7964 #ifndef SQLITE_OMIT_VIRTUALTABLE
7965 /* Opcode: VRename P1 * * P4 *
7966 **
7967 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
7968 ** This opcode invokes the corresponding xRename method. The value
7969 ** in register P1 is passed as the zName argument to the xRename method.
7970 */
7971 case OP_VRename: {
7972   sqlite3_vtab *pVtab;
7973   Mem *pName;
7974   int isLegacy;
7975 
7976   isLegacy = (db->flags & SQLITE_LegacyAlter);
7977   db->flags |= SQLITE_LegacyAlter;
7978   pVtab = pOp->p4.pVtab->pVtab;
7979   pName = &aMem[pOp->p1];
7980   assert( pVtab->pModule->xRename );
7981   assert( memIsValid(pName) );
7982   assert( p->readOnly==0 );
7983   REGISTER_TRACE(pOp->p1, pName);
7984   assert( pName->flags & MEM_Str );
7985   testcase( pName->enc==SQLITE_UTF8 );
7986   testcase( pName->enc==SQLITE_UTF16BE );
7987   testcase( pName->enc==SQLITE_UTF16LE );
7988   rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
7989   if( rc ) goto abort_due_to_error;
7990   rc = pVtab->pModule->xRename(pVtab, pName->z);
7991   if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter;
7992   sqlite3VtabImportErrmsg(p, pVtab);
7993   p->expired = 0;
7994   if( rc ) goto abort_due_to_error;
7995   break;
7996 }
7997 #endif
7998 
7999 #ifndef SQLITE_OMIT_VIRTUALTABLE
8000 /* Opcode: VUpdate P1 P2 P3 P4 P5
8001 ** Synopsis: data=r[P3@P2]
8002 **
8003 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
8004 ** This opcode invokes the corresponding xUpdate method. P2 values
8005 ** are contiguous memory cells starting at P3 to pass to the xUpdate
8006 ** invocation. The value in register (P3+P2-1) corresponds to the
8007 ** p2th element of the argv array passed to xUpdate.
8008 **
8009 ** The xUpdate method will do a DELETE or an INSERT or both.
8010 ** The argv[0] element (which corresponds to memory cell P3)
8011 ** is the rowid of a row to delete.  If argv[0] is NULL then no
8012 ** deletion occurs.  The argv[1] element is the rowid of the new
8013 ** row.  This can be NULL to have the virtual table select the new
8014 ** rowid for itself.  The subsequent elements in the array are
8015 ** the values of columns in the new row.
8016 **
8017 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
8018 ** a row to delete.
8019 **
8020 ** P1 is a boolean flag. If it is set to true and the xUpdate call
8021 ** is successful, then the value returned by sqlite3_last_insert_rowid()
8022 ** is set to the value of the rowid for the row just inserted.
8023 **
8024 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
8025 ** apply in the case of a constraint failure on an insert or update.
8026 */
8027 case OP_VUpdate: {
8028   sqlite3_vtab *pVtab;
8029   const sqlite3_module *pModule;
8030   int nArg;
8031   int i;
8032   sqlite_int64 rowid = 0;
8033   Mem **apArg;
8034   Mem *pX;
8035 
8036   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
8037        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
8038   );
8039   assert( p->readOnly==0 );
8040   if( db->mallocFailed ) goto no_mem;
8041   sqlite3VdbeIncrWriteCounter(p, 0);
8042   pVtab = pOp->p4.pVtab->pVtab;
8043   if( pVtab==0 || NEVER(pVtab->pModule==0) ){
8044     rc = SQLITE_LOCKED;
8045     goto abort_due_to_error;
8046   }
8047   pModule = pVtab->pModule;
8048   nArg = pOp->p2;
8049   assert( pOp->p4type==P4_VTAB );
8050   if( ALWAYS(pModule->xUpdate) ){
8051     u8 vtabOnConflict = db->vtabOnConflict;
8052     apArg = p->apArg;
8053     pX = &aMem[pOp->p3];
8054     for(i=0; i<nArg; i++){
8055       assert( memIsValid(pX) );
8056       memAboutToChange(p, pX);
8057       apArg[i] = pX;
8058       pX++;
8059     }
8060     db->vtabOnConflict = pOp->p5;
8061     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
8062     db->vtabOnConflict = vtabOnConflict;
8063     sqlite3VtabImportErrmsg(p, pVtab);
8064     if( rc==SQLITE_OK && pOp->p1 ){
8065       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
8066       db->lastRowid = rowid;
8067     }
8068     if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
8069       if( pOp->p5==OE_Ignore ){
8070         rc = SQLITE_OK;
8071       }else{
8072         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
8073       }
8074     }else{
8075       p->nChange++;
8076     }
8077     if( rc ) goto abort_due_to_error;
8078   }
8079   break;
8080 }
8081 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8082 
8083 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
8084 /* Opcode: Pagecount P1 P2 * * *
8085 **
8086 ** Write the current number of pages in database P1 to memory cell P2.
8087 */
8088 case OP_Pagecount: {            /* out2 */
8089   pOut = out2Prerelease(p, pOp);
8090   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
8091   break;
8092 }
8093 #endif
8094 
8095 
8096 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
8097 /* Opcode: MaxPgcnt P1 P2 P3 * *
8098 **
8099 ** Try to set the maximum page count for database P1 to the value in P3.
8100 ** Do not let the maximum page count fall below the current page count and
8101 ** do not change the maximum page count value if P3==0.
8102 **
8103 ** Store the maximum page count after the change in register P2.
8104 */
8105 case OP_MaxPgcnt: {            /* out2 */
8106   unsigned int newMax;
8107   Btree *pBt;
8108 
8109   pOut = out2Prerelease(p, pOp);
8110   pBt = db->aDb[pOp->p1].pBt;
8111   newMax = 0;
8112   if( pOp->p3 ){
8113     newMax = sqlite3BtreeLastPage(pBt);
8114     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
8115   }
8116   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
8117   break;
8118 }
8119 #endif
8120 
8121 /* Opcode: Function P1 P2 P3 P4 *
8122 ** Synopsis: r[P3]=func(r[P2@NP])
8123 **
8124 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
8125 ** contains a pointer to the function to be run) with arguments taken
8126 ** from register P2 and successors.  The number of arguments is in
8127 ** the sqlite3_context object that P4 points to.
8128 ** The result of the function is stored
8129 ** in register P3.  Register P3 must not be one of the function inputs.
8130 **
8131 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
8132 ** function was determined to be constant at compile time. If the first
8133 ** argument was constant then bit 0 of P1 is set. This is used to determine
8134 ** whether meta data associated with a user function argument using the
8135 ** sqlite3_set_auxdata() API may be safely retained until the next
8136 ** invocation of this opcode.
8137 **
8138 ** See also: AggStep, AggFinal, PureFunc
8139 */
8140 /* Opcode: PureFunc P1 P2 P3 P4 *
8141 ** Synopsis: r[P3]=func(r[P2@NP])
8142 **
8143 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
8144 ** contains a pointer to the function to be run) with arguments taken
8145 ** from register P2 and successors.  The number of arguments is in
8146 ** the sqlite3_context object that P4 points to.
8147 ** The result of the function is stored
8148 ** in register P3.  Register P3 must not be one of the function inputs.
8149 **
8150 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
8151 ** function was determined to be constant at compile time. If the first
8152 ** argument was constant then bit 0 of P1 is set. This is used to determine
8153 ** whether meta data associated with a user function argument using the
8154 ** sqlite3_set_auxdata() API may be safely retained until the next
8155 ** invocation of this opcode.
8156 **
8157 ** This opcode works exactly like OP_Function.  The only difference is in
8158 ** its name.  This opcode is used in places where the function must be
8159 ** purely non-deterministic.  Some built-in date/time functions can be
8160 ** either determinitic of non-deterministic, depending on their arguments.
8161 ** When those function are used in a non-deterministic way, they will check
8162 ** to see if they were called using OP_PureFunc instead of OP_Function, and
8163 ** if they were, they throw an error.
8164 **
8165 ** See also: AggStep, AggFinal, Function
8166 */
8167 case OP_PureFunc:              /* group */
8168 case OP_Function: {            /* group */
8169   int i;
8170   sqlite3_context *pCtx;
8171 
8172   assert( pOp->p4type==P4_FUNCCTX );
8173   pCtx = pOp->p4.pCtx;
8174 
8175   /* If this function is inside of a trigger, the register array in aMem[]
8176   ** might change from one evaluation to the next.  The next block of code
8177   ** checks to see if the register array has changed, and if so it
8178   ** reinitializes the relavant parts of the sqlite3_context object */
8179   pOut = &aMem[pOp->p3];
8180   if( pCtx->pOut != pOut ){
8181     pCtx->pVdbe = p;
8182     pCtx->pOut = pOut;
8183     for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
8184   }
8185   assert( pCtx->pVdbe==p );
8186 
8187   memAboutToChange(p, pOut);
8188 #ifdef SQLITE_DEBUG
8189   for(i=0; i<pCtx->argc; i++){
8190     assert( memIsValid(pCtx->argv[i]) );
8191     REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
8192   }
8193 #endif
8194   MemSetTypeFlag(pOut, MEM_Null);
8195   assert( pCtx->isError==0 );
8196   (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
8197 
8198   /* If the function returned an error, throw an exception */
8199   if( pCtx->isError ){
8200     if( pCtx->isError>0 ){
8201       sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
8202       rc = pCtx->isError;
8203     }
8204     sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
8205     pCtx->isError = 0;
8206     if( rc ) goto abort_due_to_error;
8207   }
8208 
8209   /* Copy the result of the function into register P3 */
8210   if( pOut->flags & (MEM_Str|MEM_Blob) ){
8211     sqlite3VdbeChangeEncoding(pOut, encoding);
8212     if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
8213   }
8214 
8215   REGISTER_TRACE(pOp->p3, pOut);
8216   UPDATE_MAX_BLOBSIZE(pOut);
8217   break;
8218 }
8219 
8220 /* Opcode: FilterAdd P1 * P3 P4 *
8221 ** Synopsis: filter(P1) += key(P3@P4)
8222 **
8223 ** Compute a hash on the P4 registers starting with r[P3] and
8224 ** add that hash to the bloom filter contained in r[P1].
8225 */
8226 case OP_FilterAdd: {
8227   u64 h;
8228 
8229   assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
8230   pIn1 = &aMem[pOp->p1];
8231   assert( pIn1->flags & MEM_Blob );
8232   assert( pIn1->n>0 );
8233   h = filterHash(aMem, pOp);
8234 #ifdef SQLITE_DEBUG
8235   if( db->flags&SQLITE_VdbeTrace ){
8236     int ii;
8237     for(ii=pOp->p3; ii<pOp->p3+pOp->p4.i; ii++){
8238       registerTrace(ii, &aMem[ii]);
8239     }
8240     printf("hash: %llu modulo %d -> %u\n", h, pIn1->n, (int)(h%pIn1->n));
8241   }
8242 #endif
8243   h %= pIn1->n;
8244   pIn1->z[h/8] |= 1<<(h&7);
8245   break;
8246 }
8247 
8248 /* Opcode: Filter P1 P2 P3 P4 *
8249 ** Synopsis: if key(P3@P4) not in filter(P1) goto P2
8250 **
8251 ** Compute a hash on the key contained in the P4 registers starting
8252 ** with r[P3].  Check to see if that hash is found in the
8253 ** bloom filter hosted by register P1.  If it is not present then
8254 ** maybe jump to P2.  Otherwise fall through.
8255 **
8256 ** False negatives are harmless.  It is always safe to fall through,
8257 ** even if the value is in the bloom filter.  A false negative causes
8258 ** more CPU cycles to be used, but it should still yield the correct
8259 ** answer.  However, an incorrect answer may well arise from a
8260 ** false positive - if the jump is taken when it should fall through.
8261 */
8262 case OP_Filter: {          /* jump */
8263   u64 h;
8264 
8265   assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
8266   pIn1 = &aMem[pOp->p1];
8267   assert( (pIn1->flags & MEM_Blob)!=0 );
8268   assert( pIn1->n >= 1 );
8269   h = filterHash(aMem, pOp);
8270 #ifdef SQLITE_DEBUG
8271   if( db->flags&SQLITE_VdbeTrace ){
8272     int ii;
8273     for(ii=pOp->p3; ii<pOp->p3+pOp->p4.i; ii++){
8274       registerTrace(ii, &aMem[ii]);
8275     }
8276     printf("hash: %llu modulo %d -> %u\n", h, pIn1->n, (int)(h%pIn1->n));
8277   }
8278 #endif
8279   h %= pIn1->n;
8280   if( (pIn1->z[h/8] & (1<<(h&7)))==0 ){
8281     VdbeBranchTaken(1, 2);
8282     p->aCounter[SQLITE_STMTSTATUS_FILTER_HIT]++;
8283     goto jump_to_p2;
8284   }else{
8285     p->aCounter[SQLITE_STMTSTATUS_FILTER_MISS]++;
8286     VdbeBranchTaken(0, 2);
8287   }
8288   break;
8289 }
8290 
8291 /* Opcode: Trace P1 P2 * P4 *
8292 **
8293 ** Write P4 on the statement trace output if statement tracing is
8294 ** enabled.
8295 **
8296 ** Operand P1 must be 0x7fffffff and P2 must positive.
8297 */
8298 /* Opcode: Init P1 P2 P3 P4 *
8299 ** Synopsis: Start at P2
8300 **
8301 ** Programs contain a single instance of this opcode as the very first
8302 ** opcode.
8303 **
8304 ** If tracing is enabled (by the sqlite3_trace()) interface, then
8305 ** the UTF-8 string contained in P4 is emitted on the trace callback.
8306 ** Or if P4 is blank, use the string returned by sqlite3_sql().
8307 **
8308 ** If P2 is not zero, jump to instruction P2.
8309 **
8310 ** Increment the value of P1 so that OP_Once opcodes will jump the
8311 ** first time they are evaluated for this run.
8312 **
8313 ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
8314 ** error is encountered.
8315 */
8316 case OP_Trace:
8317 case OP_Init: {          /* jump */
8318   int i;
8319 #ifndef SQLITE_OMIT_TRACE
8320   char *zTrace;
8321 #endif
8322 
8323   /* If the P4 argument is not NULL, then it must be an SQL comment string.
8324   ** The "--" string is broken up to prevent false-positives with srcck1.c.
8325   **
8326   ** This assert() provides evidence for:
8327   ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
8328   ** would have been returned by the legacy sqlite3_trace() interface by
8329   ** using the X argument when X begins with "--" and invoking
8330   ** sqlite3_expanded_sql(P) otherwise.
8331   */
8332   assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
8333 
8334   /* OP_Init is always instruction 0 */
8335   assert( pOp==p->aOp || pOp->opcode==OP_Trace );
8336 
8337 #ifndef SQLITE_OMIT_TRACE
8338   if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
8339    && !p->doingRerun
8340    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
8341   ){
8342 #ifndef SQLITE_OMIT_DEPRECATED
8343     if( db->mTrace & SQLITE_TRACE_LEGACY ){
8344       char *z = sqlite3VdbeExpandSql(p, zTrace);
8345       db->trace.xLegacy(db->pTraceArg, z);
8346       sqlite3_free(z);
8347     }else
8348 #endif
8349     if( db->nVdbeExec>1 ){
8350       char *z = sqlite3MPrintf(db, "-- %s", zTrace);
8351       (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
8352       sqlite3DbFree(db, z);
8353     }else{
8354       (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
8355     }
8356   }
8357 #ifdef SQLITE_USE_FCNTL_TRACE
8358   zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
8359   if( zTrace ){
8360     int j;
8361     for(j=0; j<db->nDb; j++){
8362       if( DbMaskTest(p->btreeMask, j)==0 ) continue;
8363       sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
8364     }
8365   }
8366 #endif /* SQLITE_USE_FCNTL_TRACE */
8367 #ifdef SQLITE_DEBUG
8368   if( (db->flags & SQLITE_SqlTrace)!=0
8369    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
8370   ){
8371     sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
8372   }
8373 #endif /* SQLITE_DEBUG */
8374 #endif /* SQLITE_OMIT_TRACE */
8375   assert( pOp->p2>0 );
8376   if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
8377     if( pOp->opcode==OP_Trace ) break;
8378     for(i=1; i<p->nOp; i++){
8379       if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
8380     }
8381     pOp->p1 = 0;
8382   }
8383   pOp->p1++;
8384   p->aCounter[SQLITE_STMTSTATUS_RUN]++;
8385   goto jump_to_p2;
8386 }
8387 
8388 #ifdef SQLITE_ENABLE_CURSOR_HINTS
8389 /* Opcode: CursorHint P1 * * P4 *
8390 **
8391 ** Provide a hint to cursor P1 that it only needs to return rows that
8392 ** satisfy the Expr in P4.  TK_REGISTER terms in the P4 expression refer
8393 ** to values currently held in registers.  TK_COLUMN terms in the P4
8394 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
8395 */
8396 case OP_CursorHint: {
8397   VdbeCursor *pC;
8398 
8399   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
8400   assert( pOp->p4type==P4_EXPR );
8401   pC = p->apCsr[pOp->p1];
8402   if( pC ){
8403     assert( pC->eCurType==CURTYPE_BTREE );
8404     sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
8405                            pOp->p4.pExpr, aMem);
8406   }
8407   break;
8408 }
8409 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
8410 
8411 #ifdef SQLITE_DEBUG
8412 /* Opcode:  Abortable   * * * * *
8413 **
8414 ** Verify that an Abort can happen.  Assert if an Abort at this point
8415 ** might cause database corruption.  This opcode only appears in debugging
8416 ** builds.
8417 **
8418 ** An Abort is safe if either there have been no writes, or if there is
8419 ** an active statement journal.
8420 */
8421 case OP_Abortable: {
8422   sqlite3VdbeAssertAbortable(p);
8423   break;
8424 }
8425 #endif
8426 
8427 #ifdef SQLITE_DEBUG
8428 /* Opcode:  ReleaseReg   P1 P2 P3 * P5
8429 ** Synopsis: release r[P1@P2] mask P3
8430 **
8431 ** Release registers from service.  Any content that was in the
8432 ** the registers is unreliable after this opcode completes.
8433 **
8434 ** The registers released will be the P2 registers starting at P1,
8435 ** except if bit ii of P3 set, then do not release register P1+ii.
8436 ** In other words, P3 is a mask of registers to preserve.
8437 **
8438 ** Releasing a register clears the Mem.pScopyFrom pointer.  That means
8439 ** that if the content of the released register was set using OP_SCopy,
8440 ** a change to the value of the source register for the OP_SCopy will no longer
8441 ** generate an assertion fault in sqlite3VdbeMemAboutToChange().
8442 **
8443 ** If P5 is set, then all released registers have their type set
8444 ** to MEM_Undefined so that any subsequent attempt to read the released
8445 ** register (before it is reinitialized) will generate an assertion fault.
8446 **
8447 ** P5 ought to be set on every call to this opcode.
8448 ** However, there are places in the code generator will release registers
8449 ** before their are used, under the (valid) assumption that the registers
8450 ** will not be reallocated for some other purpose before they are used and
8451 ** hence are safe to release.
8452 **
8453 ** This opcode is only available in testing and debugging builds.  It is
8454 ** not generated for release builds.  The purpose of this opcode is to help
8455 ** validate the generated bytecode.  This opcode does not actually contribute
8456 ** to computing an answer.
8457 */
8458 case OP_ReleaseReg: {
8459   Mem *pMem;
8460   int i;
8461   u32 constMask;
8462   assert( pOp->p1>0 );
8463   assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
8464   pMem = &aMem[pOp->p1];
8465   constMask = pOp->p3;
8466   for(i=0; i<pOp->p2; i++, pMem++){
8467     if( i>=32 || (constMask & MASKBIT32(i))==0 ){
8468       pMem->pScopyFrom = 0;
8469       if( i<32 && pOp->p5 ) MemSetTypeFlag(pMem, MEM_Undefined);
8470     }
8471   }
8472   break;
8473 }
8474 #endif
8475 
8476 /* Opcode: Noop * * * * *
8477 **
8478 ** Do nothing.  This instruction is often useful as a jump
8479 ** destination.
8480 */
8481 /*
8482 ** The magic Explain opcode are only inserted when explain==2 (which
8483 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
8484 ** This opcode records information from the optimizer.  It is the
8485 ** the same as a no-op.  This opcodesnever appears in a real VM program.
8486 */
8487 default: {          /* This is really OP_Noop, OP_Explain */
8488   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
8489 
8490   break;
8491 }
8492 
8493 /*****************************************************************************
8494 ** The cases of the switch statement above this line should all be indented
8495 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
8496 ** readability.  From this point on down, the normal indentation rules are
8497 ** restored.
8498 *****************************************************************************/
8499     }
8500 
8501 #ifdef VDBE_PROFILE
8502     {
8503       u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
8504       if( endTime>start ) pOrigOp->cycles += endTime - start;
8505       pOrigOp->cnt++;
8506     }
8507 #endif
8508 
8509     /* The following code adds nothing to the actual functionality
8510     ** of the program.  It is only here for testing and debugging.
8511     ** On the other hand, it does burn CPU cycles every time through
8512     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
8513     */
8514 #ifndef NDEBUG
8515     assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
8516 
8517 #ifdef SQLITE_DEBUG
8518     if( db->flags & SQLITE_VdbeTrace ){
8519       u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
8520       if( rc!=0 ) printf("rc=%d\n",rc);
8521       if( opProperty & (OPFLG_OUT2) ){
8522         registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
8523       }
8524       if( opProperty & OPFLG_OUT3 ){
8525         registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
8526       }
8527       if( opProperty==0xff ){
8528         /* Never happens.  This code exists to avoid a harmless linkage
8529         ** warning aboud sqlite3VdbeRegisterDump() being defined but not
8530         ** used. */
8531         sqlite3VdbeRegisterDump(p);
8532       }
8533     }
8534 #endif  /* SQLITE_DEBUG */
8535 #endif  /* NDEBUG */
8536   }  /* The end of the for(;;) loop the loops through opcodes */
8537 
8538   /* If we reach this point, it means that execution is finished with
8539   ** an error of some kind.
8540   */
8541 abort_due_to_error:
8542   if( db->mallocFailed ){
8543     rc = SQLITE_NOMEM_BKPT;
8544   }else if( rc==SQLITE_IOERR_CORRUPTFS ){
8545     rc = SQLITE_CORRUPT_BKPT;
8546   }
8547   assert( rc );
8548 #ifdef SQLITE_DEBUG
8549   if( db->flags & SQLITE_VdbeTrace ){
8550     const char *zTrace = p->zSql;
8551     if( zTrace==0 ){
8552       if( aOp[0].opcode==OP_Trace ){
8553         zTrace = aOp[0].p4.z;
8554       }
8555       if( zTrace==0 ) zTrace = "???";
8556     }
8557     printf("ABORT-due-to-error (rc=%d): %s\n", rc, zTrace);
8558   }
8559 #endif
8560   if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
8561     sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
8562   }
8563   p->rc = rc;
8564   sqlite3SystemError(db, rc);
8565   testcase( sqlite3GlobalConfig.xLog!=0 );
8566   sqlite3_log(rc, "statement aborts at %d: [%s] %s",
8567                    (int)(pOp - aOp), p->zSql, p->zErrMsg);
8568   sqlite3VdbeHalt(p);
8569   if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
8570   if( rc==SQLITE_CORRUPT && db->autoCommit==0 ){
8571     db->flags |= SQLITE_CorruptRdOnly;
8572   }
8573   rc = SQLITE_ERROR;
8574   if( resetSchemaOnFault>0 ){
8575     sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
8576   }
8577 
8578   /* This is the only way out of this procedure.  We have to
8579   ** release the mutexes on btrees that were acquired at the
8580   ** top. */
8581 vdbe_return:
8582 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8583   while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
8584     nProgressLimit += db->nProgressOps;
8585     if( db->xProgress(db->pProgressArg) ){
8586       nProgressLimit = LARGEST_UINT64;
8587       rc = SQLITE_INTERRUPT;
8588       goto abort_due_to_error;
8589     }
8590   }
8591 #endif
8592   p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
8593   sqlite3VdbeLeave(p);
8594   assert( rc!=SQLITE_OK || nExtraDelete==0
8595        || sqlite3_strlike("DELETE%",p->zSql,0)!=0
8596   );
8597   return rc;
8598 
8599   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
8600   ** is encountered.
8601   */
8602 too_big:
8603   sqlite3VdbeError(p, "string or blob too big");
8604   rc = SQLITE_TOOBIG;
8605   goto abort_due_to_error;
8606 
8607   /* Jump to here if a malloc() fails.
8608   */
8609 no_mem:
8610   sqlite3OomFault(db);
8611   sqlite3VdbeError(p, "out of memory");
8612   rc = SQLITE_NOMEM_BKPT;
8613   goto abort_due_to_error;
8614 
8615   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
8616   ** flag.
8617   */
8618 abort_due_to_interrupt:
8619   assert( AtomicLoad(&db->u1.isInterrupted) );
8620   rc = SQLITE_INTERRUPT;
8621   goto abort_due_to_error;
8622 }
8623