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