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