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