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