000001  /*
000002  ** 2004 May 26
000003  **
000004  ** The author disclaims copyright to this source code.  In place of
000005  ** a legal notice, here is a blessing:
000006  **
000007  **    May you do good and not evil.
000008  **    May you find forgiveness for yourself and forgive others.
000009  **    May you share freely, never taking more than you give.
000010  **
000011  *************************************************************************
000012  **
000013  ** This file contains code use to implement APIs that are part of the
000014  ** VDBE.
000015  */
000016  #include "sqliteInt.h"
000017  #include "vdbeInt.h"
000018  #include "opcodes.h"
000019  
000020  #ifndef SQLITE_OMIT_DEPRECATED
000021  /*
000022  ** Return TRUE (non-zero) of the statement supplied as an argument needs
000023  ** to be recompiled.  A statement needs to be recompiled whenever the
000024  ** execution environment changes in a way that would alter the program
000025  ** that sqlite3_prepare() generates.  For example, if new functions or
000026  ** collating sequences are registered or if an authorizer function is
000027  ** added or changed.
000028  */
000029  int sqlite3_expired(sqlite3_stmt *pStmt){
000030    Vdbe *p = (Vdbe*)pStmt;
000031    return p==0 || p->expired;
000032  }
000033  #endif
000034  
000035  /*
000036  ** Check on a Vdbe to make sure it has not been finalized.  Log
000037  ** an error and return true if it has been finalized (or is otherwise
000038  ** invalid).  Return false if it is ok.
000039  */
000040  static int vdbeSafety(Vdbe *p){
000041    if( p->db==0 ){
000042      sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
000043      return 1;
000044    }else{
000045      return 0;
000046    }
000047  }
000048  static int vdbeSafetyNotNull(Vdbe *p){
000049    if( p==0 ){
000050      sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
000051      return 1;
000052    }else{
000053      return vdbeSafety(p);
000054    }
000055  }
000056  
000057  #ifndef SQLITE_OMIT_TRACE
000058  /*
000059  ** Invoke the profile callback.  This routine is only called if we already
000060  ** know that the profile callback is defined and needs to be invoked.
000061  */
000062  static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
000063    sqlite3_int64 iNow;
000064    sqlite3_int64 iElapse;
000065    assert( p->startTime>0 );
000066    assert( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0 );
000067    assert( db->init.busy==0 );
000068    assert( p->zSql!=0 );
000069    sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
000070    iElapse = (iNow - p->startTime)*1000000;
000071  #ifndef SQLITE_OMIT_DEPRECATED
000072    if( db->xProfile ){
000073      db->xProfile(db->pProfileArg, p->zSql, iElapse);
000074    }
000075  #endif
000076    if( db->mTrace & SQLITE_TRACE_PROFILE ){
000077      db->trace.xV2(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
000078    }
000079    p->startTime = 0;
000080  }
000081  /*
000082  ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
000083  ** is needed, and it invokes the callback if it is needed.
000084  */
000085  # define checkProfileCallback(DB,P) \
000086     if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
000087  #else
000088  # define checkProfileCallback(DB,P)  /*no-op*/
000089  #endif
000090  
000091  /*
000092  ** The following routine destroys a virtual machine that is created by
000093  ** the sqlite3_compile() routine. The integer returned is an SQLITE_
000094  ** success/failure code that describes the result of executing the virtual
000095  ** machine.
000096  **
000097  ** This routine sets the error code and string returned by
000098  ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
000099  */
000100  int sqlite3_finalize(sqlite3_stmt *pStmt){
000101    int rc;
000102    if( pStmt==0 ){
000103      /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
000104      ** pointer is a harmless no-op. */
000105      rc = SQLITE_OK;
000106    }else{
000107      Vdbe *v = (Vdbe*)pStmt;
000108      sqlite3 *db = v->db;
000109      if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
000110      sqlite3_mutex_enter(db->mutex);
000111      checkProfileCallback(db, v);
000112      assert( v->eVdbeState>=VDBE_READY_STATE );
000113      rc = sqlite3VdbeReset(v);
000114      sqlite3VdbeDelete(v);
000115      rc = sqlite3ApiExit(db, rc);
000116      sqlite3LeaveMutexAndCloseZombie(db);
000117    }
000118    return rc;
000119  }
000120  
000121  /*
000122  ** Terminate the current execution of an SQL statement and reset it
000123  ** back to its starting state so that it can be reused. A success code from
000124  ** the prior execution is returned.
000125  **
000126  ** This routine sets the error code and string returned by
000127  ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
000128  */
000129  int sqlite3_reset(sqlite3_stmt *pStmt){
000130    int rc;
000131    if( pStmt==0 ){
000132      rc = SQLITE_OK;
000133    }else{
000134      Vdbe *v = (Vdbe*)pStmt;
000135      sqlite3 *db = v->db;
000136      sqlite3_mutex_enter(db->mutex);
000137      checkProfileCallback(db, v);
000138      rc = sqlite3VdbeReset(v);
000139      sqlite3VdbeRewind(v);
000140      assert( (rc & (db->errMask))==rc );
000141      rc = sqlite3ApiExit(db, rc);
000142      sqlite3_mutex_leave(db->mutex);
000143    }
000144    return rc;
000145  }
000146  
000147  /*
000148  ** Set all the parameters in the compiled SQL statement to NULL.
000149  */
000150  int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
000151    int i;
000152    int rc = SQLITE_OK;
000153    Vdbe *p = (Vdbe*)pStmt;
000154  #if SQLITE_THREADSAFE
000155    sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
000156  #endif
000157    sqlite3_mutex_enter(mutex);
000158    for(i=0; i<p->nVar; i++){
000159      sqlite3VdbeMemRelease(&p->aVar[i]);
000160      p->aVar[i].flags = MEM_Null;
000161    }
000162    assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
000163    if( p->expmask ){
000164      p->expired = 1;
000165    }
000166    sqlite3_mutex_leave(mutex);
000167    return rc;
000168  }
000169  
000170  
000171  /**************************** sqlite3_value_  *******************************
000172  ** The following routines extract information from a Mem or sqlite3_value
000173  ** structure.
000174  */
000175  const void *sqlite3_value_blob(sqlite3_value *pVal){
000176    Mem *p = (Mem*)pVal;
000177    if( p->flags & (MEM_Blob|MEM_Str) ){
000178      if( ExpandBlob(p)!=SQLITE_OK ){
000179        assert( p->flags==MEM_Null && p->z==0 );
000180        return 0;
000181      }
000182      p->flags |= MEM_Blob;
000183      return p->n ? p->z : 0;
000184    }else{
000185      return sqlite3_value_text(pVal);
000186    }
000187  }
000188  int sqlite3_value_bytes(sqlite3_value *pVal){
000189    return sqlite3ValueBytes(pVal, SQLITE_UTF8);
000190  }
000191  int sqlite3_value_bytes16(sqlite3_value *pVal){
000192    return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
000193  }
000194  double sqlite3_value_double(sqlite3_value *pVal){
000195    return sqlite3VdbeRealValue((Mem*)pVal);
000196  }
000197  int sqlite3_value_int(sqlite3_value *pVal){
000198    return (int)sqlite3VdbeIntValue((Mem*)pVal);
000199  }
000200  sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
000201    return sqlite3VdbeIntValue((Mem*)pVal);
000202  }
000203  unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
000204    Mem *pMem = (Mem*)pVal;
000205    return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
000206  }
000207  void *sqlite3_value_pointer(sqlite3_value *pVal, const char *zPType){
000208    Mem *p = (Mem*)pVal;
000209    if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
000210                   (MEM_Null|MEM_Term|MEM_Subtype)
000211     && zPType!=0
000212     && p->eSubtype=='p'
000213     && strcmp(p->u.zPType, zPType)==0
000214    ){
000215      return (void*)p->z;
000216    }else{
000217      return 0;
000218    }
000219  }
000220  const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
000221    return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
000222  }
000223  #ifndef SQLITE_OMIT_UTF16
000224  const void *sqlite3_value_text16(sqlite3_value* pVal){
000225    return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
000226  }
000227  const void *sqlite3_value_text16be(sqlite3_value *pVal){
000228    return sqlite3ValueText(pVal, SQLITE_UTF16BE);
000229  }
000230  const void *sqlite3_value_text16le(sqlite3_value *pVal){
000231    return sqlite3ValueText(pVal, SQLITE_UTF16LE);
000232  }
000233  #endif /* SQLITE_OMIT_UTF16 */
000234  /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
000235  ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
000236  ** point number string BLOB NULL
000237  */
000238  int sqlite3_value_type(sqlite3_value* pVal){
000239    static const u8 aType[] = {
000240       SQLITE_BLOB,     /* 0x00 (not possible) */
000241       SQLITE_NULL,     /* 0x01 NULL */
000242       SQLITE_TEXT,     /* 0x02 TEXT */
000243       SQLITE_NULL,     /* 0x03 (not possible) */
000244       SQLITE_INTEGER,  /* 0x04 INTEGER */
000245       SQLITE_NULL,     /* 0x05 (not possible) */
000246       SQLITE_INTEGER,  /* 0x06 INTEGER + TEXT */
000247       SQLITE_NULL,     /* 0x07 (not possible) */
000248       SQLITE_FLOAT,    /* 0x08 FLOAT */
000249       SQLITE_NULL,     /* 0x09 (not possible) */
000250       SQLITE_FLOAT,    /* 0x0a FLOAT + TEXT */
000251       SQLITE_NULL,     /* 0x0b (not possible) */
000252       SQLITE_INTEGER,  /* 0x0c (not possible) */
000253       SQLITE_NULL,     /* 0x0d (not possible) */
000254       SQLITE_INTEGER,  /* 0x0e (not possible) */
000255       SQLITE_NULL,     /* 0x0f (not possible) */
000256       SQLITE_BLOB,     /* 0x10 BLOB */
000257       SQLITE_NULL,     /* 0x11 (not possible) */
000258       SQLITE_TEXT,     /* 0x12 (not possible) */
000259       SQLITE_NULL,     /* 0x13 (not possible) */
000260       SQLITE_INTEGER,  /* 0x14 INTEGER + BLOB */
000261       SQLITE_NULL,     /* 0x15 (not possible) */
000262       SQLITE_INTEGER,  /* 0x16 (not possible) */
000263       SQLITE_NULL,     /* 0x17 (not possible) */
000264       SQLITE_FLOAT,    /* 0x18 FLOAT + BLOB */
000265       SQLITE_NULL,     /* 0x19 (not possible) */
000266       SQLITE_FLOAT,    /* 0x1a (not possible) */
000267       SQLITE_NULL,     /* 0x1b (not possible) */
000268       SQLITE_INTEGER,  /* 0x1c (not possible) */
000269       SQLITE_NULL,     /* 0x1d (not possible) */
000270       SQLITE_INTEGER,  /* 0x1e (not possible) */
000271       SQLITE_NULL,     /* 0x1f (not possible) */
000272       SQLITE_FLOAT,    /* 0x20 INTREAL */
000273       SQLITE_NULL,     /* 0x21 (not possible) */
000274       SQLITE_FLOAT,    /* 0x22 INTREAL + TEXT */
000275       SQLITE_NULL,     /* 0x23 (not possible) */
000276       SQLITE_FLOAT,    /* 0x24 (not possible) */
000277       SQLITE_NULL,     /* 0x25 (not possible) */
000278       SQLITE_FLOAT,    /* 0x26 (not possible) */
000279       SQLITE_NULL,     /* 0x27 (not possible) */
000280       SQLITE_FLOAT,    /* 0x28 (not possible) */
000281       SQLITE_NULL,     /* 0x29 (not possible) */
000282       SQLITE_FLOAT,    /* 0x2a (not possible) */
000283       SQLITE_NULL,     /* 0x2b (not possible) */
000284       SQLITE_FLOAT,    /* 0x2c (not possible) */
000285       SQLITE_NULL,     /* 0x2d (not possible) */
000286       SQLITE_FLOAT,    /* 0x2e (not possible) */
000287       SQLITE_NULL,     /* 0x2f (not possible) */
000288       SQLITE_BLOB,     /* 0x30 (not possible) */
000289       SQLITE_NULL,     /* 0x31 (not possible) */
000290       SQLITE_TEXT,     /* 0x32 (not possible) */
000291       SQLITE_NULL,     /* 0x33 (not possible) */
000292       SQLITE_FLOAT,    /* 0x34 (not possible) */
000293       SQLITE_NULL,     /* 0x35 (not possible) */
000294       SQLITE_FLOAT,    /* 0x36 (not possible) */
000295       SQLITE_NULL,     /* 0x37 (not possible) */
000296       SQLITE_FLOAT,    /* 0x38 (not possible) */
000297       SQLITE_NULL,     /* 0x39 (not possible) */
000298       SQLITE_FLOAT,    /* 0x3a (not possible) */
000299       SQLITE_NULL,     /* 0x3b (not possible) */
000300       SQLITE_FLOAT,    /* 0x3c (not possible) */
000301       SQLITE_NULL,     /* 0x3d (not possible) */
000302       SQLITE_FLOAT,    /* 0x3e (not possible) */
000303       SQLITE_NULL,     /* 0x3f (not possible) */
000304    };
000305  #ifdef SQLITE_DEBUG
000306    {
000307      int eType = SQLITE_BLOB;
000308      if( pVal->flags & MEM_Null ){
000309        eType = SQLITE_NULL;
000310      }else if( pVal->flags & (MEM_Real|MEM_IntReal) ){
000311        eType = SQLITE_FLOAT;
000312      }else if( pVal->flags & MEM_Int ){
000313        eType = SQLITE_INTEGER;
000314      }else if( pVal->flags & MEM_Str ){
000315        eType = SQLITE_TEXT;
000316      }
000317      assert( eType == aType[pVal->flags&MEM_AffMask] );
000318    }
000319  #endif
000320    return aType[pVal->flags&MEM_AffMask];
000321  }
000322  int sqlite3_value_encoding(sqlite3_value *pVal){
000323    return pVal->enc;
000324  }
000325  
000326  /* Return true if a parameter to xUpdate represents an unchanged column */
000327  int sqlite3_value_nochange(sqlite3_value *pVal){
000328    return (pVal->flags&(MEM_Null|MEM_Zero))==(MEM_Null|MEM_Zero);
000329  }
000330  
000331  /* Return true if a parameter value originated from an sqlite3_bind() */
000332  int sqlite3_value_frombind(sqlite3_value *pVal){
000333    return (pVal->flags&MEM_FromBind)!=0;
000334  }
000335  
000336  /* Make a copy of an sqlite3_value object
000337  */
000338  sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
000339    sqlite3_value *pNew;
000340    if( pOrig==0 ) return 0;
000341    pNew = sqlite3_malloc( sizeof(*pNew) );
000342    if( pNew==0 ) return 0;
000343    memset(pNew, 0, sizeof(*pNew));
000344    memcpy(pNew, pOrig, MEMCELLSIZE);
000345    pNew->flags &= ~MEM_Dyn;
000346    pNew->db = 0;
000347    if( pNew->flags&(MEM_Str|MEM_Blob) ){
000348      pNew->flags &= ~(MEM_Static|MEM_Dyn);
000349      pNew->flags |= MEM_Ephem;
000350      if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
000351        sqlite3ValueFree(pNew);
000352        pNew = 0;
000353      }
000354    }else if( pNew->flags & MEM_Null ){
000355      /* Do not duplicate pointer values */
000356      pNew->flags &= ~(MEM_Term|MEM_Subtype);
000357    }
000358    return pNew;
000359  }
000360  
000361  /* Destroy an sqlite3_value object previously obtained from
000362  ** sqlite3_value_dup().
000363  */
000364  void sqlite3_value_free(sqlite3_value *pOld){
000365    sqlite3ValueFree(pOld);
000366  }
000367   
000368  
000369  /**************************** sqlite3_result_  *******************************
000370  ** The following routines are used by user-defined functions to specify
000371  ** the function result.
000372  **
000373  ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
000374  ** result as a string or blob.  Appropriate errors are set if the string/blob
000375  ** is too big or if an OOM occurs.
000376  **
000377  ** The invokeValueDestructor(P,X) routine invokes destructor function X()
000378  ** on value P is not going to be used and need to be destroyed.
000379  */
000380  static void setResultStrOrError(
000381    sqlite3_context *pCtx,  /* Function context */
000382    const char *z,          /* String pointer */
000383    int n,                  /* Bytes in string, or negative */
000384    u8 enc,                 /* Encoding of z.  0 for BLOBs */
000385    void (*xDel)(void*)     /* Destructor function */
000386  ){
000387    Mem *pOut = pCtx->pOut;
000388    int rc = sqlite3VdbeMemSetStr(pOut, z, n, enc, xDel);
000389    if( rc ){
000390      if( rc==SQLITE_TOOBIG ){
000391        sqlite3_result_error_toobig(pCtx);
000392      }else{
000393        /* The only errors possible from sqlite3VdbeMemSetStr are
000394        ** SQLITE_TOOBIG and SQLITE_NOMEM */
000395        assert( rc==SQLITE_NOMEM );
000396        sqlite3_result_error_nomem(pCtx);
000397      }
000398      return;
000399    }
000400    sqlite3VdbeChangeEncoding(pOut, pCtx->enc);
000401    if( sqlite3VdbeMemTooBig(pOut) ){
000402      sqlite3_result_error_toobig(pCtx);
000403    }
000404  }
000405  static int invokeValueDestructor(
000406    const void *p,             /* Value to destroy */
000407    void (*xDel)(void*),       /* The destructor */
000408    sqlite3_context *pCtx      /* Set a SQLITE_TOOBIG error if no NULL */
000409  ){
000410    assert( xDel!=SQLITE_DYNAMIC );
000411    if( xDel==0 ){
000412      /* noop */
000413    }else if( xDel==SQLITE_TRANSIENT ){
000414      /* noop */
000415    }else{
000416      xDel((void*)p);
000417    }
000418    sqlite3_result_error_toobig(pCtx);
000419    return SQLITE_TOOBIG;
000420  }
000421  void sqlite3_result_blob(
000422    sqlite3_context *pCtx,
000423    const void *z,
000424    int n,
000425    void (*xDel)(void *)
000426  ){
000427    assert( n>=0 );
000428    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000429    setResultStrOrError(pCtx, z, n, 0, xDel);
000430  }
000431  void sqlite3_result_blob64(
000432    sqlite3_context *pCtx,
000433    const void *z,
000434    sqlite3_uint64 n,
000435    void (*xDel)(void *)
000436  ){
000437    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000438    assert( xDel!=SQLITE_DYNAMIC );
000439    if( n>0x7fffffff ){
000440      (void)invokeValueDestructor(z, xDel, pCtx);
000441    }else{
000442      setResultStrOrError(pCtx, z, (int)n, 0, xDel);
000443    }
000444  }
000445  void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
000446    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000447    sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
000448  }
000449  void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
000450    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000451    pCtx->isError = SQLITE_ERROR;
000452    sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
000453  }
000454  #ifndef SQLITE_OMIT_UTF16
000455  void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
000456    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000457    pCtx->isError = SQLITE_ERROR;
000458    sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
000459  }
000460  #endif
000461  void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
000462    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000463    sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
000464  }
000465  void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
000466    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000467    sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
000468  }
000469  void sqlite3_result_null(sqlite3_context *pCtx){
000470    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000471    sqlite3VdbeMemSetNull(pCtx->pOut);
000472  }
000473  void sqlite3_result_pointer(
000474    sqlite3_context *pCtx,
000475    void *pPtr,
000476    const char *zPType,
000477    void (*xDestructor)(void*)
000478  ){
000479    Mem *pOut = pCtx->pOut;
000480    assert( sqlite3_mutex_held(pOut->db->mutex) );
000481    sqlite3VdbeMemRelease(pOut);
000482    pOut->flags = MEM_Null;
000483    sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
000484  }
000485  void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
000486    Mem *pOut = pCtx->pOut;
000487    assert( sqlite3_mutex_held(pOut->db->mutex) );
000488    pOut->eSubtype = eSubtype & 0xff;
000489    pOut->flags |= MEM_Subtype;
000490  }
000491  void sqlite3_result_text(
000492    sqlite3_context *pCtx,
000493    const char *z,
000494    int n,
000495    void (*xDel)(void *)
000496  ){
000497    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000498    setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
000499  }
000500  void sqlite3_result_text64(
000501    sqlite3_context *pCtx,
000502    const char *z,
000503    sqlite3_uint64 n,
000504    void (*xDel)(void *),
000505    unsigned char enc
000506  ){
000507    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000508    assert( xDel!=SQLITE_DYNAMIC );
000509    if( enc!=SQLITE_UTF8 ){
000510      if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
000511      n &= ~(u64)1;
000512    }
000513    if( n>0x7fffffff ){
000514      (void)invokeValueDestructor(z, xDel, pCtx);
000515    }else{
000516      setResultStrOrError(pCtx, z, (int)n, enc, xDel);
000517      sqlite3VdbeMemZeroTerminateIfAble(pCtx->pOut);
000518    }
000519  }
000520  #ifndef SQLITE_OMIT_UTF16
000521  void sqlite3_result_text16(
000522    sqlite3_context *pCtx,
000523    const void *z,
000524    int n,
000525    void (*xDel)(void *)
000526  ){
000527    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000528    setResultStrOrError(pCtx, z, n & ~(u64)1, SQLITE_UTF16NATIVE, xDel);
000529  }
000530  void sqlite3_result_text16be(
000531    sqlite3_context *pCtx,
000532    const void *z,
000533    int n,
000534    void (*xDel)(void *)
000535  ){
000536    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000537    setResultStrOrError(pCtx, z, n & ~(u64)1, SQLITE_UTF16BE, xDel);
000538  }
000539  void sqlite3_result_text16le(
000540    sqlite3_context *pCtx,
000541    const void *z,
000542    int n,
000543    void (*xDel)(void *)
000544  ){
000545    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000546    setResultStrOrError(pCtx, z, n & ~(u64)1, SQLITE_UTF16LE, xDel);
000547  }
000548  #endif /* SQLITE_OMIT_UTF16 */
000549  void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
000550    Mem *pOut = pCtx->pOut;
000551    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000552    sqlite3VdbeMemCopy(pOut, pValue);
000553    sqlite3VdbeChangeEncoding(pOut, pCtx->enc);
000554    if( sqlite3VdbeMemTooBig(pOut) ){
000555      sqlite3_result_error_toobig(pCtx);
000556    }
000557  }
000558  void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
000559    sqlite3_result_zeroblob64(pCtx, n>0 ? n : 0);
000560  }
000561  int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
000562    Mem *pOut = pCtx->pOut;
000563    assert( sqlite3_mutex_held(pOut->db->mutex) );
000564    if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
000565      sqlite3_result_error_toobig(pCtx);
000566      return SQLITE_TOOBIG;
000567    }
000568  #ifndef SQLITE_OMIT_INCRBLOB
000569    sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
000570    return SQLITE_OK;
000571  #else
000572    return sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
000573  #endif
000574  }
000575  void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
000576    pCtx->isError = errCode ? errCode : -1;
000577  #ifdef SQLITE_DEBUG
000578    if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
000579  #endif
000580    if( pCtx->pOut->flags & MEM_Null ){
000581      setResultStrOrError(pCtx, sqlite3ErrStr(errCode), -1, SQLITE_UTF8,
000582                          SQLITE_STATIC);
000583    }
000584  }
000585  
000586  /* Force an SQLITE_TOOBIG error. */
000587  void sqlite3_result_error_toobig(sqlite3_context *pCtx){
000588    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000589    pCtx->isError = SQLITE_TOOBIG;
000590    sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
000591                         SQLITE_UTF8, SQLITE_STATIC);
000592  }
000593  
000594  /* An SQLITE_NOMEM error. */
000595  void sqlite3_result_error_nomem(sqlite3_context *pCtx){
000596    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000597    sqlite3VdbeMemSetNull(pCtx->pOut);
000598    pCtx->isError = SQLITE_NOMEM_BKPT;
000599    sqlite3OomFault(pCtx->pOut->db);
000600  }
000601  
000602  #ifndef SQLITE_UNTESTABLE
000603  /* Force the INT64 value currently stored as the result to be
000604  ** a MEM_IntReal value.  See the SQLITE_TESTCTRL_RESULT_INTREAL
000605  ** test-control.
000606  */
000607  void sqlite3ResultIntReal(sqlite3_context *pCtx){
000608    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000609    if( pCtx->pOut->flags & MEM_Int ){
000610      pCtx->pOut->flags &= ~MEM_Int;
000611      pCtx->pOut->flags |= MEM_IntReal;
000612    }
000613  }
000614  #endif
000615  
000616  
000617  /*
000618  ** This function is called after a transaction has been committed. It
000619  ** invokes callbacks registered with sqlite3_wal_hook() as required.
000620  */
000621  static int doWalCallbacks(sqlite3 *db){
000622    int rc = SQLITE_OK;
000623  #ifndef SQLITE_OMIT_WAL
000624    int i;
000625    for(i=0; i<db->nDb; i++){
000626      Btree *pBt = db->aDb[i].pBt;
000627      if( pBt ){
000628        int nEntry;
000629        sqlite3BtreeEnter(pBt);
000630        nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
000631        sqlite3BtreeLeave(pBt);
000632        if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){
000633          rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
000634        }
000635      }
000636    }
000637  #endif
000638    return rc;
000639  }
000640  
000641  
000642  /*
000643  ** Execute the statement pStmt, either until a row of data is ready, the
000644  ** statement is completely executed or an error occurs.
000645  **
000646  ** This routine implements the bulk of the logic behind the sqlite_step()
000647  ** API.  The only thing omitted is the automatic recompile if a
000648  ** schema change has occurred.  That detail is handled by the
000649  ** outer sqlite3_step() wrapper procedure.
000650  */
000651  static int sqlite3Step(Vdbe *p){
000652    sqlite3 *db;
000653    int rc;
000654  
000655    assert(p);
000656    db = p->db;
000657    if( p->eVdbeState!=VDBE_RUN_STATE ){
000658      restart_step:
000659      if( p->eVdbeState==VDBE_READY_STATE ){
000660        if( p->expired ){
000661          p->rc = SQLITE_SCHEMA;
000662          rc = SQLITE_ERROR;
000663          if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){
000664            /* If this statement was prepared using saved SQL and an
000665            ** error has occurred, then return the error code in p->rc to the
000666            ** caller. Set the error code in the database handle to the same
000667            ** value.
000668            */
000669            rc = sqlite3VdbeTransferError(p);
000670          }
000671          goto end_of_step;
000672        }
000673  
000674        /* If there are no other statements currently running, then
000675        ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
000676        ** from interrupting a statement that has not yet started.
000677        */
000678        if( db->nVdbeActive==0 ){
000679          AtomicStore(&db->u1.isInterrupted, 0);
000680        }
000681  
000682        assert( db->nVdbeWrite>0 || db->autoCommit==0
000683            || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
000684        );
000685  
000686  #ifndef SQLITE_OMIT_TRACE
000687        if( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0
000688            && !db->init.busy && p->zSql ){
000689          sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
000690        }else{
000691          assert( p->startTime==0 );
000692        }
000693  #endif
000694  
000695        db->nVdbeActive++;
000696        if( p->readOnly==0 ) db->nVdbeWrite++;
000697        if( p->bIsReader ) db->nVdbeRead++;
000698        p->pc = 0;
000699        p->eVdbeState = VDBE_RUN_STATE;
000700      }else
000701  
000702      if( ALWAYS(p->eVdbeState==VDBE_HALT_STATE) ){
000703        /* We used to require that sqlite3_reset() be called before retrying
000704        ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
000705        ** with version 3.7.0, we changed this so that sqlite3_reset() would
000706        ** be called automatically instead of throwing the SQLITE_MISUSE error.
000707        ** This "automatic-reset" change is not technically an incompatibility,
000708        ** since any application that receives an SQLITE_MISUSE is broken by
000709        ** definition.
000710        **
000711        ** Nevertheless, some published applications that were originally written
000712        ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
000713        ** returns, and those were broken by the automatic-reset change.  As a
000714        ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
000715        ** legacy behavior of returning SQLITE_MISUSE for cases where the
000716        ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
000717        ** or SQLITE_BUSY error.
000718        */
000719  #ifdef SQLITE_OMIT_AUTORESET
000720        if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
000721          sqlite3_reset((sqlite3_stmt*)p);
000722        }else{
000723          return SQLITE_MISUSE_BKPT;
000724        }
000725  #else
000726        sqlite3_reset((sqlite3_stmt*)p);
000727  #endif
000728        assert( p->eVdbeState==VDBE_READY_STATE );
000729        goto restart_step;
000730      }
000731    }
000732  
000733  #ifdef SQLITE_DEBUG
000734    p->rcApp = SQLITE_OK;
000735  #endif
000736  #ifndef SQLITE_OMIT_EXPLAIN
000737    if( p->explain ){
000738      rc = sqlite3VdbeList(p);
000739    }else
000740  #endif /* SQLITE_OMIT_EXPLAIN */
000741    {
000742      db->nVdbeExec++;
000743      rc = sqlite3VdbeExec(p);
000744      db->nVdbeExec--;
000745    }
000746  
000747    if( rc==SQLITE_ROW ){
000748      assert( p->rc==SQLITE_OK );
000749      assert( db->mallocFailed==0 );
000750      db->errCode = SQLITE_ROW;
000751      return SQLITE_ROW;
000752    }else{
000753  #ifndef SQLITE_OMIT_TRACE
000754      /* If the statement completed successfully, invoke the profile callback */
000755      checkProfileCallback(db, p);
000756  #endif
000757      p->pResultRow = 0;
000758      if( rc==SQLITE_DONE && db->autoCommit ){
000759        assert( p->rc==SQLITE_OK );
000760        p->rc = doWalCallbacks(db);
000761        if( p->rc!=SQLITE_OK ){
000762          rc = SQLITE_ERROR;
000763        }
000764      }else if( rc!=SQLITE_DONE && (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){
000765        /* If this statement was prepared using saved SQL and an
000766        ** error has occurred, then return the error code in p->rc to the
000767        ** caller. Set the error code in the database handle to the same value.
000768        */
000769        rc = sqlite3VdbeTransferError(p);
000770      }
000771    }
000772  
000773    db->errCode = rc;
000774    if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
000775      p->rc = SQLITE_NOMEM_BKPT;
000776      if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ) rc = p->rc;
000777    }
000778  end_of_step:
000779    /* There are only a limited number of result codes allowed from the
000780    ** statements prepared using the legacy sqlite3_prepare() interface */
000781    assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
000782         || rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
000783         || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
000784    );
000785    return (rc&db->errMask);
000786  }
000787  
000788  /*
000789  ** This is the top-level implementation of sqlite3_step().  Call
000790  ** sqlite3Step() to do most of the work.  If a schema error occurs,
000791  ** call sqlite3Reprepare() and try again.
000792  */
000793  int sqlite3_step(sqlite3_stmt *pStmt){
000794    int rc = SQLITE_OK;      /* Result from sqlite3Step() */
000795    Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
000796    int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
000797    sqlite3 *db;             /* The database connection */
000798  
000799    if( vdbeSafetyNotNull(v) ){
000800      return SQLITE_MISUSE_BKPT;
000801    }
000802    db = v->db;
000803    sqlite3_mutex_enter(db->mutex);
000804    while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
000805           && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
000806      int savedPc = v->pc;
000807      rc = sqlite3Reprepare(v);
000808      if( rc!=SQLITE_OK ){
000809        /* This case occurs after failing to recompile an sql statement.
000810        ** The error message from the SQL compiler has already been loaded
000811        ** into the database handle. This block copies the error message
000812        ** from the database handle into the statement and sets the statement
000813        ** program counter to 0 to ensure that when the statement is
000814        ** finalized or reset the parser error message is available via
000815        ** sqlite3_errmsg() and sqlite3_errcode().
000816        */
000817        const char *zErr = (const char *)sqlite3_value_text(db->pErr);
000818        sqlite3DbFree(db, v->zErrMsg);
000819        if( !db->mallocFailed ){
000820          v->zErrMsg = sqlite3DbStrDup(db, zErr);
000821          v->rc = rc = sqlite3ApiExit(db, rc);
000822        } else {
000823          v->zErrMsg = 0;
000824          v->rc = rc = SQLITE_NOMEM_BKPT;
000825        }
000826        break;
000827      }
000828      sqlite3_reset(pStmt);
000829      if( savedPc>=0 ){
000830        /* Setting minWriteFileFormat to 254 is a signal to the OP_Init and
000831        ** OP_Trace opcodes to *not* perform SQLITE_TRACE_STMT because it has
000832        ** already been done once on a prior invocation that failed due to
000833        ** SQLITE_SCHEMA.   tag-20220401a  */
000834        v->minWriteFileFormat = 254;
000835      }
000836      assert( v->expired==0 );
000837    }
000838    sqlite3_mutex_leave(db->mutex);
000839    return rc;
000840  }
000841  
000842  
000843  /*
000844  ** Extract the user data from a sqlite3_context structure and return a
000845  ** pointer to it.
000846  */
000847  void *sqlite3_user_data(sqlite3_context *p){
000848    assert( p && p->pFunc );
000849    return p->pFunc->pUserData;
000850  }
000851  
000852  /*
000853  ** Extract the user data from a sqlite3_context structure and return a
000854  ** pointer to it.
000855  **
000856  ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
000857  ** returns a copy of the pointer to the database connection (the 1st
000858  ** parameter) of the sqlite3_create_function() and
000859  ** sqlite3_create_function16() routines that originally registered the
000860  ** application defined function.
000861  */
000862  sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
000863    assert( p && p->pOut );
000864    return p->pOut->db;
000865  }
000866  
000867  /*
000868  ** If this routine is invoked from within an xColumn method of a virtual
000869  ** table, then it returns true if and only if the the call is during an
000870  ** UPDATE operation and the value of the column will not be modified
000871  ** by the UPDATE.
000872  **
000873  ** If this routine is called from any context other than within the
000874  ** xColumn method of a virtual table, then the return value is meaningless
000875  ** and arbitrary.
000876  **
000877  ** Virtual table implements might use this routine to optimize their
000878  ** performance by substituting a NULL result, or some other light-weight
000879  ** value, as a signal to the xUpdate routine that the column is unchanged.
000880  */
000881  int sqlite3_vtab_nochange(sqlite3_context *p){
000882    assert( p );
000883    return sqlite3_value_nochange(p->pOut);
000884  }
000885  
000886  /*
000887  ** The destructor function for a ValueList object.  This needs to be
000888  ** a separate function, unknowable to the application, to ensure that
000889  ** calls to sqlite3_vtab_in_first()/sqlite3_vtab_in_next() that are not
000890  ** preceded by activation of IN processing via sqlite3_vtab_int() do not
000891  ** try to access a fake ValueList object inserted by a hostile extension.
000892  */
000893  void sqlite3VdbeValueListFree(void *pToDelete){
000894    sqlite3_free(pToDelete);
000895  }
000896  
000897  /*
000898  ** Implementation of sqlite3_vtab_in_first() (if bNext==0) and
000899  ** sqlite3_vtab_in_next() (if bNext!=0).
000900  */
000901  static int valueFromValueList(
000902    sqlite3_value *pVal,        /* Pointer to the ValueList object */
000903    sqlite3_value **ppOut,      /* Store the next value from the list here */
000904    int bNext                   /* 1 for _next(). 0 for _first() */
000905  ){
000906    int rc;
000907    ValueList *pRhs;
000908  
000909    *ppOut = 0;
000910    if( pVal==0 ) return SQLITE_MISUSE;
000911    if( (pVal->flags & MEM_Dyn)==0 || pVal->xDel!=sqlite3VdbeValueListFree ){
000912      return SQLITE_ERROR;
000913    }else{
000914      assert( (pVal->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
000915                   (MEM_Null|MEM_Term|MEM_Subtype) );
000916      assert( pVal->eSubtype=='p' );
000917      assert( pVal->u.zPType!=0 && strcmp(pVal->u.zPType,"ValueList")==0 );
000918      pRhs = (ValueList*)pVal->z;
000919    }
000920    if( bNext ){
000921      rc = sqlite3BtreeNext(pRhs->pCsr, 0);
000922    }else{
000923      int dummy = 0;
000924      rc = sqlite3BtreeFirst(pRhs->pCsr, &dummy);
000925      assert( rc==SQLITE_OK || sqlite3BtreeEof(pRhs->pCsr) );
000926      if( sqlite3BtreeEof(pRhs->pCsr) ) rc = SQLITE_DONE;
000927    }
000928    if( rc==SQLITE_OK ){
000929      u32 sz;       /* Size of current row in bytes */
000930      Mem sMem;     /* Raw content of current row */
000931      memset(&sMem, 0, sizeof(sMem));
000932      sz = sqlite3BtreePayloadSize(pRhs->pCsr);
000933      rc = sqlite3VdbeMemFromBtreeZeroOffset(pRhs->pCsr,(int)sz,&sMem);
000934      if( rc==SQLITE_OK ){
000935        u8 *zBuf = (u8*)sMem.z;
000936        u32 iSerial;
000937        sqlite3_value *pOut = pRhs->pOut;
000938        int iOff = 1 + getVarint32(&zBuf[1], iSerial);
000939        sqlite3VdbeSerialGet(&zBuf[iOff], iSerial, pOut);
000940        pOut->enc = ENC(pOut->db);
000941        if( (pOut->flags & MEM_Ephem)!=0 && sqlite3VdbeMemMakeWriteable(pOut) ){
000942          rc = SQLITE_NOMEM;
000943        }else{
000944          *ppOut = pOut;
000945        }
000946      }
000947      sqlite3VdbeMemRelease(&sMem);
000948    }
000949    return rc;
000950  }
000951  
000952  /*
000953  ** Set the iterator value pVal to point to the first value in the set.
000954  ** Set (*ppOut) to point to this value before returning.
000955  */
000956  int sqlite3_vtab_in_first(sqlite3_value *pVal, sqlite3_value **ppOut){
000957    return valueFromValueList(pVal, ppOut, 0);
000958  }
000959  
000960  /*
000961  ** Set the iterator value pVal to point to the next value in the set.
000962  ** Set (*ppOut) to point to this value before returning.
000963  */
000964  int sqlite3_vtab_in_next(sqlite3_value *pVal, sqlite3_value **ppOut){
000965    return valueFromValueList(pVal, ppOut, 1);
000966  }
000967  
000968  /*
000969  ** Return the current time for a statement.  If the current time
000970  ** is requested more than once within the same run of a single prepared
000971  ** statement, the exact same time is returned for each invocation regardless
000972  ** of the amount of time that elapses between invocations.  In other words,
000973  ** the time returned is always the time of the first call.
000974  */
000975  sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
000976    int rc;
000977  #ifndef SQLITE_ENABLE_STAT4
000978    sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
000979    assert( p->pVdbe!=0 );
000980  #else
000981    sqlite3_int64 iTime = 0;
000982    sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
000983  #endif
000984    if( *piTime==0 ){
000985      rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
000986      if( rc ) *piTime = 0;
000987    }
000988    return *piTime;
000989  }
000990  
000991  /*
000992  ** Create a new aggregate context for p and return a pointer to
000993  ** its pMem->z element.
000994  */
000995  static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
000996    Mem *pMem = p->pMem;
000997    assert( (pMem->flags & MEM_Agg)==0 );
000998    if( nByte<=0 ){
000999      sqlite3VdbeMemSetNull(pMem);
001000      pMem->z = 0;
001001    }else{
001002      sqlite3VdbeMemClearAndResize(pMem, nByte);
001003      pMem->flags = MEM_Agg;
001004      pMem->u.pDef = p->pFunc;
001005      if( pMem->z ){
001006        memset(pMem->z, 0, nByte);
001007      }
001008    }
001009    return (void*)pMem->z;
001010  }
001011  
001012  /*
001013  ** Allocate or return the aggregate context for a user function.  A new
001014  ** context is allocated on the first call.  Subsequent calls return the
001015  ** same context that was returned on prior calls.
001016  */
001017  void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
001018    assert( p && p->pFunc && p->pFunc->xFinalize );
001019    assert( sqlite3_mutex_held(p->pOut->db->mutex) );
001020    testcase( nByte<0 );
001021    if( (p->pMem->flags & MEM_Agg)==0 ){
001022      return createAggContext(p, nByte);
001023    }else{
001024      return (void*)p->pMem->z;
001025    }
001026  }
001027  
001028  /*
001029  ** Return the auxiliary data pointer, if any, for the iArg'th argument to
001030  ** the user-function defined by pCtx.
001031  **
001032  ** The left-most argument is 0.
001033  **
001034  ** Undocumented behavior:  If iArg is negative then access a cache of
001035  ** auxiliary data pointers that is available to all functions within a
001036  ** single prepared statement.  The iArg values must match.
001037  */
001038  void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
001039    AuxData *pAuxData;
001040  
001041    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
001042  #if SQLITE_ENABLE_STAT4
001043    if( pCtx->pVdbe==0 ) return 0;
001044  #else
001045    assert( pCtx->pVdbe!=0 );
001046  #endif
001047    for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
001048      if(  pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
001049        return pAuxData->pAux;
001050      }
001051    }
001052    return 0;
001053  }
001054  
001055  /*
001056  ** Set the auxiliary data pointer and delete function, for the iArg'th
001057  ** argument to the user-function defined by pCtx. Any previous value is
001058  ** deleted by calling the delete function specified when it was set.
001059  **
001060  ** The left-most argument is 0.
001061  **
001062  ** Undocumented behavior:  If iArg is negative then make the data available
001063  ** to all functions within the current prepared statement using iArg as an
001064  ** access code.
001065  */
001066  void sqlite3_set_auxdata(
001067    sqlite3_context *pCtx,
001068    int iArg,
001069    void *pAux,
001070    void (*xDelete)(void*)
001071  ){
001072    AuxData *pAuxData;
001073    Vdbe *pVdbe = pCtx->pVdbe;
001074  
001075    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
001076  #ifdef SQLITE_ENABLE_STAT4
001077    if( pVdbe==0 ) goto failed;
001078  #else
001079    assert( pVdbe!=0 );
001080  #endif
001081  
001082    for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
001083      if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
001084        break;
001085      }
001086    }
001087    if( pAuxData==0 ){
001088      pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
001089      if( !pAuxData ) goto failed;
001090      pAuxData->iAuxOp = pCtx->iOp;
001091      pAuxData->iAuxArg = iArg;
001092      pAuxData->pNextAux = pVdbe->pAuxData;
001093      pVdbe->pAuxData = pAuxData;
001094      if( pCtx->isError==0 ) pCtx->isError = -1;
001095    }else if( pAuxData->xDeleteAux ){
001096      pAuxData->xDeleteAux(pAuxData->pAux);
001097    }
001098  
001099    pAuxData->pAux = pAux;
001100    pAuxData->xDeleteAux = xDelete;
001101    return;
001102  
001103  failed:
001104    if( xDelete ){
001105      xDelete(pAux);
001106    }
001107  }
001108  
001109  #ifndef SQLITE_OMIT_DEPRECATED
001110  /*
001111  ** Return the number of times the Step function of an aggregate has been
001112  ** called.
001113  **
001114  ** This function is deprecated.  Do not use it for new code.  It is
001115  ** provide only to avoid breaking legacy code.  New aggregate function
001116  ** implementations should keep their own counts within their aggregate
001117  ** context.
001118  */
001119  int sqlite3_aggregate_count(sqlite3_context *p){
001120    assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
001121    return p->pMem->n;
001122  }
001123  #endif
001124  
001125  /*
001126  ** Return the number of columns in the result set for the statement pStmt.
001127  */
001128  int sqlite3_column_count(sqlite3_stmt *pStmt){
001129    Vdbe *pVm = (Vdbe *)pStmt;
001130    if( pVm==0 ) return 0;
001131    return pVm->nResColumn;
001132  }
001133  
001134  /*
001135  ** Return the number of values available from the current row of the
001136  ** currently executing statement pStmt.
001137  */
001138  int sqlite3_data_count(sqlite3_stmt *pStmt){
001139    Vdbe *pVm = (Vdbe *)pStmt;
001140    if( pVm==0 || pVm->pResultRow==0 ) return 0;
001141    return pVm->nResColumn;
001142  }
001143  
001144  /*
001145  ** Return a pointer to static memory containing an SQL NULL value.
001146  */
001147  static const Mem *columnNullValue(void){
001148    /* Even though the Mem structure contains an element
001149    ** of type i64, on certain architectures (x86) with certain compiler
001150    ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
001151    ** instead of an 8-byte one. This all works fine, except that when
001152    ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
001153    ** that a Mem structure is located on an 8-byte boundary. To prevent
001154    ** these assert()s from failing, when building with SQLITE_DEBUG defined
001155    ** using gcc, we force nullMem to be 8-byte aligned using the magical
001156    ** __attribute__((aligned(8))) macro.  */
001157    static const Mem nullMem
001158  #if defined(SQLITE_DEBUG) && defined(__GNUC__)
001159      __attribute__((aligned(8)))
001160  #endif
001161      = {
001162          /* .u          = */ {0},
001163          /* .z          = */ (char*)0,
001164          /* .n          = */ (int)0,
001165          /* .flags      = */ (u16)MEM_Null,
001166          /* .enc        = */ (u8)0,
001167          /* .eSubtype   = */ (u8)0,
001168          /* .db         = */ (sqlite3*)0,
001169          /* .szMalloc   = */ (int)0,
001170          /* .uTemp      = */ (u32)0,
001171          /* .zMalloc    = */ (char*)0,
001172          /* .xDel       = */ (void(*)(void*))0,
001173  #ifdef SQLITE_DEBUG
001174          /* .pScopyFrom = */ (Mem*)0,
001175          /* .mScopyFlags= */ 0,
001176  #endif
001177        };
001178    return &nullMem;
001179  }
001180  
001181  /*
001182  ** Check to see if column iCol of the given statement is valid.  If
001183  ** it is, return a pointer to the Mem for the value of that column.
001184  ** If iCol is not valid, return a pointer to a Mem which has a value
001185  ** of NULL.
001186  */
001187  static Mem *columnMem(sqlite3_stmt *pStmt, int i){
001188    Vdbe *pVm;
001189    Mem *pOut;
001190  
001191    pVm = (Vdbe *)pStmt;
001192    if( pVm==0 ) return (Mem*)columnNullValue();
001193    assert( pVm->db );
001194    sqlite3_mutex_enter(pVm->db->mutex);
001195    if( pVm->pResultRow!=0 && i<pVm->nResColumn && i>=0 ){
001196      pOut = &pVm->pResultRow[i];
001197    }else{
001198      sqlite3Error(pVm->db, SQLITE_RANGE);
001199      pOut = (Mem*)columnNullValue();
001200    }
001201    return pOut;
001202  }
001203  
001204  /*
001205  ** This function is called after invoking an sqlite3_value_XXX function on a
001206  ** column value (i.e. a value returned by evaluating an SQL expression in the
001207  ** select list of a SELECT statement) that may cause a malloc() failure. If
001208  ** malloc() has failed, the threads mallocFailed flag is cleared and the result
001209  ** code of statement pStmt set to SQLITE_NOMEM.
001210  **
001211  ** Specifically, this is called from within:
001212  **
001213  **     sqlite3_column_int()
001214  **     sqlite3_column_int64()
001215  **     sqlite3_column_text()
001216  **     sqlite3_column_text16()
001217  **     sqlite3_column_real()
001218  **     sqlite3_column_bytes()
001219  **     sqlite3_column_bytes16()
001220  **     sqlite3_column_blob()
001221  */
001222  static void columnMallocFailure(sqlite3_stmt *pStmt)
001223  {
001224    /* If malloc() failed during an encoding conversion within an
001225    ** sqlite3_column_XXX API, then set the return code of the statement to
001226    ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
001227    ** and _finalize() will return NOMEM.
001228    */
001229    Vdbe *p = (Vdbe *)pStmt;
001230    if( p ){
001231      assert( p->db!=0 );
001232      assert( sqlite3_mutex_held(p->db->mutex) );
001233      p->rc = sqlite3ApiExit(p->db, p->rc);
001234      sqlite3_mutex_leave(p->db->mutex);
001235    }
001236  }
001237  
001238  /**************************** sqlite3_column_  *******************************
001239  ** The following routines are used to access elements of the current row
001240  ** in the result set.
001241  */
001242  const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
001243    const void *val;
001244    val = sqlite3_value_blob( columnMem(pStmt,i) );
001245    /* Even though there is no encoding conversion, value_blob() might
001246    ** need to call malloc() to expand the result of a zeroblob()
001247    ** expression.
001248    */
001249    columnMallocFailure(pStmt);
001250    return val;
001251  }
001252  int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
001253    int val = sqlite3_value_bytes( columnMem(pStmt,i) );
001254    columnMallocFailure(pStmt);
001255    return val;
001256  }
001257  int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
001258    int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
001259    columnMallocFailure(pStmt);
001260    return val;
001261  }
001262  double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
001263    double val = sqlite3_value_double( columnMem(pStmt,i) );
001264    columnMallocFailure(pStmt);
001265    return val;
001266  }
001267  int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
001268    int val = sqlite3_value_int( columnMem(pStmt,i) );
001269    columnMallocFailure(pStmt);
001270    return val;
001271  }
001272  sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
001273    sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
001274    columnMallocFailure(pStmt);
001275    return val;
001276  }
001277  const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
001278    const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
001279    columnMallocFailure(pStmt);
001280    return val;
001281  }
001282  sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
001283    Mem *pOut = columnMem(pStmt, i);
001284    if( pOut->flags&MEM_Static ){
001285      pOut->flags &= ~MEM_Static;
001286      pOut->flags |= MEM_Ephem;
001287    }
001288    columnMallocFailure(pStmt);
001289    return (sqlite3_value *)pOut;
001290  }
001291  #ifndef SQLITE_OMIT_UTF16
001292  const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
001293    const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
001294    columnMallocFailure(pStmt);
001295    return val;
001296  }
001297  #endif /* SQLITE_OMIT_UTF16 */
001298  int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
001299    int iType = sqlite3_value_type( columnMem(pStmt,i) );
001300    columnMallocFailure(pStmt);
001301    return iType;
001302  }
001303  
001304  /*
001305  ** Column names appropriate for EXPLAIN or EXPLAIN QUERY PLAN.
001306  */
001307  static const char * const azExplainColNames8[] = {
001308     "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",  /* EXPLAIN */
001309     "id", "parent", "notused", "detail"                         /* EQP */
001310  };
001311  static const u16 azExplainColNames16data[] = {
001312    /*   0 */  'a', 'd', 'd', 'r',                0,
001313    /*   5 */  'o', 'p', 'c', 'o', 'd', 'e',      0,
001314    /*  12 */  'p', '1',                          0, 
001315    /*  15 */  'p', '2',                          0,
001316    /*  18 */  'p', '3',                          0,
001317    /*  21 */  'p', '4',                          0,
001318    /*  24 */  'p', '5',                          0,
001319    /*  27 */  'c', 'o', 'm', 'm', 'e', 'n', 't', 0,
001320    /*  35 */  'i', 'd',                          0,
001321    /*  38 */  'p', 'a', 'r', 'e', 'n', 't',      0,
001322    /*  45 */  'n', 'o', 't', 'u', 's', 'e', 'd', 0,
001323    /*  53 */  'd', 'e', 't', 'a', 'i', 'l',      0
001324  };
001325  static const u8 iExplainColNames16[] = {
001326    0, 5, 12, 15, 18, 21, 24, 27,
001327    35, 38, 45, 53
001328  };
001329  
001330  /*
001331  ** Convert the N-th element of pStmt->pColName[] into a string using
001332  ** xFunc() then return that string.  If N is out of range, return 0.
001333  **
001334  ** There are up to 5 names for each column.  useType determines which
001335  ** name is returned.  Here are the names:
001336  **
001337  **    0      The column name as it should be displayed for output
001338  **    1      The datatype name for the column
001339  **    2      The name of the database that the column derives from
001340  **    3      The name of the table that the column derives from
001341  **    4      The name of the table column that the result column derives from
001342  **
001343  ** If the result is not a simple column reference (if it is an expression
001344  ** or a constant) then useTypes 2, 3, and 4 return NULL.
001345  */
001346  static const void *columnName(
001347    sqlite3_stmt *pStmt,     /* The statement */
001348    int N,                   /* Which column to get the name for */
001349    int useUtf16,            /* True to return the name as UTF16 */
001350    int useType              /* What type of name */
001351  ){
001352    const void *ret;
001353    Vdbe *p;
001354    int n;
001355    sqlite3 *db;
001356  #ifdef SQLITE_ENABLE_API_ARMOR
001357    if( pStmt==0 ){
001358      (void)SQLITE_MISUSE_BKPT;
001359      return 0;
001360    }
001361  #endif
001362    if( N<0 ) return 0;
001363    ret = 0;
001364    p = (Vdbe *)pStmt;
001365    db = p->db;
001366    assert( db!=0 );
001367    sqlite3_mutex_enter(db->mutex);
001368  
001369    if( p->explain ){
001370      if( useType>0 ) goto columnName_end;
001371      n = p->explain==1 ? 8 : 4;
001372      if( N>=n ) goto columnName_end;
001373      if( useUtf16 ){
001374        int i = iExplainColNames16[N + 8*p->explain - 8];
001375        ret = (void*)&azExplainColNames16data[i];
001376      }else{
001377        ret = (void*)azExplainColNames8[N + 8*p->explain - 8];
001378      }
001379      goto columnName_end;
001380    }
001381    n = p->nResColumn;
001382    if( N<n ){
001383      u8 prior_mallocFailed = db->mallocFailed;
001384      N += useType*n;
001385  #ifndef SQLITE_OMIT_UTF16
001386      if( useUtf16 ){
001387        ret = sqlite3_value_text16((sqlite3_value*)&p->aColName[N]);
001388      }else
001389  #endif
001390      {
001391        ret = sqlite3_value_text((sqlite3_value*)&p->aColName[N]);
001392      }
001393      /* A malloc may have failed inside of the _text() call. If this
001394      ** is the case, clear the mallocFailed flag and return NULL.
001395      */
001396      assert( db->mallocFailed==0 || db->mallocFailed==1 );
001397      if( db->mallocFailed > prior_mallocFailed ){
001398        sqlite3OomClear(db);
001399        ret = 0;
001400      }
001401    }
001402  columnName_end:
001403    sqlite3_mutex_leave(db->mutex);
001404    return ret;
001405  }
001406  
001407  /*
001408  ** Return the name of the Nth column of the result set returned by SQL
001409  ** statement pStmt.
001410  */
001411  const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
001412    return columnName(pStmt, N, 0, COLNAME_NAME);
001413  }
001414  #ifndef SQLITE_OMIT_UTF16
001415  const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
001416    return columnName(pStmt, N, 1, COLNAME_NAME);
001417  }
001418  #endif
001419  
001420  /*
001421  ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
001422  ** not define OMIT_DECLTYPE.
001423  */
001424  #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
001425  # error "Must not define both SQLITE_OMIT_DECLTYPE \
001426           and SQLITE_ENABLE_COLUMN_METADATA"
001427  #endif
001428  
001429  #ifndef SQLITE_OMIT_DECLTYPE
001430  /*
001431  ** Return the column declaration type (if applicable) of the 'i'th column
001432  ** of the result set of SQL statement pStmt.
001433  */
001434  const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
001435    return columnName(pStmt, N, 0, COLNAME_DECLTYPE);
001436  }
001437  #ifndef SQLITE_OMIT_UTF16
001438  const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
001439    return columnName(pStmt, N, 1, COLNAME_DECLTYPE);
001440  }
001441  #endif /* SQLITE_OMIT_UTF16 */
001442  #endif /* SQLITE_OMIT_DECLTYPE */
001443  
001444  #ifdef SQLITE_ENABLE_COLUMN_METADATA
001445  /*
001446  ** Return the name of the database from which a result column derives.
001447  ** NULL is returned if the result column is an expression or constant or
001448  ** anything else which is not an unambiguous reference to a database column.
001449  */
001450  const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
001451    return columnName(pStmt, N, 0, COLNAME_DATABASE);
001452  }
001453  #ifndef SQLITE_OMIT_UTF16
001454  const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
001455    return columnName(pStmt, N, 1, COLNAME_DATABASE);
001456  }
001457  #endif /* SQLITE_OMIT_UTF16 */
001458  
001459  /*
001460  ** Return the name of the table from which a result column derives.
001461  ** NULL is returned if the result column is an expression or constant or
001462  ** anything else which is not an unambiguous reference to a database column.
001463  */
001464  const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
001465    return columnName(pStmt, N, 0, COLNAME_TABLE);
001466  }
001467  #ifndef SQLITE_OMIT_UTF16
001468  const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
001469    return columnName(pStmt, N, 1, COLNAME_TABLE);
001470  }
001471  #endif /* SQLITE_OMIT_UTF16 */
001472  
001473  /*
001474  ** Return the name of the table column from which a result column derives.
001475  ** NULL is returned if the result column is an expression or constant or
001476  ** anything else which is not an unambiguous reference to a database column.
001477  */
001478  const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
001479    return columnName(pStmt, N, 0, COLNAME_COLUMN);
001480  }
001481  #ifndef SQLITE_OMIT_UTF16
001482  const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
001483    return columnName(pStmt, N, 1, COLNAME_COLUMN);
001484  }
001485  #endif /* SQLITE_OMIT_UTF16 */
001486  #endif /* SQLITE_ENABLE_COLUMN_METADATA */
001487  
001488  
001489  /******************************* sqlite3_bind_  ***************************
001490  **
001491  ** Routines used to attach values to wildcards in a compiled SQL statement.
001492  */
001493  /*
001494  ** Unbind the value bound to variable i in virtual machine p. This is the
001495  ** the same as binding a NULL value to the column. If the "i" parameter is
001496  ** out of range, then SQLITE_RANGE is returned. Otherwise SQLITE_OK.
001497  **
001498  ** A successful evaluation of this routine acquires the mutex on p.
001499  ** the mutex is released if any kind of error occurs.
001500  **
001501  ** The error code stored in database p->db is overwritten with the return
001502  ** value in any case.
001503  */
001504  static int vdbeUnbind(Vdbe *p, unsigned int i){
001505    Mem *pVar;
001506    if( vdbeSafetyNotNull(p) ){
001507      return SQLITE_MISUSE_BKPT;
001508    }
001509    sqlite3_mutex_enter(p->db->mutex);
001510    if( p->eVdbeState!=VDBE_READY_STATE ){
001511      sqlite3Error(p->db, SQLITE_MISUSE);
001512      sqlite3_mutex_leave(p->db->mutex);
001513      sqlite3_log(SQLITE_MISUSE,
001514          "bind on a busy prepared statement: [%s]", p->zSql);
001515      return SQLITE_MISUSE_BKPT;
001516    }
001517    if( i>=(unsigned int)p->nVar ){
001518      sqlite3Error(p->db, SQLITE_RANGE);
001519      sqlite3_mutex_leave(p->db->mutex);
001520      return SQLITE_RANGE;
001521    }
001522    pVar = &p->aVar[i];
001523    sqlite3VdbeMemRelease(pVar);
001524    pVar->flags = MEM_Null;
001525    p->db->errCode = SQLITE_OK;
001526  
001527    /* If the bit corresponding to this variable in Vdbe.expmask is set, then
001528    ** binding a new value to this variable invalidates the current query plan.
001529    **
001530    ** IMPLEMENTATION-OF: R-57496-20354 If the specific value bound to a host
001531    ** parameter in the WHERE clause might influence the choice of query plan
001532    ** for a statement, then the statement will be automatically recompiled,
001533    ** as if there had been a schema change, on the first sqlite3_step() call
001534    ** following any change to the bindings of that parameter.
001535    */
001536    assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
001537    if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
001538      p->expired = 1;
001539    }
001540    return SQLITE_OK;
001541  }
001542  
001543  /*
001544  ** Bind a text or BLOB value.
001545  */
001546  static int bindText(
001547    sqlite3_stmt *pStmt,   /* The statement to bind against */
001548    int i,                 /* Index of the parameter to bind */
001549    const void *zData,     /* Pointer to the data to be bound */
001550    i64 nData,             /* Number of bytes of data to be bound */
001551    void (*xDel)(void*),   /* Destructor for the data */
001552    u8 encoding            /* Encoding for the data */
001553  ){
001554    Vdbe *p = (Vdbe *)pStmt;
001555    Mem *pVar;
001556    int rc;
001557  
001558    rc = vdbeUnbind(p, (u32)(i-1));
001559    if( rc==SQLITE_OK ){
001560      if( zData!=0 ){
001561        pVar = &p->aVar[i-1];
001562        rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
001563        if( rc==SQLITE_OK && encoding!=0 ){
001564          rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
001565        }
001566        if( rc ){
001567          sqlite3Error(p->db, rc);
001568          rc = sqlite3ApiExit(p->db, rc);
001569        }
001570      }
001571      sqlite3_mutex_leave(p->db->mutex);
001572    }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
001573      xDel((void*)zData);
001574    }
001575    return rc;
001576  }
001577  
001578  
001579  /*
001580  ** Bind a blob value to an SQL statement variable.
001581  */
001582  int sqlite3_bind_blob(
001583    sqlite3_stmt *pStmt,
001584    int i,
001585    const void *zData,
001586    int nData,
001587    void (*xDel)(void*)
001588  ){
001589  #ifdef SQLITE_ENABLE_API_ARMOR
001590    if( nData<0 ) return SQLITE_MISUSE_BKPT;
001591  #endif
001592    return bindText(pStmt, i, zData, nData, xDel, 0);
001593  }
001594  int sqlite3_bind_blob64(
001595    sqlite3_stmt *pStmt,
001596    int i,
001597    const void *zData,
001598    sqlite3_uint64 nData,
001599    void (*xDel)(void*)
001600  ){
001601    assert( xDel!=SQLITE_DYNAMIC );
001602    return bindText(pStmt, i, zData, nData, xDel, 0);
001603  }
001604  int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
001605    int rc;
001606    Vdbe *p = (Vdbe *)pStmt;
001607    rc = vdbeUnbind(p, (u32)(i-1));
001608    if( rc==SQLITE_OK ){
001609      sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
001610      sqlite3_mutex_leave(p->db->mutex);
001611    }
001612    return rc;
001613  }
001614  int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
001615    return sqlite3_bind_int64(p, i, (i64)iValue);
001616  }
001617  int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
001618    int rc;
001619    Vdbe *p = (Vdbe *)pStmt;
001620    rc = vdbeUnbind(p, (u32)(i-1));
001621    if( rc==SQLITE_OK ){
001622      sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
001623      sqlite3_mutex_leave(p->db->mutex);
001624    }
001625    return rc;
001626  }
001627  int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
001628    int rc;
001629    Vdbe *p = (Vdbe*)pStmt;
001630    rc = vdbeUnbind(p, (u32)(i-1));
001631    if( rc==SQLITE_OK ){
001632      sqlite3_mutex_leave(p->db->mutex);
001633    }
001634    return rc;
001635  }
001636  int sqlite3_bind_pointer(
001637    sqlite3_stmt *pStmt,
001638    int i,
001639    void *pPtr,
001640    const char *zPTtype,
001641    void (*xDestructor)(void*)
001642  ){
001643    int rc;
001644    Vdbe *p = (Vdbe*)pStmt;
001645    rc = vdbeUnbind(p, (u32)(i-1));
001646    if( rc==SQLITE_OK ){
001647      sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
001648      sqlite3_mutex_leave(p->db->mutex);
001649    }else if( xDestructor ){
001650      xDestructor(pPtr);
001651    }
001652    return rc;
001653  }
001654  int sqlite3_bind_text(
001655    sqlite3_stmt *pStmt,
001656    int i,
001657    const char *zData,
001658    int nData,
001659    void (*xDel)(void*)
001660  ){
001661    return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
001662  }
001663  int sqlite3_bind_text64(
001664    sqlite3_stmt *pStmt,
001665    int i,
001666    const char *zData,
001667    sqlite3_uint64 nData,
001668    void (*xDel)(void*),
001669    unsigned char enc
001670  ){
001671    assert( xDel!=SQLITE_DYNAMIC );
001672    if( enc!=SQLITE_UTF8 ){
001673      if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
001674      nData &= ~(u16)1;
001675    }
001676    return bindText(pStmt, i, zData, nData, xDel, enc);
001677  }
001678  #ifndef SQLITE_OMIT_UTF16
001679  int sqlite3_bind_text16(
001680    sqlite3_stmt *pStmt,
001681    int i,
001682    const void *zData,
001683    int n,
001684    void (*xDel)(void*)
001685  ){
001686    return bindText(pStmt, i, zData, n & ~(u64)1, xDel, SQLITE_UTF16NATIVE);
001687  }
001688  #endif /* SQLITE_OMIT_UTF16 */
001689  int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
001690    int rc;
001691    switch( sqlite3_value_type((sqlite3_value*)pValue) ){
001692      case SQLITE_INTEGER: {
001693        rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
001694        break;
001695      }
001696      case SQLITE_FLOAT: {
001697        assert( pValue->flags & (MEM_Real|MEM_IntReal) );
001698        rc = sqlite3_bind_double(pStmt, i,
001699            (pValue->flags & MEM_Real) ? pValue->u.r : (double)pValue->u.i
001700        );
001701        break;
001702      }
001703      case SQLITE_BLOB: {
001704        if( pValue->flags & MEM_Zero ){
001705          rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
001706        }else{
001707          rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
001708        }
001709        break;
001710      }
001711      case SQLITE_TEXT: {
001712        rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
001713                                pValue->enc);
001714        break;
001715      }
001716      default: {
001717        rc = sqlite3_bind_null(pStmt, i);
001718        break;
001719      }
001720    }
001721    return rc;
001722  }
001723  int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
001724    int rc;
001725    Vdbe *p = (Vdbe *)pStmt;
001726    rc = vdbeUnbind(p, (u32)(i-1));
001727    if( rc==SQLITE_OK ){
001728  #ifndef SQLITE_OMIT_INCRBLOB
001729      sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
001730  #else
001731      rc = sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
001732  #endif
001733      sqlite3_mutex_leave(p->db->mutex);
001734    }
001735    return rc;
001736  }
001737  int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
001738    int rc;
001739    Vdbe *p = (Vdbe *)pStmt;
001740    sqlite3_mutex_enter(p->db->mutex);
001741    if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
001742      rc = SQLITE_TOOBIG;
001743    }else{
001744      assert( (n & 0x7FFFFFFF)==n );
001745      rc = sqlite3_bind_zeroblob(pStmt, i, n);
001746    }
001747    rc = sqlite3ApiExit(p->db, rc);
001748    sqlite3_mutex_leave(p->db->mutex);
001749    return rc;
001750  }
001751  
001752  /*
001753  ** Return the number of wildcards that can be potentially bound to.
001754  ** This routine is added to support DBD::SQLite. 
001755  */
001756  int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
001757    Vdbe *p = (Vdbe*)pStmt;
001758    return p ? p->nVar : 0;
001759  }
001760  
001761  /*
001762  ** Return the name of a wildcard parameter.  Return NULL if the index
001763  ** is out of range or if the wildcard is unnamed.
001764  **
001765  ** The result is always UTF-8.
001766  */
001767  const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
001768    Vdbe *p = (Vdbe*)pStmt;
001769    if( p==0 ) return 0;
001770    return sqlite3VListNumToName(p->pVList, i);
001771  }
001772  
001773  /*
001774  ** Given a wildcard parameter name, return the index of the variable
001775  ** with that name.  If there is no variable with the given name,
001776  ** return 0.
001777  */
001778  int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
001779    if( p==0 || zName==0 ) return 0;
001780    return sqlite3VListNameToNum(p->pVList, zName, nName);
001781  }
001782  int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
001783    return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
001784  }
001785  
001786  /*
001787  ** Transfer all bindings from the first statement over to the second.
001788  */
001789  int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
001790    Vdbe *pFrom = (Vdbe*)pFromStmt;
001791    Vdbe *pTo = (Vdbe*)pToStmt;
001792    int i;
001793    assert( pTo->db==pFrom->db );
001794    assert( pTo->nVar==pFrom->nVar );
001795    sqlite3_mutex_enter(pTo->db->mutex);
001796    for(i=0; i<pFrom->nVar; i++){
001797      sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
001798    }
001799    sqlite3_mutex_leave(pTo->db->mutex);
001800    return SQLITE_OK;
001801  }
001802  
001803  #ifndef SQLITE_OMIT_DEPRECATED
001804  /*
001805  ** Deprecated external interface.  Internal/core SQLite code
001806  ** should call sqlite3TransferBindings.
001807  **
001808  ** It is misuse to call this routine with statements from different
001809  ** database connections.  But as this is a deprecated interface, we
001810  ** will not bother to check for that condition.
001811  **
001812  ** If the two statements contain a different number of bindings, then
001813  ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
001814  ** SQLITE_OK is returned.
001815  */
001816  int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
001817    Vdbe *pFrom = (Vdbe*)pFromStmt;
001818    Vdbe *pTo = (Vdbe*)pToStmt;
001819    if( pFrom->nVar!=pTo->nVar ){
001820      return SQLITE_ERROR;
001821    }
001822    assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
001823    if( pTo->expmask ){
001824      pTo->expired = 1;
001825    }
001826    assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
001827    if( pFrom->expmask ){
001828      pFrom->expired = 1;
001829    }
001830    return sqlite3TransferBindings(pFromStmt, pToStmt);
001831  }
001832  #endif
001833  
001834  /*
001835  ** Return the sqlite3* database handle to which the prepared statement given
001836  ** in the argument belongs.  This is the same database handle that was
001837  ** the first argument to the sqlite3_prepare() that was used to create
001838  ** the statement in the first place.
001839  */
001840  sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
001841    return pStmt ? ((Vdbe*)pStmt)->db : 0;
001842  }
001843  
001844  /*
001845  ** Return true if the prepared statement is guaranteed to not modify the
001846  ** database.
001847  */
001848  int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
001849    return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
001850  }
001851  
001852  /*
001853  ** Return 1 if the statement is an EXPLAIN and return 2 if the
001854  ** statement is an EXPLAIN QUERY PLAN
001855  */
001856  int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt){
001857    return pStmt ? ((Vdbe*)pStmt)->explain : 0;
001858  }
001859  
001860  /*
001861  ** Set the explain mode for a statement.
001862  */
001863  int sqlite3_stmt_explain(sqlite3_stmt *pStmt, int eMode){
001864    Vdbe *v = (Vdbe*)pStmt;
001865    int rc;
001866    sqlite3_mutex_enter(v->db->mutex);
001867    if( ((int)v->explain)==eMode ){
001868      rc = SQLITE_OK;
001869    }else if( eMode<0 || eMode>2 ){
001870      rc = SQLITE_ERROR;
001871    }else if( (v->prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
001872      rc = SQLITE_ERROR;
001873    }else if( v->eVdbeState!=VDBE_READY_STATE ){
001874      rc = SQLITE_BUSY;
001875    }else if( v->nMem>=10 && (eMode!=2 || v->haveEqpOps) ){
001876      /* No reprepare necessary */
001877      v->explain = eMode;
001878      rc = SQLITE_OK;
001879    }else{
001880      v->explain = eMode;
001881      rc = sqlite3Reprepare(v);
001882      v->haveEqpOps = eMode==2;
001883    }
001884    if( v->explain ){
001885      v->nResColumn = 12 - 4*v->explain;
001886    }else{
001887      v->nResColumn = v->nResAlloc;
001888    }
001889    sqlite3_mutex_leave(v->db->mutex);
001890    return rc;
001891  }
001892  
001893  /*
001894  ** Return true if the prepared statement is in need of being reset.
001895  */
001896  int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
001897    Vdbe *v = (Vdbe*)pStmt;
001898    return v!=0 && v->eVdbeState==VDBE_RUN_STATE;
001899  }
001900  
001901  /*
001902  ** Return a pointer to the next prepared statement after pStmt associated
001903  ** with database connection pDb.  If pStmt is NULL, return the first
001904  ** prepared statement for the database connection.  Return NULL if there
001905  ** are no more.
001906  */
001907  sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
001908    sqlite3_stmt *pNext;
001909  #ifdef SQLITE_ENABLE_API_ARMOR
001910    if( !sqlite3SafetyCheckOk(pDb) ){
001911      (void)SQLITE_MISUSE_BKPT;
001912      return 0;
001913    }
001914  #endif
001915    sqlite3_mutex_enter(pDb->mutex);
001916    if( pStmt==0 ){
001917      pNext = (sqlite3_stmt*)pDb->pVdbe;
001918    }else{
001919      pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pVNext;
001920    }
001921    sqlite3_mutex_leave(pDb->mutex);
001922    return pNext;
001923  }
001924  
001925  /*
001926  ** Return the value of a status counter for a prepared statement
001927  */
001928  int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
001929    Vdbe *pVdbe = (Vdbe*)pStmt;
001930    u32 v;
001931  #ifdef SQLITE_ENABLE_API_ARMOR
001932    if( !pStmt
001933     || (op!=SQLITE_STMTSTATUS_MEMUSED && (op<0||op>=ArraySize(pVdbe->aCounter)))
001934    ){
001935      (void)SQLITE_MISUSE_BKPT;
001936      return 0;
001937    }
001938  #endif
001939    if( op==SQLITE_STMTSTATUS_MEMUSED ){
001940      sqlite3 *db = pVdbe->db;
001941      sqlite3_mutex_enter(db->mutex);
001942      v = 0;
001943      db->pnBytesFreed = (int*)&v;
001944      assert( db->lookaside.pEnd==db->lookaside.pTrueEnd );
001945      db->lookaside.pEnd = db->lookaside.pStart;
001946      sqlite3VdbeDelete(pVdbe);
001947      db->pnBytesFreed = 0;
001948      db->lookaside.pEnd = db->lookaside.pTrueEnd;
001949      sqlite3_mutex_leave(db->mutex);
001950    }else{
001951      v = pVdbe->aCounter[op];
001952      if( resetFlag ) pVdbe->aCounter[op] = 0;
001953    }
001954    return (int)v;
001955  }
001956  
001957  /*
001958  ** Return the SQL associated with a prepared statement
001959  */
001960  const char *sqlite3_sql(sqlite3_stmt *pStmt){
001961    Vdbe *p = (Vdbe *)pStmt;
001962    return p ? p->zSql : 0;
001963  }
001964  
001965  /*
001966  ** Return the SQL associated with a prepared statement with
001967  ** bound parameters expanded.  Space to hold the returned string is
001968  ** obtained from sqlite3_malloc().  The caller is responsible for
001969  ** freeing the returned string by passing it to sqlite3_free().
001970  **
001971  ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
001972  ** expanded bound parameters.
001973  */
001974  char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
001975  #ifdef SQLITE_OMIT_TRACE
001976    return 0;
001977  #else
001978    char *z = 0;
001979    const char *zSql = sqlite3_sql(pStmt);
001980    if( zSql ){
001981      Vdbe *p = (Vdbe *)pStmt;
001982      sqlite3_mutex_enter(p->db->mutex);
001983      z = sqlite3VdbeExpandSql(p, zSql);
001984      sqlite3_mutex_leave(p->db->mutex);
001985    }
001986    return z;
001987  #endif
001988  }
001989  
001990  #ifdef SQLITE_ENABLE_NORMALIZE
001991  /*
001992  ** Return the normalized SQL associated with a prepared statement.
001993  */
001994  const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt){
001995    Vdbe *p = (Vdbe *)pStmt;
001996    if( p==0 ) return 0;
001997    if( p->zNormSql==0 && ALWAYS(p->zSql!=0) ){
001998      sqlite3_mutex_enter(p->db->mutex);
001999      p->zNormSql = sqlite3Normalize(p, p->zSql);
002000      sqlite3_mutex_leave(p->db->mutex);
002001    }
002002    return p->zNormSql;
002003  }
002004  #endif /* SQLITE_ENABLE_NORMALIZE */
002005  
002006  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
002007  /*
002008  ** Allocate and populate an UnpackedRecord structure based on the serialized
002009  ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
002010  ** if successful, or a NULL pointer if an OOM error is encountered.
002011  */
002012  static UnpackedRecord *vdbeUnpackRecord(
002013    KeyInfo *pKeyInfo,
002014    int nKey,
002015    const void *pKey
002016  ){
002017    UnpackedRecord *pRet;           /* Return value */
002018  
002019    pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
002020    if( pRet ){
002021      memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
002022      sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
002023    }
002024    return pRet;
002025  }
002026  
002027  /*
002028  ** This function is called from within a pre-update callback to retrieve
002029  ** a field of the row currently being updated or deleted.
002030  */
002031  int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
002032    PreUpdate *p = db->pPreUpdate;
002033    Mem *pMem;
002034    int rc = SQLITE_OK;
002035  
002036    /* Test that this call is being made from within an SQLITE_DELETE or
002037    ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
002038    if( !p || p->op==SQLITE_INSERT ){
002039      rc = SQLITE_MISUSE_BKPT;
002040      goto preupdate_old_out;
002041    }
002042    if( p->pPk ){
002043      iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);
002044    }
002045    if( iIdx>=p->pCsr->nField || iIdx<0 ){
002046      rc = SQLITE_RANGE;
002047      goto preupdate_old_out;
002048    }
002049  
002050    /* If the old.* record has not yet been loaded into memory, do so now. */
002051    if( p->pUnpacked==0 ){
002052      u32 nRec;
002053      u8 *aRec;
002054  
002055      assert( p->pCsr->eCurType==CURTYPE_BTREE );
002056      nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
002057      aRec = sqlite3DbMallocRaw(db, nRec);
002058      if( !aRec ) goto preupdate_old_out;
002059      rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
002060      if( rc==SQLITE_OK ){
002061        p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
002062        if( !p->pUnpacked ) rc = SQLITE_NOMEM;
002063      }
002064      if( rc!=SQLITE_OK ){
002065        sqlite3DbFree(db, aRec);
002066        goto preupdate_old_out;
002067      }
002068      p->aRecord = aRec;
002069    }
002070  
002071    pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
002072    if( iIdx==p->pTab->iPKey ){
002073      sqlite3VdbeMemSetInt64(pMem, p->iKey1);
002074    }else if( iIdx>=p->pUnpacked->nField ){
002075      *ppValue = (sqlite3_value *)columnNullValue();
002076    }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
002077      if( pMem->flags & (MEM_Int|MEM_IntReal) ){
002078        testcase( pMem->flags & MEM_Int );
002079        testcase( pMem->flags & MEM_IntReal );
002080        sqlite3VdbeMemRealify(pMem);
002081      }
002082    }
002083  
002084   preupdate_old_out:
002085    sqlite3Error(db, rc);
002086    return sqlite3ApiExit(db, rc);
002087  }
002088  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
002089  
002090  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
002091  /*
002092  ** This function is called from within a pre-update callback to retrieve
002093  ** the number of columns in the row being updated, deleted or inserted.
002094  */
002095  int sqlite3_preupdate_count(sqlite3 *db){
002096    PreUpdate *p = db->pPreUpdate;
002097    return (p ? p->keyinfo.nKeyField : 0);
002098  }
002099  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
002100  
002101  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
002102  /*
002103  ** This function is designed to be called from within a pre-update callback
002104  ** only. It returns zero if the change that caused the callback was made
002105  ** immediately by a user SQL statement. Or, if the change was made by a
002106  ** trigger program, it returns the number of trigger programs currently
002107  ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
002108  ** top-level trigger etc.).
002109  **
002110  ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
002111  ** or SET DEFAULT action is considered a trigger.
002112  */
002113  int sqlite3_preupdate_depth(sqlite3 *db){
002114    PreUpdate *p = db->pPreUpdate;
002115    return (p ? p->v->nFrame : 0);
002116  }
002117  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
002118  
002119  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
002120  /*
002121  ** This function is designed to be called from within a pre-update callback
002122  ** only.
002123  */
002124  int sqlite3_preupdate_blobwrite(sqlite3 *db){
002125    PreUpdate *p = db->pPreUpdate;
002126    return (p ? p->iBlobWrite : -1);
002127  }
002128  #endif
002129  
002130  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
002131  /*
002132  ** This function is called from within a pre-update callback to retrieve
002133  ** a field of the row currently being updated or inserted.
002134  */
002135  int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
002136    PreUpdate *p = db->pPreUpdate;
002137    int rc = SQLITE_OK;
002138    Mem *pMem;
002139  
002140    if( !p || p->op==SQLITE_DELETE ){
002141      rc = SQLITE_MISUSE_BKPT;
002142      goto preupdate_new_out;
002143    }
002144    if( p->pPk && p->op!=SQLITE_UPDATE ){
002145      iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);
002146    }
002147    if( iIdx>=p->pCsr->nField || iIdx<0 ){
002148      rc = SQLITE_RANGE;
002149      goto preupdate_new_out;
002150    }
002151  
002152    if( p->op==SQLITE_INSERT ){
002153      /* For an INSERT, memory cell p->iNewReg contains the serialized record
002154      ** that is being inserted. Deserialize it. */
002155      UnpackedRecord *pUnpack = p->pNewUnpacked;
002156      if( !pUnpack ){
002157        Mem *pData = &p->v->aMem[p->iNewReg];
002158        rc = ExpandBlob(pData);
002159        if( rc!=SQLITE_OK ) goto preupdate_new_out;
002160        pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
002161        if( !pUnpack ){
002162          rc = SQLITE_NOMEM;
002163          goto preupdate_new_out;
002164        }
002165        p->pNewUnpacked = pUnpack;
002166      }
002167      pMem = &pUnpack->aMem[iIdx];
002168      if( iIdx==p->pTab->iPKey ){
002169        sqlite3VdbeMemSetInt64(pMem, p->iKey2);
002170      }else if( iIdx>=pUnpack->nField ){
002171        pMem = (sqlite3_value *)columnNullValue();
002172      }
002173    }else{
002174      /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
002175      ** value. Make a copy of the cell contents and return a pointer to it.
002176      ** It is not safe to return a pointer to the memory cell itself as the
002177      ** caller may modify the value text encoding.
002178      */
002179      assert( p->op==SQLITE_UPDATE );
002180      if( !p->aNew ){
002181        p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
002182        if( !p->aNew ){
002183          rc = SQLITE_NOMEM;
002184          goto preupdate_new_out;
002185        }
002186      }
002187      assert( iIdx>=0 && iIdx<p->pCsr->nField );
002188      pMem = &p->aNew[iIdx];
002189      if( pMem->flags==0 ){
002190        if( iIdx==p->pTab->iPKey ){
002191          sqlite3VdbeMemSetInt64(pMem, p->iKey2);
002192        }else{
002193          rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
002194          if( rc!=SQLITE_OK ) goto preupdate_new_out;
002195        }
002196      }
002197    }
002198    *ppValue = pMem;
002199  
002200   preupdate_new_out:
002201    sqlite3Error(db, rc);
002202    return sqlite3ApiExit(db, rc);
002203  }
002204  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
002205  
002206  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
002207  /*
002208  ** Return status data for a single loop within query pStmt.
002209  */
002210  int sqlite3_stmt_scanstatus_v2(
002211    sqlite3_stmt *pStmt,            /* Prepared statement being queried */
002212    int iScan,                      /* Index of loop to report on */
002213    int iScanStatusOp,              /* Which metric to return */
002214    int flags,
002215    void *pOut                      /* OUT: Write the answer here */
002216  ){
002217    Vdbe *p = (Vdbe*)pStmt;
002218    VdbeOp *aOp = p->aOp;
002219    int nOp = p->nOp;
002220    ScanStatus *pScan = 0;
002221    int idx;
002222  
002223    if( p->pFrame ){
002224      VdbeFrame *pFrame;
002225      for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
002226      aOp = pFrame->aOp;
002227      nOp = pFrame->nOp;
002228    }
002229  
002230    if( iScan<0 ){
002231      int ii;
002232      if( iScanStatusOp==SQLITE_SCANSTAT_NCYCLE ){
002233        i64 res = 0;
002234        for(ii=0; ii<nOp; ii++){
002235          res += aOp[ii].nCycle;
002236        }
002237        *(i64*)pOut = res;
002238        return 0;
002239      }
002240      return 1;
002241    }
002242    if( flags & SQLITE_SCANSTAT_COMPLEX ){
002243      idx = iScan;
002244      pScan = &p->aScan[idx];
002245    }else{
002246      /* If the COMPLEX flag is clear, then this function must ignore any
002247      ** ScanStatus structures with ScanStatus.addrLoop set to 0. */
002248      for(idx=0; idx<p->nScan; idx++){
002249        pScan = &p->aScan[idx];
002250        if( pScan->zName ){
002251          iScan--;
002252          if( iScan<0 ) break;
002253        }
002254      }
002255    }
002256    if( idx>=p->nScan ) return 1;
002257  
002258    switch( iScanStatusOp ){
002259      case SQLITE_SCANSTAT_NLOOP: {
002260        if( pScan->addrLoop>0 ){
002261          *(sqlite3_int64*)pOut = aOp[pScan->addrLoop].nExec;
002262        }else{
002263          *(sqlite3_int64*)pOut = -1;
002264        }
002265        break;
002266      }
002267      case SQLITE_SCANSTAT_NVISIT: {
002268        if( pScan->addrVisit>0 ){
002269          *(sqlite3_int64*)pOut = aOp[pScan->addrVisit].nExec;
002270        }else{
002271          *(sqlite3_int64*)pOut = -1;
002272        }
002273        break;
002274      }
002275      case SQLITE_SCANSTAT_EST: {
002276        double r = 1.0;
002277        LogEst x = pScan->nEst;
002278        while( x<100 ){
002279          x += 10;
002280          r *= 0.5;
002281        }
002282        *(double*)pOut = r*sqlite3LogEstToInt(x);
002283        break;
002284      }
002285      case SQLITE_SCANSTAT_NAME: {
002286        *(const char**)pOut = pScan->zName;
002287        break;
002288      }
002289      case SQLITE_SCANSTAT_EXPLAIN: {
002290        if( pScan->addrExplain ){
002291          *(const char**)pOut = aOp[ pScan->addrExplain ].p4.z;
002292        }else{
002293          *(const char**)pOut = 0;
002294        }
002295        break;
002296      }
002297      case SQLITE_SCANSTAT_SELECTID: {
002298        if( pScan->addrExplain ){
002299          *(int*)pOut = aOp[ pScan->addrExplain ].p1;
002300        }else{
002301          *(int*)pOut = -1;
002302        }
002303        break;
002304      }
002305      case SQLITE_SCANSTAT_PARENTID: {
002306        if( pScan->addrExplain ){
002307          *(int*)pOut = aOp[ pScan->addrExplain ].p2;
002308        }else{
002309          *(int*)pOut = -1;
002310        }
002311        break;
002312      }
002313      case SQLITE_SCANSTAT_NCYCLE: {
002314        i64 res = 0;
002315        if( pScan->aAddrRange[0]==0 ){
002316          res = -1;
002317        }else{
002318          int ii;
002319          for(ii=0; ii<ArraySize(pScan->aAddrRange); ii+=2){
002320            int iIns = pScan->aAddrRange[ii];
002321            int iEnd = pScan->aAddrRange[ii+1];
002322            if( iIns==0 ) break;
002323            if( iIns>0 ){
002324              while( iIns<=iEnd ){
002325                res += aOp[iIns].nCycle;
002326                iIns++;
002327              }
002328            }else{
002329              int iOp;
002330              for(iOp=0; iOp<nOp; iOp++){
002331                Op *pOp = &aOp[iOp];
002332                if( pOp->p1!=iEnd ) continue;
002333                if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_NCYCLE)==0 ){
002334                  continue;
002335                }
002336                res += aOp[iOp].nCycle;
002337              }
002338            }
002339          }
002340        }
002341        *(i64*)pOut = res;
002342        break;
002343      }
002344      default: {
002345        return 1;
002346      }
002347    }
002348    return 0;
002349  }
002350  
002351  /*
002352  ** Return status data for a single loop within query pStmt.
002353  */
002354  int sqlite3_stmt_scanstatus(
002355    sqlite3_stmt *pStmt,            /* Prepared statement being queried */
002356    int iScan,                      /* Index of loop to report on */
002357    int iScanStatusOp,              /* Which metric to return */
002358    void *pOut                      /* OUT: Write the answer here */
002359  ){
002360    return sqlite3_stmt_scanstatus_v2(pStmt, iScan, iScanStatusOp, 0, pOut);
002361  }
002362  
002363  /*
002364  ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
002365  */
002366  void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
002367    Vdbe *p = (Vdbe*)pStmt;
002368    int ii;
002369    for(ii=0; ii<p->nOp; ii++){
002370      Op *pOp = &p->aOp[ii];
002371      pOp->nExec = 0;
002372      pOp->nCycle = 0;
002373    }
002374  }
002375  #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */