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