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