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