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