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