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