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