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