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