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  /* Make a copy of an sqlite3_value object
000272  */
000273  sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
000274    sqlite3_value *pNew;
000275    if( pOrig==0 ) return 0;
000276    pNew = sqlite3_malloc( sizeof(*pNew) );
000277    if( pNew==0 ) return 0;
000278    memset(pNew, 0, sizeof(*pNew));
000279    memcpy(pNew, pOrig, MEMCELLSIZE);
000280    pNew->flags &= ~MEM_Dyn;
000281    pNew->db = 0;
000282    if( pNew->flags&(MEM_Str|MEM_Blob) ){
000283      pNew->flags &= ~(MEM_Static|MEM_Dyn);
000284      pNew->flags |= MEM_Ephem;
000285      if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
000286        sqlite3ValueFree(pNew);
000287        pNew = 0;
000288      }
000289    }
000290    return pNew;
000291  }
000292  
000293  /* Destroy an sqlite3_value object previously obtained from
000294  ** sqlite3_value_dup().
000295  */
000296  void sqlite3_value_free(sqlite3_value *pOld){
000297    sqlite3ValueFree(pOld);
000298  }
000299    
000300  
000301  /**************************** sqlite3_result_  *******************************
000302  ** The following routines are used by user-defined functions to specify
000303  ** the function result.
000304  **
000305  ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
000306  ** result as a string or blob but if the string or blob is too large, it
000307  ** then sets the error code to SQLITE_TOOBIG
000308  **
000309  ** The invokeValueDestructor(P,X) routine invokes destructor function X()
000310  ** on value P is not going to be used and need to be destroyed.
000311  */
000312  static void setResultStrOrError(
000313    sqlite3_context *pCtx,  /* Function context */
000314    const char *z,          /* String pointer */
000315    int n,                  /* Bytes in string, or negative */
000316    u8 enc,                 /* Encoding of z.  0 for BLOBs */
000317    void (*xDel)(void*)     /* Destructor function */
000318  ){
000319    if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
000320      sqlite3_result_error_toobig(pCtx);
000321    }
000322  }
000323  static int invokeValueDestructor(
000324    const void *p,             /* Value to destroy */
000325    void (*xDel)(void*),       /* The destructor */
000326    sqlite3_context *pCtx      /* Set a SQLITE_TOOBIG error if no NULL */
000327  ){
000328    assert( xDel!=SQLITE_DYNAMIC );
000329    if( xDel==0 ){
000330      /* noop */
000331    }else if( xDel==SQLITE_TRANSIENT ){
000332      /* noop */
000333    }else{
000334      xDel((void*)p);
000335    }
000336    if( pCtx ) sqlite3_result_error_toobig(pCtx);
000337    return SQLITE_TOOBIG;
000338  }
000339  void sqlite3_result_blob(
000340    sqlite3_context *pCtx, 
000341    const void *z, 
000342    int n, 
000343    void (*xDel)(void *)
000344  ){
000345    assert( n>=0 );
000346    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000347    setResultStrOrError(pCtx, z, n, 0, xDel);
000348  }
000349  void sqlite3_result_blob64(
000350    sqlite3_context *pCtx, 
000351    const void *z, 
000352    sqlite3_uint64 n,
000353    void (*xDel)(void *)
000354  ){
000355    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000356    assert( xDel!=SQLITE_DYNAMIC );
000357    if( n>0x7fffffff ){
000358      (void)invokeValueDestructor(z, xDel, pCtx);
000359    }else{
000360      setResultStrOrError(pCtx, z, (int)n, 0, xDel);
000361    }
000362  }
000363  void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
000364    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000365    sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
000366  }
000367  void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
000368    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000369    pCtx->isError = SQLITE_ERROR;
000370    pCtx->fErrorOrAux = 1;
000371    sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
000372  }
000373  #ifndef SQLITE_OMIT_UTF16
000374  void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
000375    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000376    pCtx->isError = SQLITE_ERROR;
000377    pCtx->fErrorOrAux = 1;
000378    sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
000379  }
000380  #endif
000381  void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
000382    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000383    sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
000384  }
000385  void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
000386    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000387    sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
000388  }
000389  void sqlite3_result_null(sqlite3_context *pCtx){
000390    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000391    sqlite3VdbeMemSetNull(pCtx->pOut);
000392  }
000393  void sqlite3_result_pointer(
000394    sqlite3_context *pCtx,
000395    void *pPtr,
000396    const char *zPType,
000397    void (*xDestructor)(void*)
000398  ){
000399    Mem *pOut = pCtx->pOut;
000400    assert( sqlite3_mutex_held(pOut->db->mutex) );
000401    sqlite3VdbeMemRelease(pOut);
000402    pOut->flags = MEM_Null;
000403    sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
000404  }
000405  void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
000406    Mem *pOut = pCtx->pOut;
000407    assert( sqlite3_mutex_held(pOut->db->mutex) );
000408    pOut->eSubtype = eSubtype & 0xff;
000409    pOut->flags |= MEM_Subtype;
000410  }
000411  void sqlite3_result_text(
000412    sqlite3_context *pCtx, 
000413    const char *z, 
000414    int n,
000415    void (*xDel)(void *)
000416  ){
000417    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000418    setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
000419  }
000420  void sqlite3_result_text64(
000421    sqlite3_context *pCtx, 
000422    const char *z, 
000423    sqlite3_uint64 n,
000424    void (*xDel)(void *),
000425    unsigned char enc
000426  ){
000427    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000428    assert( xDel!=SQLITE_DYNAMIC );
000429    if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
000430    if( n>0x7fffffff ){
000431      (void)invokeValueDestructor(z, xDel, pCtx);
000432    }else{
000433      setResultStrOrError(pCtx, z, (int)n, enc, xDel);
000434    }
000435  }
000436  #ifndef SQLITE_OMIT_UTF16
000437  void sqlite3_result_text16(
000438    sqlite3_context *pCtx, 
000439    const void *z, 
000440    int n, 
000441    void (*xDel)(void *)
000442  ){
000443    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000444    setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
000445  }
000446  void sqlite3_result_text16be(
000447    sqlite3_context *pCtx, 
000448    const void *z, 
000449    int n, 
000450    void (*xDel)(void *)
000451  ){
000452    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000453    setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
000454  }
000455  void sqlite3_result_text16le(
000456    sqlite3_context *pCtx, 
000457    const void *z, 
000458    int n, 
000459    void (*xDel)(void *)
000460  ){
000461    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000462    setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
000463  }
000464  #endif /* SQLITE_OMIT_UTF16 */
000465  void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
000466    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000467    sqlite3VdbeMemCopy(pCtx->pOut, pValue);
000468  }
000469  void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
000470    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000471    sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
000472  }
000473  int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
000474    Mem *pOut = pCtx->pOut;
000475    assert( sqlite3_mutex_held(pOut->db->mutex) );
000476    if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
000477      return SQLITE_TOOBIG;
000478    }
000479    sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
000480    return SQLITE_OK;
000481  }
000482  void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
000483    pCtx->isError = errCode;
000484    pCtx->fErrorOrAux = 1;
000485  #ifdef SQLITE_DEBUG
000486    if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
000487  #endif
000488    if( pCtx->pOut->flags & MEM_Null ){
000489      sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1, 
000490                           SQLITE_UTF8, SQLITE_STATIC);
000491    }
000492  }
000493  
000494  /* Force an SQLITE_TOOBIG error. */
000495  void sqlite3_result_error_toobig(sqlite3_context *pCtx){
000496    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000497    pCtx->isError = SQLITE_TOOBIG;
000498    pCtx->fErrorOrAux = 1;
000499    sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1, 
000500                         SQLITE_UTF8, SQLITE_STATIC);
000501  }
000502  
000503  /* An SQLITE_NOMEM error. */
000504  void sqlite3_result_error_nomem(sqlite3_context *pCtx){
000505    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000506    sqlite3VdbeMemSetNull(pCtx->pOut);
000507    pCtx->isError = SQLITE_NOMEM_BKPT;
000508    pCtx->fErrorOrAux = 1;
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  ** Return the current time for a statement.  If the current time
000750  ** is requested more than once within the same run of a single prepared
000751  ** statement, the exact same time is returned for each invocation regardless
000752  ** of the amount of time that elapses between invocations.  In other words,
000753  ** the time returned is always the time of the first call.
000754  */
000755  sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
000756    int rc;
000757  #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
000758    sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
000759    assert( p->pVdbe!=0 );
000760  #else
000761    sqlite3_int64 iTime = 0;
000762    sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
000763  #endif
000764    if( *piTime==0 ){
000765      rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
000766      if( rc ) *piTime = 0;
000767    }
000768    return *piTime;
000769  }
000770  
000771  /*
000772  ** The following is the implementation of an SQL function that always
000773  ** fails with an error message stating that the function is used in the
000774  ** wrong context.  The sqlite3_overload_function() API might construct
000775  ** SQL function that use this routine so that the functions will exist
000776  ** for name resolution but are actually overloaded by the xFindFunction
000777  ** method of virtual tables.
000778  */
000779  void sqlite3InvalidFunction(
000780    sqlite3_context *context,  /* The function calling context */
000781    int NotUsed,               /* Number of arguments to the function */
000782    sqlite3_value **NotUsed2   /* Value of each argument */
000783  ){
000784    const char *zName = context->pFunc->zName;
000785    char *zErr;
000786    UNUSED_PARAMETER2(NotUsed, NotUsed2);
000787    zErr = sqlite3_mprintf(
000788        "unable to use function %s in the requested context", zName);
000789    sqlite3_result_error(context, zErr, -1);
000790    sqlite3_free(zErr);
000791  }
000792  
000793  /*
000794  ** Create a new aggregate context for p and return a pointer to
000795  ** its pMem->z element.
000796  */
000797  static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
000798    Mem *pMem = p->pMem;
000799    assert( (pMem->flags & MEM_Agg)==0 );
000800    if( nByte<=0 ){
000801      sqlite3VdbeMemSetNull(pMem);
000802      pMem->z = 0;
000803    }else{
000804      sqlite3VdbeMemClearAndResize(pMem, nByte);
000805      pMem->flags = MEM_Agg;
000806      pMem->u.pDef = p->pFunc;
000807      if( pMem->z ){
000808        memset(pMem->z, 0, nByte);
000809      }
000810    }
000811    return (void*)pMem->z;
000812  }
000813  
000814  /*
000815  ** Allocate or return the aggregate context for a user function.  A new
000816  ** context is allocated on the first call.  Subsequent calls return the
000817  ** same context that was returned on prior calls.
000818  */
000819  void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
000820    assert( p && p->pFunc && p->pFunc->xFinalize );
000821    assert( sqlite3_mutex_held(p->pOut->db->mutex) );
000822    testcase( nByte<0 );
000823    if( (p->pMem->flags & MEM_Agg)==0 ){
000824      return createAggContext(p, nByte);
000825    }else{
000826      return (void*)p->pMem->z;
000827    }
000828  }
000829  
000830  /*
000831  ** Return the auxiliary data pointer, if any, for the iArg'th argument to
000832  ** the user-function defined by pCtx.
000833  **
000834  ** The left-most argument is 0.
000835  **
000836  ** Undocumented behavior:  If iArg is negative then access a cache of
000837  ** auxiliary data pointers that is available to all functions within a
000838  ** single prepared statement.  The iArg values must match.
000839  */
000840  void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
000841    AuxData *pAuxData;
000842  
000843    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000844  #if SQLITE_ENABLE_STAT3_OR_STAT4
000845    if( pCtx->pVdbe==0 ) return 0;
000846  #else
000847    assert( pCtx->pVdbe!=0 );
000848  #endif
000849    for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
000850      if(  pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
000851        return pAuxData->pAux;
000852      }
000853    }
000854    return 0;
000855  }
000856  
000857  /*
000858  ** Set the auxiliary data pointer and delete function, for the iArg'th
000859  ** argument to the user-function defined by pCtx. Any previous value is
000860  ** deleted by calling the delete function specified when it was set.
000861  **
000862  ** The left-most argument is 0.
000863  **
000864  ** Undocumented behavior:  If iArg is negative then make the data available
000865  ** to all functions within the current prepared statement using iArg as an
000866  ** access code.
000867  */
000868  void sqlite3_set_auxdata(
000869    sqlite3_context *pCtx, 
000870    int iArg, 
000871    void *pAux, 
000872    void (*xDelete)(void*)
000873  ){
000874    AuxData *pAuxData;
000875    Vdbe *pVdbe = pCtx->pVdbe;
000876  
000877    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
000878  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
000879    if( pVdbe==0 ) goto failed;
000880  #else
000881    assert( pVdbe!=0 );
000882  #endif
000883  
000884    for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
000885      if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
000886        break;
000887      }
000888    }
000889    if( pAuxData==0 ){
000890      pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
000891      if( !pAuxData ) goto failed;
000892      pAuxData->iAuxOp = pCtx->iOp;
000893      pAuxData->iAuxArg = iArg;
000894      pAuxData->pNextAux = pVdbe->pAuxData;
000895      pVdbe->pAuxData = pAuxData;
000896      if( pCtx->fErrorOrAux==0 ){
000897        pCtx->isError = 0;
000898        pCtx->fErrorOrAux = 1;
000899      }
000900    }else if( pAuxData->xDeleteAux ){
000901      pAuxData->xDeleteAux(pAuxData->pAux);
000902    }
000903  
000904    pAuxData->pAux = pAux;
000905    pAuxData->xDeleteAux = xDelete;
000906    return;
000907  
000908  failed:
000909    if( xDelete ){
000910      xDelete(pAux);
000911    }
000912  }
000913  
000914  #ifndef SQLITE_OMIT_DEPRECATED
000915  /*
000916  ** Return the number of times the Step function of an aggregate has been 
000917  ** called.
000918  **
000919  ** This function is deprecated.  Do not use it for new code.  It is
000920  ** provide only to avoid breaking legacy code.  New aggregate function
000921  ** implementations should keep their own counts within their aggregate
000922  ** context.
000923  */
000924  int sqlite3_aggregate_count(sqlite3_context *p){
000925    assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
000926    return p->pMem->n;
000927  }
000928  #endif
000929  
000930  /*
000931  ** Return the number of columns in the result set for the statement pStmt.
000932  */
000933  int sqlite3_column_count(sqlite3_stmt *pStmt){
000934    Vdbe *pVm = (Vdbe *)pStmt;
000935    return pVm ? pVm->nResColumn : 0;
000936  }
000937  
000938  /*
000939  ** Return the number of values available from the current row of the
000940  ** currently executing statement pStmt.
000941  */
000942  int sqlite3_data_count(sqlite3_stmt *pStmt){
000943    Vdbe *pVm = (Vdbe *)pStmt;
000944    if( pVm==0 || pVm->pResultSet==0 ) return 0;
000945    return pVm->nResColumn;
000946  }
000947  
000948  /*
000949  ** Return a pointer to static memory containing an SQL NULL value.
000950  */
000951  static const Mem *columnNullValue(void){
000952    /* Even though the Mem structure contains an element
000953    ** of type i64, on certain architectures (x86) with certain compiler
000954    ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
000955    ** instead of an 8-byte one. This all works fine, except that when
000956    ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
000957    ** that a Mem structure is located on an 8-byte boundary. To prevent
000958    ** these assert()s from failing, when building with SQLITE_DEBUG defined
000959    ** using gcc, we force nullMem to be 8-byte aligned using the magical
000960    ** __attribute__((aligned(8))) macro.  */
000961    static const Mem nullMem 
000962  #if defined(SQLITE_DEBUG) && defined(__GNUC__)
000963      __attribute__((aligned(8))) 
000964  #endif
000965      = {
000966          /* .u          = */ {0},
000967          /* .flags      = */ (u16)MEM_Null,
000968          /* .enc        = */ (u8)0,
000969          /* .eSubtype   = */ (u8)0,
000970          /* .n          = */ (int)0,
000971          /* .z          = */ (char*)0,
000972          /* .zMalloc    = */ (char*)0,
000973          /* .szMalloc   = */ (int)0,
000974          /* .uTemp      = */ (u32)0,
000975          /* .db         = */ (sqlite3*)0,
000976          /* .xDel       = */ (void(*)(void*))0,
000977  #ifdef SQLITE_DEBUG
000978          /* .pScopyFrom = */ (Mem*)0,
000979          /* .pFiller    = */ (void*)0,
000980  #endif
000981        };
000982    return &nullMem;
000983  }
000984  
000985  /*
000986  ** Check to see if column iCol of the given statement is valid.  If
000987  ** it is, return a pointer to the Mem for the value of that column.
000988  ** If iCol is not valid, return a pointer to a Mem which has a value
000989  ** of NULL.
000990  */
000991  static Mem *columnMem(sqlite3_stmt *pStmt, int i){
000992    Vdbe *pVm;
000993    Mem *pOut;
000994  
000995    pVm = (Vdbe *)pStmt;
000996    if( pVm==0 ) return (Mem*)columnNullValue();
000997    assert( pVm->db );
000998    sqlite3_mutex_enter(pVm->db->mutex);
000999    if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
001000      pOut = &pVm->pResultSet[i];
001001    }else{
001002      sqlite3Error(pVm->db, SQLITE_RANGE);
001003      pOut = (Mem*)columnNullValue();
001004    }
001005    return pOut;
001006  }
001007  
001008  /*
001009  ** This function is called after invoking an sqlite3_value_XXX function on a 
001010  ** column value (i.e. a value returned by evaluating an SQL expression in the
001011  ** select list of a SELECT statement) that may cause a malloc() failure. If 
001012  ** malloc() has failed, the threads mallocFailed flag is cleared and the result
001013  ** code of statement pStmt set to SQLITE_NOMEM.
001014  **
001015  ** Specifically, this is called from within:
001016  **
001017  **     sqlite3_column_int()
001018  **     sqlite3_column_int64()
001019  **     sqlite3_column_text()
001020  **     sqlite3_column_text16()
001021  **     sqlite3_column_real()
001022  **     sqlite3_column_bytes()
001023  **     sqlite3_column_bytes16()
001024  **     sqiite3_column_blob()
001025  */
001026  static void columnMallocFailure(sqlite3_stmt *pStmt)
001027  {
001028    /* If malloc() failed during an encoding conversion within an
001029    ** sqlite3_column_XXX API, then set the return code of the statement to
001030    ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
001031    ** and _finalize() will return NOMEM.
001032    */
001033    Vdbe *p = (Vdbe *)pStmt;
001034    if( p ){
001035      assert( p->db!=0 );
001036      assert( sqlite3_mutex_held(p->db->mutex) );
001037      p->rc = sqlite3ApiExit(p->db, p->rc);
001038      sqlite3_mutex_leave(p->db->mutex);
001039    }
001040  }
001041  
001042  /**************************** sqlite3_column_  *******************************
001043  ** The following routines are used to access elements of the current row
001044  ** in the result set.
001045  */
001046  const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
001047    const void *val;
001048    val = sqlite3_value_blob( columnMem(pStmt,i) );
001049    /* Even though there is no encoding conversion, value_blob() might
001050    ** need to call malloc() to expand the result of a zeroblob() 
001051    ** expression. 
001052    */
001053    columnMallocFailure(pStmt);
001054    return val;
001055  }
001056  int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
001057    int val = sqlite3_value_bytes( columnMem(pStmt,i) );
001058    columnMallocFailure(pStmt);
001059    return val;
001060  }
001061  int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
001062    int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
001063    columnMallocFailure(pStmt);
001064    return val;
001065  }
001066  double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
001067    double val = sqlite3_value_double( columnMem(pStmt,i) );
001068    columnMallocFailure(pStmt);
001069    return val;
001070  }
001071  int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
001072    int val = sqlite3_value_int( columnMem(pStmt,i) );
001073    columnMallocFailure(pStmt);
001074    return val;
001075  }
001076  sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
001077    sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
001078    columnMallocFailure(pStmt);
001079    return val;
001080  }
001081  const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
001082    const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
001083    columnMallocFailure(pStmt);
001084    return val;
001085  }
001086  sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
001087    Mem *pOut = columnMem(pStmt, i);
001088    if( pOut->flags&MEM_Static ){
001089      pOut->flags &= ~MEM_Static;
001090      pOut->flags |= MEM_Ephem;
001091    }
001092    columnMallocFailure(pStmt);
001093    return (sqlite3_value *)pOut;
001094  }
001095  #ifndef SQLITE_OMIT_UTF16
001096  const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
001097    const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
001098    columnMallocFailure(pStmt);
001099    return val;
001100  }
001101  #endif /* SQLITE_OMIT_UTF16 */
001102  int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
001103    int iType = sqlite3_value_type( columnMem(pStmt,i) );
001104    columnMallocFailure(pStmt);
001105    return iType;
001106  }
001107  
001108  /*
001109  ** Convert the N-th element of pStmt->pColName[] into a string using
001110  ** xFunc() then return that string.  If N is out of range, return 0.
001111  **
001112  ** There are up to 5 names for each column.  useType determines which
001113  ** name is returned.  Here are the names:
001114  **
001115  **    0      The column name as it should be displayed for output
001116  **    1      The datatype name for the column
001117  **    2      The name of the database that the column derives from
001118  **    3      The name of the table that the column derives from
001119  **    4      The name of the table column that the result column derives from
001120  **
001121  ** If the result is not a simple column reference (if it is an expression
001122  ** or a constant) then useTypes 2, 3, and 4 return NULL.
001123  */
001124  static const void *columnName(
001125    sqlite3_stmt *pStmt,
001126    int N,
001127    const void *(*xFunc)(Mem*),
001128    int useType
001129  ){
001130    const void *ret;
001131    Vdbe *p;
001132    int n;
001133    sqlite3 *db;
001134  #ifdef SQLITE_ENABLE_API_ARMOR
001135    if( pStmt==0 ){
001136      (void)SQLITE_MISUSE_BKPT;
001137      return 0;
001138    }
001139  #endif
001140    ret = 0;
001141    p = (Vdbe *)pStmt;
001142    db = p->db;
001143    assert( db!=0 );
001144    n = sqlite3_column_count(pStmt);
001145    if( N<n && N>=0 ){
001146      N += useType*n;
001147      sqlite3_mutex_enter(db->mutex);
001148      assert( db->mallocFailed==0 );
001149      ret = xFunc(&p->aColName[N]);
001150       /* A malloc may have failed inside of the xFunc() call. If this
001151      ** is the case, clear the mallocFailed flag and return NULL.
001152      */
001153      if( db->mallocFailed ){
001154        sqlite3OomClear(db);
001155        ret = 0;
001156      }
001157      sqlite3_mutex_leave(db->mutex);
001158    }
001159    return ret;
001160  }
001161  
001162  /*
001163  ** Return the name of the Nth column of the result set returned by SQL
001164  ** statement pStmt.
001165  */
001166  const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
001167    return columnName(
001168        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
001169  }
001170  #ifndef SQLITE_OMIT_UTF16
001171  const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
001172    return columnName(
001173        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
001174  }
001175  #endif
001176  
001177  /*
001178  ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
001179  ** not define OMIT_DECLTYPE.
001180  */
001181  #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
001182  # error "Must not define both SQLITE_OMIT_DECLTYPE \
001183           and SQLITE_ENABLE_COLUMN_METADATA"
001184  #endif
001185  
001186  #ifndef SQLITE_OMIT_DECLTYPE
001187  /*
001188  ** Return the column declaration type (if applicable) of the 'i'th column
001189  ** of the result set of SQL statement pStmt.
001190  */
001191  const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
001192    return columnName(
001193        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
001194  }
001195  #ifndef SQLITE_OMIT_UTF16
001196  const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
001197    return columnName(
001198        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
001199  }
001200  #endif /* SQLITE_OMIT_UTF16 */
001201  #endif /* SQLITE_OMIT_DECLTYPE */
001202  
001203  #ifdef SQLITE_ENABLE_COLUMN_METADATA
001204  /*
001205  ** Return the name of the database from which a result column derives.
001206  ** NULL is returned if the result column is an expression or constant or
001207  ** anything else which is not an unambiguous reference to a database column.
001208  */
001209  const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
001210    return columnName(
001211        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
001212  }
001213  #ifndef SQLITE_OMIT_UTF16
001214  const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
001215    return columnName(
001216        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
001217  }
001218  #endif /* SQLITE_OMIT_UTF16 */
001219  
001220  /*
001221  ** Return the name of the table from which a result column derives.
001222  ** NULL is returned if the result column is an expression or constant or
001223  ** anything else which is not an unambiguous reference to a database column.
001224  */
001225  const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
001226    return columnName(
001227        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
001228  }
001229  #ifndef SQLITE_OMIT_UTF16
001230  const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
001231    return columnName(
001232        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
001233  }
001234  #endif /* SQLITE_OMIT_UTF16 */
001235  
001236  /*
001237  ** Return the name of the table column from which a result column derives.
001238  ** NULL is returned if the result column is an expression or constant or
001239  ** anything else which is not an unambiguous reference to a database column.
001240  */
001241  const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
001242    return columnName(
001243        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
001244  }
001245  #ifndef SQLITE_OMIT_UTF16
001246  const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
001247    return columnName(
001248        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
001249  }
001250  #endif /* SQLITE_OMIT_UTF16 */
001251  #endif /* SQLITE_ENABLE_COLUMN_METADATA */
001252  
001253  
001254  /******************************* sqlite3_bind_  ***************************
001255  ** 
001256  ** Routines used to attach values to wildcards in a compiled SQL statement.
001257  */
001258  /*
001259  ** Unbind the value bound to variable i in virtual machine p. This is the 
001260  ** the same as binding a NULL value to the column. If the "i" parameter is
001261  ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
001262  **
001263  ** A successful evaluation of this routine acquires the mutex on p.
001264  ** the mutex is released if any kind of error occurs.
001265  **
001266  ** The error code stored in database p->db is overwritten with the return
001267  ** value in any case.
001268  */
001269  static int vdbeUnbind(Vdbe *p, int i){
001270    Mem *pVar;
001271    if( vdbeSafetyNotNull(p) ){
001272      return SQLITE_MISUSE_BKPT;
001273    }
001274    sqlite3_mutex_enter(p->db->mutex);
001275    if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
001276      sqlite3Error(p->db, SQLITE_MISUSE);
001277      sqlite3_mutex_leave(p->db->mutex);
001278      sqlite3_log(SQLITE_MISUSE, 
001279          "bind on a busy prepared statement: [%s]", p->zSql);
001280      return SQLITE_MISUSE_BKPT;
001281    }
001282    if( i<1 || i>p->nVar ){
001283      sqlite3Error(p->db, SQLITE_RANGE);
001284      sqlite3_mutex_leave(p->db->mutex);
001285      return SQLITE_RANGE;
001286    }
001287    i--;
001288    pVar = &p->aVar[i];
001289    sqlite3VdbeMemRelease(pVar);
001290    pVar->flags = MEM_Null;
001291    sqlite3Error(p->db, SQLITE_OK);
001292  
001293    /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
001294    ** binding a new value to this variable invalidates the current query plan.
001295    **
001296    ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
001297    ** parameter in the WHERE clause might influence the choice of query plan
001298    ** for a statement, then the statement will be automatically recompiled,
001299    ** as if there had been a schema change, on the first sqlite3_step() call
001300    ** following any change to the bindings of that parameter.
001301    */
001302    assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
001303    if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
001304      p->expired = 1;
001305    }
001306    return SQLITE_OK;
001307  }
001308  
001309  /*
001310  ** Bind a text or BLOB value.
001311  */
001312  static int bindText(
001313    sqlite3_stmt *pStmt,   /* The statement to bind against */
001314    int i,                 /* Index of the parameter to bind */
001315    const void *zData,     /* Pointer to the data to be bound */
001316    int nData,             /* Number of bytes of data to be bound */
001317    void (*xDel)(void*),   /* Destructor for the data */
001318    u8 encoding            /* Encoding for the data */
001319  ){
001320    Vdbe *p = (Vdbe *)pStmt;
001321    Mem *pVar;
001322    int rc;
001323  
001324    rc = vdbeUnbind(p, i);
001325    if( rc==SQLITE_OK ){
001326      if( zData!=0 ){
001327        pVar = &p->aVar[i-1];
001328        rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
001329        if( rc==SQLITE_OK && encoding!=0 ){
001330          rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
001331        }
001332        if( rc ){
001333          sqlite3Error(p->db, rc);
001334          rc = sqlite3ApiExit(p->db, rc);
001335        }
001336      }
001337      sqlite3_mutex_leave(p->db->mutex);
001338    }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
001339      xDel((void*)zData);
001340    }
001341    return rc;
001342  }
001343  
001344  
001345  /*
001346  ** Bind a blob value to an SQL statement variable.
001347  */
001348  int sqlite3_bind_blob(
001349    sqlite3_stmt *pStmt, 
001350    int i, 
001351    const void *zData, 
001352    int nData, 
001353    void (*xDel)(void*)
001354  ){
001355  #ifdef SQLITE_ENABLE_API_ARMOR
001356    if( nData<0 ) return SQLITE_MISUSE_BKPT;
001357  #endif
001358    return bindText(pStmt, i, zData, nData, xDel, 0);
001359  }
001360  int sqlite3_bind_blob64(
001361    sqlite3_stmt *pStmt, 
001362    int i, 
001363    const void *zData, 
001364    sqlite3_uint64 nData, 
001365    void (*xDel)(void*)
001366  ){
001367    assert( xDel!=SQLITE_DYNAMIC );
001368    if( nData>0x7fffffff ){
001369      return invokeValueDestructor(zData, xDel, 0);
001370    }else{
001371      return bindText(pStmt, i, zData, (int)nData, xDel, 0);
001372    }
001373  }
001374  int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
001375    int rc;
001376    Vdbe *p = (Vdbe *)pStmt;
001377    rc = vdbeUnbind(p, i);
001378    if( rc==SQLITE_OK ){
001379      sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
001380      sqlite3_mutex_leave(p->db->mutex);
001381    }
001382    return rc;
001383  }
001384  int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
001385    return sqlite3_bind_int64(p, i, (i64)iValue);
001386  }
001387  int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
001388    int rc;
001389    Vdbe *p = (Vdbe *)pStmt;
001390    rc = vdbeUnbind(p, i);
001391    if( rc==SQLITE_OK ){
001392      sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
001393      sqlite3_mutex_leave(p->db->mutex);
001394    }
001395    return rc;
001396  }
001397  int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
001398    int rc;
001399    Vdbe *p = (Vdbe*)pStmt;
001400    rc = vdbeUnbind(p, i);
001401    if( rc==SQLITE_OK ){
001402      sqlite3_mutex_leave(p->db->mutex);
001403    }
001404    return rc;
001405  }
001406  int sqlite3_bind_pointer(
001407    sqlite3_stmt *pStmt,
001408    int i,
001409    void *pPtr,
001410    const char *zPTtype,
001411    void (*xDestructor)(void*)
001412  ){
001413    int rc;
001414    Vdbe *p = (Vdbe*)pStmt;
001415    rc = vdbeUnbind(p, i);
001416    if( rc==SQLITE_OK ){
001417      sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
001418      sqlite3_mutex_leave(p->db->mutex);
001419    }else if( xDestructor ){
001420      xDestructor(pPtr);
001421    }
001422    return rc;
001423  }
001424  int sqlite3_bind_text( 
001425    sqlite3_stmt *pStmt, 
001426    int i, 
001427    const char *zData, 
001428    int nData, 
001429    void (*xDel)(void*)
001430  ){
001431    return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
001432  }
001433  int sqlite3_bind_text64( 
001434    sqlite3_stmt *pStmt, 
001435    int i, 
001436    const char *zData, 
001437    sqlite3_uint64 nData, 
001438    void (*xDel)(void*),
001439    unsigned char enc
001440  ){
001441    assert( xDel!=SQLITE_DYNAMIC );
001442    if( nData>0x7fffffff ){
001443      return invokeValueDestructor(zData, xDel, 0);
001444    }else{
001445      if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
001446      return bindText(pStmt, i, zData, (int)nData, xDel, enc);
001447    }
001448  }
001449  #ifndef SQLITE_OMIT_UTF16
001450  int sqlite3_bind_text16(
001451    sqlite3_stmt *pStmt, 
001452    int i, 
001453    const void *zData, 
001454    int nData, 
001455    void (*xDel)(void*)
001456  ){
001457    return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
001458  }
001459  #endif /* SQLITE_OMIT_UTF16 */
001460  int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
001461    int rc;
001462    switch( sqlite3_value_type((sqlite3_value*)pValue) ){
001463      case SQLITE_INTEGER: {
001464        rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
001465        break;
001466      }
001467      case SQLITE_FLOAT: {
001468        rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
001469        break;
001470      }
001471      case SQLITE_BLOB: {
001472        if( pValue->flags & MEM_Zero ){
001473          rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
001474        }else{
001475          rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
001476        }
001477        break;
001478      }
001479      case SQLITE_TEXT: {
001480        rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
001481                                pValue->enc);
001482        break;
001483      }
001484      default: {
001485        rc = sqlite3_bind_null(pStmt, i);
001486        break;
001487      }
001488    }
001489    return rc;
001490  }
001491  int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
001492    int rc;
001493    Vdbe *p = (Vdbe *)pStmt;
001494    rc = vdbeUnbind(p, i);
001495    if( rc==SQLITE_OK ){
001496      sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
001497      sqlite3_mutex_leave(p->db->mutex);
001498    }
001499    return rc;
001500  }
001501  int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
001502    int rc;
001503    Vdbe *p = (Vdbe *)pStmt;
001504    sqlite3_mutex_enter(p->db->mutex);
001505    if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
001506      rc = SQLITE_TOOBIG;
001507    }else{
001508      assert( (n & 0x7FFFFFFF)==n );
001509      rc = sqlite3_bind_zeroblob(pStmt, i, n);
001510    }
001511    rc = sqlite3ApiExit(p->db, rc);
001512    sqlite3_mutex_leave(p->db->mutex);
001513    return rc;
001514  }
001515  
001516  /*
001517  ** Return the number of wildcards that can be potentially bound to.
001518  ** This routine is added to support DBD::SQLite.  
001519  */
001520  int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
001521    Vdbe *p = (Vdbe*)pStmt;
001522    return p ? p->nVar : 0;
001523  }
001524  
001525  /*
001526  ** Return the name of a wildcard parameter.  Return NULL if the index
001527  ** is out of range or if the wildcard is unnamed.
001528  **
001529  ** The result is always UTF-8.
001530  */
001531  const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
001532    Vdbe *p = (Vdbe*)pStmt;
001533    if( p==0 ) return 0;
001534    return sqlite3VListNumToName(p->pVList, i);
001535  }
001536  
001537  /*
001538  ** Given a wildcard parameter name, return the index of the variable
001539  ** with that name.  If there is no variable with the given name,
001540  ** return 0.
001541  */
001542  int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
001543    if( p==0 || zName==0 ) return 0;
001544    return sqlite3VListNameToNum(p->pVList, zName, nName);
001545  }
001546  int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
001547    return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
001548  }
001549  
001550  /*
001551  ** Transfer all bindings from the first statement over to the second.
001552  */
001553  int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
001554    Vdbe *pFrom = (Vdbe*)pFromStmt;
001555    Vdbe *pTo = (Vdbe*)pToStmt;
001556    int i;
001557    assert( pTo->db==pFrom->db );
001558    assert( pTo->nVar==pFrom->nVar );
001559    sqlite3_mutex_enter(pTo->db->mutex);
001560    for(i=0; i<pFrom->nVar; i++){
001561      sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
001562    }
001563    sqlite3_mutex_leave(pTo->db->mutex);
001564    return SQLITE_OK;
001565  }
001566  
001567  #ifndef SQLITE_OMIT_DEPRECATED
001568  /*
001569  ** Deprecated external interface.  Internal/core SQLite code
001570  ** should call sqlite3TransferBindings.
001571  **
001572  ** It is misuse to call this routine with statements from different
001573  ** database connections.  But as this is a deprecated interface, we
001574  ** will not bother to check for that condition.
001575  **
001576  ** If the two statements contain a different number of bindings, then
001577  ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
001578  ** SQLITE_OK is returned.
001579  */
001580  int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
001581    Vdbe *pFrom = (Vdbe*)pFromStmt;
001582    Vdbe *pTo = (Vdbe*)pToStmt;
001583    if( pFrom->nVar!=pTo->nVar ){
001584      return SQLITE_ERROR;
001585    }
001586    assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
001587    if( pTo->expmask ){
001588      pTo->expired = 1;
001589    }
001590    assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
001591    if( pFrom->expmask ){
001592      pFrom->expired = 1;
001593    }
001594    return sqlite3TransferBindings(pFromStmt, pToStmt);
001595  }
001596  #endif
001597  
001598  /*
001599  ** Return the sqlite3* database handle to which the prepared statement given
001600  ** in the argument belongs.  This is the same database handle that was
001601  ** the first argument to the sqlite3_prepare() that was used to create
001602  ** the statement in the first place.
001603  */
001604  sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
001605    return pStmt ? ((Vdbe*)pStmt)->db : 0;
001606  }
001607  
001608  /*
001609  ** Return true if the prepared statement is guaranteed to not modify the
001610  ** database.
001611  */
001612  int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
001613    return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
001614  }
001615  
001616  /*
001617  ** Return true if the prepared statement is in need of being reset.
001618  */
001619  int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
001620    Vdbe *v = (Vdbe*)pStmt;
001621    return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
001622  }
001623  
001624  /*
001625  ** Return a pointer to the next prepared statement after pStmt associated
001626  ** with database connection pDb.  If pStmt is NULL, return the first
001627  ** prepared statement for the database connection.  Return NULL if there
001628  ** are no more.
001629  */
001630  sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
001631    sqlite3_stmt *pNext;
001632  #ifdef SQLITE_ENABLE_API_ARMOR
001633    if( !sqlite3SafetyCheckOk(pDb) ){
001634      (void)SQLITE_MISUSE_BKPT;
001635      return 0;
001636    }
001637  #endif
001638    sqlite3_mutex_enter(pDb->mutex);
001639    if( pStmt==0 ){
001640      pNext = (sqlite3_stmt*)pDb->pVdbe;
001641    }else{
001642      pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
001643    }
001644    sqlite3_mutex_leave(pDb->mutex);
001645    return pNext;
001646  }
001647  
001648  /*
001649  ** Return the value of a status counter for a prepared statement
001650  */
001651  int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
001652    Vdbe *pVdbe = (Vdbe*)pStmt;
001653    u32 v;
001654  #ifdef SQLITE_ENABLE_API_ARMOR
001655    if( !pStmt ){
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_PREUPDATE_HOOK
001710  /*
001711  ** Allocate and populate an UnpackedRecord structure based on the serialized
001712  ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
001713  ** if successful, or a NULL pointer if an OOM error is encountered.
001714  */
001715  static UnpackedRecord *vdbeUnpackRecord(
001716    KeyInfo *pKeyInfo, 
001717    int nKey, 
001718    const void *pKey
001719  ){
001720    UnpackedRecord *pRet;           /* Return value */
001721  
001722    pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
001723    if( pRet ){
001724      memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
001725      sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
001726    }
001727    return pRet;
001728  }
001729  
001730  /*
001731  ** This function is called from within a pre-update callback to retrieve
001732  ** a field of the row currently being updated or deleted.
001733  */
001734  int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
001735    PreUpdate *p = db->pPreUpdate;
001736    Mem *pMem;
001737    int rc = SQLITE_OK;
001738  
001739    /* Test that this call is being made from within an SQLITE_DELETE or
001740    ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
001741    if( !p || p->op==SQLITE_INSERT ){
001742      rc = SQLITE_MISUSE_BKPT;
001743      goto preupdate_old_out;
001744    }
001745    if( p->pPk ){
001746      iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
001747    }
001748    if( iIdx>=p->pCsr->nField || iIdx<0 ){
001749      rc = SQLITE_RANGE;
001750      goto preupdate_old_out;
001751    }
001752  
001753    /* If the old.* record has not yet been loaded into memory, do so now. */
001754    if( p->pUnpacked==0 ){
001755      u32 nRec;
001756      u8 *aRec;
001757  
001758      nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
001759      aRec = sqlite3DbMallocRaw(db, nRec);
001760      if( !aRec ) goto preupdate_old_out;
001761      rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
001762      if( rc==SQLITE_OK ){
001763        p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
001764        if( !p->pUnpacked ) rc = SQLITE_NOMEM;
001765      }
001766      if( rc!=SQLITE_OK ){
001767        sqlite3DbFree(db, aRec);
001768        goto preupdate_old_out;
001769      }
001770      p->aRecord = aRec;
001771    }
001772  
001773    pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
001774    if( iIdx==p->pTab->iPKey ){
001775      sqlite3VdbeMemSetInt64(pMem, p->iKey1);
001776    }else if( iIdx>=p->pUnpacked->nField ){
001777      *ppValue = (sqlite3_value *)columnNullValue();
001778    }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
001779      if( pMem->flags & MEM_Int ){
001780        sqlite3VdbeMemRealify(pMem);
001781      }
001782    }
001783  
001784   preupdate_old_out:
001785    sqlite3Error(db, rc);
001786    return sqlite3ApiExit(db, rc);
001787  }
001788  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
001789  
001790  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
001791  /*
001792  ** This function is called from within a pre-update callback to retrieve
001793  ** the number of columns in the row being updated, deleted or inserted.
001794  */
001795  int sqlite3_preupdate_count(sqlite3 *db){
001796    PreUpdate *p = db->pPreUpdate;
001797    return (p ? p->keyinfo.nKeyField : 0);
001798  }
001799  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
001800  
001801  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
001802  /*
001803  ** This function is designed to be called from within a pre-update callback
001804  ** only. It returns zero if the change that caused the callback was made
001805  ** immediately by a user SQL statement. Or, if the change was made by a
001806  ** trigger program, it returns the number of trigger programs currently
001807  ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a 
001808  ** top-level trigger etc.).
001809  **
001810  ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
001811  ** or SET DEFAULT action is considered a trigger.
001812  */
001813  int sqlite3_preupdate_depth(sqlite3 *db){
001814    PreUpdate *p = db->pPreUpdate;
001815    return (p ? p->v->nFrame : 0);
001816  }
001817  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
001818  
001819  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
001820  /*
001821  ** This function is called from within a pre-update callback to retrieve
001822  ** a field of the row currently being updated or inserted.
001823  */
001824  int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
001825    PreUpdate *p = db->pPreUpdate;
001826    int rc = SQLITE_OK;
001827    Mem *pMem;
001828  
001829    if( !p || p->op==SQLITE_DELETE ){
001830      rc = SQLITE_MISUSE_BKPT;
001831      goto preupdate_new_out;
001832    }
001833    if( p->pPk && p->op!=SQLITE_UPDATE ){
001834      iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
001835    }
001836    if( iIdx>=p->pCsr->nField || iIdx<0 ){
001837      rc = SQLITE_RANGE;
001838      goto preupdate_new_out;
001839    }
001840  
001841    if( p->op==SQLITE_INSERT ){
001842      /* For an INSERT, memory cell p->iNewReg contains the serialized record
001843      ** that is being inserted. Deserialize it. */
001844      UnpackedRecord *pUnpack = p->pNewUnpacked;
001845      if( !pUnpack ){
001846        Mem *pData = &p->v->aMem[p->iNewReg];
001847        rc = ExpandBlob(pData);
001848        if( rc!=SQLITE_OK ) goto preupdate_new_out;
001849        pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
001850        if( !pUnpack ){
001851          rc = SQLITE_NOMEM;
001852          goto preupdate_new_out;
001853        }
001854        p->pNewUnpacked = pUnpack;
001855      }
001856      pMem = &pUnpack->aMem[iIdx];
001857      if( iIdx==p->pTab->iPKey ){
001858        sqlite3VdbeMemSetInt64(pMem, p->iKey2);
001859      }else if( iIdx>=pUnpack->nField ){
001860        pMem = (sqlite3_value *)columnNullValue();
001861      }
001862    }else{
001863      /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
001864      ** value. Make a copy of the cell contents and return a pointer to it.
001865      ** It is not safe to return a pointer to the memory cell itself as the
001866      ** caller may modify the value text encoding.
001867      */
001868      assert( p->op==SQLITE_UPDATE );
001869      if( !p->aNew ){
001870        p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
001871        if( !p->aNew ){
001872          rc = SQLITE_NOMEM;
001873          goto preupdate_new_out;
001874        }
001875      }
001876      assert( iIdx>=0 && iIdx<p->pCsr->nField );
001877      pMem = &p->aNew[iIdx];
001878      if( pMem->flags==0 ){
001879        if( iIdx==p->pTab->iPKey ){
001880          sqlite3VdbeMemSetInt64(pMem, p->iKey2);
001881        }else{
001882          rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
001883          if( rc!=SQLITE_OK ) goto preupdate_new_out;
001884        }
001885      }
001886    }
001887    *ppValue = pMem;
001888  
001889   preupdate_new_out:
001890    sqlite3Error(db, rc);
001891    return sqlite3ApiExit(db, rc);
001892  }
001893  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
001894  
001895  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
001896  /*
001897  ** Return status data for a single loop within query pStmt.
001898  */
001899  int sqlite3_stmt_scanstatus(
001900    sqlite3_stmt *pStmt,            /* Prepared statement being queried */
001901    int idx,                        /* Index of loop to report on */
001902    int iScanStatusOp,              /* Which metric to return */
001903    void *pOut                      /* OUT: Write the answer here */
001904  ){
001905    Vdbe *p = (Vdbe*)pStmt;
001906    ScanStatus *pScan;
001907    if( idx<0 || idx>=p->nScan ) return 1;
001908    pScan = &p->aScan[idx];
001909    switch( iScanStatusOp ){
001910      case SQLITE_SCANSTAT_NLOOP: {
001911        *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
001912        break;
001913      }
001914      case SQLITE_SCANSTAT_NVISIT: {
001915        *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
001916        break;
001917      }
001918      case SQLITE_SCANSTAT_EST: {
001919        double r = 1.0;
001920        LogEst x = pScan->nEst;
001921        while( x<100 ){
001922          x += 10;
001923          r *= 0.5;
001924        }
001925        *(double*)pOut = r*sqlite3LogEstToInt(x);
001926        break;
001927      }
001928      case SQLITE_SCANSTAT_NAME: {
001929        *(const char**)pOut = pScan->zName;
001930        break;
001931      }
001932      case SQLITE_SCANSTAT_EXPLAIN: {
001933        if( pScan->addrExplain ){
001934          *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
001935        }else{
001936          *(const char**)pOut = 0;
001937        }
001938        break;
001939      }
001940      case SQLITE_SCANSTAT_SELECTID: {
001941        if( pScan->addrExplain ){
001942          *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
001943        }else{
001944          *(int*)pOut = -1;
001945        }
001946        break;
001947      }
001948      default: {
001949        return 1;
001950      }
001951    }
001952    return 0;
001953  }
001954  
001955  /*
001956  ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
001957  */
001958  void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
001959    Vdbe *p = (Vdbe*)pStmt;
001960    memset(p->anExec, 0, p->nOp * sizeof(i64));
001961  }
001962  #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */