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