000001  /*
000002  ** 2001 September 15
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  ** Main file for the SQLite library.  The routines in this file
000013  ** implement the programmer interface to the library.  Routines in
000014  ** other files are for internal use by SQLite and should not be
000015  ** accessed by users of the library.
000016  */
000017  #include "sqliteInt.h"
000018  
000019  #ifdef SQLITE_ENABLE_FTS3
000020  # include "fts3.h"
000021  #endif
000022  #ifdef SQLITE_ENABLE_RTREE
000023  # include "rtree.h"
000024  #endif
000025  #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
000026  # include "sqliteicu.h"
000027  #endif
000028  #ifdef SQLITE_ENABLE_JSON1
000029  int sqlite3Json1Init(sqlite3*);
000030  #endif
000031  #ifdef SQLITE_ENABLE_STMTVTAB
000032  int sqlite3StmtVtabInit(sqlite3*);
000033  #endif
000034  #ifdef SQLITE_ENABLE_FTS5
000035  int sqlite3Fts5Init(sqlite3*);
000036  #endif
000037  
000038  #ifndef SQLITE_AMALGAMATION
000039  /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
000040  ** contains the text of SQLITE_VERSION macro. 
000041  */
000042  const char sqlite3_version[] = SQLITE_VERSION;
000043  #endif
000044  
000045  /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
000046  ** a pointer to the to the sqlite3_version[] string constant. 
000047  */
000048  const char *sqlite3_libversion(void){ return sqlite3_version; }
000049  
000050  /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
000051  ** pointer to a string constant whose value is the same as the
000052  ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
000053  ** an edited copy of the amalgamation, then the last four characters of
000054  ** the hash might be different from SQLITE_SOURCE_ID.
000055  */
000056  const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
000057  
000058  /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
000059  ** returns an integer equal to SQLITE_VERSION_NUMBER.
000060  */
000061  int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
000062  
000063  /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
000064  ** zero if and only if SQLite was compiled with mutexing code omitted due to
000065  ** the SQLITE_THREADSAFE compile-time option being set to 0.
000066  */
000067  int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
000068  
000069  /*
000070  ** When compiling the test fixture or with debugging enabled (on Win32),
000071  ** this variable being set to non-zero will cause OSTRACE macros to emit
000072  ** extra diagnostic information.
000073  */
000074  #ifdef SQLITE_HAVE_OS_TRACE
000075  # ifndef SQLITE_DEBUG_OS_TRACE
000076  #   define SQLITE_DEBUG_OS_TRACE 0
000077  # endif
000078    int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
000079  #endif
000080  
000081  #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
000082  /*
000083  ** If the following function pointer is not NULL and if
000084  ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
000085  ** I/O active are written using this function.  These messages
000086  ** are intended for debugging activity only.
000087  */
000088  SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
000089  #endif
000090  
000091  /*
000092  ** If the following global variable points to a string which is the
000093  ** name of a directory, then that directory will be used to store
000094  ** temporary files.
000095  **
000096  ** See also the "PRAGMA temp_store_directory" SQL command.
000097  */
000098  char *sqlite3_temp_directory = 0;
000099  
000100  /*
000101  ** If the following global variable points to a string which is the
000102  ** name of a directory, then that directory will be used to store
000103  ** all database files specified with a relative pathname.
000104  **
000105  ** See also the "PRAGMA data_store_directory" SQL command.
000106  */
000107  char *sqlite3_data_directory = 0;
000108  
000109  /*
000110  ** Initialize SQLite.  
000111  **
000112  ** This routine must be called to initialize the memory allocation,
000113  ** VFS, and mutex subsystems prior to doing any serious work with
000114  ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
000115  ** this routine will be called automatically by key routines such as
000116  ** sqlite3_open().  
000117  **
000118  ** This routine is a no-op except on its very first call for the process,
000119  ** or for the first call after a call to sqlite3_shutdown.
000120  **
000121  ** The first thread to call this routine runs the initialization to
000122  ** completion.  If subsequent threads call this routine before the first
000123  ** thread has finished the initialization process, then the subsequent
000124  ** threads must block until the first thread finishes with the initialization.
000125  **
000126  ** The first thread might call this routine recursively.  Recursive
000127  ** calls to this routine should not block, of course.  Otherwise the
000128  ** initialization process would never complete.
000129  **
000130  ** Let X be the first thread to enter this routine.  Let Y be some other
000131  ** thread.  Then while the initial invocation of this routine by X is
000132  ** incomplete, it is required that:
000133  **
000134  **    *  Calls to this routine from Y must block until the outer-most
000135  **       call by X completes.
000136  **
000137  **    *  Recursive calls to this routine from thread X return immediately
000138  **       without blocking.
000139  */
000140  int sqlite3_initialize(void){
000141    MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
000142    int rc;                                      /* Result code */
000143  #ifdef SQLITE_EXTRA_INIT
000144    int bRunExtraInit = 0;                       /* Extra initialization needed */
000145  #endif
000146  
000147  #ifdef SQLITE_OMIT_WSD
000148    rc = sqlite3_wsd_init(4096, 24);
000149    if( rc!=SQLITE_OK ){
000150      return rc;
000151    }
000152  #endif
000153  
000154    /* If the following assert() fails on some obscure processor/compiler
000155    ** combination, the work-around is to set the correct pointer
000156    ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
000157    assert( SQLITE_PTRSIZE==sizeof(char*) );
000158  
000159    /* If SQLite is already completely initialized, then this call
000160    ** to sqlite3_initialize() should be a no-op.  But the initialization
000161    ** must be complete.  So isInit must not be set until the very end
000162    ** of this routine.
000163    */
000164    if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
000165  
000166    /* Make sure the mutex subsystem is initialized.  If unable to 
000167    ** initialize the mutex subsystem, return early with the error.
000168    ** If the system is so sick that we are unable to allocate a mutex,
000169    ** there is not much SQLite is going to be able to do.
000170    **
000171    ** The mutex subsystem must take care of serializing its own
000172    ** initialization.
000173    */
000174    rc = sqlite3MutexInit();
000175    if( rc ) return rc;
000176  
000177    /* Initialize the malloc() system and the recursive pInitMutex mutex.
000178    ** This operation is protected by the STATIC_MASTER mutex.  Note that
000179    ** MutexAlloc() is called for a static mutex prior to initializing the
000180    ** malloc subsystem - this implies that the allocation of a static
000181    ** mutex must not require support from the malloc subsystem.
000182    */
000183    MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
000184    sqlite3_mutex_enter(pMaster);
000185    sqlite3GlobalConfig.isMutexInit = 1;
000186    if( !sqlite3GlobalConfig.isMallocInit ){
000187      rc = sqlite3MallocInit();
000188    }
000189    if( rc==SQLITE_OK ){
000190      sqlite3GlobalConfig.isMallocInit = 1;
000191      if( !sqlite3GlobalConfig.pInitMutex ){
000192        sqlite3GlobalConfig.pInitMutex =
000193             sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
000194        if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
000195          rc = SQLITE_NOMEM_BKPT;
000196        }
000197      }
000198    }
000199    if( rc==SQLITE_OK ){
000200      sqlite3GlobalConfig.nRefInitMutex++;
000201    }
000202    sqlite3_mutex_leave(pMaster);
000203  
000204    /* If rc is not SQLITE_OK at this point, then either the malloc
000205    ** subsystem could not be initialized or the system failed to allocate
000206    ** the pInitMutex mutex. Return an error in either case.  */
000207    if( rc!=SQLITE_OK ){
000208      return rc;
000209    }
000210  
000211    /* Do the rest of the initialization under the recursive mutex so
000212    ** that we will be able to handle recursive calls into
000213    ** sqlite3_initialize().  The recursive calls normally come through
000214    ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
000215    ** recursive calls might also be possible.
000216    **
000217    ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
000218    ** to the xInit method, so the xInit method need not be threadsafe.
000219    **
000220    ** The following mutex is what serializes access to the appdef pcache xInit
000221    ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
000222    ** call to sqlite3PcacheInitialize().
000223    */
000224    sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
000225    if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
000226      sqlite3GlobalConfig.inProgress = 1;
000227  #ifdef SQLITE_ENABLE_SQLLOG
000228      {
000229        extern void sqlite3_init_sqllog(void);
000230        sqlite3_init_sqllog();
000231      }
000232  #endif
000233      memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
000234      sqlite3RegisterBuiltinFunctions();
000235      if( sqlite3GlobalConfig.isPCacheInit==0 ){
000236        rc = sqlite3PcacheInitialize();
000237      }
000238      if( rc==SQLITE_OK ){
000239        sqlite3GlobalConfig.isPCacheInit = 1;
000240        rc = sqlite3OsInit();
000241      }
000242  #ifdef SQLITE_ENABLE_DESERIALIZE
000243      if( rc==SQLITE_OK ){
000244        rc = sqlite3MemdbInit();
000245      }
000246  #endif
000247      if( rc==SQLITE_OK ){
000248        sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
000249            sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
000250        sqlite3GlobalConfig.isInit = 1;
000251  #ifdef SQLITE_EXTRA_INIT
000252        bRunExtraInit = 1;
000253  #endif
000254      }
000255      sqlite3GlobalConfig.inProgress = 0;
000256    }
000257    sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
000258  
000259    /* Go back under the static mutex and clean up the recursive
000260    ** mutex to prevent a resource leak.
000261    */
000262    sqlite3_mutex_enter(pMaster);
000263    sqlite3GlobalConfig.nRefInitMutex--;
000264    if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
000265      assert( sqlite3GlobalConfig.nRefInitMutex==0 );
000266      sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
000267      sqlite3GlobalConfig.pInitMutex = 0;
000268    }
000269    sqlite3_mutex_leave(pMaster);
000270  
000271    /* The following is just a sanity check to make sure SQLite has
000272    ** been compiled correctly.  It is important to run this code, but
000273    ** we don't want to run it too often and soak up CPU cycles for no
000274    ** reason.  So we run it once during initialization.
000275    */
000276  #ifndef NDEBUG
000277  #ifndef SQLITE_OMIT_FLOATING_POINT
000278    /* This section of code's only "output" is via assert() statements. */
000279    if( rc==SQLITE_OK ){
000280      u64 x = (((u64)1)<<63)-1;
000281      double y;
000282      assert(sizeof(x)==8);
000283      assert(sizeof(x)==sizeof(y));
000284      memcpy(&y, &x, 8);
000285      assert( sqlite3IsNaN(y) );
000286    }
000287  #endif
000288  #endif
000289  
000290    /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
000291    ** compile-time option.
000292    */
000293  #ifdef SQLITE_EXTRA_INIT
000294    if( bRunExtraInit ){
000295      int SQLITE_EXTRA_INIT(const char*);
000296      rc = SQLITE_EXTRA_INIT(0);
000297    }
000298  #endif
000299  
000300    return rc;
000301  }
000302  
000303  /*
000304  ** Undo the effects of sqlite3_initialize().  Must not be called while
000305  ** there are outstanding database connections or memory allocations or
000306  ** while any part of SQLite is otherwise in use in any thread.  This
000307  ** routine is not threadsafe.  But it is safe to invoke this routine
000308  ** on when SQLite is already shut down.  If SQLite is already shut down
000309  ** when this routine is invoked, then this routine is a harmless no-op.
000310  */
000311  int sqlite3_shutdown(void){
000312  #ifdef SQLITE_OMIT_WSD
000313    int rc = sqlite3_wsd_init(4096, 24);
000314    if( rc!=SQLITE_OK ){
000315      return rc;
000316    }
000317  #endif
000318  
000319    if( sqlite3GlobalConfig.isInit ){
000320  #ifdef SQLITE_EXTRA_SHUTDOWN
000321      void SQLITE_EXTRA_SHUTDOWN(void);
000322      SQLITE_EXTRA_SHUTDOWN();
000323  #endif
000324      sqlite3_os_end();
000325      sqlite3_reset_auto_extension();
000326      sqlite3GlobalConfig.isInit = 0;
000327    }
000328    if( sqlite3GlobalConfig.isPCacheInit ){
000329      sqlite3PcacheShutdown();
000330      sqlite3GlobalConfig.isPCacheInit = 0;
000331    }
000332    if( sqlite3GlobalConfig.isMallocInit ){
000333      sqlite3MallocEnd();
000334      sqlite3GlobalConfig.isMallocInit = 0;
000335  
000336  #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
000337      /* The heap subsystem has now been shutdown and these values are supposed
000338      ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
000339      ** which would rely on that heap subsystem; therefore, make sure these
000340      ** values cannot refer to heap memory that was just invalidated when the
000341      ** heap subsystem was shutdown.  This is only done if the current call to
000342      ** this function resulted in the heap subsystem actually being shutdown.
000343      */
000344      sqlite3_data_directory = 0;
000345      sqlite3_temp_directory = 0;
000346  #endif
000347    }
000348    if( sqlite3GlobalConfig.isMutexInit ){
000349      sqlite3MutexEnd();
000350      sqlite3GlobalConfig.isMutexInit = 0;
000351    }
000352  
000353    return SQLITE_OK;
000354  }
000355  
000356  /*
000357  ** This API allows applications to modify the global configuration of
000358  ** the SQLite library at run-time.
000359  **
000360  ** This routine should only be called when there are no outstanding
000361  ** database connections or memory allocations.  This routine is not
000362  ** threadsafe.  Failure to heed these warnings can lead to unpredictable
000363  ** behavior.
000364  */
000365  int sqlite3_config(int op, ...){
000366    va_list ap;
000367    int rc = SQLITE_OK;
000368  
000369    /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
000370    ** the SQLite library is in use. */
000371    if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
000372  
000373    va_start(ap, op);
000374    switch( op ){
000375  
000376      /* Mutex configuration options are only available in a threadsafe
000377      ** compile.
000378      */
000379  #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0  /* IMP: R-54466-46756 */
000380      case SQLITE_CONFIG_SINGLETHREAD: {
000381        /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
000382        ** Single-thread. */
000383        sqlite3GlobalConfig.bCoreMutex = 0;  /* Disable mutex on core */
000384        sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
000385        break;
000386      }
000387  #endif
000388  #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
000389      case SQLITE_CONFIG_MULTITHREAD: {
000390        /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
000391        ** Multi-thread. */
000392        sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
000393        sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
000394        break;
000395      }
000396  #endif
000397  #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
000398      case SQLITE_CONFIG_SERIALIZED: {
000399        /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
000400        ** Serialized. */
000401        sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
000402        sqlite3GlobalConfig.bFullMutex = 1;  /* Enable mutex on connections */
000403        break;
000404      }
000405  #endif
000406  #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
000407      case SQLITE_CONFIG_MUTEX: {
000408        /* Specify an alternative mutex implementation */
000409        sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
000410        break;
000411      }
000412  #endif
000413  #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
000414      case SQLITE_CONFIG_GETMUTEX: {
000415        /* Retrieve the current mutex implementation */
000416        *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
000417        break;
000418      }
000419  #endif
000420  
000421      case SQLITE_CONFIG_MALLOC: {
000422        /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
000423        ** single argument which is a pointer to an instance of the
000424        ** sqlite3_mem_methods structure. The argument specifies alternative
000425        ** low-level memory allocation routines to be used in place of the memory
000426        ** allocation routines built into SQLite. */
000427        sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
000428        break;
000429      }
000430      case SQLITE_CONFIG_GETMALLOC: {
000431        /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
000432        ** single argument which is a pointer to an instance of the
000433        ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
000434        ** filled with the currently defined memory allocation routines. */
000435        if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
000436        *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
000437        break;
000438      }
000439      case SQLITE_CONFIG_MEMSTATUS: {
000440        /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
000441        ** single argument of type int, interpreted as a boolean, which enables
000442        ** or disables the collection of memory allocation statistics. */
000443        sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
000444        break;
000445      }
000446      case SQLITE_CONFIG_SMALL_MALLOC: {
000447        sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
000448        break;
000449      }
000450      case SQLITE_CONFIG_PAGECACHE: {
000451        /* EVIDENCE-OF: R-18761-36601 There are three arguments to
000452        ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
000453        ** the size of each page cache line (sz), and the number of cache lines
000454        ** (N). */
000455        sqlite3GlobalConfig.pPage = va_arg(ap, void*);
000456        sqlite3GlobalConfig.szPage = va_arg(ap, int);
000457        sqlite3GlobalConfig.nPage = va_arg(ap, int);
000458        break;
000459      }
000460      case SQLITE_CONFIG_PCACHE_HDRSZ: {
000461        /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
000462        ** a single parameter which is a pointer to an integer and writes into
000463        ** that integer the number of extra bytes per page required for each page
000464        ** in SQLITE_CONFIG_PAGECACHE. */
000465        *va_arg(ap, int*) = 
000466            sqlite3HeaderSizeBtree() +
000467            sqlite3HeaderSizePcache() +
000468            sqlite3HeaderSizePcache1();
000469        break;
000470      }
000471  
000472      case SQLITE_CONFIG_PCACHE: {
000473        /* no-op */
000474        break;
000475      }
000476      case SQLITE_CONFIG_GETPCACHE: {
000477        /* now an error */
000478        rc = SQLITE_ERROR;
000479        break;
000480      }
000481  
000482      case SQLITE_CONFIG_PCACHE2: {
000483        /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
000484        ** single argument which is a pointer to an sqlite3_pcache_methods2
000485        ** object. This object specifies the interface to a custom page cache
000486        ** implementation. */
000487        sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
000488        break;
000489      }
000490      case SQLITE_CONFIG_GETPCACHE2: {
000491        /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
000492        ** single argument which is a pointer to an sqlite3_pcache_methods2
000493        ** object. SQLite copies of the current page cache implementation into
000494        ** that object. */
000495        if( sqlite3GlobalConfig.pcache2.xInit==0 ){
000496          sqlite3PCacheSetDefault();
000497        }
000498        *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
000499        break;
000500      }
000501  
000502  /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
000503  ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
000504  ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
000505  #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
000506      case SQLITE_CONFIG_HEAP: {
000507        /* EVIDENCE-OF: R-19854-42126 There are three arguments to
000508        ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
000509        ** number of bytes in the memory buffer, and the minimum allocation size.
000510        */
000511        sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
000512        sqlite3GlobalConfig.nHeap = va_arg(ap, int);
000513        sqlite3GlobalConfig.mnReq = va_arg(ap, int);
000514  
000515        if( sqlite3GlobalConfig.mnReq<1 ){
000516          sqlite3GlobalConfig.mnReq = 1;
000517        }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
000518          /* cap min request size at 2^12 */
000519          sqlite3GlobalConfig.mnReq = (1<<12);
000520        }
000521  
000522        if( sqlite3GlobalConfig.pHeap==0 ){
000523          /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
000524          ** is NULL, then SQLite reverts to using its default memory allocator
000525          ** (the system malloc() implementation), undoing any prior invocation of
000526          ** SQLITE_CONFIG_MALLOC.
000527          **
000528          ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
000529          ** revert to its default implementation when sqlite3_initialize() is run
000530          */
000531          memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
000532        }else{
000533          /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
000534          ** alternative memory allocator is engaged to handle all of SQLites
000535          ** memory allocation needs. */
000536  #ifdef SQLITE_ENABLE_MEMSYS3
000537          sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
000538  #endif
000539  #ifdef SQLITE_ENABLE_MEMSYS5
000540          sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
000541  #endif
000542        }
000543        break;
000544      }
000545  #endif
000546  
000547      case SQLITE_CONFIG_LOOKASIDE: {
000548        sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
000549        sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
000550        break;
000551      }
000552      
000553      /* Record a pointer to the logger function and its first argument.
000554      ** The default is NULL.  Logging is disabled if the function pointer is
000555      ** NULL.
000556      */
000557      case SQLITE_CONFIG_LOG: {
000558        /* MSVC is picky about pulling func ptrs from va lists.
000559        ** http://support.microsoft.com/kb/47961
000560        ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
000561        */
000562        typedef void(*LOGFUNC_t)(void*,int,const char*);
000563        sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
000564        sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
000565        break;
000566      }
000567  
000568      /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
000569      ** can be changed at start-time using the
000570      ** sqlite3_config(SQLITE_CONFIG_URI,1) or
000571      ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
000572      */
000573      case SQLITE_CONFIG_URI: {
000574        /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
000575        ** argument of type int. If non-zero, then URI handling is globally
000576        ** enabled. If the parameter is zero, then URI handling is globally
000577        ** disabled. */
000578        sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
000579        break;
000580      }
000581  
000582      case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
000583        /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
000584        ** option takes a single integer argument which is interpreted as a
000585        ** boolean in order to enable or disable the use of covering indices for
000586        ** full table scans in the query optimizer. */
000587        sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
000588        break;
000589      }
000590  
000591  #ifdef SQLITE_ENABLE_SQLLOG
000592      case SQLITE_CONFIG_SQLLOG: {
000593        typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
000594        sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
000595        sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
000596        break;
000597      }
000598  #endif
000599  
000600      case SQLITE_CONFIG_MMAP_SIZE: {
000601        /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
000602        ** integer (sqlite3_int64) values that are the default mmap size limit
000603        ** (the default setting for PRAGMA mmap_size) and the maximum allowed
000604        ** mmap size limit. */
000605        sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
000606        sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
000607        /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
000608        ** negative, then that argument is changed to its compile-time default.
000609        **
000610        ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
000611        ** silently truncated if necessary so that it does not exceed the
000612        ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
000613        ** compile-time option.
000614        */
000615        if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
000616          mxMmap = SQLITE_MAX_MMAP_SIZE;
000617        }
000618        if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
000619        if( szMmap>mxMmap) szMmap = mxMmap;
000620        sqlite3GlobalConfig.mxMmap = mxMmap;
000621        sqlite3GlobalConfig.szMmap = szMmap;
000622        break;
000623      }
000624  
000625  #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
000626      case SQLITE_CONFIG_WIN32_HEAPSIZE: {
000627        /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
000628        ** unsigned integer value that specifies the maximum size of the created
000629        ** heap. */
000630        sqlite3GlobalConfig.nHeap = va_arg(ap, int);
000631        break;
000632      }
000633  #endif
000634  
000635      case SQLITE_CONFIG_PMASZ: {
000636        sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
000637        break;
000638      }
000639  
000640      case SQLITE_CONFIG_STMTJRNL_SPILL: {
000641        sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
000642        break;
000643      }
000644  
000645  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
000646      case SQLITE_CONFIG_SORTERREF_SIZE: {
000647        int iVal = va_arg(ap, int);
000648        if( iVal<0 ){
000649          iVal = SQLITE_DEFAULT_SORTERREF_SIZE;
000650        }
000651        sqlite3GlobalConfig.szSorterRef = (u32)iVal;
000652        break;
000653      }
000654  #endif /* SQLITE_ENABLE_SORTER_REFERENCES */
000655  
000656  #ifdef SQLITE_ENABLE_DESERIALIZE
000657      case SQLITE_CONFIG_MEMDB_MAXSIZE: {
000658        sqlite3GlobalConfig.mxMemdbSize = va_arg(ap, sqlite3_int64);
000659        break;
000660      }
000661  #endif /* SQLITE_ENABLE_DESERIALIZE */
000662  
000663      default: {
000664        rc = SQLITE_ERROR;
000665        break;
000666      }
000667    }
000668    va_end(ap);
000669    return rc;
000670  }
000671  
000672  /*
000673  ** Set up the lookaside buffers for a database connection.
000674  ** Return SQLITE_OK on success.  
000675  ** If lookaside is already active, return SQLITE_BUSY.
000676  **
000677  ** The sz parameter is the number of bytes in each lookaside slot.
000678  ** The cnt parameter is the number of slots.  If pStart is NULL the
000679  ** space for the lookaside memory is obtained from sqlite3_malloc().
000680  ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
000681  ** the lookaside memory.
000682  */
000683  static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
000684  #ifndef SQLITE_OMIT_LOOKASIDE
000685    void *pStart;
000686    
000687    if( sqlite3LookasideUsed(db,0)>0 ){
000688      return SQLITE_BUSY;
000689    }
000690    /* Free any existing lookaside buffer for this handle before
000691    ** allocating a new one so we don't have to have space for 
000692    ** both at the same time.
000693    */
000694    if( db->lookaside.bMalloced ){
000695      sqlite3_free(db->lookaside.pStart);
000696    }
000697    /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
000698    ** than a pointer to be useful.
000699    */
000700    sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
000701    if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
000702    if( cnt<0 ) cnt = 0;
000703    if( sz==0 || cnt==0 ){
000704      sz = 0;
000705      pStart = 0;
000706    }else if( pBuf==0 ){
000707      sqlite3BeginBenignMalloc();
000708      pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
000709      sqlite3EndBenignMalloc();
000710      if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
000711    }else{
000712      pStart = pBuf;
000713    }
000714    db->lookaside.pStart = pStart;
000715    db->lookaside.pInit = 0;
000716    db->lookaside.pFree = 0;
000717    db->lookaside.sz = (u16)sz;
000718    if( pStart ){
000719      int i;
000720      LookasideSlot *p;
000721      assert( sz > (int)sizeof(LookasideSlot*) );
000722      db->lookaside.nSlot = cnt;
000723      p = (LookasideSlot*)pStart;
000724      for(i=cnt-1; i>=0; i--){
000725        p->pNext = db->lookaside.pInit;
000726        db->lookaside.pInit = p;
000727        p = (LookasideSlot*)&((u8*)p)[sz];
000728      }
000729      db->lookaside.pEnd = p;
000730      db->lookaside.bDisable = 0;
000731      db->lookaside.bMalloced = pBuf==0 ?1:0;
000732    }else{
000733      db->lookaside.pStart = db;
000734      db->lookaside.pEnd = db;
000735      db->lookaside.bDisable = 1;
000736      db->lookaside.bMalloced = 0;
000737      db->lookaside.nSlot = 0;
000738    }
000739  #endif /* SQLITE_OMIT_LOOKASIDE */
000740    return SQLITE_OK;
000741  }
000742  
000743  /*
000744  ** Return the mutex associated with a database connection.
000745  */
000746  sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
000747  #ifdef SQLITE_ENABLE_API_ARMOR
000748    if( !sqlite3SafetyCheckOk(db) ){
000749      (void)SQLITE_MISUSE_BKPT;
000750      return 0;
000751    }
000752  #endif
000753    return db->mutex;
000754  }
000755  
000756  /*
000757  ** Free up as much memory as we can from the given database
000758  ** connection.
000759  */
000760  int sqlite3_db_release_memory(sqlite3 *db){
000761    int i;
000762  
000763  #ifdef SQLITE_ENABLE_API_ARMOR
000764    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
000765  #endif
000766    sqlite3_mutex_enter(db->mutex);
000767    sqlite3BtreeEnterAll(db);
000768    for(i=0; i<db->nDb; i++){
000769      Btree *pBt = db->aDb[i].pBt;
000770      if( pBt ){
000771        Pager *pPager = sqlite3BtreePager(pBt);
000772        sqlite3PagerShrink(pPager);
000773      }
000774    }
000775    sqlite3BtreeLeaveAll(db);
000776    sqlite3_mutex_leave(db->mutex);
000777    return SQLITE_OK;
000778  }
000779  
000780  /*
000781  ** Flush any dirty pages in the pager-cache for any attached database
000782  ** to disk.
000783  */
000784  int sqlite3_db_cacheflush(sqlite3 *db){
000785    int i;
000786    int rc = SQLITE_OK;
000787    int bSeenBusy = 0;
000788  
000789  #ifdef SQLITE_ENABLE_API_ARMOR
000790    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
000791  #endif
000792    sqlite3_mutex_enter(db->mutex);
000793    sqlite3BtreeEnterAll(db);
000794    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
000795      Btree *pBt = db->aDb[i].pBt;
000796      if( pBt && sqlite3BtreeIsInTrans(pBt) ){
000797        Pager *pPager = sqlite3BtreePager(pBt);
000798        rc = sqlite3PagerFlush(pPager);
000799        if( rc==SQLITE_BUSY ){
000800          bSeenBusy = 1;
000801          rc = SQLITE_OK;
000802        }
000803      }
000804    }
000805    sqlite3BtreeLeaveAll(db);
000806    sqlite3_mutex_leave(db->mutex);
000807    return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
000808  }
000809  
000810  /*
000811  ** Configuration settings for an individual database connection
000812  */
000813  int sqlite3_db_config(sqlite3 *db, int op, ...){
000814    va_list ap;
000815    int rc;
000816    va_start(ap, op);
000817    switch( op ){
000818      case SQLITE_DBCONFIG_MAINDBNAME: {
000819        /* IMP: R-06824-28531 */
000820        /* IMP: R-36257-52125 */
000821        db->aDb[0].zDbSName = va_arg(ap,char*);
000822        rc = SQLITE_OK;
000823        break;
000824      }
000825      case SQLITE_DBCONFIG_LOOKASIDE: {
000826        void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
000827        int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
000828        int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
000829        rc = setupLookaside(db, pBuf, sz, cnt);
000830        break;
000831      }
000832      default: {
000833        static const struct {
000834          int op;      /* The opcode */
000835          u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
000836        } aFlagOp[] = {
000837          { SQLITE_DBCONFIG_ENABLE_FKEY,           SQLITE_ForeignKeys    },
000838          { SQLITE_DBCONFIG_ENABLE_TRIGGER,        SQLITE_EnableTrigger  },
000839          { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer  },
000840          { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension  },
000841          { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE,      SQLITE_NoCkptOnClose  },
000842          { SQLITE_DBCONFIG_ENABLE_QPSG,           SQLITE_EnableQPSG     },
000843          { SQLITE_DBCONFIG_TRIGGER_EQP,           SQLITE_TriggerEQP     },
000844          { SQLITE_DBCONFIG_RESET_DATABASE,        SQLITE_ResetDatabase  },
000845          { SQLITE_DBCONFIG_DEFENSIVE,             SQLITE_Defensive      },
000846        };
000847        unsigned int i;
000848        rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
000849        for(i=0; i<ArraySize(aFlagOp); i++){
000850          if( aFlagOp[i].op==op ){
000851            int onoff = va_arg(ap, int);
000852            int *pRes = va_arg(ap, int*);
000853            u64 oldFlags = db->flags;
000854            if( onoff>0 ){
000855              db->flags |= aFlagOp[i].mask;
000856            }else if( onoff==0 ){
000857              db->flags &= ~(u64)aFlagOp[i].mask;
000858            }
000859            if( oldFlags!=db->flags ){
000860              sqlite3ExpirePreparedStatements(db, 0);
000861            }
000862            if( pRes ){
000863              *pRes = (db->flags & aFlagOp[i].mask)!=0;
000864            }
000865            rc = SQLITE_OK;
000866            break;
000867          }
000868        }
000869        break;
000870      }
000871    }
000872    va_end(ap);
000873    return rc;
000874  }
000875  
000876  
000877  /*
000878  ** Return true if the buffer z[0..n-1] contains all spaces.
000879  */
000880  static int allSpaces(const char *z, int n){
000881    while( n>0 && z[n-1]==' ' ){ n--; }
000882    return n==0;
000883  }
000884  
000885  /*
000886  ** This is the default collating function named "BINARY" which is always
000887  ** available.
000888  **
000889  ** If the padFlag argument is not NULL then space padding at the end
000890  ** of strings is ignored.  This implements the RTRIM collation.
000891  */
000892  static int binCollFunc(
000893    void *padFlag,
000894    int nKey1, const void *pKey1,
000895    int nKey2, const void *pKey2
000896  ){
000897    int rc, n;
000898    n = nKey1<nKey2 ? nKey1 : nKey2;
000899    /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
000900    ** strings byte by byte using the memcmp() function from the standard C
000901    ** library. */
000902    assert( pKey1 && pKey2 );
000903    rc = memcmp(pKey1, pKey2, n);
000904    if( rc==0 ){
000905      if( padFlag
000906       && allSpaces(((char*)pKey1)+n, nKey1-n)
000907       && allSpaces(((char*)pKey2)+n, nKey2-n)
000908      ){
000909        /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
000910        ** spaces at the end of either string do not change the result. In other
000911        ** words, strings will compare equal to one another as long as they
000912        ** differ only in the number of spaces at the end.
000913        */
000914      }else{
000915        rc = nKey1 - nKey2;
000916      }
000917    }
000918    return rc;
000919  }
000920  
000921  /*
000922  ** Return true if CollSeq is the default built-in BINARY.
000923  */
000924  int sqlite3IsBinary(const CollSeq *p){
000925    assert( p==0 || p->xCmp!=binCollFunc || p->pUser!=0
000926              || strcmp(p->zName,"BINARY")==0 );
000927    return p==0 || (p->xCmp==binCollFunc && p->pUser==0);
000928  }
000929  
000930  /*
000931  ** Another built-in collating sequence: NOCASE. 
000932  **
000933  ** This collating sequence is intended to be used for "case independent
000934  ** comparison". SQLite's knowledge of upper and lower case equivalents
000935  ** extends only to the 26 characters used in the English language.
000936  **
000937  ** At the moment there is only a UTF-8 implementation.
000938  */
000939  static int nocaseCollatingFunc(
000940    void *NotUsed,
000941    int nKey1, const void *pKey1,
000942    int nKey2, const void *pKey2
000943  ){
000944    int r = sqlite3StrNICmp(
000945        (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
000946    UNUSED_PARAMETER(NotUsed);
000947    if( 0==r ){
000948      r = nKey1-nKey2;
000949    }
000950    return r;
000951  }
000952  
000953  /*
000954  ** Return the ROWID of the most recent insert
000955  */
000956  sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
000957  #ifdef SQLITE_ENABLE_API_ARMOR
000958    if( !sqlite3SafetyCheckOk(db) ){
000959      (void)SQLITE_MISUSE_BKPT;
000960      return 0;
000961    }
000962  #endif
000963    return db->lastRowid;
000964  }
000965  
000966  /*
000967  ** Set the value returned by the sqlite3_last_insert_rowid() API function.
000968  */
000969  void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
000970  #ifdef SQLITE_ENABLE_API_ARMOR
000971    if( !sqlite3SafetyCheckOk(db) ){
000972      (void)SQLITE_MISUSE_BKPT;
000973      return;
000974    }
000975  #endif
000976    sqlite3_mutex_enter(db->mutex);
000977    db->lastRowid = iRowid;
000978    sqlite3_mutex_leave(db->mutex);
000979  }
000980  
000981  /*
000982  ** Return the number of changes in the most recent call to sqlite3_exec().
000983  */
000984  int sqlite3_changes(sqlite3 *db){
000985  #ifdef SQLITE_ENABLE_API_ARMOR
000986    if( !sqlite3SafetyCheckOk(db) ){
000987      (void)SQLITE_MISUSE_BKPT;
000988      return 0;
000989    }
000990  #endif
000991    return db->nChange;
000992  }
000993  
000994  /*
000995  ** Return the number of changes since the database handle was opened.
000996  */
000997  int sqlite3_total_changes(sqlite3 *db){
000998  #ifdef SQLITE_ENABLE_API_ARMOR
000999    if( !sqlite3SafetyCheckOk(db) ){
001000      (void)SQLITE_MISUSE_BKPT;
001001      return 0;
001002    }
001003  #endif
001004    return db->nTotalChange;
001005  }
001006  
001007  /*
001008  ** Close all open savepoints. This function only manipulates fields of the
001009  ** database handle object, it does not close any savepoints that may be open
001010  ** at the b-tree/pager level.
001011  */
001012  void sqlite3CloseSavepoints(sqlite3 *db){
001013    while( db->pSavepoint ){
001014      Savepoint *pTmp = db->pSavepoint;
001015      db->pSavepoint = pTmp->pNext;
001016      sqlite3DbFree(db, pTmp);
001017    }
001018    db->nSavepoint = 0;
001019    db->nStatement = 0;
001020    db->isTransactionSavepoint = 0;
001021  }
001022  
001023  /*
001024  ** Invoke the destructor function associated with FuncDef p, if any. Except,
001025  ** if this is not the last copy of the function, do not invoke it. Multiple
001026  ** copies of a single function are created when create_function() is called
001027  ** with SQLITE_ANY as the encoding.
001028  */
001029  static void functionDestroy(sqlite3 *db, FuncDef *p){
001030    FuncDestructor *pDestructor = p->u.pDestructor;
001031    if( pDestructor ){
001032      pDestructor->nRef--;
001033      if( pDestructor->nRef==0 ){
001034        pDestructor->xDestroy(pDestructor->pUserData);
001035        sqlite3DbFree(db, pDestructor);
001036      }
001037    }
001038  }
001039  
001040  /*
001041  ** Disconnect all sqlite3_vtab objects that belong to database connection
001042  ** db. This is called when db is being closed.
001043  */
001044  static void disconnectAllVtab(sqlite3 *db){
001045  #ifndef SQLITE_OMIT_VIRTUALTABLE
001046    int i;
001047    HashElem *p;
001048    sqlite3BtreeEnterAll(db);
001049    for(i=0; i<db->nDb; i++){
001050      Schema *pSchema = db->aDb[i].pSchema;
001051      if( pSchema ){
001052        for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
001053          Table *pTab = (Table *)sqliteHashData(p);
001054          if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
001055        }
001056      }
001057    }
001058    for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
001059      Module *pMod = (Module *)sqliteHashData(p);
001060      if( pMod->pEpoTab ){
001061        sqlite3VtabDisconnect(db, pMod->pEpoTab);
001062      }
001063    }
001064    sqlite3VtabUnlockList(db);
001065    sqlite3BtreeLeaveAll(db);
001066  #else
001067    UNUSED_PARAMETER(db);
001068  #endif
001069  }
001070  
001071  /*
001072  ** Return TRUE if database connection db has unfinalized prepared
001073  ** statements or unfinished sqlite3_backup objects.  
001074  */
001075  static int connectionIsBusy(sqlite3 *db){
001076    int j;
001077    assert( sqlite3_mutex_held(db->mutex) );
001078    if( db->pVdbe ) return 1;
001079    for(j=0; j<db->nDb; j++){
001080      Btree *pBt = db->aDb[j].pBt;
001081      if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
001082    }
001083    return 0;
001084  }
001085  
001086  /*
001087  ** Close an existing SQLite database
001088  */
001089  static int sqlite3Close(sqlite3 *db, int forceZombie){
001090    if( !db ){
001091      /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
001092      ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
001093      return SQLITE_OK;
001094    }
001095    if( !sqlite3SafetyCheckSickOrOk(db) ){
001096      return SQLITE_MISUSE_BKPT;
001097    }
001098    sqlite3_mutex_enter(db->mutex);
001099    if( db->mTrace & SQLITE_TRACE_CLOSE ){
001100      db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
001101    }
001102  
001103    /* Force xDisconnect calls on all virtual tables */
001104    disconnectAllVtab(db);
001105  
001106    /* If a transaction is open, the disconnectAllVtab() call above
001107    ** will not have called the xDisconnect() method on any virtual
001108    ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
001109    ** call will do so. We need to do this before the check for active
001110    ** SQL statements below, as the v-table implementation may be storing
001111    ** some prepared statements internally.
001112    */
001113    sqlite3VtabRollback(db);
001114  
001115    /* Legacy behavior (sqlite3_close() behavior) is to return
001116    ** SQLITE_BUSY if the connection can not be closed immediately.
001117    */
001118    if( !forceZombie && connectionIsBusy(db) ){
001119      sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
001120         "statements or unfinished backups");
001121      sqlite3_mutex_leave(db->mutex);
001122      return SQLITE_BUSY;
001123    }
001124  
001125  #ifdef SQLITE_ENABLE_SQLLOG
001126    if( sqlite3GlobalConfig.xSqllog ){
001127      /* Closing the handle. Fourth parameter is passed the value 2. */
001128      sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
001129    }
001130  #endif
001131  
001132    /* Convert the connection into a zombie and then close it.
001133    */
001134    db->magic = SQLITE_MAGIC_ZOMBIE;
001135    sqlite3LeaveMutexAndCloseZombie(db);
001136    return SQLITE_OK;
001137  }
001138  
001139  /*
001140  ** Two variations on the public interface for closing a database
001141  ** connection. The sqlite3_close() version returns SQLITE_BUSY and
001142  ** leaves the connection option if there are unfinalized prepared
001143  ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
001144  ** version forces the connection to become a zombie if there are
001145  ** unclosed resources, and arranges for deallocation when the last
001146  ** prepare statement or sqlite3_backup closes.
001147  */
001148  int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
001149  int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
001150  
001151  
001152  /*
001153  ** Close the mutex on database connection db.
001154  **
001155  ** Furthermore, if database connection db is a zombie (meaning that there
001156  ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
001157  ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
001158  ** finished, then free all resources.
001159  */
001160  void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
001161    HashElem *i;                    /* Hash table iterator */
001162    int j;
001163  
001164    /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
001165    ** or if the connection has not yet been closed by sqlite3_close_v2(),
001166    ** then just leave the mutex and return.
001167    */
001168    if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
001169      sqlite3_mutex_leave(db->mutex);
001170      return;
001171    }
001172  
001173    /* If we reach this point, it means that the database connection has
001174    ** closed all sqlite3_stmt and sqlite3_backup objects and has been
001175    ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
001176    ** go ahead and free all resources.
001177    */
001178  
001179    /* If a transaction is open, roll it back. This also ensures that if
001180    ** any database schemas have been modified by an uncommitted transaction
001181    ** they are reset. And that the required b-tree mutex is held to make
001182    ** the pager rollback and schema reset an atomic operation. */
001183    sqlite3RollbackAll(db, SQLITE_OK);
001184  
001185    /* Free any outstanding Savepoint structures. */
001186    sqlite3CloseSavepoints(db);
001187  
001188    /* Close all database connections */
001189    for(j=0; j<db->nDb; j++){
001190      struct Db *pDb = &db->aDb[j];
001191      if( pDb->pBt ){
001192        sqlite3BtreeClose(pDb->pBt);
001193        pDb->pBt = 0;
001194        if( j!=1 ){
001195          pDb->pSchema = 0;
001196        }
001197      }
001198    }
001199    /* Clear the TEMP schema separately and last */
001200    if( db->aDb[1].pSchema ){
001201      sqlite3SchemaClear(db->aDb[1].pSchema);
001202    }
001203    sqlite3VtabUnlockList(db);
001204  
001205    /* Free up the array of auxiliary databases */
001206    sqlite3CollapseDatabaseArray(db);
001207    assert( db->nDb<=2 );
001208    assert( db->aDb==db->aDbStatic );
001209  
001210    /* Tell the code in notify.c that the connection no longer holds any
001211    ** locks and does not require any further unlock-notify callbacks.
001212    */
001213    sqlite3ConnectionClosed(db);
001214  
001215    for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
001216      FuncDef *pNext, *p;
001217      p = sqliteHashData(i);
001218      do{
001219        functionDestroy(db, p);
001220        pNext = p->pNext;
001221        sqlite3DbFree(db, p);
001222        p = pNext;
001223      }while( p );
001224    }
001225    sqlite3HashClear(&db->aFunc);
001226    for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
001227      CollSeq *pColl = (CollSeq *)sqliteHashData(i);
001228      /* Invoke any destructors registered for collation sequence user data. */
001229      for(j=0; j<3; j++){
001230        if( pColl[j].xDel ){
001231          pColl[j].xDel(pColl[j].pUser);
001232        }
001233      }
001234      sqlite3DbFree(db, pColl);
001235    }
001236    sqlite3HashClear(&db->aCollSeq);
001237  #ifndef SQLITE_OMIT_VIRTUALTABLE
001238    for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
001239      Module *pMod = (Module *)sqliteHashData(i);
001240      if( pMod->xDestroy ){
001241        pMod->xDestroy(pMod->pAux);
001242      }
001243      sqlite3VtabEponymousTableClear(db, pMod);
001244      sqlite3DbFree(db, pMod);
001245    }
001246    sqlite3HashClear(&db->aModule);
001247  #endif
001248  
001249    sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
001250    sqlite3ValueFree(db->pErr);
001251    sqlite3CloseExtensions(db);
001252  #if SQLITE_USER_AUTHENTICATION
001253    sqlite3_free(db->auth.zAuthUser);
001254    sqlite3_free(db->auth.zAuthPW);
001255  #endif
001256  
001257    db->magic = SQLITE_MAGIC_ERROR;
001258  
001259    /* The temp-database schema is allocated differently from the other schema
001260    ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
001261    ** So it needs to be freed here. Todo: Why not roll the temp schema into
001262    ** the same sqliteMalloc() as the one that allocates the database 
001263    ** structure?
001264    */
001265    sqlite3DbFree(db, db->aDb[1].pSchema);
001266    sqlite3_mutex_leave(db->mutex);
001267    db->magic = SQLITE_MAGIC_CLOSED;
001268    sqlite3_mutex_free(db->mutex);
001269    assert( sqlite3LookasideUsed(db,0)==0 );
001270    if( db->lookaside.bMalloced ){
001271      sqlite3_free(db->lookaside.pStart);
001272    }
001273    sqlite3_free(db);
001274  }
001275  
001276  /*
001277  ** Rollback all database files.  If tripCode is not SQLITE_OK, then
001278  ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
001279  ** breaker") and made to return tripCode if there are any further
001280  ** attempts to use that cursor.  Read cursors remain open and valid
001281  ** but are "saved" in case the table pages are moved around.
001282  */
001283  void sqlite3RollbackAll(sqlite3 *db, int tripCode){
001284    int i;
001285    int inTrans = 0;
001286    int schemaChange;
001287    assert( sqlite3_mutex_held(db->mutex) );
001288    sqlite3BeginBenignMalloc();
001289  
001290    /* Obtain all b-tree mutexes before making any calls to BtreeRollback(). 
001291    ** This is important in case the transaction being rolled back has
001292    ** modified the database schema. If the b-tree mutexes are not taken
001293    ** here, then another shared-cache connection might sneak in between
001294    ** the database rollback and schema reset, which can cause false
001295    ** corruption reports in some cases.  */
001296    sqlite3BtreeEnterAll(db);
001297    schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
001298  
001299    for(i=0; i<db->nDb; i++){
001300      Btree *p = db->aDb[i].pBt;
001301      if( p ){
001302        if( sqlite3BtreeIsInTrans(p) ){
001303          inTrans = 1;
001304        }
001305        sqlite3BtreeRollback(p, tripCode, !schemaChange);
001306      }
001307    }
001308    sqlite3VtabRollback(db);
001309    sqlite3EndBenignMalloc();
001310  
001311    if( schemaChange ){
001312      sqlite3ExpirePreparedStatements(db, 0);
001313      sqlite3ResetAllSchemasOfConnection(db);
001314    }
001315    sqlite3BtreeLeaveAll(db);
001316  
001317    /* Any deferred constraint violations have now been resolved. */
001318    db->nDeferredCons = 0;
001319    db->nDeferredImmCons = 0;
001320    db->flags &= ~(u64)SQLITE_DeferFKs;
001321  
001322    /* If one has been configured, invoke the rollback-hook callback */
001323    if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
001324      db->xRollbackCallback(db->pRollbackArg);
001325    }
001326  }
001327  
001328  /*
001329  ** Return a static string containing the name corresponding to the error code
001330  ** specified in the argument.
001331  */
001332  #if defined(SQLITE_NEED_ERR_NAME)
001333  const char *sqlite3ErrName(int rc){
001334    const char *zName = 0;
001335    int i, origRc = rc;
001336    for(i=0; i<2 && zName==0; i++, rc &= 0xff){
001337      switch( rc ){
001338        case SQLITE_OK:                 zName = "SQLITE_OK";                break;
001339        case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
001340        case SQLITE_ERROR_SNAPSHOT:     zName = "SQLITE_ERROR_SNAPSHOT";    break;
001341        case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
001342        case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
001343        case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
001344        case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
001345        case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
001346        case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
001347        case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
001348        case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
001349        case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
001350        case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
001351        case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
001352        case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
001353        case SQLITE_READONLY_CANTINIT:  zName = "SQLITE_READONLY_CANTINIT"; break;
001354        case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
001355        case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
001356        case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break;
001357        case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
001358        case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
001359        case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
001360        case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
001361        case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
001362        case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
001363        case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
001364        case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
001365        case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
001366        case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
001367        case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
001368        case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
001369        case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
001370        case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
001371        case SQLITE_IOERR_CHECKRESERVEDLOCK:
001372                                  zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
001373        case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
001374        case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
001375        case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
001376        case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
001377        case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
001378        case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
001379        case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
001380        case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
001381        case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
001382        case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
001383        case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
001384        case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
001385        case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
001386        case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
001387        case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
001388        case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
001389        case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
001390        case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
001391        case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
001392        case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
001393        case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
001394        case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
001395        case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
001396        case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
001397        case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
001398        case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
001399        case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
001400        case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
001401        case SQLITE_CONSTRAINT_FOREIGNKEY:
001402                                  zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
001403        case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
001404        case SQLITE_CONSTRAINT_PRIMARYKEY:
001405                                  zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
001406        case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
001407        case SQLITE_CONSTRAINT_COMMITHOOK:
001408                                  zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
001409        case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
001410        case SQLITE_CONSTRAINT_FUNCTION:
001411                                  zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
001412        case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
001413        case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
001414        case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
001415        case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
001416        case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
001417        case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
001418        case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
001419        case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
001420        case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
001421        case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
001422        case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
001423        case SQLITE_NOTICE_RECOVER_ROLLBACK:
001424                                  zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
001425        case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
001426        case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
001427        case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
001428      }
001429    }
001430    if( zName==0 ){
001431      static char zBuf[50];
001432      sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
001433      zName = zBuf;
001434    }
001435    return zName;
001436  }
001437  #endif
001438  
001439  /*
001440  ** Return a static string that describes the kind of error specified in the
001441  ** argument.
001442  */
001443  const char *sqlite3ErrStr(int rc){
001444    static const char* const aMsg[] = {
001445      /* SQLITE_OK          */ "not an error",
001446      /* SQLITE_ERROR       */ "SQL logic error",
001447      /* SQLITE_INTERNAL    */ 0,
001448      /* SQLITE_PERM        */ "access permission denied",
001449      /* SQLITE_ABORT       */ "query aborted",
001450      /* SQLITE_BUSY        */ "database is locked",
001451      /* SQLITE_LOCKED      */ "database table is locked",
001452      /* SQLITE_NOMEM       */ "out of memory",
001453      /* SQLITE_READONLY    */ "attempt to write a readonly database",
001454      /* SQLITE_INTERRUPT   */ "interrupted",
001455      /* SQLITE_IOERR       */ "disk I/O error",
001456      /* SQLITE_CORRUPT     */ "database disk image is malformed",
001457      /* SQLITE_NOTFOUND    */ "unknown operation",
001458      /* SQLITE_FULL        */ "database or disk is full",
001459      /* SQLITE_CANTOPEN    */ "unable to open database file",
001460      /* SQLITE_PROTOCOL    */ "locking protocol",
001461      /* SQLITE_EMPTY       */ 0,
001462      /* SQLITE_SCHEMA      */ "database schema has changed",
001463      /* SQLITE_TOOBIG      */ "string or blob too big",
001464      /* SQLITE_CONSTRAINT  */ "constraint failed",
001465      /* SQLITE_MISMATCH    */ "datatype mismatch",
001466      /* SQLITE_MISUSE      */ "bad parameter or other API misuse",
001467  #ifdef SQLITE_DISABLE_LFS
001468      /* SQLITE_NOLFS       */ "large file support is disabled",
001469  #else
001470      /* SQLITE_NOLFS       */ 0,
001471  #endif
001472      /* SQLITE_AUTH        */ "authorization denied",
001473      /* SQLITE_FORMAT      */ 0,
001474      /* SQLITE_RANGE       */ "column index out of range",
001475      /* SQLITE_NOTADB      */ "file is not a database",
001476      /* SQLITE_NOTICE      */ "notification message",
001477      /* SQLITE_WARNING     */ "warning message",
001478    };
001479    const char *zErr = "unknown error";
001480    switch( rc ){
001481      case SQLITE_ABORT_ROLLBACK: {
001482        zErr = "abort due to ROLLBACK";
001483        break;
001484      }
001485      case SQLITE_ROW: {
001486        zErr = "another row available";
001487        break;
001488      }
001489      case SQLITE_DONE: {
001490        zErr = "no more rows available";
001491        break;
001492      }
001493      default: {
001494        rc &= 0xff;
001495        if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
001496          zErr = aMsg[rc];
001497        }
001498        break;
001499      }
001500    }
001501    return zErr;
001502  }
001503  
001504  /*
001505  ** This routine implements a busy callback that sleeps and tries
001506  ** again until a timeout value is reached.  The timeout value is
001507  ** an integer number of milliseconds passed in as the first
001508  ** argument.
001509  **
001510  ** Return non-zero to retry the lock.  Return zero to stop trying
001511  ** and cause SQLite to return SQLITE_BUSY.
001512  */
001513  static int sqliteDefaultBusyCallback(
001514    void *ptr,               /* Database connection */
001515    int count,               /* Number of times table has been busy */
001516    sqlite3_file *pFile      /* The file on which the lock occurred */
001517  ){
001518  #if SQLITE_OS_WIN || HAVE_USLEEP
001519    /* This case is for systems that have support for sleeping for fractions of
001520    ** a second.  Examples:  All windows systems, unix systems with usleep() */
001521    static const u8 delays[] =
001522       { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
001523    static const u8 totals[] =
001524       { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
001525  # define NDELAY ArraySize(delays)
001526    sqlite3 *db = (sqlite3 *)ptr;
001527    int tmout = db->busyTimeout;
001528    int delay, prior;
001529  
001530  #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
001531    if( sqlite3OsFileControl(pFile,SQLITE_FCNTL_LOCK_TIMEOUT,&tmout)==SQLITE_OK ){
001532      if( count ){
001533        tmout = 0;
001534        sqlite3OsFileControl(pFile, SQLITE_FCNTL_LOCK_TIMEOUT, &tmout);
001535        return 0;
001536      }else{
001537        return 1;
001538      }
001539    }
001540  #else
001541    UNUSED_PARAMETER(pFile);
001542  #endif
001543    assert( count>=0 );
001544    if( count < NDELAY ){
001545      delay = delays[count];
001546      prior = totals[count];
001547    }else{
001548      delay = delays[NDELAY-1];
001549      prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
001550    }
001551    if( prior + delay > tmout ){
001552      delay = tmout - prior;
001553      if( delay<=0 ) return 0;
001554    }
001555    sqlite3OsSleep(db->pVfs, delay*1000);
001556    return 1;
001557  #else
001558    /* This case for unix systems that lack usleep() support.  Sleeping
001559    ** must be done in increments of whole seconds */
001560    sqlite3 *db = (sqlite3 *)ptr;
001561    int tmout = ((sqlite3 *)ptr)->busyTimeout;
001562    UNUSED_PARAMETER(pFile);
001563    if( (count+1)*1000 > tmout ){
001564      return 0;
001565    }
001566    sqlite3OsSleep(db->pVfs, 1000000);
001567    return 1;
001568  #endif
001569  }
001570  
001571  /*
001572  ** Invoke the given busy handler.
001573  **
001574  ** This routine is called when an operation failed to acquire a
001575  ** lock on VFS file pFile.
001576  **
001577  ** If this routine returns non-zero, the lock is retried.  If it
001578  ** returns 0, the operation aborts with an SQLITE_BUSY error.
001579  */
001580  int sqlite3InvokeBusyHandler(BusyHandler *p, sqlite3_file *pFile){
001581    int rc;
001582    if( p->xBusyHandler==0 || p->nBusy<0 ) return 0;
001583    if( p->bExtraFileArg ){
001584      /* Add an extra parameter with the pFile pointer to the end of the
001585      ** callback argument list */
001586      int (*xTra)(void*,int,sqlite3_file*);
001587      xTra = (int(*)(void*,int,sqlite3_file*))p->xBusyHandler;
001588      rc = xTra(p->pBusyArg, p->nBusy, pFile);
001589    }else{
001590      /* Legacy style busy handler callback */
001591      rc = p->xBusyHandler(p->pBusyArg, p->nBusy);
001592    }
001593    if( rc==0 ){
001594      p->nBusy = -1;
001595    }else{
001596      p->nBusy++;
001597    }
001598    return rc; 
001599  }
001600  
001601  /*
001602  ** This routine sets the busy callback for an Sqlite database to the
001603  ** given callback function with the given argument.
001604  */
001605  int sqlite3_busy_handler(
001606    sqlite3 *db,
001607    int (*xBusy)(void*,int),
001608    void *pArg
001609  ){
001610  #ifdef SQLITE_ENABLE_API_ARMOR
001611    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
001612  #endif
001613    sqlite3_mutex_enter(db->mutex);
001614    db->busyHandler.xBusyHandler = xBusy;
001615    db->busyHandler.pBusyArg = pArg;
001616    db->busyHandler.nBusy = 0;
001617    db->busyHandler.bExtraFileArg = 0;
001618    db->busyTimeout = 0;
001619    sqlite3_mutex_leave(db->mutex);
001620    return SQLITE_OK;
001621  }
001622  
001623  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
001624  /*
001625  ** This routine sets the progress callback for an Sqlite database to the
001626  ** given callback function with the given argument. The progress callback will
001627  ** be invoked every nOps opcodes.
001628  */
001629  void sqlite3_progress_handler(
001630    sqlite3 *db, 
001631    int nOps,
001632    int (*xProgress)(void*), 
001633    void *pArg
001634  ){
001635  #ifdef SQLITE_ENABLE_API_ARMOR
001636    if( !sqlite3SafetyCheckOk(db) ){
001637      (void)SQLITE_MISUSE_BKPT;
001638      return;
001639    }
001640  #endif
001641    sqlite3_mutex_enter(db->mutex);
001642    if( nOps>0 ){
001643      db->xProgress = xProgress;
001644      db->nProgressOps = (unsigned)nOps;
001645      db->pProgressArg = pArg;
001646    }else{
001647      db->xProgress = 0;
001648      db->nProgressOps = 0;
001649      db->pProgressArg = 0;
001650    }
001651    sqlite3_mutex_leave(db->mutex);
001652  }
001653  #endif
001654  
001655  
001656  /*
001657  ** This routine installs a default busy handler that waits for the
001658  ** specified number of milliseconds before returning 0.
001659  */
001660  int sqlite3_busy_timeout(sqlite3 *db, int ms){
001661  #ifdef SQLITE_ENABLE_API_ARMOR
001662    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
001663  #endif
001664    if( ms>0 ){
001665      sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
001666                               (void*)db);
001667      db->busyTimeout = ms;
001668      db->busyHandler.bExtraFileArg = 1;
001669    }else{
001670      sqlite3_busy_handler(db, 0, 0);
001671    }
001672    return SQLITE_OK;
001673  }
001674  
001675  /*
001676  ** Cause any pending operation to stop at its earliest opportunity.
001677  */
001678  void sqlite3_interrupt(sqlite3 *db){
001679  #ifdef SQLITE_ENABLE_API_ARMOR
001680    if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){
001681      (void)SQLITE_MISUSE_BKPT;
001682      return;
001683    }
001684  #endif
001685    db->u1.isInterrupted = 1;
001686  }
001687  
001688  
001689  /*
001690  ** This function is exactly the same as sqlite3_create_function(), except
001691  ** that it is designed to be called by internal code. The difference is
001692  ** that if a malloc() fails in sqlite3_create_function(), an error code
001693  ** is returned and the mallocFailed flag cleared. 
001694  */
001695  int sqlite3CreateFunc(
001696    sqlite3 *db,
001697    const char *zFunctionName,
001698    int nArg,
001699    int enc,
001700    void *pUserData,
001701    void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
001702    void (*xStep)(sqlite3_context*,int,sqlite3_value **),
001703    void (*xFinal)(sqlite3_context*),
001704    void (*xValue)(sqlite3_context*),
001705    void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
001706    FuncDestructor *pDestructor
001707  ){
001708    FuncDef *p;
001709    int nName;
001710    int extraFlags;
001711  
001712    assert( sqlite3_mutex_held(db->mutex) );
001713    assert( xValue==0 || xSFunc==0 );
001714    if( zFunctionName==0                /* Must have a valid name */
001715     || (xSFunc!=0 && xFinal!=0)        /* Not both xSFunc and xFinal */
001716     || ((xFinal==0)!=(xStep==0))       /* Both or neither of xFinal and xStep */
001717     || ((xValue==0)!=(xInverse==0))    /* Both or neither of xValue, xInverse */
001718     || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG)
001719     || (255<(nName = sqlite3Strlen30( zFunctionName)))
001720    ){
001721      return SQLITE_MISUSE_BKPT;
001722    }
001723  
001724    assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
001725    extraFlags = enc &  SQLITE_DETERMINISTIC;
001726    enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
001727    
001728  #ifndef SQLITE_OMIT_UTF16
001729    /* If SQLITE_UTF16 is specified as the encoding type, transform this
001730    ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
001731    ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
001732    **
001733    ** If SQLITE_ANY is specified, add three versions of the function
001734    ** to the hash table.
001735    */
001736    if( enc==SQLITE_UTF16 ){
001737      enc = SQLITE_UTF16NATIVE;
001738    }else if( enc==SQLITE_ANY ){
001739      int rc;
001740      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
001741           pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
001742      if( rc==SQLITE_OK ){
001743        rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
001744            pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
001745      }
001746      if( rc!=SQLITE_OK ){
001747        return rc;
001748      }
001749      enc = SQLITE_UTF16BE;
001750    }
001751  #else
001752    enc = SQLITE_UTF8;
001753  #endif
001754    
001755    /* Check if an existing function is being overridden or deleted. If so,
001756    ** and there are active VMs, then return SQLITE_BUSY. If a function
001757    ** is being overridden/deleted but there are no active VMs, allow the
001758    ** operation to continue but invalidate all precompiled statements.
001759    */
001760    p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
001761    if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){
001762      if( db->nVdbeActive ){
001763        sqlite3ErrorWithMsg(db, SQLITE_BUSY, 
001764          "unable to delete/modify user-function due to active statements");
001765        assert( !db->mallocFailed );
001766        return SQLITE_BUSY;
001767      }else{
001768        sqlite3ExpirePreparedStatements(db, 0);
001769      }
001770    }
001771  
001772    p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
001773    assert(p || db->mallocFailed);
001774    if( !p ){
001775      return SQLITE_NOMEM_BKPT;
001776    }
001777  
001778    /* If an older version of the function with a configured destructor is
001779    ** being replaced invoke the destructor function here. */
001780    functionDestroy(db, p);
001781  
001782    if( pDestructor ){
001783      pDestructor->nRef++;
001784    }
001785    p->u.pDestructor = pDestructor;
001786    p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
001787    testcase( p->funcFlags & SQLITE_DETERMINISTIC );
001788    p->xSFunc = xSFunc ? xSFunc : xStep;
001789    p->xFinalize = xFinal;
001790    p->xValue = xValue;
001791    p->xInverse = xInverse;
001792    p->pUserData = pUserData;
001793    p->nArg = (u16)nArg;
001794    return SQLITE_OK;
001795  }
001796  
001797  /*
001798  ** Worker function used by utf-8 APIs that create new functions:
001799  **
001800  **    sqlite3_create_function()
001801  **    sqlite3_create_function_v2()
001802  **    sqlite3_create_window_function()
001803  */
001804  static int createFunctionApi(
001805    sqlite3 *db,
001806    const char *zFunc,
001807    int nArg,
001808    int enc,
001809    void *p,
001810    void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
001811    void (*xStep)(sqlite3_context*,int,sqlite3_value**),
001812    void (*xFinal)(sqlite3_context*),
001813    void (*xValue)(sqlite3_context*),
001814    void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
001815    void(*xDestroy)(void*)
001816  ){
001817    int rc = SQLITE_ERROR;
001818    FuncDestructor *pArg = 0;
001819  
001820  #ifdef SQLITE_ENABLE_API_ARMOR
001821    if( !sqlite3SafetyCheckOk(db) ){
001822      return SQLITE_MISUSE_BKPT;
001823    }
001824  #endif
001825    sqlite3_mutex_enter(db->mutex);
001826    if( xDestroy ){
001827      pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor));
001828      if( !pArg ){
001829        sqlite3OomFault(db);
001830        xDestroy(p);
001831        goto out;
001832      }
001833      pArg->nRef = 0;
001834      pArg->xDestroy = xDestroy;
001835      pArg->pUserData = p;
001836    }
001837    rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, 
001838        xSFunc, xStep, xFinal, xValue, xInverse, pArg
001839    );
001840    if( pArg && pArg->nRef==0 ){
001841      assert( rc!=SQLITE_OK );
001842      xDestroy(p);
001843      sqlite3_free(pArg);
001844    }
001845  
001846   out:
001847    rc = sqlite3ApiExit(db, rc);
001848    sqlite3_mutex_leave(db->mutex);
001849    return rc;
001850  }
001851  
001852  /*
001853  ** Create new user functions.
001854  */
001855  int sqlite3_create_function(
001856    sqlite3 *db,
001857    const char *zFunc,
001858    int nArg,
001859    int enc,
001860    void *p,
001861    void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
001862    void (*xStep)(sqlite3_context*,int,sqlite3_value **),
001863    void (*xFinal)(sqlite3_context*)
001864  ){
001865    return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
001866                                      xFinal, 0, 0, 0);
001867  }
001868  int sqlite3_create_function_v2(
001869    sqlite3 *db,
001870    const char *zFunc,
001871    int nArg,
001872    int enc,
001873    void *p,
001874    void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
001875    void (*xStep)(sqlite3_context*,int,sqlite3_value **),
001876    void (*xFinal)(sqlite3_context*),
001877    void (*xDestroy)(void *)
001878  ){
001879    return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
001880                                      xFinal, 0, 0, xDestroy);
001881  }
001882  int sqlite3_create_window_function(
001883    sqlite3 *db,
001884    const char *zFunc,
001885    int nArg,
001886    int enc,
001887    void *p,
001888    void (*xStep)(sqlite3_context*,int,sqlite3_value **),
001889    void (*xFinal)(sqlite3_context*),
001890    void (*xValue)(sqlite3_context*),
001891    void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
001892    void (*xDestroy)(void *)
001893  ){
001894    return createFunctionApi(db, zFunc, nArg, enc, p, 0, xStep,
001895                                      xFinal, xValue, xInverse, xDestroy);
001896  }
001897  
001898  #ifndef SQLITE_OMIT_UTF16
001899  int sqlite3_create_function16(
001900    sqlite3 *db,
001901    const void *zFunctionName,
001902    int nArg,
001903    int eTextRep,
001904    void *p,
001905    void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
001906    void (*xStep)(sqlite3_context*,int,sqlite3_value**),
001907    void (*xFinal)(sqlite3_context*)
001908  ){
001909    int rc;
001910    char *zFunc8;
001911  
001912  #ifdef SQLITE_ENABLE_API_ARMOR
001913    if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
001914  #endif
001915    sqlite3_mutex_enter(db->mutex);
001916    assert( !db->mallocFailed );
001917    zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
001918    rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0,0,0);
001919    sqlite3DbFree(db, zFunc8);
001920    rc = sqlite3ApiExit(db, rc);
001921    sqlite3_mutex_leave(db->mutex);
001922    return rc;
001923  }
001924  #endif
001925  
001926  
001927  /*
001928  ** The following is the implementation of an SQL function that always
001929  ** fails with an error message stating that the function is used in the
001930  ** wrong context.  The sqlite3_overload_function() API might construct
001931  ** SQL function that use this routine so that the functions will exist
001932  ** for name resolution but are actually overloaded by the xFindFunction
001933  ** method of virtual tables.
001934  */
001935  static void sqlite3InvalidFunction(
001936    sqlite3_context *context,  /* The function calling context */
001937    int NotUsed,               /* Number of arguments to the function */
001938    sqlite3_value **NotUsed2   /* Value of each argument */
001939  ){
001940    const char *zName = (const char*)sqlite3_user_data(context);
001941    char *zErr;
001942    UNUSED_PARAMETER2(NotUsed, NotUsed2);
001943    zErr = sqlite3_mprintf(
001944        "unable to use function %s in the requested context", zName);
001945    sqlite3_result_error(context, zErr, -1);
001946    sqlite3_free(zErr);
001947  }
001948  
001949  /*
001950  ** Declare that a function has been overloaded by a virtual table.
001951  **
001952  ** If the function already exists as a regular global function, then
001953  ** this routine is a no-op.  If the function does not exist, then create
001954  ** a new one that always throws a run-time error.  
001955  **
001956  ** When virtual tables intend to provide an overloaded function, they
001957  ** should call this routine to make sure the global function exists.
001958  ** A global function must exist in order for name resolution to work
001959  ** properly.
001960  */
001961  int sqlite3_overload_function(
001962    sqlite3 *db,
001963    const char *zName,
001964    int nArg
001965  ){
001966    int rc;
001967    char *zCopy;
001968  
001969  #ifdef SQLITE_ENABLE_API_ARMOR
001970    if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
001971      return SQLITE_MISUSE_BKPT;
001972    }
001973  #endif
001974    sqlite3_mutex_enter(db->mutex);
001975    rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0;
001976    sqlite3_mutex_leave(db->mutex);
001977    if( rc ) return SQLITE_OK;
001978    zCopy = sqlite3_mprintf(zName);
001979    if( zCopy==0 ) return SQLITE_NOMEM;
001980    return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8,
001981                             zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free);
001982  }
001983  
001984  #ifndef SQLITE_OMIT_TRACE
001985  /*
001986  ** Register a trace function.  The pArg from the previously registered trace
001987  ** is returned.  
001988  **
001989  ** A NULL trace function means that no tracing is executes.  A non-NULL
001990  ** trace is a pointer to a function that is invoked at the start of each
001991  ** SQL statement.
001992  */
001993  #ifndef SQLITE_OMIT_DEPRECATED
001994  void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
001995    void *pOld;
001996  
001997  #ifdef SQLITE_ENABLE_API_ARMOR
001998    if( !sqlite3SafetyCheckOk(db) ){
001999      (void)SQLITE_MISUSE_BKPT;
002000      return 0;
002001    }
002002  #endif
002003    sqlite3_mutex_enter(db->mutex);
002004    pOld = db->pTraceArg;
002005    db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
002006    db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
002007    db->pTraceArg = pArg;
002008    sqlite3_mutex_leave(db->mutex);
002009    return pOld;
002010  }
002011  #endif /* SQLITE_OMIT_DEPRECATED */
002012  
002013  /* Register a trace callback using the version-2 interface.
002014  */
002015  int sqlite3_trace_v2(
002016    sqlite3 *db,                               /* Trace this connection */
002017    unsigned mTrace,                           /* Mask of events to be traced */
002018    int(*xTrace)(unsigned,void*,void*,void*),  /* Callback to invoke */
002019    void *pArg                                 /* Context */
002020  ){
002021  #ifdef SQLITE_ENABLE_API_ARMOR
002022    if( !sqlite3SafetyCheckOk(db) ){
002023      return SQLITE_MISUSE_BKPT;
002024    }
002025  #endif
002026    sqlite3_mutex_enter(db->mutex);
002027    if( mTrace==0 ) xTrace = 0;
002028    if( xTrace==0 ) mTrace = 0;
002029    db->mTrace = mTrace;
002030    db->xTrace = xTrace;
002031    db->pTraceArg = pArg;
002032    sqlite3_mutex_leave(db->mutex);
002033    return SQLITE_OK;
002034  }
002035  
002036  #ifndef SQLITE_OMIT_DEPRECATED
002037  /*
002038  ** Register a profile function.  The pArg from the previously registered 
002039  ** profile function is returned.  
002040  **
002041  ** A NULL profile function means that no profiling is executes.  A non-NULL
002042  ** profile is a pointer to a function that is invoked at the conclusion of
002043  ** each SQL statement that is run.
002044  */
002045  void *sqlite3_profile(
002046    sqlite3 *db,
002047    void (*xProfile)(void*,const char*,sqlite_uint64),
002048    void *pArg
002049  ){
002050    void *pOld;
002051  
002052  #ifdef SQLITE_ENABLE_API_ARMOR
002053    if( !sqlite3SafetyCheckOk(db) ){
002054      (void)SQLITE_MISUSE_BKPT;
002055      return 0;
002056    }
002057  #endif
002058    sqlite3_mutex_enter(db->mutex);
002059    pOld = db->pProfileArg;
002060    db->xProfile = xProfile;
002061    db->pProfileArg = pArg;
002062    db->mTrace &= SQLITE_TRACE_NONLEGACY_MASK;
002063    if( db->xProfile ) db->mTrace |= SQLITE_TRACE_XPROFILE;
002064    sqlite3_mutex_leave(db->mutex);
002065    return pOld;
002066  }
002067  #endif /* SQLITE_OMIT_DEPRECATED */
002068  #endif /* SQLITE_OMIT_TRACE */
002069  
002070  /*
002071  ** Register a function to be invoked when a transaction commits.
002072  ** If the invoked function returns non-zero, then the commit becomes a
002073  ** rollback.
002074  */
002075  void *sqlite3_commit_hook(
002076    sqlite3 *db,              /* Attach the hook to this database */
002077    int (*xCallback)(void*),  /* Function to invoke on each commit */
002078    void *pArg                /* Argument to the function */
002079  ){
002080    void *pOld;
002081  
002082  #ifdef SQLITE_ENABLE_API_ARMOR
002083    if( !sqlite3SafetyCheckOk(db) ){
002084      (void)SQLITE_MISUSE_BKPT;
002085      return 0;
002086    }
002087  #endif
002088    sqlite3_mutex_enter(db->mutex);
002089    pOld = db->pCommitArg;
002090    db->xCommitCallback = xCallback;
002091    db->pCommitArg = pArg;
002092    sqlite3_mutex_leave(db->mutex);
002093    return pOld;
002094  }
002095  
002096  /*
002097  ** Register a callback to be invoked each time a row is updated,
002098  ** inserted or deleted using this database connection.
002099  */
002100  void *sqlite3_update_hook(
002101    sqlite3 *db,              /* Attach the hook to this database */
002102    void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
002103    void *pArg                /* Argument to the function */
002104  ){
002105    void *pRet;
002106  
002107  #ifdef SQLITE_ENABLE_API_ARMOR
002108    if( !sqlite3SafetyCheckOk(db) ){
002109      (void)SQLITE_MISUSE_BKPT;
002110      return 0;
002111    }
002112  #endif
002113    sqlite3_mutex_enter(db->mutex);
002114    pRet = db->pUpdateArg;
002115    db->xUpdateCallback = xCallback;
002116    db->pUpdateArg = pArg;
002117    sqlite3_mutex_leave(db->mutex);
002118    return pRet;
002119  }
002120  
002121  /*
002122  ** Register a callback to be invoked each time a transaction is rolled
002123  ** back by this database connection.
002124  */
002125  void *sqlite3_rollback_hook(
002126    sqlite3 *db,              /* Attach the hook to this database */
002127    void (*xCallback)(void*), /* Callback function */
002128    void *pArg                /* Argument to the function */
002129  ){
002130    void *pRet;
002131  
002132  #ifdef SQLITE_ENABLE_API_ARMOR
002133    if( !sqlite3SafetyCheckOk(db) ){
002134      (void)SQLITE_MISUSE_BKPT;
002135      return 0;
002136    }
002137  #endif
002138    sqlite3_mutex_enter(db->mutex);
002139    pRet = db->pRollbackArg;
002140    db->xRollbackCallback = xCallback;
002141    db->pRollbackArg = pArg;
002142    sqlite3_mutex_leave(db->mutex);
002143    return pRet;
002144  }
002145  
002146  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
002147  /*
002148  ** Register a callback to be invoked each time a row is updated,
002149  ** inserted or deleted using this database connection.
002150  */
002151  void *sqlite3_preupdate_hook(
002152    sqlite3 *db,              /* Attach the hook to this database */
002153    void(*xCallback)(         /* Callback function */
002154      void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
002155    void *pArg                /* First callback argument */
002156  ){
002157    void *pRet;
002158    sqlite3_mutex_enter(db->mutex);
002159    pRet = db->pPreUpdateArg;
002160    db->xPreUpdateCallback = xCallback;
002161    db->pPreUpdateArg = pArg;
002162    sqlite3_mutex_leave(db->mutex);
002163    return pRet;
002164  }
002165  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
002166  
002167  #ifndef SQLITE_OMIT_WAL
002168  /*
002169  ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
002170  ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
002171  ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
002172  ** wal_autocheckpoint()).
002173  */ 
002174  int sqlite3WalDefaultHook(
002175    void *pClientData,     /* Argument */
002176    sqlite3 *db,           /* Connection */
002177    const char *zDb,       /* Database */
002178    int nFrame             /* Size of WAL */
002179  ){
002180    if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
002181      sqlite3BeginBenignMalloc();
002182      sqlite3_wal_checkpoint(db, zDb);
002183      sqlite3EndBenignMalloc();
002184    }
002185    return SQLITE_OK;
002186  }
002187  #endif /* SQLITE_OMIT_WAL */
002188  
002189  /*
002190  ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
002191  ** a database after committing a transaction if there are nFrame or
002192  ** more frames in the log file. Passing zero or a negative value as the
002193  ** nFrame parameter disables automatic checkpoints entirely.
002194  **
002195  ** The callback registered by this function replaces any existing callback
002196  ** registered using sqlite3_wal_hook(). Likewise, registering a callback
002197  ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
002198  ** configured by this function.
002199  */
002200  int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
002201  #ifdef SQLITE_OMIT_WAL
002202    UNUSED_PARAMETER(db);
002203    UNUSED_PARAMETER(nFrame);
002204  #else
002205  #ifdef SQLITE_ENABLE_API_ARMOR
002206    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
002207  #endif
002208    if( nFrame>0 ){
002209      sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
002210    }else{
002211      sqlite3_wal_hook(db, 0, 0);
002212    }
002213  #endif
002214    return SQLITE_OK;
002215  }
002216  
002217  /*
002218  ** Register a callback to be invoked each time a transaction is written
002219  ** into the write-ahead-log by this database connection.
002220  */
002221  void *sqlite3_wal_hook(
002222    sqlite3 *db,                    /* Attach the hook to this db handle */
002223    int(*xCallback)(void *, sqlite3*, const char*, int),
002224    void *pArg                      /* First argument passed to xCallback() */
002225  ){
002226  #ifndef SQLITE_OMIT_WAL
002227    void *pRet;
002228  #ifdef SQLITE_ENABLE_API_ARMOR
002229    if( !sqlite3SafetyCheckOk(db) ){
002230      (void)SQLITE_MISUSE_BKPT;
002231      return 0;
002232    }
002233  #endif
002234    sqlite3_mutex_enter(db->mutex);
002235    pRet = db->pWalArg;
002236    db->xWalCallback = xCallback;
002237    db->pWalArg = pArg;
002238    sqlite3_mutex_leave(db->mutex);
002239    return pRet;
002240  #else
002241    return 0;
002242  #endif
002243  }
002244  
002245  /*
002246  ** Checkpoint database zDb.
002247  */
002248  int sqlite3_wal_checkpoint_v2(
002249    sqlite3 *db,                    /* Database handle */
002250    const char *zDb,                /* Name of attached database (or NULL) */
002251    int eMode,                      /* SQLITE_CHECKPOINT_* value */
002252    int *pnLog,                     /* OUT: Size of WAL log in frames */
002253    int *pnCkpt                     /* OUT: Total number of frames checkpointed */
002254  ){
002255  #ifdef SQLITE_OMIT_WAL
002256    return SQLITE_OK;
002257  #else
002258    int rc;                         /* Return code */
002259    int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
002260  
002261  #ifdef SQLITE_ENABLE_API_ARMOR
002262    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
002263  #endif
002264  
002265    /* Initialize the output variables to -1 in case an error occurs. */
002266    if( pnLog ) *pnLog = -1;
002267    if( pnCkpt ) *pnCkpt = -1;
002268  
002269    assert( SQLITE_CHECKPOINT_PASSIVE==0 );
002270    assert( SQLITE_CHECKPOINT_FULL==1 );
002271    assert( SQLITE_CHECKPOINT_RESTART==2 );
002272    assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
002273    if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
002274      /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
002275      ** mode: */
002276      return SQLITE_MISUSE;
002277    }
002278  
002279    sqlite3_mutex_enter(db->mutex);
002280    if( zDb && zDb[0] ){
002281      iDb = sqlite3FindDbName(db, zDb);
002282    }
002283    if( iDb<0 ){
002284      rc = SQLITE_ERROR;
002285      sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
002286    }else{
002287      db->busyHandler.nBusy = 0;
002288      rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
002289      sqlite3Error(db, rc);
002290    }
002291    rc = sqlite3ApiExit(db, rc);
002292  
002293    /* If there are no active statements, clear the interrupt flag at this
002294    ** point.  */
002295    if( db->nVdbeActive==0 ){
002296      db->u1.isInterrupted = 0;
002297    }
002298  
002299    sqlite3_mutex_leave(db->mutex);
002300    return rc;
002301  #endif
002302  }
002303  
002304  
002305  /*
002306  ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
002307  ** to contains a zero-length string, all attached databases are 
002308  ** checkpointed.
002309  */
002310  int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
002311    /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
002312    ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
002313    return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
002314  }
002315  
002316  #ifndef SQLITE_OMIT_WAL
002317  /*
002318  ** Run a checkpoint on database iDb. This is a no-op if database iDb is
002319  ** not currently open in WAL mode.
002320  **
002321  ** If a transaction is open on the database being checkpointed, this 
002322  ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
002323  ** an error occurs while running the checkpoint, an SQLite error code is 
002324  ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
002325  **
002326  ** The mutex on database handle db should be held by the caller. The mutex
002327  ** associated with the specific b-tree being checkpointed is taken by
002328  ** this function while the checkpoint is running.
002329  **
002330  ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
002331  ** checkpointed. If an error is encountered it is returned immediately -
002332  ** no attempt is made to checkpoint any remaining databases.
002333  **
002334  ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
002335  ** or TRUNCATE.
002336  */
002337  int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
002338    int rc = SQLITE_OK;             /* Return code */
002339    int i;                          /* Used to iterate through attached dbs */
002340    int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
002341  
002342    assert( sqlite3_mutex_held(db->mutex) );
002343    assert( !pnLog || *pnLog==-1 );
002344    assert( !pnCkpt || *pnCkpt==-1 );
002345  
002346    for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
002347      if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
002348        rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
002349        pnLog = 0;
002350        pnCkpt = 0;
002351        if( rc==SQLITE_BUSY ){
002352          bBusy = 1;
002353          rc = SQLITE_OK;
002354        }
002355      }
002356    }
002357  
002358    return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
002359  }
002360  #endif /* SQLITE_OMIT_WAL */
002361  
002362  /*
002363  ** This function returns true if main-memory should be used instead of
002364  ** a temporary file for transient pager files and statement journals.
002365  ** The value returned depends on the value of db->temp_store (runtime
002366  ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
002367  ** following table describes the relationship between these two values
002368  ** and this functions return value.
002369  **
002370  **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
002371  **   -----------------     --------------     ------------------------------
002372  **   0                     any                file      (return 0)
002373  **   1                     1                  file      (return 0)
002374  **   1                     2                  memory    (return 1)
002375  **   1                     0                  file      (return 0)
002376  **   2                     1                  file      (return 0)
002377  **   2                     2                  memory    (return 1)
002378  **   2                     0                  memory    (return 1)
002379  **   3                     any                memory    (return 1)
002380  */
002381  int sqlite3TempInMemory(const sqlite3 *db){
002382  #if SQLITE_TEMP_STORE==1
002383    return ( db->temp_store==2 );
002384  #endif
002385  #if SQLITE_TEMP_STORE==2
002386    return ( db->temp_store!=1 );
002387  #endif
002388  #if SQLITE_TEMP_STORE==3
002389    UNUSED_PARAMETER(db);
002390    return 1;
002391  #endif
002392  #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
002393    UNUSED_PARAMETER(db);
002394    return 0;
002395  #endif
002396  }
002397  
002398  /*
002399  ** Return UTF-8 encoded English language explanation of the most recent
002400  ** error.
002401  */
002402  const char *sqlite3_errmsg(sqlite3 *db){
002403    const char *z;
002404    if( !db ){
002405      return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
002406    }
002407    if( !sqlite3SafetyCheckSickOrOk(db) ){
002408      return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
002409    }
002410    sqlite3_mutex_enter(db->mutex);
002411    if( db->mallocFailed ){
002412      z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
002413    }else{
002414      testcase( db->pErr==0 );
002415      z = db->errCode ? (char*)sqlite3_value_text(db->pErr) : 0;
002416      assert( !db->mallocFailed );
002417      if( z==0 ){
002418        z = sqlite3ErrStr(db->errCode);
002419      }
002420    }
002421    sqlite3_mutex_leave(db->mutex);
002422    return z;
002423  }
002424  
002425  #ifndef SQLITE_OMIT_UTF16
002426  /*
002427  ** Return UTF-16 encoded English language explanation of the most recent
002428  ** error.
002429  */
002430  const void *sqlite3_errmsg16(sqlite3 *db){
002431    static const u16 outOfMem[] = {
002432      'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
002433    };
002434    static const u16 misuse[] = {
002435      'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
002436      'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
002437      'm', 'i', 's', 'u', 's', 'e', 0
002438    };
002439  
002440    const void *z;
002441    if( !db ){
002442      return (void *)outOfMem;
002443    }
002444    if( !sqlite3SafetyCheckSickOrOk(db) ){
002445      return (void *)misuse;
002446    }
002447    sqlite3_mutex_enter(db->mutex);
002448    if( db->mallocFailed ){
002449      z = (void *)outOfMem;
002450    }else{
002451      z = sqlite3_value_text16(db->pErr);
002452      if( z==0 ){
002453        sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
002454        z = sqlite3_value_text16(db->pErr);
002455      }
002456      /* A malloc() may have failed within the call to sqlite3_value_text16()
002457      ** above. If this is the case, then the db->mallocFailed flag needs to
002458      ** be cleared before returning. Do this directly, instead of via
002459      ** sqlite3ApiExit(), to avoid setting the database handle error message.
002460      */
002461      sqlite3OomClear(db);
002462    }
002463    sqlite3_mutex_leave(db->mutex);
002464    return z;
002465  }
002466  #endif /* SQLITE_OMIT_UTF16 */
002467  
002468  /*
002469  ** Return the most recent error code generated by an SQLite routine. If NULL is
002470  ** passed to this function, we assume a malloc() failed during sqlite3_open().
002471  */
002472  int sqlite3_errcode(sqlite3 *db){
002473    if( db && !sqlite3SafetyCheckSickOrOk(db) ){
002474      return SQLITE_MISUSE_BKPT;
002475    }
002476    if( !db || db->mallocFailed ){
002477      return SQLITE_NOMEM_BKPT;
002478    }
002479    return db->errCode & db->errMask;
002480  }
002481  int sqlite3_extended_errcode(sqlite3 *db){
002482    if( db && !sqlite3SafetyCheckSickOrOk(db) ){
002483      return SQLITE_MISUSE_BKPT;
002484    }
002485    if( !db || db->mallocFailed ){
002486      return SQLITE_NOMEM_BKPT;
002487    }
002488    return db->errCode;
002489  }
002490  int sqlite3_system_errno(sqlite3 *db){
002491    return db ? db->iSysErrno : 0;
002492  }  
002493  
002494  /*
002495  ** Return a string that describes the kind of error specified in the
002496  ** argument.  For now, this simply calls the internal sqlite3ErrStr()
002497  ** function.
002498  */
002499  const char *sqlite3_errstr(int rc){
002500    return sqlite3ErrStr(rc);
002501  }
002502  
002503  /*
002504  ** Create a new collating function for database "db".  The name is zName
002505  ** and the encoding is enc.
002506  */
002507  static int createCollation(
002508    sqlite3* db,
002509    const char *zName, 
002510    u8 enc,
002511    void* pCtx,
002512    int(*xCompare)(void*,int,const void*,int,const void*),
002513    void(*xDel)(void*)
002514  ){
002515    CollSeq *pColl;
002516    int enc2;
002517    
002518    assert( sqlite3_mutex_held(db->mutex) );
002519  
002520    /* If SQLITE_UTF16 is specified as the encoding type, transform this
002521    ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
002522    ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
002523    */
002524    enc2 = enc;
002525    testcase( enc2==SQLITE_UTF16 );
002526    testcase( enc2==SQLITE_UTF16_ALIGNED );
002527    if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
002528      enc2 = SQLITE_UTF16NATIVE;
002529    }
002530    if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
002531      return SQLITE_MISUSE_BKPT;
002532    }
002533  
002534    /* Check if this call is removing or replacing an existing collation 
002535    ** sequence. If so, and there are active VMs, return busy. If there
002536    ** are no active VMs, invalidate any pre-compiled statements.
002537    */
002538    pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
002539    if( pColl && pColl->xCmp ){
002540      if( db->nVdbeActive ){
002541        sqlite3ErrorWithMsg(db, SQLITE_BUSY, 
002542          "unable to delete/modify collation sequence due to active statements");
002543        return SQLITE_BUSY;
002544      }
002545      sqlite3ExpirePreparedStatements(db, 0);
002546  
002547      /* If collation sequence pColl was created directly by a call to
002548      ** sqlite3_create_collation, and not generated by synthCollSeq(),
002549      ** then any copies made by synthCollSeq() need to be invalidated.
002550      ** Also, collation destructor - CollSeq.xDel() - function may need
002551      ** to be called.
002552      */ 
002553      if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
002554        CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
002555        int j;
002556        for(j=0; j<3; j++){
002557          CollSeq *p = &aColl[j];
002558          if( p->enc==pColl->enc ){
002559            if( p->xDel ){
002560              p->xDel(p->pUser);
002561            }
002562            p->xCmp = 0;
002563          }
002564        }
002565      }
002566    }
002567  
002568    pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
002569    if( pColl==0 ) return SQLITE_NOMEM_BKPT;
002570    pColl->xCmp = xCompare;
002571    pColl->pUser = pCtx;
002572    pColl->xDel = xDel;
002573    pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
002574    sqlite3Error(db, SQLITE_OK);
002575    return SQLITE_OK;
002576  }
002577  
002578  
002579  /*
002580  ** This array defines hard upper bounds on limit values.  The
002581  ** initializer must be kept in sync with the SQLITE_LIMIT_*
002582  ** #defines in sqlite3.h.
002583  */
002584  static const int aHardLimit[] = {
002585    SQLITE_MAX_LENGTH,
002586    SQLITE_MAX_SQL_LENGTH,
002587    SQLITE_MAX_COLUMN,
002588    SQLITE_MAX_EXPR_DEPTH,
002589    SQLITE_MAX_COMPOUND_SELECT,
002590    SQLITE_MAX_VDBE_OP,
002591    SQLITE_MAX_FUNCTION_ARG,
002592    SQLITE_MAX_ATTACHED,
002593    SQLITE_MAX_LIKE_PATTERN_LENGTH,
002594    SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
002595    SQLITE_MAX_TRIGGER_DEPTH,
002596    SQLITE_MAX_WORKER_THREADS,
002597  };
002598  
002599  /*
002600  ** Make sure the hard limits are set to reasonable values
002601  */
002602  #if SQLITE_MAX_LENGTH<100
002603  # error SQLITE_MAX_LENGTH must be at least 100
002604  #endif
002605  #if SQLITE_MAX_SQL_LENGTH<100
002606  # error SQLITE_MAX_SQL_LENGTH must be at least 100
002607  #endif
002608  #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
002609  # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
002610  #endif
002611  #if SQLITE_MAX_COMPOUND_SELECT<2
002612  # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
002613  #endif
002614  #if SQLITE_MAX_VDBE_OP<40
002615  # error SQLITE_MAX_VDBE_OP must be at least 40
002616  #endif
002617  #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
002618  # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
002619  #endif
002620  #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
002621  # error SQLITE_MAX_ATTACHED must be between 0 and 125
002622  #endif
002623  #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
002624  # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
002625  #endif
002626  #if SQLITE_MAX_COLUMN>32767
002627  # error SQLITE_MAX_COLUMN must not exceed 32767
002628  #endif
002629  #if SQLITE_MAX_TRIGGER_DEPTH<1
002630  # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
002631  #endif
002632  #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
002633  # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
002634  #endif
002635  
002636  
002637  /*
002638  ** Change the value of a limit.  Report the old value.
002639  ** If an invalid limit index is supplied, report -1.
002640  ** Make no changes but still report the old value if the
002641  ** new limit is negative.
002642  **
002643  ** A new lower limit does not shrink existing constructs.
002644  ** It merely prevents new constructs that exceed the limit
002645  ** from forming.
002646  */
002647  int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
002648    int oldLimit;
002649  
002650  #ifdef SQLITE_ENABLE_API_ARMOR
002651    if( !sqlite3SafetyCheckOk(db) ){
002652      (void)SQLITE_MISUSE_BKPT;
002653      return -1;
002654    }
002655  #endif
002656  
002657    /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
002658    ** there is a hard upper bound set at compile-time by a C preprocessor
002659    ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
002660    ** "_MAX_".)
002661    */
002662    assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
002663    assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
002664    assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
002665    assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
002666    assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
002667    assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
002668    assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
002669    assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
002670    assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
002671                                                 SQLITE_MAX_LIKE_PATTERN_LENGTH );
002672    assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
002673    assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
002674    assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
002675    assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
002676  
002677  
002678    if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
002679      return -1;
002680    }
002681    oldLimit = db->aLimit[limitId];
002682    if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
002683      if( newLimit>aHardLimit[limitId] ){
002684        newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
002685      }
002686      db->aLimit[limitId] = newLimit;
002687    }
002688    return oldLimit;                     /* IMP: R-53341-35419 */
002689  }
002690  
002691  /*
002692  ** This function is used to parse both URIs and non-URI filenames passed by the
002693  ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
002694  ** URIs specified as part of ATTACH statements.
002695  **
002696  ** The first argument to this function is the name of the VFS to use (or
002697  ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
002698  ** query parameter. The second argument contains the URI (or non-URI filename)
002699  ** itself. When this function is called the *pFlags variable should contain
002700  ** the default flags to open the database handle with. The value stored in
002701  ** *pFlags may be updated before returning if the URI filename contains 
002702  ** "cache=xxx" or "mode=xxx" query parameters.
002703  **
002704  ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
002705  ** the VFS that should be used to open the database file. *pzFile is set to
002706  ** point to a buffer containing the name of the file to open. It is the 
002707  ** responsibility of the caller to eventually call sqlite3_free() to release
002708  ** this buffer.
002709  **
002710  ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
002711  ** may be set to point to a buffer containing an English language error 
002712  ** message. It is the responsibility of the caller to eventually release
002713  ** this buffer by calling sqlite3_free().
002714  */
002715  int sqlite3ParseUri(
002716    const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
002717    const char *zUri,               /* Nul-terminated URI to parse */
002718    unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
002719    sqlite3_vfs **ppVfs,            /* OUT: VFS to use */ 
002720    char **pzFile,                  /* OUT: Filename component of URI */
002721    char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
002722  ){
002723    int rc = SQLITE_OK;
002724    unsigned int flags = *pFlags;
002725    const char *zVfs = zDefaultVfs;
002726    char *zFile;
002727    char c;
002728    int nUri = sqlite3Strlen30(zUri);
002729  
002730    assert( *pzErrMsg==0 );
002731  
002732    if( ((flags & SQLITE_OPEN_URI)             /* IMP: R-48725-32206 */
002733              || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
002734     && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
002735    ){
002736      char *zOpt;
002737      int eState;                   /* Parser state when parsing URI */
002738      int iIn;                      /* Input character index */
002739      int iOut = 0;                 /* Output character index */
002740      u64 nByte = nUri+2;           /* Bytes of space to allocate */
002741  
002742      /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen 
002743      ** method that there may be extra parameters following the file-name.  */
002744      flags |= SQLITE_OPEN_URI;
002745  
002746      for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
002747      zFile = sqlite3_malloc64(nByte);
002748      if( !zFile ) return SQLITE_NOMEM_BKPT;
002749  
002750      iIn = 5;
002751  #ifdef SQLITE_ALLOW_URI_AUTHORITY
002752      if( strncmp(zUri+5, "///", 3)==0 ){
002753        iIn = 7;
002754        /* The following condition causes URIs with five leading / characters
002755        ** like file://///host/path to be converted into UNCs like //host/path.
002756        ** The correct URI for that UNC has only two or four leading / characters
002757        ** file://host/path or file:////host/path.  But 5 leading slashes is a 
002758        ** common error, we are told, so we handle it as a special case. */
002759        if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
002760      }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
002761        iIn = 16;
002762      }
002763  #else
002764      /* Discard the scheme and authority segments of the URI. */
002765      if( zUri[5]=='/' && zUri[6]=='/' ){
002766        iIn = 7;
002767        while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
002768        if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
002769          *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", 
002770              iIn-7, &zUri[7]);
002771          rc = SQLITE_ERROR;
002772          goto parse_uri_out;
002773        }
002774      }
002775  #endif
002776  
002777      /* Copy the filename and any query parameters into the zFile buffer. 
002778      ** Decode %HH escape codes along the way. 
002779      **
002780      ** Within this loop, variable eState may be set to 0, 1 or 2, depending
002781      ** on the parsing context. As follows:
002782      **
002783      **   0: Parsing file-name.
002784      **   1: Parsing name section of a name=value query parameter.
002785      **   2: Parsing value section of a name=value query parameter.
002786      */
002787      eState = 0;
002788      while( (c = zUri[iIn])!=0 && c!='#' ){
002789        iIn++;
002790        if( c=='%' 
002791         && sqlite3Isxdigit(zUri[iIn]) 
002792         && sqlite3Isxdigit(zUri[iIn+1]) 
002793        ){
002794          int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
002795          octet += sqlite3HexToInt(zUri[iIn++]);
002796  
002797          assert( octet>=0 && octet<256 );
002798          if( octet==0 ){
002799  #ifndef SQLITE_ENABLE_URI_00_ERROR
002800            /* This branch is taken when "%00" appears within the URI. In this
002801            ** case we ignore all text in the remainder of the path, name or
002802            ** value currently being parsed. So ignore the current character
002803            ** and skip to the next "?", "=" or "&", as appropriate. */
002804            while( (c = zUri[iIn])!=0 && c!='#' 
002805                && (eState!=0 || c!='?')
002806                && (eState!=1 || (c!='=' && c!='&'))
002807                && (eState!=2 || c!='&')
002808            ){
002809              iIn++;
002810            }
002811            continue;
002812  #else
002813            /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
002814            *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
002815            rc = SQLITE_ERROR;
002816            goto parse_uri_out;
002817  #endif
002818          }
002819          c = octet;
002820        }else if( eState==1 && (c=='&' || c=='=') ){
002821          if( zFile[iOut-1]==0 ){
002822            /* An empty option name. Ignore this option altogether. */
002823            while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
002824            continue;
002825          }
002826          if( c=='&' ){
002827            zFile[iOut++] = '\0';
002828          }else{
002829            eState = 2;
002830          }
002831          c = 0;
002832        }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
002833          c = 0;
002834          eState = 1;
002835        }
002836        zFile[iOut++] = c;
002837      }
002838      if( eState==1 ) zFile[iOut++] = '\0';
002839      zFile[iOut++] = '\0';
002840      zFile[iOut++] = '\0';
002841  
002842      /* Check if there were any options specified that should be interpreted 
002843      ** here. Options that are interpreted here include "vfs" and those that
002844      ** correspond to flags that may be passed to the sqlite3_open_v2()
002845      ** method. */
002846      zOpt = &zFile[sqlite3Strlen30(zFile)+1];
002847      while( zOpt[0] ){
002848        int nOpt = sqlite3Strlen30(zOpt);
002849        char *zVal = &zOpt[nOpt+1];
002850        int nVal = sqlite3Strlen30(zVal);
002851  
002852        if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
002853          zVfs = zVal;
002854        }else{
002855          struct OpenMode {
002856            const char *z;
002857            int mode;
002858          } *aMode = 0;
002859          char *zModeType = 0;
002860          int mask = 0;
002861          int limit = 0;
002862  
002863          if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
002864            static struct OpenMode aCacheMode[] = {
002865              { "shared",  SQLITE_OPEN_SHAREDCACHE },
002866              { "private", SQLITE_OPEN_PRIVATECACHE },
002867              { 0, 0 }
002868            };
002869  
002870            mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
002871            aMode = aCacheMode;
002872            limit = mask;
002873            zModeType = "cache";
002874          }
002875          if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
002876            static struct OpenMode aOpenMode[] = {
002877              { "ro",  SQLITE_OPEN_READONLY },
002878              { "rw",  SQLITE_OPEN_READWRITE }, 
002879              { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
002880              { "memory", SQLITE_OPEN_MEMORY },
002881              { 0, 0 }
002882            };
002883  
002884            mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
002885                     | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
002886            aMode = aOpenMode;
002887            limit = mask & flags;
002888            zModeType = "access";
002889          }
002890  
002891          if( aMode ){
002892            int i;
002893            int mode = 0;
002894            for(i=0; aMode[i].z; i++){
002895              const char *z = aMode[i].z;
002896              if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
002897                mode = aMode[i].mode;
002898                break;
002899              }
002900            }
002901            if( mode==0 ){
002902              *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
002903              rc = SQLITE_ERROR;
002904              goto parse_uri_out;
002905            }
002906            if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
002907              *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
002908                                          zModeType, zVal);
002909              rc = SQLITE_PERM;
002910              goto parse_uri_out;
002911            }
002912            flags = (flags & ~mask) | mode;
002913          }
002914        }
002915  
002916        zOpt = &zVal[nVal+1];
002917      }
002918  
002919    }else{
002920      zFile = sqlite3_malloc64(nUri+2);
002921      if( !zFile ) return SQLITE_NOMEM_BKPT;
002922      if( nUri ){
002923        memcpy(zFile, zUri, nUri);
002924      }
002925      zFile[nUri] = '\0';
002926      zFile[nUri+1] = '\0';
002927      flags &= ~SQLITE_OPEN_URI;
002928    }
002929  
002930    *ppVfs = sqlite3_vfs_find(zVfs);
002931    if( *ppVfs==0 ){
002932      *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
002933      rc = SQLITE_ERROR;
002934    }
002935   parse_uri_out:
002936    if( rc!=SQLITE_OK ){
002937      sqlite3_free(zFile);
002938      zFile = 0;
002939    }
002940    *pFlags = flags;
002941    *pzFile = zFile;
002942    return rc;
002943  }
002944  
002945  #if defined(SQLITE_HAS_CODEC)
002946  /*
002947  ** Process URI filename query parameters relevant to the SQLite Encryption
002948  ** Extension.  Return true if any of the relevant query parameters are
002949  ** seen and return false if not.
002950  */
002951  int sqlite3CodecQueryParameters(
002952    sqlite3 *db,           /* Database connection */
002953    const char *zDb,       /* Which schema is being created/attached */
002954    const char *zUri       /* URI filename */
002955  ){
002956    const char *zKey;
002957    if( (zKey = sqlite3_uri_parameter(zUri, "hexkey"))!=0 && zKey[0] ){
002958      u8 iByte;
002959      int i;
002960      char zDecoded[40];
002961      for(i=0, iByte=0; i<sizeof(zDecoded)*2 && sqlite3Isxdigit(zKey[i]); i++){
002962        iByte = (iByte<<4) + sqlite3HexToInt(zKey[i]);
002963        if( (i&1)!=0 ) zDecoded[i/2] = iByte;
002964      }
002965      sqlite3_key_v2(db, zDb, zDecoded, i/2);
002966      return 1;
002967    }else if( (zKey = sqlite3_uri_parameter(zUri, "key"))!=0 ){
002968      sqlite3_key_v2(db, zDb, zKey, sqlite3Strlen30(zKey));
002969      return 1;
002970    }else if( (zKey = sqlite3_uri_parameter(zUri, "textkey"))!=0 ){
002971      sqlite3_key_v2(db, zDb, zKey, -1);
002972      return 1;
002973    }else{
002974      return 0;
002975    }
002976  }
002977  #endif
002978  
002979  
002980  /*
002981  ** This routine does the work of opening a database on behalf of
002982  ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
002983  ** is UTF-8 encoded.
002984  */
002985  static int openDatabase(
002986    const char *zFilename, /* Database filename UTF-8 encoded */
002987    sqlite3 **ppDb,        /* OUT: Returned database handle */
002988    unsigned int flags,    /* Operational flags */
002989    const char *zVfs       /* Name of the VFS to use */
002990  ){
002991    sqlite3 *db;                    /* Store allocated handle here */
002992    int rc;                         /* Return code */
002993    int isThreadsafe;               /* True for threadsafe connections */
002994    char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
002995    char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
002996  
002997  #ifdef SQLITE_ENABLE_API_ARMOR
002998    if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
002999  #endif
003000    *ppDb = 0;
003001  #ifndef SQLITE_OMIT_AUTOINIT
003002    rc = sqlite3_initialize();
003003    if( rc ) return rc;
003004  #endif
003005  
003006    if( sqlite3GlobalConfig.bCoreMutex==0 ){
003007      isThreadsafe = 0;
003008    }else if( flags & SQLITE_OPEN_NOMUTEX ){
003009      isThreadsafe = 0;
003010    }else if( flags & SQLITE_OPEN_FULLMUTEX ){
003011      isThreadsafe = 1;
003012    }else{
003013      isThreadsafe = sqlite3GlobalConfig.bFullMutex;
003014    }
003015  
003016    if( flags & SQLITE_OPEN_PRIVATECACHE ){
003017      flags &= ~SQLITE_OPEN_SHAREDCACHE;
003018    }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
003019      flags |= SQLITE_OPEN_SHAREDCACHE;
003020    }
003021  
003022    /* Remove harmful bits from the flags parameter
003023    **
003024    ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
003025    ** dealt with in the previous code block.  Besides these, the only
003026    ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
003027    ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
003028    ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
003029    ** off all other flags.
003030    */
003031    flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
003032                 SQLITE_OPEN_EXCLUSIVE |
003033                 SQLITE_OPEN_MAIN_DB |
003034                 SQLITE_OPEN_TEMP_DB | 
003035                 SQLITE_OPEN_TRANSIENT_DB | 
003036                 SQLITE_OPEN_MAIN_JOURNAL | 
003037                 SQLITE_OPEN_TEMP_JOURNAL | 
003038                 SQLITE_OPEN_SUBJOURNAL | 
003039                 SQLITE_OPEN_MASTER_JOURNAL |
003040                 SQLITE_OPEN_NOMUTEX |
003041                 SQLITE_OPEN_FULLMUTEX |
003042                 SQLITE_OPEN_WAL
003043               );
003044  
003045    /* Allocate the sqlite data structure */
003046    db = sqlite3MallocZero( sizeof(sqlite3) );
003047    if( db==0 ) goto opendb_out;
003048    if( isThreadsafe 
003049  #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
003050     || sqlite3GlobalConfig.bCoreMutex
003051  #endif
003052    ){
003053      db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
003054      if( db->mutex==0 ){
003055        sqlite3_free(db);
003056        db = 0;
003057        goto opendb_out;
003058      }
003059      if( isThreadsafe==0 ){
003060        sqlite3MutexWarnOnContention(db->mutex);
003061      }
003062    }
003063    sqlite3_mutex_enter(db->mutex);
003064    db->errMask = 0xff;
003065    db->nDb = 2;
003066    db->magic = SQLITE_MAGIC_BUSY;
003067    db->aDb = db->aDbStatic;
003068    db->lookaside.bDisable = 1;
003069  
003070    assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
003071    memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
003072    db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
003073    db->autoCommit = 1;
003074    db->nextAutovac = -1;
003075    db->szMmap = sqlite3GlobalConfig.szMmap;
003076    db->nextPagesize = 0;
003077    db->nMaxSorterMmap = 0x7FFFFFFF;
003078    db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
003079  #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
003080                   | SQLITE_AutoIndex
003081  #endif
003082  #if SQLITE_DEFAULT_CKPTFULLFSYNC
003083                   | SQLITE_CkptFullFSync
003084  #endif
003085  #if SQLITE_DEFAULT_FILE_FORMAT<4
003086                   | SQLITE_LegacyFileFmt
003087  #endif
003088  #ifdef SQLITE_ENABLE_LOAD_EXTENSION
003089                   | SQLITE_LoadExtension
003090  #endif
003091  #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
003092                   | SQLITE_RecTriggers
003093  #endif
003094  #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
003095                   | SQLITE_ForeignKeys
003096  #endif
003097  #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
003098                   | SQLITE_ReverseOrder
003099  #endif
003100  #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
003101                   | SQLITE_CellSizeCk
003102  #endif
003103  #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
003104                   | SQLITE_Fts3Tokenizer
003105  #endif
003106  #if defined(SQLITE_ENABLE_QPSG)
003107                   | SQLITE_EnableQPSG
003108  #endif
003109  #if defined(SQLITE_DEFAULT_DEFENSIVE)
003110                   | SQLITE_Defensive
003111  #endif
003112        ;
003113    sqlite3HashInit(&db->aCollSeq);
003114  #ifndef SQLITE_OMIT_VIRTUALTABLE
003115    sqlite3HashInit(&db->aModule);
003116  #endif
003117  
003118    /* Add the default collation sequence BINARY. BINARY works for both UTF-8
003119    ** and UTF-16, so add a version for each to avoid any unnecessary
003120    ** conversions. The only error that can occur here is a malloc() failure.
003121    **
003122    ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
003123    ** functions:
003124    */
003125    createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
003126    createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
003127    createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
003128    createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
003129    createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
003130    if( db->mallocFailed ){
003131      goto opendb_out;
003132    }
003133    /* EVIDENCE-OF: R-08308-17224 The default collating function for all
003134    ** strings is BINARY. 
003135    */
003136    db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
003137    assert( db->pDfltColl!=0 );
003138  
003139    /* Parse the filename/URI argument
003140    **
003141    ** Only allow sensible combinations of bits in the flags argument.  
003142    ** Throw an error if any non-sense combination is used.  If we
003143    ** do not block illegal combinations here, it could trigger
003144    ** assert() statements in deeper layers.  Sensible combinations
003145    ** are:
003146    **
003147    **  1:  SQLITE_OPEN_READONLY
003148    **  2:  SQLITE_OPEN_READWRITE
003149    **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
003150    */
003151    db->openFlags = flags;
003152    assert( SQLITE_OPEN_READONLY  == 0x01 );
003153    assert( SQLITE_OPEN_READWRITE == 0x02 );
003154    assert( SQLITE_OPEN_CREATE    == 0x04 );
003155    testcase( (1<<(flags&7))==0x02 ); /* READONLY */
003156    testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
003157    testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
003158    if( ((1<<(flags&7)) & 0x46)==0 ){
003159      rc = SQLITE_MISUSE_BKPT;  /* IMP: R-65497-44594 */
003160    }else{
003161      rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
003162    }
003163    if( rc!=SQLITE_OK ){
003164      if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
003165      sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
003166      sqlite3_free(zErrMsg);
003167      goto opendb_out;
003168    }
003169  
003170    /* Open the backend database driver */
003171    rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
003172                          flags | SQLITE_OPEN_MAIN_DB);
003173    if( rc!=SQLITE_OK ){
003174      if( rc==SQLITE_IOERR_NOMEM ){
003175        rc = SQLITE_NOMEM_BKPT;
003176      }
003177      sqlite3Error(db, rc);
003178      goto opendb_out;
003179    }
003180    sqlite3BtreeEnter(db->aDb[0].pBt);
003181    db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
003182    if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
003183    sqlite3BtreeLeave(db->aDb[0].pBt);
003184    db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
003185  
003186    /* The default safety_level for the main database is FULL; for the temp
003187    ** database it is OFF. This matches the pager layer defaults.  
003188    */
003189    db->aDb[0].zDbSName = "main";
003190    db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
003191    db->aDb[1].zDbSName = "temp";
003192    db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
003193  
003194    db->magic = SQLITE_MAGIC_OPEN;
003195    if( db->mallocFailed ){
003196      goto opendb_out;
003197    }
003198  
003199    /* Register all built-in functions, but do not attempt to read the
003200    ** database schema yet. This is delayed until the first time the database
003201    ** is accessed.
003202    */
003203    sqlite3Error(db, SQLITE_OK);
003204    sqlite3RegisterPerConnectionBuiltinFunctions(db);
003205    rc = sqlite3_errcode(db);
003206  
003207  #ifdef SQLITE_ENABLE_FTS5
003208    /* Register any built-in FTS5 module before loading the automatic
003209    ** extensions. This allows automatic extensions to register FTS5 
003210    ** tokenizers and auxiliary functions.  */
003211    if( !db->mallocFailed && rc==SQLITE_OK ){
003212      rc = sqlite3Fts5Init(db);
003213    }
003214  #endif
003215  
003216    /* Load automatic extensions - extensions that have been registered
003217    ** using the sqlite3_automatic_extension() API.
003218    */
003219    if( rc==SQLITE_OK ){
003220      sqlite3AutoLoadExtensions(db);
003221      rc = sqlite3_errcode(db);
003222      if( rc!=SQLITE_OK ){
003223        goto opendb_out;
003224      }
003225    }
003226  
003227  #ifdef SQLITE_ENABLE_FTS1
003228    if( !db->mallocFailed ){
003229      extern int sqlite3Fts1Init(sqlite3*);
003230      rc = sqlite3Fts1Init(db);
003231    }
003232  #endif
003233  
003234  #ifdef SQLITE_ENABLE_FTS2
003235    if( !db->mallocFailed && rc==SQLITE_OK ){
003236      extern int sqlite3Fts2Init(sqlite3*);
003237      rc = sqlite3Fts2Init(db);
003238    }
003239  #endif
003240  
003241  #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
003242    if( !db->mallocFailed && rc==SQLITE_OK ){
003243      rc = sqlite3Fts3Init(db);
003244    }
003245  #endif
003246  
003247  #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
003248    if( !db->mallocFailed && rc==SQLITE_OK ){
003249      rc = sqlite3IcuInit(db);
003250    }
003251  #endif
003252  
003253  #ifdef SQLITE_ENABLE_RTREE
003254    if( !db->mallocFailed && rc==SQLITE_OK){
003255      rc = sqlite3RtreeInit(db);
003256    }
003257  #endif
003258  
003259  #ifdef SQLITE_ENABLE_DBPAGE_VTAB
003260    if( !db->mallocFailed && rc==SQLITE_OK){
003261      rc = sqlite3DbpageRegister(db);
003262    }
003263  #endif
003264  
003265  #ifdef SQLITE_ENABLE_DBSTAT_VTAB
003266    if( !db->mallocFailed && rc==SQLITE_OK){
003267      rc = sqlite3DbstatRegister(db);
003268    }
003269  #endif
003270  
003271  #ifdef SQLITE_ENABLE_JSON1
003272    if( !db->mallocFailed && rc==SQLITE_OK){
003273      rc = sqlite3Json1Init(db);
003274    }
003275  #endif
003276  
003277  #ifdef SQLITE_ENABLE_STMTVTAB
003278    if( !db->mallocFailed && rc==SQLITE_OK){
003279      rc = sqlite3StmtVtabInit(db);
003280    }
003281  #endif
003282  
003283    /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
003284    ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
003285    ** mode.  Doing nothing at all also makes NORMAL the default.
003286    */
003287  #ifdef SQLITE_DEFAULT_LOCKING_MODE
003288    db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
003289    sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
003290                            SQLITE_DEFAULT_LOCKING_MODE);
003291  #endif
003292  
003293    if( rc ) sqlite3Error(db, rc);
003294  
003295    /* Enable the lookaside-malloc subsystem */
003296    setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
003297                          sqlite3GlobalConfig.nLookaside);
003298  
003299    sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
003300  
003301  opendb_out:
003302    if( db ){
003303      assert( db->mutex!=0 || isThreadsafe==0
003304             || sqlite3GlobalConfig.bFullMutex==0 );
003305      sqlite3_mutex_leave(db->mutex);
003306    }
003307    rc = sqlite3_errcode(db);
003308    assert( db!=0 || rc==SQLITE_NOMEM );
003309    if( rc==SQLITE_NOMEM ){
003310      sqlite3_close(db);
003311      db = 0;
003312    }else if( rc!=SQLITE_OK ){
003313      db->magic = SQLITE_MAGIC_SICK;
003314    }
003315    *ppDb = db;
003316  #ifdef SQLITE_ENABLE_SQLLOG
003317    if( sqlite3GlobalConfig.xSqllog ){
003318      /* Opening a db handle. Fourth parameter is passed 0. */
003319      void *pArg = sqlite3GlobalConfig.pSqllogArg;
003320      sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
003321    }
003322  #endif
003323  #if defined(SQLITE_HAS_CODEC)
003324    if( rc==SQLITE_OK ) sqlite3CodecQueryParameters(db, 0, zOpen);
003325  #endif
003326    sqlite3_free(zOpen);
003327    return rc & 0xff;
003328  }
003329  
003330  
003331  /*
003332  ** Open a new database handle.
003333  */
003334  int sqlite3_open(
003335    const char *zFilename, 
003336    sqlite3 **ppDb 
003337  ){
003338    return openDatabase(zFilename, ppDb,
003339                        SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
003340  }
003341  int sqlite3_open_v2(
003342    const char *filename,   /* Database filename (UTF-8) */
003343    sqlite3 **ppDb,         /* OUT: SQLite db handle */
003344    int flags,              /* Flags */
003345    const char *zVfs        /* Name of VFS module to use */
003346  ){
003347    return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
003348  }
003349  
003350  #ifndef SQLITE_OMIT_UTF16
003351  /*
003352  ** Open a new database handle.
003353  */
003354  int sqlite3_open16(
003355    const void *zFilename, 
003356    sqlite3 **ppDb
003357  ){
003358    char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
003359    sqlite3_value *pVal;
003360    int rc;
003361  
003362  #ifdef SQLITE_ENABLE_API_ARMOR
003363    if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
003364  #endif
003365    *ppDb = 0;
003366  #ifndef SQLITE_OMIT_AUTOINIT
003367    rc = sqlite3_initialize();
003368    if( rc ) return rc;
003369  #endif
003370    if( zFilename==0 ) zFilename = "\000\000";
003371    pVal = sqlite3ValueNew(0);
003372    sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
003373    zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
003374    if( zFilename8 ){
003375      rc = openDatabase(zFilename8, ppDb,
003376                        SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
003377      assert( *ppDb || rc==SQLITE_NOMEM );
003378      if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
003379        SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
003380      }
003381    }else{
003382      rc = SQLITE_NOMEM_BKPT;
003383    }
003384    sqlite3ValueFree(pVal);
003385  
003386    return rc & 0xff;
003387  }
003388  #endif /* SQLITE_OMIT_UTF16 */
003389  
003390  /*
003391  ** Register a new collation sequence with the database handle db.
003392  */
003393  int sqlite3_create_collation(
003394    sqlite3* db, 
003395    const char *zName, 
003396    int enc, 
003397    void* pCtx,
003398    int(*xCompare)(void*,int,const void*,int,const void*)
003399  ){
003400    return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
003401  }
003402  
003403  /*
003404  ** Register a new collation sequence with the database handle db.
003405  */
003406  int sqlite3_create_collation_v2(
003407    sqlite3* db, 
003408    const char *zName, 
003409    int enc, 
003410    void* pCtx,
003411    int(*xCompare)(void*,int,const void*,int,const void*),
003412    void(*xDel)(void*)
003413  ){
003414    int rc;
003415  
003416  #ifdef SQLITE_ENABLE_API_ARMOR
003417    if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
003418  #endif
003419    sqlite3_mutex_enter(db->mutex);
003420    assert( !db->mallocFailed );
003421    rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
003422    rc = sqlite3ApiExit(db, rc);
003423    sqlite3_mutex_leave(db->mutex);
003424    return rc;
003425  }
003426  
003427  #ifndef SQLITE_OMIT_UTF16
003428  /*
003429  ** Register a new collation sequence with the database handle db.
003430  */
003431  int sqlite3_create_collation16(
003432    sqlite3* db, 
003433    const void *zName,
003434    int enc, 
003435    void* pCtx,
003436    int(*xCompare)(void*,int,const void*,int,const void*)
003437  ){
003438    int rc = SQLITE_OK;
003439    char *zName8;
003440  
003441  #ifdef SQLITE_ENABLE_API_ARMOR
003442    if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
003443  #endif
003444    sqlite3_mutex_enter(db->mutex);
003445    assert( !db->mallocFailed );
003446    zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
003447    if( zName8 ){
003448      rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
003449      sqlite3DbFree(db, zName8);
003450    }
003451    rc = sqlite3ApiExit(db, rc);
003452    sqlite3_mutex_leave(db->mutex);
003453    return rc;
003454  }
003455  #endif /* SQLITE_OMIT_UTF16 */
003456  
003457  /*
003458  ** Register a collation sequence factory callback with the database handle
003459  ** db. Replace any previously installed collation sequence factory.
003460  */
003461  int sqlite3_collation_needed(
003462    sqlite3 *db, 
003463    void *pCollNeededArg, 
003464    void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
003465  ){
003466  #ifdef SQLITE_ENABLE_API_ARMOR
003467    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
003468  #endif
003469    sqlite3_mutex_enter(db->mutex);
003470    db->xCollNeeded = xCollNeeded;
003471    db->xCollNeeded16 = 0;
003472    db->pCollNeededArg = pCollNeededArg;
003473    sqlite3_mutex_leave(db->mutex);
003474    return SQLITE_OK;
003475  }
003476  
003477  #ifndef SQLITE_OMIT_UTF16
003478  /*
003479  ** Register a collation sequence factory callback with the database handle
003480  ** db. Replace any previously installed collation sequence factory.
003481  */
003482  int sqlite3_collation_needed16(
003483    sqlite3 *db, 
003484    void *pCollNeededArg, 
003485    void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
003486  ){
003487  #ifdef SQLITE_ENABLE_API_ARMOR
003488    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
003489  #endif
003490    sqlite3_mutex_enter(db->mutex);
003491    db->xCollNeeded = 0;
003492    db->xCollNeeded16 = xCollNeeded16;
003493    db->pCollNeededArg = pCollNeededArg;
003494    sqlite3_mutex_leave(db->mutex);
003495    return SQLITE_OK;
003496  }
003497  #endif /* SQLITE_OMIT_UTF16 */
003498  
003499  #ifndef SQLITE_OMIT_DEPRECATED
003500  /*
003501  ** This function is now an anachronism. It used to be used to recover from a
003502  ** malloc() failure, but SQLite now does this automatically.
003503  */
003504  int sqlite3_global_recover(void){
003505    return SQLITE_OK;
003506  }
003507  #endif
003508  
003509  /*
003510  ** Test to see whether or not the database connection is in autocommit
003511  ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
003512  ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
003513  ** by the next COMMIT or ROLLBACK.
003514  */
003515  int sqlite3_get_autocommit(sqlite3 *db){
003516  #ifdef SQLITE_ENABLE_API_ARMOR
003517    if( !sqlite3SafetyCheckOk(db) ){
003518      (void)SQLITE_MISUSE_BKPT;
003519      return 0;
003520    }
003521  #endif
003522    return db->autoCommit;
003523  }
003524  
003525  /*
003526  ** The following routines are substitutes for constants SQLITE_CORRUPT,
003527  ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
003528  ** constants.  They serve two purposes:
003529  **
003530  **   1.  Serve as a convenient place to set a breakpoint in a debugger
003531  **       to detect when version error conditions occurs.
003532  **
003533  **   2.  Invoke sqlite3_log() to provide the source code location where
003534  **       a low-level error is first detected.
003535  */
003536  int sqlite3ReportError(int iErr, int lineno, const char *zType){
003537    sqlite3_log(iErr, "%s at line %d of [%.10s]",
003538                zType, lineno, 20+sqlite3_sourceid());
003539    return iErr;
003540  }
003541  int sqlite3CorruptError(int lineno){
003542    testcase( sqlite3GlobalConfig.xLog!=0 );
003543    return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
003544  }
003545  int sqlite3MisuseError(int lineno){
003546    testcase( sqlite3GlobalConfig.xLog!=0 );
003547    return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
003548  }
003549  int sqlite3CantopenError(int lineno){
003550    testcase( sqlite3GlobalConfig.xLog!=0 );
003551    return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
003552  }
003553  #ifdef SQLITE_DEBUG
003554  int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
003555    char zMsg[100];
003556    sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
003557    testcase( sqlite3GlobalConfig.xLog!=0 );
003558    return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
003559  }
003560  int sqlite3NomemError(int lineno){
003561    testcase( sqlite3GlobalConfig.xLog!=0 );
003562    return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
003563  }
003564  int sqlite3IoerrnomemError(int lineno){
003565    testcase( sqlite3GlobalConfig.xLog!=0 );
003566    return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
003567  }
003568  #endif
003569  
003570  #ifndef SQLITE_OMIT_DEPRECATED
003571  /*
003572  ** This is a convenience routine that makes sure that all thread-specific
003573  ** data for this thread has been deallocated.
003574  **
003575  ** SQLite no longer uses thread-specific data so this routine is now a
003576  ** no-op.  It is retained for historical compatibility.
003577  */
003578  void sqlite3_thread_cleanup(void){
003579  }
003580  #endif
003581  
003582  /*
003583  ** Return meta information about a specific column of a database table.
003584  ** See comment in sqlite3.h (sqlite.h.in) for details.
003585  */
003586  int sqlite3_table_column_metadata(
003587    sqlite3 *db,                /* Connection handle */
003588    const char *zDbName,        /* Database name or NULL */
003589    const char *zTableName,     /* Table name */
003590    const char *zColumnName,    /* Column name */
003591    char const **pzDataType,    /* OUTPUT: Declared data type */
003592    char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
003593    int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
003594    int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
003595    int *pAutoinc               /* OUTPUT: True if column is auto-increment */
003596  ){
003597    int rc;
003598    char *zErrMsg = 0;
003599    Table *pTab = 0;
003600    Column *pCol = 0;
003601    int iCol = 0;
003602    char const *zDataType = 0;
003603    char const *zCollSeq = 0;
003604    int notnull = 0;
003605    int primarykey = 0;
003606    int autoinc = 0;
003607  
003608  
003609  #ifdef SQLITE_ENABLE_API_ARMOR
003610    if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
003611      return SQLITE_MISUSE_BKPT;
003612    }
003613  #endif
003614  
003615    /* Ensure the database schema has been loaded */
003616    sqlite3_mutex_enter(db->mutex);
003617    sqlite3BtreeEnterAll(db);
003618    rc = sqlite3Init(db, &zErrMsg);
003619    if( SQLITE_OK!=rc ){
003620      goto error_out;
003621    }
003622  
003623    /* Locate the table in question */
003624    pTab = sqlite3FindTable(db, zTableName, zDbName);
003625    if( !pTab || pTab->pSelect ){
003626      pTab = 0;
003627      goto error_out;
003628    }
003629  
003630    /* Find the column for which info is requested */
003631    if( zColumnName==0 ){
003632      /* Query for existance of table only */
003633    }else{
003634      for(iCol=0; iCol<pTab->nCol; iCol++){
003635        pCol = &pTab->aCol[iCol];
003636        if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
003637          break;
003638        }
003639      }
003640      if( iCol==pTab->nCol ){
003641        if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
003642          iCol = pTab->iPKey;
003643          pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
003644        }else{
003645          pTab = 0;
003646          goto error_out;
003647        }
003648      }
003649    }
003650  
003651    /* The following block stores the meta information that will be returned
003652    ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
003653    ** and autoinc. At this point there are two possibilities:
003654    ** 
003655    **     1. The specified column name was rowid", "oid" or "_rowid_" 
003656    **        and there is no explicitly declared IPK column. 
003657    **
003658    **     2. The table is not a view and the column name identified an 
003659    **        explicitly declared column. Copy meta information from *pCol.
003660    */ 
003661    if( pCol ){
003662      zDataType = sqlite3ColumnType(pCol,0);
003663      zCollSeq = pCol->zColl;
003664      notnull = pCol->notNull!=0;
003665      primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
003666      autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
003667    }else{
003668      zDataType = "INTEGER";
003669      primarykey = 1;
003670    }
003671    if( !zCollSeq ){
003672      zCollSeq = sqlite3StrBINARY;
003673    }
003674  
003675  error_out:
003676    sqlite3BtreeLeaveAll(db);
003677  
003678    /* Whether the function call succeeded or failed, set the output parameters
003679    ** to whatever their local counterparts contain. If an error did occur,
003680    ** this has the effect of zeroing all output parameters.
003681    */
003682    if( pzDataType ) *pzDataType = zDataType;
003683    if( pzCollSeq ) *pzCollSeq = zCollSeq;
003684    if( pNotNull ) *pNotNull = notnull;
003685    if( pPrimaryKey ) *pPrimaryKey = primarykey;
003686    if( pAutoinc ) *pAutoinc = autoinc;
003687  
003688    if( SQLITE_OK==rc && !pTab ){
003689      sqlite3DbFree(db, zErrMsg);
003690      zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
003691          zColumnName);
003692      rc = SQLITE_ERROR;
003693    }
003694    sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
003695    sqlite3DbFree(db, zErrMsg);
003696    rc = sqlite3ApiExit(db, rc);
003697    sqlite3_mutex_leave(db->mutex);
003698    return rc;
003699  }
003700  
003701  /*
003702  ** Sleep for a little while.  Return the amount of time slept.
003703  */
003704  int sqlite3_sleep(int ms){
003705    sqlite3_vfs *pVfs;
003706    int rc;
003707    pVfs = sqlite3_vfs_find(0);
003708    if( pVfs==0 ) return 0;
003709  
003710    /* This function works in milliseconds, but the underlying OsSleep() 
003711    ** API uses microseconds. Hence the 1000's.
003712    */
003713    rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
003714    return rc;
003715  }
003716  
003717  /*
003718  ** Enable or disable the extended result codes.
003719  */
003720  int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
003721  #ifdef SQLITE_ENABLE_API_ARMOR
003722    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
003723  #endif
003724    sqlite3_mutex_enter(db->mutex);
003725    db->errMask = onoff ? 0xffffffff : 0xff;
003726    sqlite3_mutex_leave(db->mutex);
003727    return SQLITE_OK;
003728  }
003729  
003730  /*
003731  ** Invoke the xFileControl method on a particular database.
003732  */
003733  int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
003734    int rc = SQLITE_ERROR;
003735    Btree *pBtree;
003736  
003737  #ifdef SQLITE_ENABLE_API_ARMOR
003738    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
003739  #endif
003740    sqlite3_mutex_enter(db->mutex);
003741    pBtree = sqlite3DbNameToBtree(db, zDbName);
003742    if( pBtree ){
003743      Pager *pPager;
003744      sqlite3_file *fd;
003745      sqlite3BtreeEnter(pBtree);
003746      pPager = sqlite3BtreePager(pBtree);
003747      assert( pPager!=0 );
003748      fd = sqlite3PagerFile(pPager);
003749      assert( fd!=0 );
003750      if( op==SQLITE_FCNTL_FILE_POINTER ){
003751        *(sqlite3_file**)pArg = fd;
003752        rc = SQLITE_OK;
003753      }else if( op==SQLITE_FCNTL_VFS_POINTER ){
003754        *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
003755        rc = SQLITE_OK;
003756      }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
003757        *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
003758        rc = SQLITE_OK;
003759      }else if( op==SQLITE_FCNTL_DATA_VERSION ){
003760        *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager);
003761        rc = SQLITE_OK;
003762      }else{
003763        rc = sqlite3OsFileControl(fd, op, pArg);
003764      }
003765      sqlite3BtreeLeave(pBtree);
003766    }
003767    sqlite3_mutex_leave(db->mutex);
003768    return rc;
003769  }
003770  
003771  /*
003772  ** Interface to the testing logic.
003773  */
003774  int sqlite3_test_control(int op, ...){
003775    int rc = 0;
003776  #ifdef SQLITE_UNTESTABLE
003777    UNUSED_PARAMETER(op);
003778  #else
003779    va_list ap;
003780    va_start(ap, op);
003781    switch( op ){
003782  
003783      /*
003784      ** Save the current state of the PRNG.
003785      */
003786      case SQLITE_TESTCTRL_PRNG_SAVE: {
003787        sqlite3PrngSaveState();
003788        break;
003789      }
003790  
003791      /*
003792      ** Restore the state of the PRNG to the last state saved using
003793      ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
003794      ** this verb acts like PRNG_RESET.
003795      */
003796      case SQLITE_TESTCTRL_PRNG_RESTORE: {
003797        sqlite3PrngRestoreState();
003798        break;
003799      }
003800  
003801      /*
003802      ** Reset the PRNG back to its uninitialized state.  The next call
003803      ** to sqlite3_randomness() will reseed the PRNG using a single call
003804      ** to the xRandomness method of the default VFS.
003805      */
003806      case SQLITE_TESTCTRL_PRNG_RESET: {
003807        sqlite3_randomness(0,0);
003808        break;
003809      }
003810  
003811      /*
003812      **  sqlite3_test_control(BITVEC_TEST, size, program)
003813      **
003814      ** Run a test against a Bitvec object of size.  The program argument
003815      ** is an array of integers that defines the test.  Return -1 on a
003816      ** memory allocation error, 0 on success, or non-zero for an error.
003817      ** See the sqlite3BitvecBuiltinTest() for additional information.
003818      */
003819      case SQLITE_TESTCTRL_BITVEC_TEST: {
003820        int sz = va_arg(ap, int);
003821        int *aProg = va_arg(ap, int*);
003822        rc = sqlite3BitvecBuiltinTest(sz, aProg);
003823        break;
003824      }
003825  
003826      /*
003827      **  sqlite3_test_control(FAULT_INSTALL, xCallback)
003828      **
003829      ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
003830      ** if xCallback is not NULL.
003831      **
003832      ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
003833      ** is called immediately after installing the new callback and the return
003834      ** value from sqlite3FaultSim(0) becomes the return from
003835      ** sqlite3_test_control().
003836      */
003837      case SQLITE_TESTCTRL_FAULT_INSTALL: {
003838        /* MSVC is picky about pulling func ptrs from va lists.
003839        ** http://support.microsoft.com/kb/47961
003840        ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
003841        */
003842        typedef int(*TESTCALLBACKFUNC_t)(int);
003843        sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
003844        rc = sqlite3FaultSim(0);
003845        break;
003846      }
003847  
003848      /*
003849      **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
003850      **
003851      ** Register hooks to call to indicate which malloc() failures 
003852      ** are benign.
003853      */
003854      case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
003855        typedef void (*void_function)(void);
003856        void_function xBenignBegin;
003857        void_function xBenignEnd;
003858        xBenignBegin = va_arg(ap, void_function);
003859        xBenignEnd = va_arg(ap, void_function);
003860        sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
003861        break;
003862      }
003863  
003864      /*
003865      **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
003866      **
003867      ** Set the PENDING byte to the value in the argument, if X>0.
003868      ** Make no changes if X==0.  Return the value of the pending byte
003869      ** as it existing before this routine was called.
003870      **
003871      ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
003872      ** an incompatible database file format.  Changing the PENDING byte
003873      ** while any database connection is open results in undefined and
003874      ** deleterious behavior.
003875      */
003876      case SQLITE_TESTCTRL_PENDING_BYTE: {
003877        rc = PENDING_BYTE;
003878  #ifndef SQLITE_OMIT_WSD
003879        {
003880          unsigned int newVal = va_arg(ap, unsigned int);
003881          if( newVal ) sqlite3PendingByte = newVal;
003882        }
003883  #endif
003884        break;
003885      }
003886  
003887      /*
003888      **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
003889      **
003890      ** This action provides a run-time test to see whether or not
003891      ** assert() was enabled at compile-time.  If X is true and assert()
003892      ** is enabled, then the return value is true.  If X is true and
003893      ** assert() is disabled, then the return value is zero.  If X is
003894      ** false and assert() is enabled, then the assertion fires and the
003895      ** process aborts.  If X is false and assert() is disabled, then the
003896      ** return value is zero.
003897      */
003898      case SQLITE_TESTCTRL_ASSERT: {
003899        volatile int x = 0;
003900        assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
003901        rc = x;
003902        break;
003903      }
003904  
003905  
003906      /*
003907      **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
003908      **
003909      ** This action provides a run-time test to see how the ALWAYS and
003910      ** NEVER macros were defined at compile-time.
003911      **
003912      ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
003913      **
003914      ** The recommended test is X==2.  If the return value is 2, that means
003915      ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
003916      ** default setting.  If the return value is 1, then ALWAYS() is either
003917      ** hard-coded to true or else it asserts if its argument is false.
003918      ** The first behavior (hard-coded to true) is the case if
003919      ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
003920      ** behavior (assert if the argument to ALWAYS() is false) is the case if
003921      ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
003922      **
003923      ** The run-time test procedure might look something like this:
003924      **
003925      **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
003926      **      // ALWAYS() and NEVER() are no-op pass-through macros
003927      **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
003928      **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
003929      **    }else{
003930      **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
003931      **    }
003932      */
003933      case SQLITE_TESTCTRL_ALWAYS: {
003934        int x = va_arg(ap,int);
003935        rc = x ? ALWAYS(x) : 0;
003936        break;
003937      }
003938  
003939      /*
003940      **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
003941      **
003942      ** The integer returned reveals the byte-order of the computer on which
003943      ** SQLite is running:
003944      **
003945      **       1     big-endian,    determined at run-time
003946      **      10     little-endian, determined at run-time
003947      **  432101     big-endian,    determined at compile-time
003948      **  123410     little-endian, determined at compile-time
003949      */ 
003950      case SQLITE_TESTCTRL_BYTEORDER: {
003951        rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
003952        break;
003953      }
003954  
003955      /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
003956      **
003957      ** Set the nReserve size to N for the main database on the database
003958      ** connection db.
003959      */
003960      case SQLITE_TESTCTRL_RESERVE: {
003961        sqlite3 *db = va_arg(ap, sqlite3*);
003962        int x = va_arg(ap,int);
003963        sqlite3_mutex_enter(db->mutex);
003964        sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
003965        sqlite3_mutex_leave(db->mutex);
003966        break;
003967      }
003968  
003969      /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
003970      **
003971      ** Enable or disable various optimizations for testing purposes.  The 
003972      ** argument N is a bitmask of optimizations to be disabled.  For normal
003973      ** operation N should be 0.  The idea is that a test program (like the
003974      ** SQL Logic Test or SLT test module) can run the same SQL multiple times
003975      ** with various optimizations disabled to verify that the same answer
003976      ** is obtained in every case.
003977      */
003978      case SQLITE_TESTCTRL_OPTIMIZATIONS: {
003979        sqlite3 *db = va_arg(ap, sqlite3*);
003980        db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
003981        break;
003982      }
003983  
003984      /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
003985      **
003986      ** If parameter onoff is non-zero, subsequent calls to localtime()
003987      ** and its variants fail. If onoff is zero, undo this setting.
003988      */
003989      case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
003990        sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
003991        break;
003992      }
003993  
003994      /*   sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCS, int onoff);
003995      **
003996      ** If parameter onoff is non-zero, internal-use-only SQL functions
003997      ** are visible to ordinary SQL.  This is useful for testing but is
003998      ** unsafe because invalid parameters to those internal-use-only functions
003999      ** can result in crashes or segfaults.
004000      */
004001      case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: {
004002        sqlite3GlobalConfig.bInternalFunctions = va_arg(ap, int);
004003        break;
004004      }
004005  
004006      /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
004007      **
004008      ** Set or clear a flag that indicates that the database file is always well-
004009      ** formed and never corrupt.  This flag is clear by default, indicating that
004010      ** database files might have arbitrary corruption.  Setting the flag during
004011      ** testing causes certain assert() statements in the code to be activated
004012      ** that demonstrat invariants on well-formed database files.
004013      */
004014      case SQLITE_TESTCTRL_NEVER_CORRUPT: {
004015        sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
004016        break;
004017      }
004018  
004019      /* Set the threshold at which OP_Once counters reset back to zero.
004020      ** By default this is 0x7ffffffe (over 2 billion), but that value is
004021      ** too big to test in a reasonable amount of time, so this control is
004022      ** provided to set a small and easily reachable reset value.
004023      */
004024      case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
004025        sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
004026        break;
004027      }
004028  
004029      /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
004030      **
004031      ** Set the VDBE coverage callback function to xCallback with context 
004032      ** pointer ptr.
004033      */
004034      case SQLITE_TESTCTRL_VDBE_COVERAGE: {
004035  #ifdef SQLITE_VDBE_COVERAGE
004036        typedef void (*branch_callback)(void*,unsigned int,
004037                                        unsigned char,unsigned char);
004038        sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
004039        sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
004040  #endif
004041        break;
004042      }
004043  
004044      /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
004045      case SQLITE_TESTCTRL_SORTER_MMAP: {
004046        sqlite3 *db = va_arg(ap, sqlite3*);
004047        db->nMaxSorterMmap = va_arg(ap, int);
004048        break;
004049      }
004050  
004051      /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
004052      **
004053      ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
004054      ** not.
004055      */
004056      case SQLITE_TESTCTRL_ISINIT: {
004057        if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
004058        break;
004059      }
004060  
004061      /*  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
004062      **
004063      ** This test control is used to create imposter tables.  "db" is a pointer
004064      ** to the database connection.  dbName is the database name (ex: "main" or
004065      ** "temp") which will receive the imposter.  "onOff" turns imposter mode on
004066      ** or off.  "tnum" is the root page of the b-tree to which the imposter
004067      ** table should connect.
004068      **
004069      ** Enable imposter mode only when the schema has already been parsed.  Then
004070      ** run a single CREATE TABLE statement to construct the imposter table in
004071      ** the parsed schema.  Then turn imposter mode back off again.
004072      **
004073      ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
004074      ** the schema to be reparsed the next time it is needed.  This has the
004075      ** effect of erasing all imposter tables.
004076      */
004077      case SQLITE_TESTCTRL_IMPOSTER: {
004078        sqlite3 *db = va_arg(ap, sqlite3*);
004079        sqlite3_mutex_enter(db->mutex);
004080        db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
004081        db->init.busy = db->init.imposterTable = va_arg(ap,int);
004082        db->init.newTnum = va_arg(ap,int);
004083        if( db->init.busy==0 && db->init.newTnum>0 ){
004084          sqlite3ResetAllSchemasOfConnection(db);
004085        }
004086        sqlite3_mutex_leave(db->mutex);
004087        break;
004088      }
004089  
004090  #if defined(YYCOVERAGE)
004091      /*  sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
004092      **
004093      ** This test control (only available when SQLite is compiled with
004094      ** -DYYCOVERAGE) writes a report onto "out" that shows all
004095      ** state/lookahead combinations in the parser state machine
004096      ** which are never exercised.  If any state is missed, make the
004097      ** return code SQLITE_ERROR.
004098      */
004099      case SQLITE_TESTCTRL_PARSER_COVERAGE: {
004100        FILE *out = va_arg(ap, FILE*);
004101        if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
004102        break;
004103      }
004104  #endif /* defined(YYCOVERAGE) */
004105    }
004106    va_end(ap);
004107  #endif /* SQLITE_UNTESTABLE */
004108    return rc;
004109  }
004110  
004111  /*
004112  ** This is a utility routine, useful to VFS implementations, that checks
004113  ** to see if a database file was a URI that contained a specific query 
004114  ** parameter, and if so obtains the value of the query parameter.
004115  **
004116  ** The zFilename argument is the filename pointer passed into the xOpen()
004117  ** method of a VFS implementation.  The zParam argument is the name of the
004118  ** query parameter we seek.  This routine returns the value of the zParam
004119  ** parameter if it exists.  If the parameter does not exist, this routine
004120  ** returns a NULL pointer.
004121  */
004122  const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
004123    if( zFilename==0 || zParam==0 ) return 0;
004124    zFilename += sqlite3Strlen30(zFilename) + 1;
004125    while( zFilename[0] ){
004126      int x = strcmp(zFilename, zParam);
004127      zFilename += sqlite3Strlen30(zFilename) + 1;
004128      if( x==0 ) return zFilename;
004129      zFilename += sqlite3Strlen30(zFilename) + 1;
004130    }
004131    return 0;
004132  }
004133  
004134  /*
004135  ** Return a boolean value for a query parameter.
004136  */
004137  int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
004138    const char *z = sqlite3_uri_parameter(zFilename, zParam);
004139    bDflt = bDflt!=0;
004140    return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
004141  }
004142  
004143  /*
004144  ** Return a 64-bit integer value for a query parameter.
004145  */
004146  sqlite3_int64 sqlite3_uri_int64(
004147    const char *zFilename,    /* Filename as passed to xOpen */
004148    const char *zParam,       /* URI parameter sought */
004149    sqlite3_int64 bDflt       /* return if parameter is missing */
004150  ){
004151    const char *z = sqlite3_uri_parameter(zFilename, zParam);
004152    sqlite3_int64 v;
004153    if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
004154      bDflt = v;
004155    }
004156    return bDflt;
004157  }
004158  
004159  /*
004160  ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
004161  */
004162  Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
004163    int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
004164    return iDb<0 ? 0 : db->aDb[iDb].pBt;
004165  }
004166  
004167  /*
004168  ** Return the filename of the database associated with a database
004169  ** connection.
004170  */
004171  const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
004172    Btree *pBt;
004173  #ifdef SQLITE_ENABLE_API_ARMOR
004174    if( !sqlite3SafetyCheckOk(db) ){
004175      (void)SQLITE_MISUSE_BKPT;
004176      return 0;
004177    }
004178  #endif
004179    pBt = sqlite3DbNameToBtree(db, zDbName);
004180    return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
004181  }
004182  
004183  /*
004184  ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
004185  ** no such database exists.
004186  */
004187  int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
004188    Btree *pBt;
004189  #ifdef SQLITE_ENABLE_API_ARMOR
004190    if( !sqlite3SafetyCheckOk(db) ){
004191      (void)SQLITE_MISUSE_BKPT;
004192      return -1;
004193    }
004194  #endif
004195    pBt = sqlite3DbNameToBtree(db, zDbName);
004196    return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
004197  }
004198  
004199  #ifdef SQLITE_ENABLE_SNAPSHOT
004200  /*
004201  ** Obtain a snapshot handle for the snapshot of database zDb currently 
004202  ** being read by handle db.
004203  */
004204  int sqlite3_snapshot_get(
004205    sqlite3 *db, 
004206    const char *zDb,
004207    sqlite3_snapshot **ppSnapshot
004208  ){
004209    int rc = SQLITE_ERROR;
004210  #ifndef SQLITE_OMIT_WAL
004211  
004212  #ifdef SQLITE_ENABLE_API_ARMOR
004213    if( !sqlite3SafetyCheckOk(db) ){
004214      return SQLITE_MISUSE_BKPT;
004215    }
004216  #endif
004217    sqlite3_mutex_enter(db->mutex);
004218  
004219    if( db->autoCommit==0 ){
004220      int iDb = sqlite3FindDbName(db, zDb);
004221      if( iDb==0 || iDb>1 ){
004222        Btree *pBt = db->aDb[iDb].pBt;
004223        if( 0==sqlite3BtreeIsInTrans(pBt) ){
004224          rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
004225          if( rc==SQLITE_OK ){
004226            rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
004227          }
004228        }
004229      }
004230    }
004231  
004232    sqlite3_mutex_leave(db->mutex);
004233  #endif   /* SQLITE_OMIT_WAL */
004234    return rc;
004235  }
004236  
004237  /*
004238  ** Open a read-transaction on the snapshot idendified by pSnapshot.
004239  */
004240  int sqlite3_snapshot_open(
004241    sqlite3 *db, 
004242    const char *zDb, 
004243    sqlite3_snapshot *pSnapshot
004244  ){
004245    int rc = SQLITE_ERROR;
004246  #ifndef SQLITE_OMIT_WAL
004247  
004248  #ifdef SQLITE_ENABLE_API_ARMOR
004249    if( !sqlite3SafetyCheckOk(db) ){
004250      return SQLITE_MISUSE_BKPT;
004251    }
004252  #endif
004253    sqlite3_mutex_enter(db->mutex);
004254    if( db->autoCommit==0 ){
004255      int iDb;
004256      iDb = sqlite3FindDbName(db, zDb);
004257      if( iDb==0 || iDb>1 ){
004258        Btree *pBt = db->aDb[iDb].pBt;
004259        if( sqlite3BtreeIsInTrans(pBt)==0 ){
004260          Pager *pPager = sqlite3BtreePager(pBt);
004261          int bUnlock = 0;
004262          if( sqlite3BtreeIsInReadTrans(pBt) ){
004263            if( db->nVdbeActive==0 ){
004264              rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot);
004265              if( rc==SQLITE_OK ){
004266                bUnlock = 1;
004267                rc = sqlite3BtreeCommit(pBt);
004268              }
004269            }
004270          }else{
004271            rc = SQLITE_OK;
004272          }
004273          if( rc==SQLITE_OK ){
004274            rc = sqlite3PagerSnapshotOpen(pPager, pSnapshot);
004275          }
004276          if( rc==SQLITE_OK ){
004277            rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
004278            sqlite3PagerSnapshotOpen(pPager, 0);
004279          }
004280          if( bUnlock ){
004281            sqlite3PagerSnapshotUnlock(pPager);
004282          }
004283        }
004284      }
004285    }
004286  
004287    sqlite3_mutex_leave(db->mutex);
004288  #endif   /* SQLITE_OMIT_WAL */
004289    return rc;
004290  }
004291  
004292  /*
004293  ** Recover as many snapshots as possible from the wal file associated with
004294  ** schema zDb of database db.
004295  */
004296  int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
004297    int rc = SQLITE_ERROR;
004298    int iDb;
004299  #ifndef SQLITE_OMIT_WAL
004300  
004301  #ifdef SQLITE_ENABLE_API_ARMOR
004302    if( !sqlite3SafetyCheckOk(db) ){
004303      return SQLITE_MISUSE_BKPT;
004304    }
004305  #endif
004306  
004307    sqlite3_mutex_enter(db->mutex);
004308    iDb = sqlite3FindDbName(db, zDb);
004309    if( iDb==0 || iDb>1 ){
004310      Btree *pBt = db->aDb[iDb].pBt;
004311      if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
004312        rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
004313        if( rc==SQLITE_OK ){
004314          rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
004315          sqlite3BtreeCommit(pBt);
004316        }
004317      }
004318    }
004319    sqlite3_mutex_leave(db->mutex);
004320  #endif   /* SQLITE_OMIT_WAL */
004321    return rc;
004322  }
004323  
004324  /*
004325  ** Free a snapshot handle obtained from sqlite3_snapshot_get().
004326  */
004327  void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
004328    sqlite3_free(pSnapshot);
004329  }
004330  #endif /* SQLITE_ENABLE_SNAPSHOT */
004331  
004332  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
004333  /*
004334  ** Given the name of a compile-time option, return true if that option
004335  ** was used and false if not.
004336  **
004337  ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
004338  ** is not required for a match.
004339  */
004340  int sqlite3_compileoption_used(const char *zOptName){
004341    int i, n;
004342    int nOpt;
004343    const char **azCompileOpt;
004344   
004345  #if SQLITE_ENABLE_API_ARMOR
004346    if( zOptName==0 ){
004347      (void)SQLITE_MISUSE_BKPT;
004348      return 0;
004349    }
004350  #endif
004351  
004352    azCompileOpt = sqlite3CompileOptions(&nOpt);
004353  
004354    if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
004355    n = sqlite3Strlen30(zOptName);
004356  
004357    /* Since nOpt is normally in single digits, a linear search is 
004358    ** adequate. No need for a binary search. */
004359    for(i=0; i<nOpt; i++){
004360      if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
004361       && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
004362      ){
004363        return 1;
004364      }
004365    }
004366    return 0;
004367  }
004368  
004369  /*
004370  ** Return the N-th compile-time option string.  If N is out of range,
004371  ** return a NULL pointer.
004372  */
004373  const char *sqlite3_compileoption_get(int N){
004374    int nOpt;
004375    const char **azCompileOpt;
004376    azCompileOpt = sqlite3CompileOptions(&nOpt);
004377    if( N>=0 && N<nOpt ){
004378      return azCompileOpt[N];
004379    }
004380    return 0;
004381  }
004382  #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */