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