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