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