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