File:  [ELWIX - Embedded LightWeight unIX -] / embedaddon / sqlite3 / src / vdbe.c
Revision 1.1.1.1 (vendor branch): download - view: text, annotated - select for diffs - revision graph
Tue Feb 21 17:04:17 2012 UTC (12 years, 8 months ago) by misho
Branches: sqlite3, MAIN
CVS tags: v3_7_10, HEAD
sqlite3

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>