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