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