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( (db->mDbFlags&DBFLAG_SchemaChange)!=0 && db->init.busy==0 ){
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    FuncDestructor *pDestructor
001687  ){
001688    FuncDef *p;
001689    int nName;
001690    int extraFlags;
001691  
001692    assert( sqlite3_mutex_held(db->mutex) );
001693    if( zFunctionName==0 ||
001694        (xSFunc && (xFinal || xStep)) || 
001695        (!xSFunc && (xFinal && !xStep)) ||
001696        (!xSFunc && (!xFinal && xStep)) ||
001697        (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
001698        (255<(nName = sqlite3Strlen30( zFunctionName))) ){
001699      return SQLITE_MISUSE_BKPT;
001700    }
001701  
001702    assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
001703    extraFlags = enc &  SQLITE_DETERMINISTIC;
001704    enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
001705    
001706  #ifndef SQLITE_OMIT_UTF16
001707    /* If SQLITE_UTF16 is specified as the encoding type, transform this
001708    ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
001709    ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
001710    **
001711    ** If SQLITE_ANY is specified, add three versions of the function
001712    ** to the hash table.
001713    */
001714    if( enc==SQLITE_UTF16 ){
001715      enc = SQLITE_UTF16NATIVE;
001716    }else if( enc==SQLITE_ANY ){
001717      int rc;
001718      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
001719           pUserData, xSFunc, xStep, xFinal, pDestructor);
001720      if( rc==SQLITE_OK ){
001721        rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
001722            pUserData, xSFunc, xStep, xFinal, pDestructor);
001723      }
001724      if( rc!=SQLITE_OK ){
001725        return rc;
001726      }
001727      enc = SQLITE_UTF16BE;
001728    }
001729  #else
001730    enc = SQLITE_UTF8;
001731  #endif
001732    
001733    /* Check if an existing function is being overridden or deleted. If so,
001734    ** and there are active VMs, then return SQLITE_BUSY. If a function
001735    ** is being overridden/deleted but there are no active VMs, allow the
001736    ** operation to continue but invalidate all precompiled statements.
001737    */
001738    p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
001739    if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
001740      if( db->nVdbeActive ){
001741        sqlite3ErrorWithMsg(db, SQLITE_BUSY, 
001742          "unable to delete/modify user-function due to active statements");
001743        assert( !db->mallocFailed );
001744        return SQLITE_BUSY;
001745      }else{
001746        sqlite3ExpirePreparedStatements(db);
001747      }
001748    }
001749  
001750    p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
001751    assert(p || db->mallocFailed);
001752    if( !p ){
001753      return SQLITE_NOMEM_BKPT;
001754    }
001755  
001756    /* If an older version of the function with a configured destructor is
001757    ** being replaced invoke the destructor function here. */
001758    functionDestroy(db, p);
001759  
001760    if( pDestructor ){
001761      pDestructor->nRef++;
001762    }
001763    p->u.pDestructor = pDestructor;
001764    p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
001765    testcase( p->funcFlags & SQLITE_DETERMINISTIC );
001766    p->xSFunc = xSFunc ? xSFunc : xStep;
001767    p->xFinalize = xFinal;
001768    p->pUserData = pUserData;
001769    p->nArg = (u16)nArg;
001770    return SQLITE_OK;
001771  }
001772  
001773  /*
001774  ** Create new user functions.
001775  */
001776  int sqlite3_create_function(
001777    sqlite3 *db,
001778    const char *zFunc,
001779    int nArg,
001780    int enc,
001781    void *p,
001782    void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
001783    void (*xStep)(sqlite3_context*,int,sqlite3_value **),
001784    void (*xFinal)(sqlite3_context*)
001785  ){
001786    return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep,
001787                                      xFinal, 0);
001788  }
001789  
001790  int sqlite3_create_function_v2(
001791    sqlite3 *db,
001792    const char *zFunc,
001793    int nArg,
001794    int enc,
001795    void *p,
001796    void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
001797    void (*xStep)(sqlite3_context*,int,sqlite3_value **),
001798    void (*xFinal)(sqlite3_context*),
001799    void (*xDestroy)(void *)
001800  ){
001801    int rc = SQLITE_ERROR;
001802    FuncDestructor *pArg = 0;
001803  
001804  #ifdef SQLITE_ENABLE_API_ARMOR
001805    if( !sqlite3SafetyCheckOk(db) ){
001806      return SQLITE_MISUSE_BKPT;
001807    }
001808  #endif
001809    sqlite3_mutex_enter(db->mutex);
001810    if( xDestroy ){
001811      pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor));
001812      if( !pArg ){
001813        sqlite3OomFault(db);
001814        xDestroy(p);
001815        goto out;
001816      }
001817      pArg->nRef = 0;
001818      pArg->xDestroy = xDestroy;
001819      pArg->pUserData = p;
001820    }
001821    rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
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  #ifndef SQLITE_OMIT_UTF16
001835  int sqlite3_create_function16(
001836    sqlite3 *db,
001837    const void *zFunctionName,
001838    int nArg,
001839    int eTextRep,
001840    void *p,
001841    void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
001842    void (*xStep)(sqlite3_context*,int,sqlite3_value**),
001843    void (*xFinal)(sqlite3_context*)
001844  ){
001845    int rc;
001846    char *zFunc8;
001847  
001848  #ifdef SQLITE_ENABLE_API_ARMOR
001849    if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
001850  #endif
001851    sqlite3_mutex_enter(db->mutex);
001852    assert( !db->mallocFailed );
001853    zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
001854    rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0);
001855    sqlite3DbFree(db, zFunc8);
001856    rc = sqlite3ApiExit(db, rc);
001857    sqlite3_mutex_leave(db->mutex);
001858    return rc;
001859  }
001860  #endif
001861  
001862  
001863  /*
001864  ** The following is the implementation of an SQL function that always
001865  ** fails with an error message stating that the function is used in the
001866  ** wrong context.  The sqlite3_overload_function() API might construct
001867  ** SQL function that use this routine so that the functions will exist
001868  ** for name resolution but are actually overloaded by the xFindFunction
001869  ** method of virtual tables.
001870  */
001871  static void sqlite3InvalidFunction(
001872    sqlite3_context *context,  /* The function calling context */
001873    int NotUsed,               /* Number of arguments to the function */
001874    sqlite3_value **NotUsed2   /* Value of each argument */
001875  ){
001876    const char *zName = (const char*)sqlite3_user_data(context);
001877    char *zErr;
001878    UNUSED_PARAMETER2(NotUsed, NotUsed2);
001879    zErr = sqlite3_mprintf(
001880        "unable to use function %s in the requested context", zName);
001881    sqlite3_result_error(context, zErr, -1);
001882    sqlite3_free(zErr);
001883  }
001884  
001885  /*
001886  ** Declare that a function has been overloaded by a virtual table.
001887  **
001888  ** If the function already exists as a regular global function, then
001889  ** this routine is a no-op.  If the function does not exist, then create
001890  ** a new one that always throws a run-time error.  
001891  **
001892  ** When virtual tables intend to provide an overloaded function, they
001893  ** should call this routine to make sure the global function exists.
001894  ** A global function must exist in order for name resolution to work
001895  ** properly.
001896  */
001897  int sqlite3_overload_function(
001898    sqlite3 *db,
001899    const char *zName,
001900    int nArg
001901  ){
001902    int rc;
001903    char *zCopy;
001904  
001905  #ifdef SQLITE_ENABLE_API_ARMOR
001906    if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
001907      return SQLITE_MISUSE_BKPT;
001908    }
001909  #endif
001910    sqlite3_mutex_enter(db->mutex);
001911    rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0;
001912    sqlite3_mutex_leave(db->mutex);
001913    if( rc ) return SQLITE_OK;
001914    zCopy = sqlite3_mprintf(zName);
001915    if( zCopy==0 ) return SQLITE_NOMEM;
001916    return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8,
001917                             zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free);
001918  }
001919  
001920  #ifndef SQLITE_OMIT_TRACE
001921  /*
001922  ** Register a trace function.  The pArg from the previously registered trace
001923  ** is returned.  
001924  **
001925  ** A NULL trace function means that no tracing is executes.  A non-NULL
001926  ** trace is a pointer to a function that is invoked at the start of each
001927  ** SQL statement.
001928  */
001929  #ifndef SQLITE_OMIT_DEPRECATED
001930  void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
001931    void *pOld;
001932  
001933  #ifdef SQLITE_ENABLE_API_ARMOR
001934    if( !sqlite3SafetyCheckOk(db) ){
001935      (void)SQLITE_MISUSE_BKPT;
001936      return 0;
001937    }
001938  #endif
001939    sqlite3_mutex_enter(db->mutex);
001940    pOld = db->pTraceArg;
001941    db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
001942    db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
001943    db->pTraceArg = pArg;
001944    sqlite3_mutex_leave(db->mutex);
001945    return pOld;
001946  }
001947  #endif /* SQLITE_OMIT_DEPRECATED */
001948  
001949  /* Register a trace callback using the version-2 interface.
001950  */
001951  int sqlite3_trace_v2(
001952    sqlite3 *db,                               /* Trace this connection */
001953    unsigned mTrace,                           /* Mask of events to be traced */
001954    int(*xTrace)(unsigned,void*,void*,void*),  /* Callback to invoke */
001955    void *pArg                                 /* Context */
001956  ){
001957  #ifdef SQLITE_ENABLE_API_ARMOR
001958    if( !sqlite3SafetyCheckOk(db) ){
001959      return SQLITE_MISUSE_BKPT;
001960    }
001961  #endif
001962    sqlite3_mutex_enter(db->mutex);
001963    if( mTrace==0 ) xTrace = 0;
001964    if( xTrace==0 ) mTrace = 0;
001965    db->mTrace = mTrace;
001966    db->xTrace = xTrace;
001967    db->pTraceArg = pArg;
001968    sqlite3_mutex_leave(db->mutex);
001969    return SQLITE_OK;
001970  }
001971  
001972  #ifndef SQLITE_OMIT_DEPRECATED
001973  /*
001974  ** Register a profile function.  The pArg from the previously registered 
001975  ** profile function is returned.  
001976  **
001977  ** A NULL profile function means that no profiling is executes.  A non-NULL
001978  ** profile is a pointer to a function that is invoked at the conclusion of
001979  ** each SQL statement that is run.
001980  */
001981  void *sqlite3_profile(
001982    sqlite3 *db,
001983    void (*xProfile)(void*,const char*,sqlite_uint64),
001984    void *pArg
001985  ){
001986    void *pOld;
001987  
001988  #ifdef SQLITE_ENABLE_API_ARMOR
001989    if( !sqlite3SafetyCheckOk(db) ){
001990      (void)SQLITE_MISUSE_BKPT;
001991      return 0;
001992    }
001993  #endif
001994    sqlite3_mutex_enter(db->mutex);
001995    pOld = db->pProfileArg;
001996    db->xProfile = xProfile;
001997    db->pProfileArg = pArg;
001998    sqlite3_mutex_leave(db->mutex);
001999    return pOld;
002000  }
002001  #endif /* SQLITE_OMIT_DEPRECATED */
002002  #endif /* SQLITE_OMIT_TRACE */
002003  
002004  /*
002005  ** Register a function to be invoked when a transaction commits.
002006  ** If the invoked function returns non-zero, then the commit becomes a
002007  ** rollback.
002008  */
002009  void *sqlite3_commit_hook(
002010    sqlite3 *db,              /* Attach the hook to this database */
002011    int (*xCallback)(void*),  /* Function to invoke on each commit */
002012    void *pArg                /* Argument to the function */
002013  ){
002014    void *pOld;
002015  
002016  #ifdef SQLITE_ENABLE_API_ARMOR
002017    if( !sqlite3SafetyCheckOk(db) ){
002018      (void)SQLITE_MISUSE_BKPT;
002019      return 0;
002020    }
002021  #endif
002022    sqlite3_mutex_enter(db->mutex);
002023    pOld = db->pCommitArg;
002024    db->xCommitCallback = xCallback;
002025    db->pCommitArg = pArg;
002026    sqlite3_mutex_leave(db->mutex);
002027    return pOld;
002028  }
002029  
002030  /*
002031  ** Register a callback to be invoked each time a row is updated,
002032  ** inserted or deleted using this database connection.
002033  */
002034  void *sqlite3_update_hook(
002035    sqlite3 *db,              /* Attach the hook to this database */
002036    void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
002037    void *pArg                /* Argument to the function */
002038  ){
002039    void *pRet;
002040  
002041  #ifdef SQLITE_ENABLE_API_ARMOR
002042    if( !sqlite3SafetyCheckOk(db) ){
002043      (void)SQLITE_MISUSE_BKPT;
002044      return 0;
002045    }
002046  #endif
002047    sqlite3_mutex_enter(db->mutex);
002048    pRet = db->pUpdateArg;
002049    db->xUpdateCallback = xCallback;
002050    db->pUpdateArg = pArg;
002051    sqlite3_mutex_leave(db->mutex);
002052    return pRet;
002053  }
002054  
002055  /*
002056  ** Register a callback to be invoked each time a transaction is rolled
002057  ** back by this database connection.
002058  */
002059  void *sqlite3_rollback_hook(
002060    sqlite3 *db,              /* Attach the hook to this database */
002061    void (*xCallback)(void*), /* Callback function */
002062    void *pArg                /* Argument to the function */
002063  ){
002064    void *pRet;
002065  
002066  #ifdef SQLITE_ENABLE_API_ARMOR
002067    if( !sqlite3SafetyCheckOk(db) ){
002068      (void)SQLITE_MISUSE_BKPT;
002069      return 0;
002070    }
002071  #endif
002072    sqlite3_mutex_enter(db->mutex);
002073    pRet = db->pRollbackArg;
002074    db->xRollbackCallback = xCallback;
002075    db->pRollbackArg = pArg;
002076    sqlite3_mutex_leave(db->mutex);
002077    return pRet;
002078  }
002079  
002080  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
002081  /*
002082  ** Register a callback to be invoked each time a row is updated,
002083  ** inserted or deleted using this database connection.
002084  */
002085  void *sqlite3_preupdate_hook(
002086    sqlite3 *db,              /* Attach the hook to this database */
002087    void(*xCallback)(         /* Callback function */
002088      void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
002089    void *pArg                /* First callback argument */
002090  ){
002091    void *pRet;
002092    sqlite3_mutex_enter(db->mutex);
002093    pRet = db->pPreUpdateArg;
002094    db->xPreUpdateCallback = xCallback;
002095    db->pPreUpdateArg = pArg;
002096    sqlite3_mutex_leave(db->mutex);
002097    return pRet;
002098  }
002099  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
002100  
002101  #ifndef SQLITE_OMIT_WAL
002102  /*
002103  ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
002104  ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
002105  ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
002106  ** wal_autocheckpoint()).
002107  */ 
002108  int sqlite3WalDefaultHook(
002109    void *pClientData,     /* Argument */
002110    sqlite3 *db,           /* Connection */
002111    const char *zDb,       /* Database */
002112    int nFrame             /* Size of WAL */
002113  ){
002114    if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
002115      sqlite3BeginBenignMalloc();
002116      sqlite3_wal_checkpoint(db, zDb);
002117      sqlite3EndBenignMalloc();
002118    }
002119    return SQLITE_OK;
002120  }
002121  #endif /* SQLITE_OMIT_WAL */
002122  
002123  /*
002124  ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
002125  ** a database after committing a transaction if there are nFrame or
002126  ** more frames in the log file. Passing zero or a negative value as the
002127  ** nFrame parameter disables automatic checkpoints entirely.
002128  **
002129  ** The callback registered by this function replaces any existing callback
002130  ** registered using sqlite3_wal_hook(). Likewise, registering a callback
002131  ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
002132  ** configured by this function.
002133  */
002134  int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
002135  #ifdef SQLITE_OMIT_WAL
002136    UNUSED_PARAMETER(db);
002137    UNUSED_PARAMETER(nFrame);
002138  #else
002139  #ifdef SQLITE_ENABLE_API_ARMOR
002140    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
002141  #endif
002142    if( nFrame>0 ){
002143      sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
002144    }else{
002145      sqlite3_wal_hook(db, 0, 0);
002146    }
002147  #endif
002148    return SQLITE_OK;
002149  }
002150  
002151  /*
002152  ** Register a callback to be invoked each time a transaction is written
002153  ** into the write-ahead-log by this database connection.
002154  */
002155  void *sqlite3_wal_hook(
002156    sqlite3 *db,                    /* Attach the hook to this db handle */
002157    int(*xCallback)(void *, sqlite3*, const char*, int),
002158    void *pArg                      /* First argument passed to xCallback() */
002159  ){
002160  #ifndef SQLITE_OMIT_WAL
002161    void *pRet;
002162  #ifdef SQLITE_ENABLE_API_ARMOR
002163    if( !sqlite3SafetyCheckOk(db) ){
002164      (void)SQLITE_MISUSE_BKPT;
002165      return 0;
002166    }
002167  #endif
002168    sqlite3_mutex_enter(db->mutex);
002169    pRet = db->pWalArg;
002170    db->xWalCallback = xCallback;
002171    db->pWalArg = pArg;
002172    sqlite3_mutex_leave(db->mutex);
002173    return pRet;
002174  #else
002175    return 0;
002176  #endif
002177  }
002178  
002179  /*
002180  ** Checkpoint database zDb.
002181  */
002182  int sqlite3_wal_checkpoint_v2(
002183    sqlite3 *db,                    /* Database handle */
002184    const char *zDb,                /* Name of attached database (or NULL) */
002185    int eMode,                      /* SQLITE_CHECKPOINT_* value */
002186    int *pnLog,                     /* OUT: Size of WAL log in frames */
002187    int *pnCkpt                     /* OUT: Total number of frames checkpointed */
002188  ){
002189  #ifdef SQLITE_OMIT_WAL
002190    return SQLITE_OK;
002191  #else
002192    int rc;                         /* Return code */
002193    int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
002194  
002195  #ifdef SQLITE_ENABLE_API_ARMOR
002196    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
002197  #endif
002198  
002199    /* Initialize the output variables to -1 in case an error occurs. */
002200    if( pnLog ) *pnLog = -1;
002201    if( pnCkpt ) *pnCkpt = -1;
002202  
002203    assert( SQLITE_CHECKPOINT_PASSIVE==0 );
002204    assert( SQLITE_CHECKPOINT_FULL==1 );
002205    assert( SQLITE_CHECKPOINT_RESTART==2 );
002206    assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
002207    if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
002208      /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
002209      ** mode: */
002210      return SQLITE_MISUSE;
002211    }
002212  
002213    sqlite3_mutex_enter(db->mutex);
002214    if( zDb && zDb[0] ){
002215      iDb = sqlite3FindDbName(db, zDb);
002216    }
002217    if( iDb<0 ){
002218      rc = SQLITE_ERROR;
002219      sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
002220    }else{
002221      db->busyHandler.nBusy = 0;
002222      rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
002223      sqlite3Error(db, rc);
002224    }
002225    rc = sqlite3ApiExit(db, rc);
002226  
002227    /* If there are no active statements, clear the interrupt flag at this
002228    ** point.  */
002229    if( db->nVdbeActive==0 ){
002230      db->u1.isInterrupted = 0;
002231    }
002232  
002233    sqlite3_mutex_leave(db->mutex);
002234    return rc;
002235  #endif
002236  }
002237  
002238  
002239  /*
002240  ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
002241  ** to contains a zero-length string, all attached databases are 
002242  ** checkpointed.
002243  */
002244  int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
002245    /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
002246    ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
002247    return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
002248  }
002249  
002250  #ifndef SQLITE_OMIT_WAL
002251  /*
002252  ** Run a checkpoint on database iDb. This is a no-op if database iDb is
002253  ** not currently open in WAL mode.
002254  **
002255  ** If a transaction is open on the database being checkpointed, this 
002256  ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
002257  ** an error occurs while running the checkpoint, an SQLite error code is 
002258  ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
002259  **
002260  ** The mutex on database handle db should be held by the caller. The mutex
002261  ** associated with the specific b-tree being checkpointed is taken by
002262  ** this function while the checkpoint is running.
002263  **
002264  ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
002265  ** checkpointed. If an error is encountered it is returned immediately -
002266  ** no attempt is made to checkpoint any remaining databases.
002267  **
002268  ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
002269  ** or TRUNCATE.
002270  */
002271  int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
002272    int rc = SQLITE_OK;             /* Return code */
002273    int i;                          /* Used to iterate through attached dbs */
002274    int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
002275  
002276    assert( sqlite3_mutex_held(db->mutex) );
002277    assert( !pnLog || *pnLog==-1 );
002278    assert( !pnCkpt || *pnCkpt==-1 );
002279  
002280    for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
002281      if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
002282        rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
002283        pnLog = 0;
002284        pnCkpt = 0;
002285        if( rc==SQLITE_BUSY ){
002286          bBusy = 1;
002287          rc = SQLITE_OK;
002288        }
002289      }
002290    }
002291  
002292    return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
002293  }
002294  #endif /* SQLITE_OMIT_WAL */
002295  
002296  /*
002297  ** This function returns true if main-memory should be used instead of
002298  ** a temporary file for transient pager files and statement journals.
002299  ** The value returned depends on the value of db->temp_store (runtime
002300  ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
002301  ** following table describes the relationship between these two values
002302  ** and this functions return value.
002303  **
002304  **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
002305  **   -----------------     --------------     ------------------------------
002306  **   0                     any                file      (return 0)
002307  **   1                     1                  file      (return 0)
002308  **   1                     2                  memory    (return 1)
002309  **   1                     0                  file      (return 0)
002310  **   2                     1                  file      (return 0)
002311  **   2                     2                  memory    (return 1)
002312  **   2                     0                  memory    (return 1)
002313  **   3                     any                memory    (return 1)
002314  */
002315  int sqlite3TempInMemory(const sqlite3 *db){
002316  #if SQLITE_TEMP_STORE==1
002317    return ( db->temp_store==2 );
002318  #endif
002319  #if SQLITE_TEMP_STORE==2
002320    return ( db->temp_store!=1 );
002321  #endif
002322  #if SQLITE_TEMP_STORE==3
002323    UNUSED_PARAMETER(db);
002324    return 1;
002325  #endif
002326  #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
002327    UNUSED_PARAMETER(db);
002328    return 0;
002329  #endif
002330  }
002331  
002332  /*
002333  ** Return UTF-8 encoded English language explanation of the most recent
002334  ** error.
002335  */
002336  const char *sqlite3_errmsg(sqlite3 *db){
002337    const char *z;
002338    if( !db ){
002339      return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
002340    }
002341    if( !sqlite3SafetyCheckSickOrOk(db) ){
002342      return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
002343    }
002344    sqlite3_mutex_enter(db->mutex);
002345    if( db->mallocFailed ){
002346      z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
002347    }else{
002348      testcase( db->pErr==0 );
002349      z = (char*)sqlite3_value_text(db->pErr);
002350      assert( !db->mallocFailed );
002351      if( z==0 ){
002352        z = sqlite3ErrStr(db->errCode);
002353      }
002354    }
002355    sqlite3_mutex_leave(db->mutex);
002356    return z;
002357  }
002358  
002359  #ifndef SQLITE_OMIT_UTF16
002360  /*
002361  ** Return UTF-16 encoded English language explanation of the most recent
002362  ** error.
002363  */
002364  const void *sqlite3_errmsg16(sqlite3 *db){
002365    static const u16 outOfMem[] = {
002366      'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
002367    };
002368    static const u16 misuse[] = {
002369      'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
002370      'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
002371      'm', 'i', 's', 'u', 's', 'e', 0
002372    };
002373  
002374    const void *z;
002375    if( !db ){
002376      return (void *)outOfMem;
002377    }
002378    if( !sqlite3SafetyCheckSickOrOk(db) ){
002379      return (void *)misuse;
002380    }
002381    sqlite3_mutex_enter(db->mutex);
002382    if( db->mallocFailed ){
002383      z = (void *)outOfMem;
002384    }else{
002385      z = sqlite3_value_text16(db->pErr);
002386      if( z==0 ){
002387        sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
002388        z = sqlite3_value_text16(db->pErr);
002389      }
002390      /* A malloc() may have failed within the call to sqlite3_value_text16()
002391      ** above. If this is the case, then the db->mallocFailed flag needs to
002392      ** be cleared before returning. Do this directly, instead of via
002393      ** sqlite3ApiExit(), to avoid setting the database handle error message.
002394      */
002395      sqlite3OomClear(db);
002396    }
002397    sqlite3_mutex_leave(db->mutex);
002398    return z;
002399  }
002400  #endif /* SQLITE_OMIT_UTF16 */
002401  
002402  /*
002403  ** Return the most recent error code generated by an SQLite routine. If NULL is
002404  ** passed to this function, we assume a malloc() failed during sqlite3_open().
002405  */
002406  int sqlite3_errcode(sqlite3 *db){
002407    if( db && !sqlite3SafetyCheckSickOrOk(db) ){
002408      return SQLITE_MISUSE_BKPT;
002409    }
002410    if( !db || db->mallocFailed ){
002411      return SQLITE_NOMEM_BKPT;
002412    }
002413    return db->errCode & db->errMask;
002414  }
002415  int sqlite3_extended_errcode(sqlite3 *db){
002416    if( db && !sqlite3SafetyCheckSickOrOk(db) ){
002417      return SQLITE_MISUSE_BKPT;
002418    }
002419    if( !db || db->mallocFailed ){
002420      return SQLITE_NOMEM_BKPT;
002421    }
002422    return db->errCode;
002423  }
002424  int sqlite3_system_errno(sqlite3 *db){
002425    return db ? db->iSysErrno : 0;
002426  }  
002427  
002428  /*
002429  ** Return a string that describes the kind of error specified in the
002430  ** argument.  For now, this simply calls the internal sqlite3ErrStr()
002431  ** function.
002432  */
002433  const char *sqlite3_errstr(int rc){
002434    return sqlite3ErrStr(rc);
002435  }
002436  
002437  /*
002438  ** Create a new collating function for database "db".  The name is zName
002439  ** and the encoding is enc.
002440  */
002441  static int createCollation(
002442    sqlite3* db,
002443    const char *zName, 
002444    u8 enc,
002445    void* pCtx,
002446    int(*xCompare)(void*,int,const void*,int,const void*),
002447    void(*xDel)(void*)
002448  ){
002449    CollSeq *pColl;
002450    int enc2;
002451    
002452    assert( sqlite3_mutex_held(db->mutex) );
002453  
002454    /* If SQLITE_UTF16 is specified as the encoding type, transform this
002455    ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
002456    ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
002457    */
002458    enc2 = enc;
002459    testcase( enc2==SQLITE_UTF16 );
002460    testcase( enc2==SQLITE_UTF16_ALIGNED );
002461    if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
002462      enc2 = SQLITE_UTF16NATIVE;
002463    }
002464    if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
002465      return SQLITE_MISUSE_BKPT;
002466    }
002467  
002468    /* Check if this call is removing or replacing an existing collation 
002469    ** sequence. If so, and there are active VMs, return busy. If there
002470    ** are no active VMs, invalidate any pre-compiled statements.
002471    */
002472    pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
002473    if( pColl && pColl->xCmp ){
002474      if( db->nVdbeActive ){
002475        sqlite3ErrorWithMsg(db, SQLITE_BUSY, 
002476          "unable to delete/modify collation sequence due to active statements");
002477        return SQLITE_BUSY;
002478      }
002479      sqlite3ExpirePreparedStatements(db);
002480  
002481      /* If collation sequence pColl was created directly by a call to
002482      ** sqlite3_create_collation, and not generated by synthCollSeq(),
002483      ** then any copies made by synthCollSeq() need to be invalidated.
002484      ** Also, collation destructor - CollSeq.xDel() - function may need
002485      ** to be called.
002486      */ 
002487      if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
002488        CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
002489        int j;
002490        for(j=0; j<3; j++){
002491          CollSeq *p = &aColl[j];
002492          if( p->enc==pColl->enc ){
002493            if( p->xDel ){
002494              p->xDel(p->pUser);
002495            }
002496            p->xCmp = 0;
002497          }
002498        }
002499      }
002500    }
002501  
002502    pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
002503    if( pColl==0 ) return SQLITE_NOMEM_BKPT;
002504    pColl->xCmp = xCompare;
002505    pColl->pUser = pCtx;
002506    pColl->xDel = xDel;
002507    pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
002508    sqlite3Error(db, SQLITE_OK);
002509    return SQLITE_OK;
002510  }
002511  
002512  
002513  /*
002514  ** This array defines hard upper bounds on limit values.  The
002515  ** initializer must be kept in sync with the SQLITE_LIMIT_*
002516  ** #defines in sqlite3.h.
002517  */
002518  static const int aHardLimit[] = {
002519    SQLITE_MAX_LENGTH,
002520    SQLITE_MAX_SQL_LENGTH,
002521    SQLITE_MAX_COLUMN,
002522    SQLITE_MAX_EXPR_DEPTH,
002523    SQLITE_MAX_COMPOUND_SELECT,
002524    SQLITE_MAX_VDBE_OP,
002525    SQLITE_MAX_FUNCTION_ARG,
002526    SQLITE_MAX_ATTACHED,
002527    SQLITE_MAX_LIKE_PATTERN_LENGTH,
002528    SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
002529    SQLITE_MAX_TRIGGER_DEPTH,
002530    SQLITE_MAX_WORKER_THREADS,
002531  };
002532  
002533  /*
002534  ** Make sure the hard limits are set to reasonable values
002535  */
002536  #if SQLITE_MAX_LENGTH<100
002537  # error SQLITE_MAX_LENGTH must be at least 100
002538  #endif
002539  #if SQLITE_MAX_SQL_LENGTH<100
002540  # error SQLITE_MAX_SQL_LENGTH must be at least 100
002541  #endif
002542  #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
002543  # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
002544  #endif
002545  #if SQLITE_MAX_COMPOUND_SELECT<2
002546  # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
002547  #endif
002548  #if SQLITE_MAX_VDBE_OP<40
002549  # error SQLITE_MAX_VDBE_OP must be at least 40
002550  #endif
002551  #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
002552  # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
002553  #endif
002554  #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
002555  # error SQLITE_MAX_ATTACHED must be between 0 and 125
002556  #endif
002557  #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
002558  # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
002559  #endif
002560  #if SQLITE_MAX_COLUMN>32767
002561  # error SQLITE_MAX_COLUMN must not exceed 32767
002562  #endif
002563  #if SQLITE_MAX_TRIGGER_DEPTH<1
002564  # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
002565  #endif
002566  #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
002567  # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
002568  #endif
002569  
002570  
002571  /*
002572  ** Change the value of a limit.  Report the old value.
002573  ** If an invalid limit index is supplied, report -1.
002574  ** Make no changes but still report the old value if the
002575  ** new limit is negative.
002576  **
002577  ** A new lower limit does not shrink existing constructs.
002578  ** It merely prevents new constructs that exceed the limit
002579  ** from forming.
002580  */
002581  int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
002582    int oldLimit;
002583  
002584  #ifdef SQLITE_ENABLE_API_ARMOR
002585    if( !sqlite3SafetyCheckOk(db) ){
002586      (void)SQLITE_MISUSE_BKPT;
002587      return -1;
002588    }
002589  #endif
002590  
002591    /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
002592    ** there is a hard upper bound set at compile-time by a C preprocessor
002593    ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
002594    ** "_MAX_".)
002595    */
002596    assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
002597    assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
002598    assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
002599    assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
002600    assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
002601    assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
002602    assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
002603    assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
002604    assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
002605                                                 SQLITE_MAX_LIKE_PATTERN_LENGTH );
002606    assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
002607    assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
002608    assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
002609    assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
002610  
002611  
002612    if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
002613      return -1;
002614    }
002615    oldLimit = db->aLimit[limitId];
002616    if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
002617      if( newLimit>aHardLimit[limitId] ){
002618        newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
002619      }
002620      db->aLimit[limitId] = newLimit;
002621    }
002622    return oldLimit;                     /* IMP: R-53341-35419 */
002623  }
002624  
002625  /*
002626  ** This function is used to parse both URIs and non-URI filenames passed by the
002627  ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
002628  ** URIs specified as part of ATTACH statements.
002629  **
002630  ** The first argument to this function is the name of the VFS to use (or
002631  ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
002632  ** query parameter. The second argument contains the URI (or non-URI filename)
002633  ** itself. When this function is called the *pFlags variable should contain
002634  ** the default flags to open the database handle with. The value stored in
002635  ** *pFlags may be updated before returning if the URI filename contains 
002636  ** "cache=xxx" or "mode=xxx" query parameters.
002637  **
002638  ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
002639  ** the VFS that should be used to open the database file. *pzFile is set to
002640  ** point to a buffer containing the name of the file to open. It is the 
002641  ** responsibility of the caller to eventually call sqlite3_free() to release
002642  ** this buffer.
002643  **
002644  ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
002645  ** may be set to point to a buffer containing an English language error 
002646  ** message. It is the responsibility of the caller to eventually release
002647  ** this buffer by calling sqlite3_free().
002648  */
002649  int sqlite3ParseUri(
002650    const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
002651    const char *zUri,               /* Nul-terminated URI to parse */
002652    unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
002653    sqlite3_vfs **ppVfs,            /* OUT: VFS to use */ 
002654    char **pzFile,                  /* OUT: Filename component of URI */
002655    char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
002656  ){
002657    int rc = SQLITE_OK;
002658    unsigned int flags = *pFlags;
002659    const char *zVfs = zDefaultVfs;
002660    char *zFile;
002661    char c;
002662    int nUri = sqlite3Strlen30(zUri);
002663  
002664    assert( *pzErrMsg==0 );
002665  
002666    if( ((flags & SQLITE_OPEN_URI)             /* IMP: R-48725-32206 */
002667              || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
002668     && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
002669    ){
002670      char *zOpt;
002671      int eState;                   /* Parser state when parsing URI */
002672      int iIn;                      /* Input character index */
002673      int iOut = 0;                 /* Output character index */
002674      u64 nByte = nUri+2;           /* Bytes of space to allocate */
002675  
002676      /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen 
002677      ** method that there may be extra parameters following the file-name.  */
002678      flags |= SQLITE_OPEN_URI;
002679  
002680      for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
002681      zFile = sqlite3_malloc64(nByte);
002682      if( !zFile ) return SQLITE_NOMEM_BKPT;
002683  
002684      iIn = 5;
002685  #ifdef SQLITE_ALLOW_URI_AUTHORITY
002686      if( strncmp(zUri+5, "///", 3)==0 ){
002687        iIn = 7;
002688        /* The following condition causes URIs with five leading / characters
002689        ** like file://///host/path to be converted into UNCs like //host/path.
002690        ** The correct URI for that UNC has only two or four leading / characters
002691        ** file://host/path or file:////host/path.  But 5 leading slashes is a 
002692        ** common error, we are told, so we handle it as a special case. */
002693        if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
002694      }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
002695        iIn = 16;
002696      }
002697  #else
002698      /* Discard the scheme and authority segments of the URI. */
002699      if( zUri[5]=='/' && zUri[6]=='/' ){
002700        iIn = 7;
002701        while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
002702        if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
002703          *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", 
002704              iIn-7, &zUri[7]);
002705          rc = SQLITE_ERROR;
002706          goto parse_uri_out;
002707        }
002708      }
002709  #endif
002710  
002711      /* Copy the filename and any query parameters into the zFile buffer. 
002712      ** Decode %HH escape codes along the way. 
002713      **
002714      ** Within this loop, variable eState may be set to 0, 1 or 2, depending
002715      ** on the parsing context. As follows:
002716      **
002717      **   0: Parsing file-name.
002718      **   1: Parsing name section of a name=value query parameter.
002719      **   2: Parsing value section of a name=value query parameter.
002720      */
002721      eState = 0;
002722      while( (c = zUri[iIn])!=0 && c!='#' ){
002723        iIn++;
002724        if( c=='%' 
002725         && sqlite3Isxdigit(zUri[iIn]) 
002726         && sqlite3Isxdigit(zUri[iIn+1]) 
002727        ){
002728          int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
002729          octet += sqlite3HexToInt(zUri[iIn++]);
002730  
002731          assert( octet>=0 && octet<256 );
002732          if( octet==0 ){
002733  #ifndef SQLITE_ENABLE_URI_00_ERROR
002734            /* This branch is taken when "%00" appears within the URI. In this
002735            ** case we ignore all text in the remainder of the path, name or
002736            ** value currently being parsed. So ignore the current character
002737            ** and skip to the next "?", "=" or "&", as appropriate. */
002738            while( (c = zUri[iIn])!=0 && c!='#' 
002739                && (eState!=0 || c!='?')
002740                && (eState!=1 || (c!='=' && c!='&'))
002741                && (eState!=2 || c!='&')
002742            ){
002743              iIn++;
002744            }
002745            continue;
002746  #else
002747            /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
002748            *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
002749            rc = SQLITE_ERROR;
002750            goto parse_uri_out;
002751  #endif
002752          }
002753          c = octet;
002754        }else if( eState==1 && (c=='&' || c=='=') ){
002755          if( zFile[iOut-1]==0 ){
002756            /* An empty option name. Ignore this option altogether. */
002757            while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
002758            continue;
002759          }
002760          if( c=='&' ){
002761            zFile[iOut++] = '\0';
002762          }else{
002763            eState = 2;
002764          }
002765          c = 0;
002766        }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
002767          c = 0;
002768          eState = 1;
002769        }
002770        zFile[iOut++] = c;
002771      }
002772      if( eState==1 ) zFile[iOut++] = '\0';
002773      zFile[iOut++] = '\0';
002774      zFile[iOut++] = '\0';
002775  
002776      /* Check if there were any options specified that should be interpreted 
002777      ** here. Options that are interpreted here include "vfs" and those that
002778      ** correspond to flags that may be passed to the sqlite3_open_v2()
002779      ** method. */
002780      zOpt = &zFile[sqlite3Strlen30(zFile)+1];
002781      while( zOpt[0] ){
002782        int nOpt = sqlite3Strlen30(zOpt);
002783        char *zVal = &zOpt[nOpt+1];
002784        int nVal = sqlite3Strlen30(zVal);
002785  
002786        if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
002787          zVfs = zVal;
002788        }else{
002789          struct OpenMode {
002790            const char *z;
002791            int mode;
002792          } *aMode = 0;
002793          char *zModeType = 0;
002794          int mask = 0;
002795          int limit = 0;
002796  
002797          if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
002798            static struct OpenMode aCacheMode[] = {
002799              { "shared",  SQLITE_OPEN_SHAREDCACHE },
002800              { "private", SQLITE_OPEN_PRIVATECACHE },
002801              { 0, 0 }
002802            };
002803  
002804            mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
002805            aMode = aCacheMode;
002806            limit = mask;
002807            zModeType = "cache";
002808          }
002809          if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
002810            static struct OpenMode aOpenMode[] = {
002811              { "ro",  SQLITE_OPEN_READONLY },
002812              { "rw",  SQLITE_OPEN_READWRITE }, 
002813              { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
002814              { "memory", SQLITE_OPEN_MEMORY },
002815              { 0, 0 }
002816            };
002817  
002818            mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
002819                     | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
002820            aMode = aOpenMode;
002821            limit = mask & flags;
002822            zModeType = "access";
002823          }
002824  
002825          if( aMode ){
002826            int i;
002827            int mode = 0;
002828            for(i=0; aMode[i].z; i++){
002829              const char *z = aMode[i].z;
002830              if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
002831                mode = aMode[i].mode;
002832                break;
002833              }
002834            }
002835            if( mode==0 ){
002836              *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
002837              rc = SQLITE_ERROR;
002838              goto parse_uri_out;
002839            }
002840            if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
002841              *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
002842                                          zModeType, zVal);
002843              rc = SQLITE_PERM;
002844              goto parse_uri_out;
002845            }
002846            flags = (flags & ~mask) | mode;
002847          }
002848        }
002849  
002850        zOpt = &zVal[nVal+1];
002851      }
002852  
002853    }else{
002854      zFile = sqlite3_malloc64(nUri+2);
002855      if( !zFile ) return SQLITE_NOMEM_BKPT;
002856      if( nUri ){
002857        memcpy(zFile, zUri, nUri);
002858      }
002859      zFile[nUri] = '\0';
002860      zFile[nUri+1] = '\0';
002861      flags &= ~SQLITE_OPEN_URI;
002862    }
002863  
002864    *ppVfs = sqlite3_vfs_find(zVfs);
002865    if( *ppVfs==0 ){
002866      *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
002867      rc = SQLITE_ERROR;
002868    }
002869   parse_uri_out:
002870    if( rc!=SQLITE_OK ){
002871      sqlite3_free(zFile);
002872      zFile = 0;
002873    }
002874    *pFlags = flags;
002875    *pzFile = zFile;
002876    return rc;
002877  }
002878  
002879  
002880  /*
002881  ** This routine does the work of opening a database on behalf of
002882  ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
002883  ** is UTF-8 encoded.
002884  */
002885  static int openDatabase(
002886    const char *zFilename, /* Database filename UTF-8 encoded */
002887    sqlite3 **ppDb,        /* OUT: Returned database handle */
002888    unsigned int flags,    /* Operational flags */
002889    const char *zVfs       /* Name of the VFS to use */
002890  ){
002891    sqlite3 *db;                    /* Store allocated handle here */
002892    int rc;                         /* Return code */
002893    int isThreadsafe;               /* True for threadsafe connections */
002894    char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
002895    char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
002896  
002897  #ifdef SQLITE_ENABLE_API_ARMOR
002898    if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
002899  #endif
002900    *ppDb = 0;
002901  #ifndef SQLITE_OMIT_AUTOINIT
002902    rc = sqlite3_initialize();
002903    if( rc ) return rc;
002904  #endif
002905  
002906    if( sqlite3GlobalConfig.bCoreMutex==0 ){
002907      isThreadsafe = 0;
002908    }else if( flags & SQLITE_OPEN_NOMUTEX ){
002909      isThreadsafe = 0;
002910    }else if( flags & SQLITE_OPEN_FULLMUTEX ){
002911      isThreadsafe = 1;
002912    }else{
002913      isThreadsafe = sqlite3GlobalConfig.bFullMutex;
002914    }
002915  
002916    if( flags & SQLITE_OPEN_PRIVATECACHE ){
002917      flags &= ~SQLITE_OPEN_SHAREDCACHE;
002918    }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
002919      flags |= SQLITE_OPEN_SHAREDCACHE;
002920    }
002921  
002922    /* Remove harmful bits from the flags parameter
002923    **
002924    ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
002925    ** dealt with in the previous code block.  Besides these, the only
002926    ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
002927    ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
002928    ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
002929    ** off all other flags.
002930    */
002931    flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
002932                 SQLITE_OPEN_EXCLUSIVE |
002933                 SQLITE_OPEN_MAIN_DB |
002934                 SQLITE_OPEN_TEMP_DB | 
002935                 SQLITE_OPEN_TRANSIENT_DB | 
002936                 SQLITE_OPEN_MAIN_JOURNAL | 
002937                 SQLITE_OPEN_TEMP_JOURNAL | 
002938                 SQLITE_OPEN_SUBJOURNAL | 
002939                 SQLITE_OPEN_MASTER_JOURNAL |
002940                 SQLITE_OPEN_NOMUTEX |
002941                 SQLITE_OPEN_FULLMUTEX |
002942                 SQLITE_OPEN_WAL
002943               );
002944  
002945    /* Allocate the sqlite data structure */
002946    db = sqlite3MallocZero( sizeof(sqlite3) );
002947    if( db==0 ) goto opendb_out;
002948    if( isThreadsafe 
002949  #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
002950     || sqlite3GlobalConfig.bCoreMutex
002951  #endif
002952    ){
002953      db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
002954      if( db->mutex==0 ){
002955        sqlite3_free(db);
002956        db = 0;
002957        goto opendb_out;
002958      }
002959      if( isThreadsafe==0 ){
002960        sqlite3MutexWarnOnContention(db->mutex);
002961      }
002962    }
002963    sqlite3_mutex_enter(db->mutex);
002964    db->errMask = 0xff;
002965    db->nDb = 2;
002966    db->magic = SQLITE_MAGIC_BUSY;
002967    db->aDb = db->aDbStatic;
002968  
002969    assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
002970    memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
002971    db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
002972    db->autoCommit = 1;
002973    db->nextAutovac = -1;
002974    db->szMmap = sqlite3GlobalConfig.szMmap;
002975    db->nextPagesize = 0;
002976    db->nMaxSorterMmap = 0x7FFFFFFF;
002977    db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
002978  #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
002979                   | SQLITE_AutoIndex
002980  #endif
002981  #if SQLITE_DEFAULT_CKPTFULLFSYNC
002982                   | SQLITE_CkptFullFSync
002983  #endif
002984  #if SQLITE_DEFAULT_FILE_FORMAT<4
002985                   | SQLITE_LegacyFileFmt
002986  #endif
002987  #ifdef SQLITE_ENABLE_LOAD_EXTENSION
002988                   | SQLITE_LoadExtension
002989  #endif
002990  #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
002991                   | SQLITE_RecTriggers
002992  #endif
002993  #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
002994                   | SQLITE_ForeignKeys
002995  #endif
002996  #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
002997                   | SQLITE_ReverseOrder
002998  #endif
002999  #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
003000                   | SQLITE_CellSizeCk
003001  #endif
003002  #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
003003                   | SQLITE_Fts3Tokenizer
003004  #endif
003005  #if defined(SQLITE_ENABLE_QPSG)
003006                   | SQLITE_EnableQPSG
003007  #endif
003008        ;
003009    sqlite3HashInit(&db->aCollSeq);
003010  #ifndef SQLITE_OMIT_VIRTUALTABLE
003011    sqlite3HashInit(&db->aModule);
003012  #endif
003013  
003014    /* Add the default collation sequence BINARY. BINARY works for both UTF-8
003015    ** and UTF-16, so add a version for each to avoid any unnecessary
003016    ** conversions. The only error that can occur here is a malloc() failure.
003017    **
003018    ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
003019    ** functions:
003020    */
003021    createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
003022    createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
003023    createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
003024    createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
003025    createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
003026    if( db->mallocFailed ){
003027      goto opendb_out;
003028    }
003029    /* EVIDENCE-OF: R-08308-17224 The default collating function for all
003030    ** strings is BINARY. 
003031    */
003032    db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
003033    assert( db->pDfltColl!=0 );
003034  
003035    /* Parse the filename/URI argument
003036    **
003037    ** Only allow sensible combinations of bits in the flags argument.  
003038    ** Throw an error if any non-sense combination is used.  If we
003039    ** do not block illegal combinations here, it could trigger
003040    ** assert() statements in deeper layers.  Sensible combinations
003041    ** are:
003042    **
003043    **  1:  SQLITE_OPEN_READONLY
003044    **  2:  SQLITE_OPEN_READWRITE
003045    **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
003046    */
003047    db->openFlags = flags;
003048    assert( SQLITE_OPEN_READONLY  == 0x01 );
003049    assert( SQLITE_OPEN_READWRITE == 0x02 );
003050    assert( SQLITE_OPEN_CREATE    == 0x04 );
003051    testcase( (1<<(flags&7))==0x02 ); /* READONLY */
003052    testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
003053    testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
003054    if( ((1<<(flags&7)) & 0x46)==0 ){
003055      rc = SQLITE_MISUSE_BKPT;  /* IMP: R-65497-44594 */
003056    }else{
003057      rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
003058    }
003059    if( rc!=SQLITE_OK ){
003060      if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
003061      sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
003062      sqlite3_free(zErrMsg);
003063      goto opendb_out;
003064    }
003065  
003066    /* Open the backend database driver */
003067    rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
003068                          flags | SQLITE_OPEN_MAIN_DB);
003069    if( rc!=SQLITE_OK ){
003070      if( rc==SQLITE_IOERR_NOMEM ){
003071        rc = SQLITE_NOMEM_BKPT;
003072      }
003073      sqlite3Error(db, rc);
003074      goto opendb_out;
003075    }
003076    sqlite3BtreeEnter(db->aDb[0].pBt);
003077    db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
003078    if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
003079    sqlite3BtreeLeave(db->aDb[0].pBt);
003080    db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
003081  
003082    /* The default safety_level for the main database is FULL; for the temp
003083    ** database it is OFF. This matches the pager layer defaults.  
003084    */
003085    db->aDb[0].zDbSName = "main";
003086    db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
003087    db->aDb[1].zDbSName = "temp";
003088    db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
003089  
003090    db->magic = SQLITE_MAGIC_OPEN;
003091    if( db->mallocFailed ){
003092      goto opendb_out;
003093    }
003094  
003095    /* Register all built-in functions, but do not attempt to read the
003096    ** database schema yet. This is delayed until the first time the database
003097    ** is accessed.
003098    */
003099    sqlite3Error(db, SQLITE_OK);
003100    sqlite3RegisterPerConnectionBuiltinFunctions(db);
003101    rc = sqlite3_errcode(db);
003102  
003103  #ifdef SQLITE_ENABLE_FTS5
003104    /* Register any built-in FTS5 module before loading the automatic
003105    ** extensions. This allows automatic extensions to register FTS5 
003106    ** tokenizers and auxiliary functions.  */
003107    if( !db->mallocFailed && rc==SQLITE_OK ){
003108      rc = sqlite3Fts5Init(db);
003109    }
003110  #endif
003111  
003112    /* Load automatic extensions - extensions that have been registered
003113    ** using the sqlite3_automatic_extension() API.
003114    */
003115    if( rc==SQLITE_OK ){
003116      sqlite3AutoLoadExtensions(db);
003117      rc = sqlite3_errcode(db);
003118      if( rc!=SQLITE_OK ){
003119        goto opendb_out;
003120      }
003121    }
003122  
003123  #ifdef SQLITE_ENABLE_FTS1
003124    if( !db->mallocFailed ){
003125      extern int sqlite3Fts1Init(sqlite3*);
003126      rc = sqlite3Fts1Init(db);
003127    }
003128  #endif
003129  
003130  #ifdef SQLITE_ENABLE_FTS2
003131    if( !db->mallocFailed && rc==SQLITE_OK ){
003132      extern int sqlite3Fts2Init(sqlite3*);
003133      rc = sqlite3Fts2Init(db);
003134    }
003135  #endif
003136  
003137  #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
003138    if( !db->mallocFailed && rc==SQLITE_OK ){
003139      rc = sqlite3Fts3Init(db);
003140    }
003141  #endif
003142  
003143  #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
003144    if( !db->mallocFailed && rc==SQLITE_OK ){
003145      rc = sqlite3IcuInit(db);
003146    }
003147  #endif
003148  
003149  #ifdef SQLITE_ENABLE_RTREE
003150    if( !db->mallocFailed && rc==SQLITE_OK){
003151      rc = sqlite3RtreeInit(db);
003152    }
003153  #endif
003154  
003155  #ifdef SQLITE_ENABLE_DBPAGE_VTAB
003156    if( !db->mallocFailed && rc==SQLITE_OK){
003157      rc = sqlite3DbpageRegister(db);
003158    }
003159  #endif
003160  
003161  #ifdef SQLITE_ENABLE_DBSTAT_VTAB
003162    if( !db->mallocFailed && rc==SQLITE_OK){
003163      rc = sqlite3DbstatRegister(db);
003164    }
003165  #endif
003166  
003167  #ifdef SQLITE_ENABLE_JSON1
003168    if( !db->mallocFailed && rc==SQLITE_OK){
003169      rc = sqlite3Json1Init(db);
003170    }
003171  #endif
003172  
003173  #ifdef SQLITE_ENABLE_STMTVTAB
003174    if( !db->mallocFailed && rc==SQLITE_OK){
003175      rc = sqlite3StmtVtabInit(db);
003176    }
003177  #endif
003178  
003179    /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
003180    ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
003181    ** mode.  Doing nothing at all also makes NORMAL the default.
003182    */
003183  #ifdef SQLITE_DEFAULT_LOCKING_MODE
003184    db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
003185    sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
003186                            SQLITE_DEFAULT_LOCKING_MODE);
003187  #endif
003188  
003189    if( rc ) sqlite3Error(db, rc);
003190  
003191    /* Enable the lookaside-malloc subsystem */
003192    setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
003193                          sqlite3GlobalConfig.nLookaside);
003194  
003195    sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
003196  
003197  opendb_out:
003198    if( db ){
003199      assert( db->mutex!=0 || isThreadsafe==0
003200             || sqlite3GlobalConfig.bFullMutex==0 );
003201      sqlite3_mutex_leave(db->mutex);
003202    }
003203    rc = sqlite3_errcode(db);
003204    assert( db!=0 || rc==SQLITE_NOMEM );
003205    if( rc==SQLITE_NOMEM ){
003206      sqlite3_close(db);
003207      db = 0;
003208    }else if( rc!=SQLITE_OK ){
003209      db->magic = SQLITE_MAGIC_SICK;
003210    }
003211    *ppDb = db;
003212  #ifdef SQLITE_ENABLE_SQLLOG
003213    if( sqlite3GlobalConfig.xSqllog ){
003214      /* Opening a db handle. Fourth parameter is passed 0. */
003215      void *pArg = sqlite3GlobalConfig.pSqllogArg;
003216      sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
003217    }
003218  #endif
003219  #if defined(SQLITE_HAS_CODEC)
003220    if( rc==SQLITE_OK ){
003221      const char *zKey;
003222      if( (zKey = sqlite3_uri_parameter(zOpen, "hexkey"))!=0 && zKey[0] ){
003223        u8 iByte;
003224        int i;
003225        char zDecoded[40];
003226        for(i=0, iByte=0; i<sizeof(zDecoded)*2 && sqlite3Isxdigit(zKey[i]); i++){
003227          iByte = (iByte<<4) + sqlite3HexToInt(zKey[i]);
003228          if( (i&1)!=0 ) zDecoded[i/2] = iByte;
003229        }
003230        sqlite3_key_v2(db, 0, zDecoded, i/2);
003231      }else if( (zKey = sqlite3_uri_parameter(zOpen, "key"))!=0 ){
003232        sqlite3_key_v2(db, 0, zKey, sqlite3Strlen30(zKey));
003233      }
003234    }
003235  #endif
003236    sqlite3_free(zOpen);
003237    return rc & 0xff;
003238  }
003239  
003240  /*
003241  ** Open a new database handle.
003242  */
003243  int sqlite3_open(
003244    const char *zFilename, 
003245    sqlite3 **ppDb 
003246  ){
003247    return openDatabase(zFilename, ppDb,
003248                        SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
003249  }
003250  int sqlite3_open_v2(
003251    const char *filename,   /* Database filename (UTF-8) */
003252    sqlite3 **ppDb,         /* OUT: SQLite db handle */
003253    int flags,              /* Flags */
003254    const char *zVfs        /* Name of VFS module to use */
003255  ){
003256    return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
003257  }
003258  
003259  #ifndef SQLITE_OMIT_UTF16
003260  /*
003261  ** Open a new database handle.
003262  */
003263  int sqlite3_open16(
003264    const void *zFilename, 
003265    sqlite3 **ppDb
003266  ){
003267    char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
003268    sqlite3_value *pVal;
003269    int rc;
003270  
003271  #ifdef SQLITE_ENABLE_API_ARMOR
003272    if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
003273  #endif
003274    *ppDb = 0;
003275  #ifndef SQLITE_OMIT_AUTOINIT
003276    rc = sqlite3_initialize();
003277    if( rc ) return rc;
003278  #endif
003279    if( zFilename==0 ) zFilename = "\000\000";
003280    pVal = sqlite3ValueNew(0);
003281    sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
003282    zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
003283    if( zFilename8 ){
003284      rc = openDatabase(zFilename8, ppDb,
003285                        SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
003286      assert( *ppDb || rc==SQLITE_NOMEM );
003287      if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
003288        SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
003289      }
003290    }else{
003291      rc = SQLITE_NOMEM_BKPT;
003292    }
003293    sqlite3ValueFree(pVal);
003294  
003295    return rc & 0xff;
003296  }
003297  #endif /* SQLITE_OMIT_UTF16 */
003298  
003299  /*
003300  ** Register a new collation sequence with the database handle db.
003301  */
003302  int sqlite3_create_collation(
003303    sqlite3* db, 
003304    const char *zName, 
003305    int enc, 
003306    void* pCtx,
003307    int(*xCompare)(void*,int,const void*,int,const void*)
003308  ){
003309    return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
003310  }
003311  
003312  /*
003313  ** Register a new collation sequence with the database handle db.
003314  */
003315  int sqlite3_create_collation_v2(
003316    sqlite3* db, 
003317    const char *zName, 
003318    int enc, 
003319    void* pCtx,
003320    int(*xCompare)(void*,int,const void*,int,const void*),
003321    void(*xDel)(void*)
003322  ){
003323    int rc;
003324  
003325  #ifdef SQLITE_ENABLE_API_ARMOR
003326    if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
003327  #endif
003328    sqlite3_mutex_enter(db->mutex);
003329    assert( !db->mallocFailed );
003330    rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
003331    rc = sqlite3ApiExit(db, rc);
003332    sqlite3_mutex_leave(db->mutex);
003333    return rc;
003334  }
003335  
003336  #ifndef SQLITE_OMIT_UTF16
003337  /*
003338  ** Register a new collation sequence with the database handle db.
003339  */
003340  int sqlite3_create_collation16(
003341    sqlite3* db, 
003342    const void *zName,
003343    int enc, 
003344    void* pCtx,
003345    int(*xCompare)(void*,int,const void*,int,const void*)
003346  ){
003347    int rc = SQLITE_OK;
003348    char *zName8;
003349  
003350  #ifdef SQLITE_ENABLE_API_ARMOR
003351    if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
003352  #endif
003353    sqlite3_mutex_enter(db->mutex);
003354    assert( !db->mallocFailed );
003355    zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
003356    if( zName8 ){
003357      rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
003358      sqlite3DbFree(db, zName8);
003359    }
003360    rc = sqlite3ApiExit(db, rc);
003361    sqlite3_mutex_leave(db->mutex);
003362    return rc;
003363  }
003364  #endif /* SQLITE_OMIT_UTF16 */
003365  
003366  /*
003367  ** Register a collation sequence factory callback with the database handle
003368  ** db. Replace any previously installed collation sequence factory.
003369  */
003370  int sqlite3_collation_needed(
003371    sqlite3 *db, 
003372    void *pCollNeededArg, 
003373    void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
003374  ){
003375  #ifdef SQLITE_ENABLE_API_ARMOR
003376    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
003377  #endif
003378    sqlite3_mutex_enter(db->mutex);
003379    db->xCollNeeded = xCollNeeded;
003380    db->xCollNeeded16 = 0;
003381    db->pCollNeededArg = pCollNeededArg;
003382    sqlite3_mutex_leave(db->mutex);
003383    return SQLITE_OK;
003384  }
003385  
003386  #ifndef SQLITE_OMIT_UTF16
003387  /*
003388  ** Register a collation sequence factory callback with the database handle
003389  ** db. Replace any previously installed collation sequence factory.
003390  */
003391  int sqlite3_collation_needed16(
003392    sqlite3 *db, 
003393    void *pCollNeededArg, 
003394    void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
003395  ){
003396  #ifdef SQLITE_ENABLE_API_ARMOR
003397    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
003398  #endif
003399    sqlite3_mutex_enter(db->mutex);
003400    db->xCollNeeded = 0;
003401    db->xCollNeeded16 = xCollNeeded16;
003402    db->pCollNeededArg = pCollNeededArg;
003403    sqlite3_mutex_leave(db->mutex);
003404    return SQLITE_OK;
003405  }
003406  #endif /* SQLITE_OMIT_UTF16 */
003407  
003408  #ifndef SQLITE_OMIT_DEPRECATED
003409  /*
003410  ** This function is now an anachronism. It used to be used to recover from a
003411  ** malloc() failure, but SQLite now does this automatically.
003412  */
003413  int sqlite3_global_recover(void){
003414    return SQLITE_OK;
003415  }
003416  #endif
003417  
003418  /*
003419  ** Test to see whether or not the database connection is in autocommit
003420  ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
003421  ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
003422  ** by the next COMMIT or ROLLBACK.
003423  */
003424  int sqlite3_get_autocommit(sqlite3 *db){
003425  #ifdef SQLITE_ENABLE_API_ARMOR
003426    if( !sqlite3SafetyCheckOk(db) ){
003427      (void)SQLITE_MISUSE_BKPT;
003428      return 0;
003429    }
003430  #endif
003431    return db->autoCommit;
003432  }
003433  
003434  /*
003435  ** The following routines are substitutes for constants SQLITE_CORRUPT,
003436  ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
003437  ** constants.  They serve two purposes:
003438  **
003439  **   1.  Serve as a convenient place to set a breakpoint in a debugger
003440  **       to detect when version error conditions occurs.
003441  **
003442  **   2.  Invoke sqlite3_log() to provide the source code location where
003443  **       a low-level error is first detected.
003444  */
003445  int sqlite3ReportError(int iErr, int lineno, const char *zType){
003446    sqlite3_log(iErr, "%s at line %d of [%.10s]",
003447                zType, lineno, 20+sqlite3_sourceid());
003448    return iErr;
003449  }
003450  int sqlite3CorruptError(int lineno){
003451    testcase( sqlite3GlobalConfig.xLog!=0 );
003452    return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
003453  }
003454  int sqlite3MisuseError(int lineno){
003455    testcase( sqlite3GlobalConfig.xLog!=0 );
003456    return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
003457  }
003458  int sqlite3CantopenError(int lineno){
003459    testcase( sqlite3GlobalConfig.xLog!=0 );
003460    return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
003461  }
003462  #ifdef SQLITE_DEBUG
003463  int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
003464    char zMsg[100];
003465    sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
003466    testcase( sqlite3GlobalConfig.xLog!=0 );
003467    return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
003468  }
003469  int sqlite3NomemError(int lineno){
003470    testcase( sqlite3GlobalConfig.xLog!=0 );
003471    return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
003472  }
003473  int sqlite3IoerrnomemError(int lineno){
003474    testcase( sqlite3GlobalConfig.xLog!=0 );
003475    return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
003476  }
003477  #endif
003478  
003479  #ifndef SQLITE_OMIT_DEPRECATED
003480  /*
003481  ** This is a convenience routine that makes sure that all thread-specific
003482  ** data for this thread has been deallocated.
003483  **
003484  ** SQLite no longer uses thread-specific data so this routine is now a
003485  ** no-op.  It is retained for historical compatibility.
003486  */
003487  void sqlite3_thread_cleanup(void){
003488  }
003489  #endif
003490  
003491  /*
003492  ** Return meta information about a specific column of a database table.
003493  ** See comment in sqlite3.h (sqlite.h.in) for details.
003494  */
003495  int sqlite3_table_column_metadata(
003496    sqlite3 *db,                /* Connection handle */
003497    const char *zDbName,        /* Database name or NULL */
003498    const char *zTableName,     /* Table name */
003499    const char *zColumnName,    /* Column name */
003500    char const **pzDataType,    /* OUTPUT: Declared data type */
003501    char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
003502    int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
003503    int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
003504    int *pAutoinc               /* OUTPUT: True if column is auto-increment */
003505  ){
003506    int rc;
003507    char *zErrMsg = 0;
003508    Table *pTab = 0;
003509    Column *pCol = 0;
003510    int iCol = 0;
003511    char const *zDataType = 0;
003512    char const *zCollSeq = 0;
003513    int notnull = 0;
003514    int primarykey = 0;
003515    int autoinc = 0;
003516  
003517  
003518  #ifdef SQLITE_ENABLE_API_ARMOR
003519    if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
003520      return SQLITE_MISUSE_BKPT;
003521    }
003522  #endif
003523  
003524    /* Ensure the database schema has been loaded */
003525    sqlite3_mutex_enter(db->mutex);
003526    sqlite3BtreeEnterAll(db);
003527    rc = sqlite3Init(db, &zErrMsg);
003528    if( SQLITE_OK!=rc ){
003529      goto error_out;
003530    }
003531  
003532    /* Locate the table in question */
003533    pTab = sqlite3FindTable(db, zTableName, zDbName);
003534    if( !pTab || pTab->pSelect ){
003535      pTab = 0;
003536      goto error_out;
003537    }
003538  
003539    /* Find the column for which info is requested */
003540    if( zColumnName==0 ){
003541      /* Query for existance of table only */
003542    }else{
003543      for(iCol=0; iCol<pTab->nCol; iCol++){
003544        pCol = &pTab->aCol[iCol];
003545        if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
003546          break;
003547        }
003548      }
003549      if( iCol==pTab->nCol ){
003550        if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
003551          iCol = pTab->iPKey;
003552          pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
003553        }else{
003554          pTab = 0;
003555          goto error_out;
003556        }
003557      }
003558    }
003559  
003560    /* The following block stores the meta information that will be returned
003561    ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
003562    ** and autoinc. At this point there are two possibilities:
003563    ** 
003564    **     1. The specified column name was rowid", "oid" or "_rowid_" 
003565    **        and there is no explicitly declared IPK column. 
003566    **
003567    **     2. The table is not a view and the column name identified an 
003568    **        explicitly declared column. Copy meta information from *pCol.
003569    */ 
003570    if( pCol ){
003571      zDataType = sqlite3ColumnType(pCol,0);
003572      zCollSeq = pCol->zColl;
003573      notnull = pCol->notNull!=0;
003574      primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
003575      autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
003576    }else{
003577      zDataType = "INTEGER";
003578      primarykey = 1;
003579    }
003580    if( !zCollSeq ){
003581      zCollSeq = sqlite3StrBINARY;
003582    }
003583  
003584  error_out:
003585    sqlite3BtreeLeaveAll(db);
003586  
003587    /* Whether the function call succeeded or failed, set the output parameters
003588    ** to whatever their local counterparts contain. If an error did occur,
003589    ** this has the effect of zeroing all output parameters.
003590    */
003591    if( pzDataType ) *pzDataType = zDataType;
003592    if( pzCollSeq ) *pzCollSeq = zCollSeq;
003593    if( pNotNull ) *pNotNull = notnull;
003594    if( pPrimaryKey ) *pPrimaryKey = primarykey;
003595    if( pAutoinc ) *pAutoinc = autoinc;
003596  
003597    if( SQLITE_OK==rc && !pTab ){
003598      sqlite3DbFree(db, zErrMsg);
003599      zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
003600          zColumnName);
003601      rc = SQLITE_ERROR;
003602    }
003603    sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
003604    sqlite3DbFree(db, zErrMsg);
003605    rc = sqlite3ApiExit(db, rc);
003606    sqlite3_mutex_leave(db->mutex);
003607    return rc;
003608  }
003609  
003610  /*
003611  ** Sleep for a little while.  Return the amount of time slept.
003612  */
003613  int sqlite3_sleep(int ms){
003614    sqlite3_vfs *pVfs;
003615    int rc;
003616    pVfs = sqlite3_vfs_find(0);
003617    if( pVfs==0 ) return 0;
003618  
003619    /* This function works in milliseconds, but the underlying OsSleep() 
003620    ** API uses microseconds. Hence the 1000's.
003621    */
003622    rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
003623    return rc;
003624  }
003625  
003626  /*
003627  ** Enable or disable the extended result codes.
003628  */
003629  int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
003630  #ifdef SQLITE_ENABLE_API_ARMOR
003631    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
003632  #endif
003633    sqlite3_mutex_enter(db->mutex);
003634    db->errMask = onoff ? 0xffffffff : 0xff;
003635    sqlite3_mutex_leave(db->mutex);
003636    return SQLITE_OK;
003637  }
003638  
003639  /*
003640  ** Invoke the xFileControl method on a particular database.
003641  */
003642  int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
003643    int rc = SQLITE_ERROR;
003644    Btree *pBtree;
003645  
003646  #ifdef SQLITE_ENABLE_API_ARMOR
003647    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
003648  #endif
003649    sqlite3_mutex_enter(db->mutex);
003650    pBtree = sqlite3DbNameToBtree(db, zDbName);
003651    if( pBtree ){
003652      Pager *pPager;
003653      sqlite3_file *fd;
003654      sqlite3BtreeEnter(pBtree);
003655      pPager = sqlite3BtreePager(pBtree);
003656      assert( pPager!=0 );
003657      fd = sqlite3PagerFile(pPager);
003658      assert( fd!=0 );
003659      if( op==SQLITE_FCNTL_FILE_POINTER ){
003660        *(sqlite3_file**)pArg = fd;
003661        rc = SQLITE_OK;
003662      }else if( op==SQLITE_FCNTL_VFS_POINTER ){
003663        *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
003664        rc = SQLITE_OK;
003665      }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
003666        *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
003667        rc = SQLITE_OK;
003668      }else{
003669        rc = sqlite3OsFileControl(fd, op, pArg);
003670      }
003671      sqlite3BtreeLeave(pBtree);
003672    }
003673    sqlite3_mutex_leave(db->mutex);
003674    return rc;
003675  }
003676  
003677  /*
003678  ** Interface to the testing logic.
003679  */
003680  int sqlite3_test_control(int op, ...){
003681    int rc = 0;
003682  #ifdef SQLITE_UNTESTABLE
003683    UNUSED_PARAMETER(op);
003684  #else
003685    va_list ap;
003686    va_start(ap, op);
003687    switch( op ){
003688  
003689      /*
003690      ** Save the current state of the PRNG.
003691      */
003692      case SQLITE_TESTCTRL_PRNG_SAVE: {
003693        sqlite3PrngSaveState();
003694        break;
003695      }
003696  
003697      /*
003698      ** Restore the state of the PRNG to the last state saved using
003699      ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
003700      ** this verb acts like PRNG_RESET.
003701      */
003702      case SQLITE_TESTCTRL_PRNG_RESTORE: {
003703        sqlite3PrngRestoreState();
003704        break;
003705      }
003706  
003707      /*
003708      ** Reset the PRNG back to its uninitialized state.  The next call
003709      ** to sqlite3_randomness() will reseed the PRNG using a single call
003710      ** to the xRandomness method of the default VFS.
003711      */
003712      case SQLITE_TESTCTRL_PRNG_RESET: {
003713        sqlite3_randomness(0,0);
003714        break;
003715      }
003716  
003717      /*
003718      **  sqlite3_test_control(BITVEC_TEST, size, program)
003719      **
003720      ** Run a test against a Bitvec object of size.  The program argument
003721      ** is an array of integers that defines the test.  Return -1 on a
003722      ** memory allocation error, 0 on success, or non-zero for an error.
003723      ** See the sqlite3BitvecBuiltinTest() for additional information.
003724      */
003725      case SQLITE_TESTCTRL_BITVEC_TEST: {
003726        int sz = va_arg(ap, int);
003727        int *aProg = va_arg(ap, int*);
003728        rc = sqlite3BitvecBuiltinTest(sz, aProg);
003729        break;
003730      }
003731  
003732      /*
003733      **  sqlite3_test_control(FAULT_INSTALL, xCallback)
003734      **
003735      ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
003736      ** if xCallback is not NULL.
003737      **
003738      ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
003739      ** is called immediately after installing the new callback and the return
003740      ** value from sqlite3FaultSim(0) becomes the return from
003741      ** sqlite3_test_control().
003742      */
003743      case SQLITE_TESTCTRL_FAULT_INSTALL: {
003744        /* MSVC is picky about pulling func ptrs from va lists.
003745        ** http://support.microsoft.com/kb/47961
003746        ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
003747        */
003748        typedef int(*TESTCALLBACKFUNC_t)(int);
003749        sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
003750        rc = sqlite3FaultSim(0);
003751        break;
003752      }
003753  
003754      /*
003755      **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
003756      **
003757      ** Register hooks to call to indicate which malloc() failures 
003758      ** are benign.
003759      */
003760      case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
003761        typedef void (*void_function)(void);
003762        void_function xBenignBegin;
003763        void_function xBenignEnd;
003764        xBenignBegin = va_arg(ap, void_function);
003765        xBenignEnd = va_arg(ap, void_function);
003766        sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
003767        break;
003768      }
003769  
003770      /*
003771      **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
003772      **
003773      ** Set the PENDING byte to the value in the argument, if X>0.
003774      ** Make no changes if X==0.  Return the value of the pending byte
003775      ** as it existing before this routine was called.
003776      **
003777      ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
003778      ** an incompatible database file format.  Changing the PENDING byte
003779      ** while any database connection is open results in undefined and
003780      ** deleterious behavior.
003781      */
003782      case SQLITE_TESTCTRL_PENDING_BYTE: {
003783        rc = PENDING_BYTE;
003784  #ifndef SQLITE_OMIT_WSD
003785        {
003786          unsigned int newVal = va_arg(ap, unsigned int);
003787          if( newVal ) sqlite3PendingByte = newVal;
003788        }
003789  #endif
003790        break;
003791      }
003792  
003793      /*
003794      **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
003795      **
003796      ** This action provides a run-time test to see whether or not
003797      ** assert() was enabled at compile-time.  If X is true and assert()
003798      ** is enabled, then the return value is true.  If X is true and
003799      ** assert() is disabled, then the return value is zero.  If X is
003800      ** false and assert() is enabled, then the assertion fires and the
003801      ** process aborts.  If X is false and assert() is disabled, then the
003802      ** return value is zero.
003803      */
003804      case SQLITE_TESTCTRL_ASSERT: {
003805        volatile int x = 0;
003806        assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
003807        rc = x;
003808        break;
003809      }
003810  
003811  
003812      /*
003813      **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
003814      **
003815      ** This action provides a run-time test to see how the ALWAYS and
003816      ** NEVER macros were defined at compile-time.
003817      **
003818      ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
003819      **
003820      ** The recommended test is X==2.  If the return value is 2, that means
003821      ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
003822      ** default setting.  If the return value is 1, then ALWAYS() is either
003823      ** hard-coded to true or else it asserts if its argument is false.
003824      ** The first behavior (hard-coded to true) is the case if
003825      ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
003826      ** behavior (assert if the argument to ALWAYS() is false) is the case if
003827      ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
003828      **
003829      ** The run-time test procedure might look something like this:
003830      **
003831      **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
003832      **      // ALWAYS() and NEVER() are no-op pass-through macros
003833      **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
003834      **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
003835      **    }else{
003836      **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
003837      **    }
003838      */
003839      case SQLITE_TESTCTRL_ALWAYS: {
003840        int x = va_arg(ap,int);
003841        rc = x ? ALWAYS(x) : 0;
003842        break;
003843      }
003844  
003845      /*
003846      **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
003847      **
003848      ** The integer returned reveals the byte-order of the computer on which
003849      ** SQLite is running:
003850      **
003851      **       1     big-endian,    determined at run-time
003852      **      10     little-endian, determined at run-time
003853      **  432101     big-endian,    determined at compile-time
003854      **  123410     little-endian, determined at compile-time
003855      */ 
003856      case SQLITE_TESTCTRL_BYTEORDER: {
003857        rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
003858        break;
003859      }
003860  
003861      /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
003862      **
003863      ** Set the nReserve size to N for the main database on the database
003864      ** connection db.
003865      */
003866      case SQLITE_TESTCTRL_RESERVE: {
003867        sqlite3 *db = va_arg(ap, sqlite3*);
003868        int x = va_arg(ap,int);
003869        sqlite3_mutex_enter(db->mutex);
003870        sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
003871        sqlite3_mutex_leave(db->mutex);
003872        break;
003873      }
003874  
003875      /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
003876      **
003877      ** Enable or disable various optimizations for testing purposes.  The 
003878      ** argument N is a bitmask of optimizations to be disabled.  For normal
003879      ** operation N should be 0.  The idea is that a test program (like the
003880      ** SQL Logic Test or SLT test module) can run the same SQL multiple times
003881      ** with various optimizations disabled to verify that the same answer
003882      ** is obtained in every case.
003883      */
003884      case SQLITE_TESTCTRL_OPTIMIZATIONS: {
003885        sqlite3 *db = va_arg(ap, sqlite3*);
003886        db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
003887        break;
003888      }
003889  
003890      /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
003891      **
003892      ** If parameter onoff is non-zero, configure the wrappers so that all
003893      ** subsequent calls to localtime() and variants fail. If onoff is zero,
003894      ** undo this setting.
003895      */
003896      case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
003897        sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
003898        break;
003899      }
003900  
003901      /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
003902      **
003903      ** Set or clear a flag that indicates that the database file is always well-
003904      ** formed and never corrupt.  This flag is clear by default, indicating that
003905      ** database files might have arbitrary corruption.  Setting the flag during
003906      ** testing causes certain assert() statements in the code to be activated
003907      ** that demonstrat invariants on well-formed database files.
003908      */
003909      case SQLITE_TESTCTRL_NEVER_CORRUPT: {
003910        sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
003911        break;
003912      }
003913  
003914      /* Set the threshold at which OP_Once counters reset back to zero.
003915      ** By default this is 0x7ffffffe (over 2 billion), but that value is
003916      ** too big to test in a reasonable amount of time, so this control is
003917      ** provided to set a small and easily reachable reset value.
003918      */
003919      case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
003920        sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
003921        break;
003922      }
003923  
003924      /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
003925      **
003926      ** Set the VDBE coverage callback function to xCallback with context 
003927      ** pointer ptr.
003928      */
003929      case SQLITE_TESTCTRL_VDBE_COVERAGE: {
003930  #ifdef SQLITE_VDBE_COVERAGE
003931        typedef void (*branch_callback)(void*,int,u8,u8);
003932        sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
003933        sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
003934  #endif
003935        break;
003936      }
003937  
003938      /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
003939      case SQLITE_TESTCTRL_SORTER_MMAP: {
003940        sqlite3 *db = va_arg(ap, sqlite3*);
003941        db->nMaxSorterMmap = va_arg(ap, int);
003942        break;
003943      }
003944  
003945      /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
003946      **
003947      ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
003948      ** not.
003949      */
003950      case SQLITE_TESTCTRL_ISINIT: {
003951        if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
003952        break;
003953      }
003954  
003955      /*  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
003956      **
003957      ** This test control is used to create imposter tables.  "db" is a pointer
003958      ** to the database connection.  dbName is the database name (ex: "main" or
003959      ** "temp") which will receive the imposter.  "onOff" turns imposter mode on
003960      ** or off.  "tnum" is the root page of the b-tree to which the imposter
003961      ** table should connect.
003962      **
003963      ** Enable imposter mode only when the schema has already been parsed.  Then
003964      ** run a single CREATE TABLE statement to construct the imposter table in
003965      ** the parsed schema.  Then turn imposter mode back off again.
003966      **
003967      ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
003968      ** the schema to be reparsed the next time it is needed.  This has the
003969      ** effect of erasing all imposter tables.
003970      */
003971      case SQLITE_TESTCTRL_IMPOSTER: {
003972        sqlite3 *db = va_arg(ap, sqlite3*);
003973        sqlite3_mutex_enter(db->mutex);
003974        db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
003975        db->init.busy = db->init.imposterTable = va_arg(ap,int);
003976        db->init.newTnum = va_arg(ap,int);
003977        if( db->init.busy==0 && db->init.newTnum>0 ){
003978          sqlite3ResetAllSchemasOfConnection(db);
003979        }
003980        sqlite3_mutex_leave(db->mutex);
003981        break;
003982      }
003983  
003984  #if defined(YYCOVERAGE)
003985      /*  sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
003986      **
003987      ** This test control (only available when SQLite is compiled with
003988      ** -DYYCOVERAGE) writes a report onto "out" that shows all
003989      ** state/lookahead combinations in the parser state machine
003990      ** which are never exercised.  If any state is missed, make the
003991      ** return code SQLITE_ERROR.
003992      */
003993      case SQLITE_TESTCTRL_PARSER_COVERAGE: {
003994        FILE *out = va_arg(ap, FILE*);
003995        if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
003996        break;
003997      }
003998  #endif /* defined(YYCOVERAGE) */
003999    }
004000    va_end(ap);
004001  #endif /* SQLITE_UNTESTABLE */
004002    return rc;
004003  }
004004  
004005  /*
004006  ** This is a utility routine, useful to VFS implementations, that checks
004007  ** to see if a database file was a URI that contained a specific query 
004008  ** parameter, and if so obtains the value of the query parameter.
004009  **
004010  ** The zFilename argument is the filename pointer passed into the xOpen()
004011  ** method of a VFS implementation.  The zParam argument is the name of the
004012  ** query parameter we seek.  This routine returns the value of the zParam
004013  ** parameter if it exists.  If the parameter does not exist, this routine
004014  ** returns a NULL pointer.
004015  */
004016  const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
004017    if( zFilename==0 || zParam==0 ) return 0;
004018    zFilename += sqlite3Strlen30(zFilename) + 1;
004019    while( zFilename[0] ){
004020      int x = strcmp(zFilename, zParam);
004021      zFilename += sqlite3Strlen30(zFilename) + 1;
004022      if( x==0 ) return zFilename;
004023      zFilename += sqlite3Strlen30(zFilename) + 1;
004024    }
004025    return 0;
004026  }
004027  
004028  /*
004029  ** Return a boolean value for a query parameter.
004030  */
004031  int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
004032    const char *z = sqlite3_uri_parameter(zFilename, zParam);
004033    bDflt = bDflt!=0;
004034    return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
004035  }
004036  
004037  /*
004038  ** Return a 64-bit integer value for a query parameter.
004039  */
004040  sqlite3_int64 sqlite3_uri_int64(
004041    const char *zFilename,    /* Filename as passed to xOpen */
004042    const char *zParam,       /* URI parameter sought */
004043    sqlite3_int64 bDflt       /* return if parameter is missing */
004044  ){
004045    const char *z = sqlite3_uri_parameter(zFilename, zParam);
004046    sqlite3_int64 v;
004047    if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
004048      bDflt = v;
004049    }
004050    return bDflt;
004051  }
004052  
004053  /*
004054  ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
004055  */
004056  Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
004057    int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
004058    return iDb<0 ? 0 : db->aDb[iDb].pBt;
004059  }
004060  
004061  /*
004062  ** Return the filename of the database associated with a database
004063  ** connection.
004064  */
004065  const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
004066    Btree *pBt;
004067  #ifdef SQLITE_ENABLE_API_ARMOR
004068    if( !sqlite3SafetyCheckOk(db) ){
004069      (void)SQLITE_MISUSE_BKPT;
004070      return 0;
004071    }
004072  #endif
004073    pBt = sqlite3DbNameToBtree(db, zDbName);
004074    return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
004075  }
004076  
004077  /*
004078  ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
004079  ** no such database exists.
004080  */
004081  int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
004082    Btree *pBt;
004083  #ifdef SQLITE_ENABLE_API_ARMOR
004084    if( !sqlite3SafetyCheckOk(db) ){
004085      (void)SQLITE_MISUSE_BKPT;
004086      return -1;
004087    }
004088  #endif
004089    pBt = sqlite3DbNameToBtree(db, zDbName);
004090    return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
004091  }
004092  
004093  #ifdef SQLITE_ENABLE_SNAPSHOT
004094  /*
004095  ** Obtain a snapshot handle for the snapshot of database zDb currently 
004096  ** being read by handle db.
004097  */
004098  int sqlite3_snapshot_get(
004099    sqlite3 *db, 
004100    const char *zDb,
004101    sqlite3_snapshot **ppSnapshot
004102  ){
004103    int rc = SQLITE_ERROR;
004104  #ifndef SQLITE_OMIT_WAL
004105  
004106  #ifdef SQLITE_ENABLE_API_ARMOR
004107    if( !sqlite3SafetyCheckOk(db) ){
004108      return SQLITE_MISUSE_BKPT;
004109    }
004110  #endif
004111    sqlite3_mutex_enter(db->mutex);
004112  
004113    if( db->autoCommit==0 ){
004114      int iDb = sqlite3FindDbName(db, zDb);
004115      if( iDb==0 || iDb>1 ){
004116        Btree *pBt = db->aDb[iDb].pBt;
004117        if( 0==sqlite3BtreeIsInTrans(pBt) ){
004118          rc = sqlite3BtreeBeginTrans(pBt, 0);
004119          if( rc==SQLITE_OK ){
004120            rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
004121          }
004122        }
004123      }
004124    }
004125  
004126    sqlite3_mutex_leave(db->mutex);
004127  #endif   /* SQLITE_OMIT_WAL */
004128    return rc;
004129  }
004130  
004131  /*
004132  ** Open a read-transaction on the snapshot idendified by pSnapshot.
004133  */
004134  int sqlite3_snapshot_open(
004135    sqlite3 *db, 
004136    const char *zDb, 
004137    sqlite3_snapshot *pSnapshot
004138  ){
004139    int rc = SQLITE_ERROR;
004140  #ifndef SQLITE_OMIT_WAL
004141  
004142  #ifdef SQLITE_ENABLE_API_ARMOR
004143    if( !sqlite3SafetyCheckOk(db) ){
004144      return SQLITE_MISUSE_BKPT;
004145    }
004146  #endif
004147    sqlite3_mutex_enter(db->mutex);
004148    if( db->autoCommit==0 ){
004149      int iDb;
004150      iDb = sqlite3FindDbName(db, zDb);
004151      if( iDb==0 || iDb>1 ){
004152        Btree *pBt = db->aDb[iDb].pBt;
004153        if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
004154          rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
004155          if( rc==SQLITE_OK ){
004156            rc = sqlite3BtreeBeginTrans(pBt, 0);
004157            sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
004158          }
004159        }
004160      }
004161    }
004162  
004163    sqlite3_mutex_leave(db->mutex);
004164  #endif   /* SQLITE_OMIT_WAL */
004165    return rc;
004166  }
004167  
004168  /*
004169  ** Recover as many snapshots as possible from the wal file associated with
004170  ** schema zDb of database db.
004171  */
004172  int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
004173    int rc = SQLITE_ERROR;
004174    int iDb;
004175  #ifndef SQLITE_OMIT_WAL
004176  
004177  #ifdef SQLITE_ENABLE_API_ARMOR
004178    if( !sqlite3SafetyCheckOk(db) ){
004179      return SQLITE_MISUSE_BKPT;
004180    }
004181  #endif
004182  
004183    sqlite3_mutex_enter(db->mutex);
004184    iDb = sqlite3FindDbName(db, zDb);
004185    if( iDb==0 || iDb>1 ){
004186      Btree *pBt = db->aDb[iDb].pBt;
004187      if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
004188        rc = sqlite3BtreeBeginTrans(pBt, 0);
004189        if( rc==SQLITE_OK ){
004190          rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
004191          sqlite3BtreeCommit(pBt);
004192        }
004193      }
004194    }
004195    sqlite3_mutex_leave(db->mutex);
004196  #endif   /* SQLITE_OMIT_WAL */
004197    return rc;
004198  }
004199  
004200  /*
004201  ** Free a snapshot handle obtained from sqlite3_snapshot_get().
004202  */
004203  void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
004204    sqlite3_free(pSnapshot);
004205  }
004206  #endif /* SQLITE_ENABLE_SNAPSHOT */
004207  
004208  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
004209  /*
004210  ** Given the name of a compile-time option, return true if that option
004211  ** was used and false if not.
004212  **
004213  ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
004214  ** is not required for a match.
004215  */
004216  int sqlite3_compileoption_used(const char *zOptName){
004217    int i, n;
004218    int nOpt;
004219    const char **azCompileOpt;
004220   
004221  #if SQLITE_ENABLE_API_ARMOR
004222    if( zOptName==0 ){
004223      (void)SQLITE_MISUSE_BKPT;
004224      return 0;
004225    }
004226  #endif
004227  
004228    azCompileOpt = sqlite3CompileOptions(&nOpt);
004229  
004230    if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
004231    n = sqlite3Strlen30(zOptName);
004232  
004233    /* Since nOpt is normally in single digits, a linear search is 
004234    ** adequate. No need for a binary search. */
004235    for(i=0; i<nOpt; i++){
004236      if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
004237       && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
004238      ){
004239        return 1;
004240      }
004241    }
004242    return 0;
004243  }
004244  
004245  /*
004246  ** Return the N-th compile-time option string.  If N is out of range,
004247  ** return a NULL pointer.
004248  */
004249  const char *sqlite3_compileoption_get(int N){
004250    int nOpt;
004251    const char **azCompileOpt;
004252    azCompileOpt = sqlite3CompileOptions(&nOpt);
004253    if( N>=0 && N<nOpt ){
004254      return azCompileOpt[N];
004255    }
004256    return 0;
004257  }
004258  #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */