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