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