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