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