000001  /*
000002  ** 2001 September 15
000003  **
000004  ** The author disclaims copyright to this source code.  In place of
000005  ** a legal notice, here is a blessing:
000006  **
000007  **    May you do good and not evil.
000008  **    May you find forgiveness for yourself and forgive others.
000009  **    May you share freely, never taking more than you give.
000010  **
000011  *************************************************************************
000012  ** Main file for the SQLite library.  The routines in this file
000013  ** implement the programmer interface to the library.  Routines in
000014  ** other files are for internal use by SQLite and should not be
000015  ** accessed by users of the library.
000016  */
000017  #include "sqliteInt.h"
000018  
000019  #ifdef SQLITE_ENABLE_FTS3
000020  # include "fts3.h"
000021  #endif
000022  #ifdef SQLITE_ENABLE_RTREE
000023  # include "rtree.h"
000024  #endif
000025  #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
000026  # include "sqliteicu.h"
000027  #endif
000028  
000029  /*
000030  ** This is an extension initializer that is a no-op and always
000031  ** succeeds, except that it fails if the fault-simulation is set
000032  ** to 500.
000033  */
000034  static int sqlite3TestExtInit(sqlite3 *db){
000035    (void)db;
000036    return sqlite3FaultSim(500);
000037  }
000038  
000039  
000040  /*
000041  ** Forward declarations of external module initializer functions
000042  ** for modules that need them.
000043  */
000044  #ifdef SQLITE_ENABLE_FTS5
000045  int sqlite3Fts5Init(sqlite3*);
000046  #endif
000047  #ifdef SQLITE_ENABLE_STMTVTAB
000048  int sqlite3StmtVtabInit(sqlite3*);
000049  #endif
000050  #ifdef SQLITE_EXTRA_AUTOEXT
000051  int SQLITE_EXTRA_AUTOEXT(sqlite3*);
000052  #endif
000053  /*
000054  ** An array of pointers to extension initializer functions for
000055  ** built-in extensions.
000056  */
000057  static int (*const sqlite3BuiltinExtensions[])(sqlite3*) = {
000058  #ifdef SQLITE_ENABLE_FTS3
000059    sqlite3Fts3Init,
000060  #endif
000061  #ifdef SQLITE_ENABLE_FTS5
000062    sqlite3Fts5Init,
000063  #endif
000064  #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
000065    sqlite3IcuInit,
000066  #endif
000067  #ifdef SQLITE_ENABLE_RTREE
000068    sqlite3RtreeInit,
000069  #endif
000070  #ifdef SQLITE_ENABLE_DBPAGE_VTAB
000071    sqlite3DbpageRegister,
000072  #endif
000073  #ifdef SQLITE_ENABLE_DBSTAT_VTAB
000074    sqlite3DbstatRegister,
000075  #endif
000076    sqlite3TestExtInit,
000077  #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
000078    sqlite3JsonTableFunctions,
000079  #endif
000080  #ifdef SQLITE_ENABLE_STMTVTAB
000081    sqlite3StmtVtabInit,
000082  #endif
000083  #ifdef SQLITE_ENABLE_BYTECODE_VTAB
000084    sqlite3VdbeBytecodeVtabInit,
000085  #endif
000086  #ifdef SQLITE_EXTRA_AUTOEXT
000087    SQLITE_EXTRA_AUTOEXT,
000088  #endif
000089  };
000090  
000091  #ifndef SQLITE_AMALGAMATION
000092  /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
000093  ** contains the text of SQLITE_VERSION macro.
000094  */
000095  const char sqlite3_version[] = SQLITE_VERSION;
000096  #endif
000097  
000098  /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
000099  ** a pointer to the to the sqlite3_version[] string constant.
000100  */
000101  const char *sqlite3_libversion(void){ return sqlite3_version; }
000102  
000103  /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
000104  ** pointer to a string constant whose value is the same as the
000105  ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
000106  ** an edited copy of the amalgamation, then the last four characters of
000107  ** the hash might be different from SQLITE_SOURCE_ID.
000108  */
000109  const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
000110  
000111  /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
000112  ** returns an integer equal to SQLITE_VERSION_NUMBER.
000113  */
000114  int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
000115  
000116  /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
000117  ** zero if and only if SQLite was compiled with mutexing code omitted due to
000118  ** the SQLITE_THREADSAFE compile-time option being set to 0.
000119  */
000120  int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
000121  
000122  /*
000123  ** When compiling the test fixture or with debugging enabled (on Win32),
000124  ** this variable being set to non-zero will cause OSTRACE macros to emit
000125  ** extra diagnostic information.
000126  */
000127  #ifdef SQLITE_HAVE_OS_TRACE
000128  # ifndef SQLITE_DEBUG_OS_TRACE
000129  #   define SQLITE_DEBUG_OS_TRACE 0
000130  # endif
000131    int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
000132  #endif
000133  
000134  #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
000135  /*
000136  ** If the following function pointer is not NULL and if
000137  ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
000138  ** I/O active are written using this function.  These messages
000139  ** are intended for debugging activity only.
000140  */
000141  SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
000142  #endif
000143  
000144  /*
000145  ** If the following global variable points to a string which is the
000146  ** name of a directory, then that directory will be used to store
000147  ** temporary files.
000148  **
000149  ** See also the "PRAGMA temp_store_directory" SQL command.
000150  */
000151  char *sqlite3_temp_directory = 0;
000152  
000153  /*
000154  ** If the following global variable points to a string which is the
000155  ** name of a directory, then that directory will be used to store
000156  ** all database files specified with a relative pathname.
000157  **
000158  ** See also the "PRAGMA data_store_directory" SQL command.
000159  */
000160  char *sqlite3_data_directory = 0;
000161  
000162  /*
000163  ** Determine whether or not high-precision (long double) floating point
000164  ** math works correctly on CPU currently running.
000165  */
000166  static SQLITE_NOINLINE int hasHighPrecisionDouble(int rc){
000167    if( sizeof(LONGDOUBLE_TYPE)<=8 ){
000168      /* If the size of "long double" is not more than 8, then
000169      ** high-precision math is not possible. */
000170      return 0;
000171    }else{
000172      /* Just because sizeof(long double)>8 does not mean that the underlying
000173      ** hardware actually supports high-precision floating point.  For example,
000174      ** clearing the 0x100 bit in the floating-point control word on Intel
000175      ** processors will make long double work like double, even though long
000176      ** double takes up more space.  The only way to determine if long double
000177      ** actually works is to run an experiment. */
000178      LONGDOUBLE_TYPE a, b, c;
000179      rc++;
000180      a = 1.0+rc*0.1;
000181      b = 1.0e+18+rc*25.0;
000182      c = a+b;
000183      return b!=c;
000184    }
000185  }
000186  
000187  
000188  /*
000189  ** Initialize SQLite. 
000190  **
000191  ** This routine must be called to initialize the memory allocation,
000192  ** VFS, and mutex subsystems prior to doing any serious work with
000193  ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
000194  ** this routine will be called automatically by key routines such as
000195  ** sqlite3_open(). 
000196  **
000197  ** This routine is a no-op except on its very first call for the process,
000198  ** or for the first call after a call to sqlite3_shutdown.
000199  **
000200  ** The first thread to call this routine runs the initialization to
000201  ** completion.  If subsequent threads call this routine before the first
000202  ** thread has finished the initialization process, then the subsequent
000203  ** threads must block until the first thread finishes with the initialization.
000204  **
000205  ** The first thread might call this routine recursively.  Recursive
000206  ** calls to this routine should not block, of course.  Otherwise the
000207  ** initialization process would never complete.
000208  **
000209  ** Let X be the first thread to enter this routine.  Let Y be some other
000210  ** thread.  Then while the initial invocation of this routine by X is
000211  ** incomplete, it is required that:
000212  **
000213  **    *  Calls to this routine from Y must block until the outer-most
000214  **       call by X completes.
000215  **
000216  **    *  Recursive calls to this routine from thread X return immediately
000217  **       without blocking.
000218  */
000219  int sqlite3_initialize(void){
000220    MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )      /* The main static mutex */
000221    int rc;                                      /* Result code */
000222  #ifdef SQLITE_EXTRA_INIT
000223    int bRunExtraInit = 0;                       /* Extra initialization needed */
000224  #endif
000225  
000226  #ifdef SQLITE_OMIT_WSD
000227    rc = sqlite3_wsd_init(4096, 24);
000228    if( rc!=SQLITE_OK ){
000229      return rc;
000230    }
000231  #endif
000232  
000233    /* If the following assert() fails on some obscure processor/compiler
000234    ** combination, the work-around is to set the correct pointer
000235    ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
000236    assert( SQLITE_PTRSIZE==sizeof(char*) );
000237  
000238    /* If SQLite is already completely initialized, then this call
000239    ** to sqlite3_initialize() should be a no-op.  But the initialization
000240    ** must be complete.  So isInit must not be set until the very end
000241    ** of this routine.
000242    */
000243    if( sqlite3GlobalConfig.isInit ){
000244      sqlite3MemoryBarrier();
000245      return SQLITE_OK;
000246    }
000247  
000248    /* Make sure the mutex subsystem is initialized.  If unable to
000249    ** initialize the mutex subsystem, return early with the error.
000250    ** If the system is so sick that we are unable to allocate a mutex,
000251    ** there is not much SQLite is going to be able to do.
000252    **
000253    ** The mutex subsystem must take care of serializing its own
000254    ** initialization.
000255    */
000256    rc = sqlite3MutexInit();
000257    if( rc ) return rc;
000258  
000259    /* Initialize the malloc() system and the recursive pInitMutex mutex.
000260    ** This operation is protected by the STATIC_MAIN mutex.  Note that
000261    ** MutexAlloc() is called for a static mutex prior to initializing the
000262    ** malloc subsystem - this implies that the allocation of a static
000263    ** mutex must not require support from the malloc subsystem.
000264    */
000265    MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
000266    sqlite3_mutex_enter(pMainMtx);
000267    sqlite3GlobalConfig.isMutexInit = 1;
000268    if( !sqlite3GlobalConfig.isMallocInit ){
000269      rc = sqlite3MallocInit();
000270    }
000271    if( rc==SQLITE_OK ){
000272      sqlite3GlobalConfig.isMallocInit = 1;
000273      if( !sqlite3GlobalConfig.pInitMutex ){
000274        sqlite3GlobalConfig.pInitMutex =
000275             sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
000276        if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
000277          rc = SQLITE_NOMEM_BKPT;
000278        }
000279      }
000280    }
000281    if( rc==SQLITE_OK ){
000282      sqlite3GlobalConfig.nRefInitMutex++;
000283    }
000284    sqlite3_mutex_leave(pMainMtx);
000285  
000286    /* If rc is not SQLITE_OK at this point, then either the malloc
000287    ** subsystem could not be initialized or the system failed to allocate
000288    ** the pInitMutex mutex. Return an error in either case.  */
000289    if( rc!=SQLITE_OK ){
000290      return rc;
000291    }
000292  
000293    /* Do the rest of the initialization under the recursive mutex so
000294    ** that we will be able to handle recursive calls into
000295    ** sqlite3_initialize().  The recursive calls normally come through
000296    ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
000297    ** recursive calls might also be possible.
000298    **
000299    ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
000300    ** to the xInit method, so the xInit method need not be threadsafe.
000301    **
000302    ** The following mutex is what serializes access to the appdef pcache xInit
000303    ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
000304    ** call to sqlite3PcacheInitialize().
000305    */
000306    sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
000307    if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
000308      sqlite3GlobalConfig.inProgress = 1;
000309  #ifdef SQLITE_ENABLE_SQLLOG
000310      {
000311        extern void sqlite3_init_sqllog(void);
000312        sqlite3_init_sqllog();
000313      }
000314  #endif
000315      memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
000316      sqlite3RegisterBuiltinFunctions();
000317      if( sqlite3GlobalConfig.isPCacheInit==0 ){
000318        rc = sqlite3PcacheInitialize();
000319      }
000320      if( rc==SQLITE_OK ){
000321        sqlite3GlobalConfig.isPCacheInit = 1;
000322        rc = sqlite3OsInit();
000323      }
000324  #ifndef SQLITE_OMIT_DESERIALIZE
000325      if( rc==SQLITE_OK ){
000326        rc = sqlite3MemdbInit();
000327      }
000328  #endif
000329      if( rc==SQLITE_OK ){
000330        sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
000331            sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
000332        sqlite3MemoryBarrier();
000333        sqlite3GlobalConfig.isInit = 1;
000334  #ifdef SQLITE_EXTRA_INIT
000335        bRunExtraInit = 1;
000336  #endif
000337      }
000338      sqlite3GlobalConfig.inProgress = 0;
000339    }
000340    sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
000341  
000342    /* Go back under the static mutex and clean up the recursive
000343    ** mutex to prevent a resource leak.
000344    */
000345    sqlite3_mutex_enter(pMainMtx);
000346    sqlite3GlobalConfig.nRefInitMutex--;
000347    if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
000348      assert( sqlite3GlobalConfig.nRefInitMutex==0 );
000349      sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
000350      sqlite3GlobalConfig.pInitMutex = 0;
000351    }
000352    sqlite3_mutex_leave(pMainMtx);
000353  
000354    /* The following is just a sanity check to make sure SQLite has
000355    ** been compiled correctly.  It is important to run this code, but
000356    ** we don't want to run it too often and soak up CPU cycles for no
000357    ** reason.  So we run it once during initialization.
000358    */
000359  #ifndef NDEBUG
000360  #ifndef SQLITE_OMIT_FLOATING_POINT
000361    /* This section of code's only "output" is via assert() statements. */
000362    if( rc==SQLITE_OK ){
000363      u64 x = (((u64)1)<<63)-1;
000364      double y;
000365      assert(sizeof(x)==8);
000366      assert(sizeof(x)==sizeof(y));
000367      memcpy(&y, &x, 8);
000368      assert( sqlite3IsNaN(y) );
000369    }
000370  #endif
000371  #endif
000372  
000373    /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
000374    ** compile-time option.
000375    */
000376  #ifdef SQLITE_EXTRA_INIT
000377    if( bRunExtraInit ){
000378      int SQLITE_EXTRA_INIT(const char*);
000379      rc = SQLITE_EXTRA_INIT(0);
000380    }
000381  #endif
000382  
000383    /* Experimentally determine if high-precision floating point is
000384    ** available. */
000385  #ifndef SQLITE_OMIT_WSD
000386    sqlite3Config.bUseLongDouble = hasHighPrecisionDouble(rc);
000387  #endif
000388  
000389    return rc;
000390  }
000391  
000392  /*
000393  ** Undo the effects of sqlite3_initialize().  Must not be called while
000394  ** there are outstanding database connections or memory allocations or
000395  ** while any part of SQLite is otherwise in use in any thread.  This
000396  ** routine is not threadsafe.  But it is safe to invoke this routine
000397  ** on when SQLite is already shut down.  If SQLite is already shut down
000398  ** when this routine is invoked, then this routine is a harmless no-op.
000399  */
000400  int sqlite3_shutdown(void){
000401  #ifdef SQLITE_OMIT_WSD
000402    int rc = sqlite3_wsd_init(4096, 24);
000403    if( rc!=SQLITE_OK ){
000404      return rc;
000405    }
000406  #endif
000407  
000408    if( sqlite3GlobalConfig.isInit ){
000409  #ifdef SQLITE_EXTRA_SHUTDOWN
000410      void SQLITE_EXTRA_SHUTDOWN(void);
000411      SQLITE_EXTRA_SHUTDOWN();
000412  #endif
000413      sqlite3_os_end();
000414      sqlite3_reset_auto_extension();
000415      sqlite3GlobalConfig.isInit = 0;
000416    }
000417    if( sqlite3GlobalConfig.isPCacheInit ){
000418      sqlite3PcacheShutdown();
000419      sqlite3GlobalConfig.isPCacheInit = 0;
000420    }
000421    if( sqlite3GlobalConfig.isMallocInit ){
000422      sqlite3MallocEnd();
000423      sqlite3GlobalConfig.isMallocInit = 0;
000424  
000425  #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
000426      /* The heap subsystem has now been shutdown and these values are supposed
000427      ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
000428      ** which would rely on that heap subsystem; therefore, make sure these
000429      ** values cannot refer to heap memory that was just invalidated when the
000430      ** heap subsystem was shutdown.  This is only done if the current call to
000431      ** this function resulted in the heap subsystem actually being shutdown.
000432      */
000433      sqlite3_data_directory = 0;
000434      sqlite3_temp_directory = 0;
000435  #endif
000436    }
000437    if( sqlite3GlobalConfig.isMutexInit ){
000438      sqlite3MutexEnd();
000439      sqlite3GlobalConfig.isMutexInit = 0;
000440    }
000441  
000442    return SQLITE_OK;
000443  }
000444  
000445  /*
000446  ** This API allows applications to modify the global configuration of
000447  ** the SQLite library at run-time.
000448  **
000449  ** This routine should only be called when there are no outstanding
000450  ** database connections or memory allocations.  This routine is not
000451  ** threadsafe.  Failure to heed these warnings can lead to unpredictable
000452  ** behavior.
000453  */
000454  int sqlite3_config(int op, ...){
000455    va_list ap;
000456    int rc = SQLITE_OK;
000457  
000458    /* sqlite3_config() normally returns SQLITE_MISUSE if it is invoked while
000459    ** the SQLite library is in use.  Except, a few selected opcodes
000460    ** are allowed.
000461    */
000462    if( sqlite3GlobalConfig.isInit ){
000463      static const u64 mAnytimeConfigOption = 0
000464         | MASKBIT64( SQLITE_CONFIG_LOG )
000465         | MASKBIT64( SQLITE_CONFIG_PCACHE_HDRSZ )
000466      ;
000467      if( op<0 || op>63 || (MASKBIT64(op) & mAnytimeConfigOption)==0 ){
000468        return SQLITE_MISUSE_BKPT;
000469      }
000470      testcase( op==SQLITE_CONFIG_LOG );
000471      testcase( op==SQLITE_CONFIG_PCACHE_HDRSZ );
000472    }
000473  
000474    va_start(ap, op);
000475    switch( op ){
000476  
000477      /* Mutex configuration options are only available in a threadsafe
000478      ** compile.
000479      */
000480  #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0  /* IMP: R-54466-46756 */
000481      case SQLITE_CONFIG_SINGLETHREAD: {
000482        /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
000483        ** Single-thread. */
000484        sqlite3GlobalConfig.bCoreMutex = 0;  /* Disable mutex on core */
000485        sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
000486        break;
000487      }
000488  #endif
000489  #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
000490      case SQLITE_CONFIG_MULTITHREAD: {
000491        /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
000492        ** Multi-thread. */
000493        sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
000494        sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
000495        break;
000496      }
000497  #endif
000498  #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
000499      case SQLITE_CONFIG_SERIALIZED: {
000500        /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
000501        ** Serialized. */
000502        sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
000503        sqlite3GlobalConfig.bFullMutex = 1;  /* Enable mutex on connections */
000504        break;
000505      }
000506  #endif
000507  #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
000508      case SQLITE_CONFIG_MUTEX: {
000509        /* Specify an alternative mutex implementation */
000510        sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
000511        break;
000512      }
000513  #endif
000514  #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
000515      case SQLITE_CONFIG_GETMUTEX: {
000516        /* Retrieve the current mutex implementation */
000517        *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
000518        break;
000519      }
000520  #endif
000521  
000522      case SQLITE_CONFIG_MALLOC: {
000523        /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
000524        ** single argument which is a pointer to an instance of the
000525        ** sqlite3_mem_methods structure. The argument specifies alternative
000526        ** low-level memory allocation routines to be used in place of the memory
000527        ** allocation routines built into SQLite. */
000528        sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
000529        break;
000530      }
000531      case SQLITE_CONFIG_GETMALLOC: {
000532        /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
000533        ** single argument which is a pointer to an instance of the
000534        ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
000535        ** filled with the currently defined memory allocation routines. */
000536        if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
000537        *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
000538        break;
000539      }
000540      case SQLITE_CONFIG_MEMSTATUS: {
000541        assert( !sqlite3GlobalConfig.isInit );  /* Cannot change at runtime */
000542        /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
000543        ** single argument of type int, interpreted as a boolean, which enables
000544        ** or disables the collection of memory allocation statistics. */
000545        sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
000546        break;
000547      }
000548      case SQLITE_CONFIG_SMALL_MALLOC: {
000549        sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
000550        break;
000551      }
000552      case SQLITE_CONFIG_PAGECACHE: {
000553        /* EVIDENCE-OF: R-18761-36601 There are three arguments to
000554        ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
000555        ** the size of each page cache line (sz), and the number of cache lines
000556        ** (N). */
000557        sqlite3GlobalConfig.pPage = va_arg(ap, void*);
000558        sqlite3GlobalConfig.szPage = va_arg(ap, int);
000559        sqlite3GlobalConfig.nPage = va_arg(ap, int);
000560        break;
000561      }
000562      case SQLITE_CONFIG_PCACHE_HDRSZ: {
000563        /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
000564        ** a single parameter which is a pointer to an integer and writes into
000565        ** that integer the number of extra bytes per page required for each page
000566        ** in SQLITE_CONFIG_PAGECACHE. */
000567        *va_arg(ap, int*) =
000568            sqlite3HeaderSizeBtree() +
000569            sqlite3HeaderSizePcache() +
000570            sqlite3HeaderSizePcache1();
000571        break;
000572      }
000573  
000574      case SQLITE_CONFIG_PCACHE: {
000575        /* no-op */
000576        break;
000577      }
000578      case SQLITE_CONFIG_GETPCACHE: {
000579        /* now an error */
000580        rc = SQLITE_ERROR;
000581        break;
000582      }
000583  
000584      case SQLITE_CONFIG_PCACHE2: {
000585        /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
000586        ** single argument which is a pointer to an sqlite3_pcache_methods2
000587        ** object. This object specifies the interface to a custom page cache
000588        ** implementation. */
000589        sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
000590        break;
000591      }
000592      case SQLITE_CONFIG_GETPCACHE2: {
000593        /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
000594        ** single argument which is a pointer to an sqlite3_pcache_methods2
000595        ** object. SQLite copies of the current page cache implementation into
000596        ** that object. */
000597        if( sqlite3GlobalConfig.pcache2.xInit==0 ){
000598          sqlite3PCacheSetDefault();
000599        }
000600        *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
000601        break;
000602      }
000603  
000604  /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
000605  ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
000606  ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
000607  #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
000608      case SQLITE_CONFIG_HEAP: {
000609        /* EVIDENCE-OF: R-19854-42126 There are three arguments to
000610        ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
000611        ** number of bytes in the memory buffer, and the minimum allocation size.
000612        */
000613        sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
000614        sqlite3GlobalConfig.nHeap = va_arg(ap, int);
000615        sqlite3GlobalConfig.mnReq = va_arg(ap, int);
000616  
000617        if( sqlite3GlobalConfig.mnReq<1 ){
000618          sqlite3GlobalConfig.mnReq = 1;
000619        }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
000620          /* cap min request size at 2^12 */
000621          sqlite3GlobalConfig.mnReq = (1<<12);
000622        }
000623  
000624        if( sqlite3GlobalConfig.pHeap==0 ){
000625          /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
000626          ** is NULL, then SQLite reverts to using its default memory allocator
000627          ** (the system malloc() implementation), undoing any prior invocation of
000628          ** SQLITE_CONFIG_MALLOC.
000629          **
000630          ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
000631          ** revert to its default implementation when sqlite3_initialize() is run
000632          */
000633          memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
000634        }else{
000635          /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
000636          ** alternative memory allocator is engaged to handle all of SQLites
000637          ** memory allocation needs. */
000638  #ifdef SQLITE_ENABLE_MEMSYS3
000639          sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
000640  #endif
000641  #ifdef SQLITE_ENABLE_MEMSYS5
000642          sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
000643  #endif
000644        }
000645        break;
000646      }
000647  #endif
000648  
000649      case SQLITE_CONFIG_LOOKASIDE: {
000650        sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
000651        sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
000652        break;
000653      }
000654     
000655      /* Record a pointer to the logger function and its first argument.
000656      ** The default is NULL.  Logging is disabled if the function pointer is
000657      ** NULL.
000658      */
000659      case SQLITE_CONFIG_LOG: {
000660        /* MSVC is picky about pulling func ptrs from va lists.
000661        ** http://support.microsoft.com/kb/47961
000662        ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
000663        */
000664        typedef void(*LOGFUNC_t)(void*,int,const char*);
000665        LOGFUNC_t xLog = va_arg(ap, LOGFUNC_t);
000666        void *pLogArg = va_arg(ap, void*);
000667        AtomicStore(&sqlite3GlobalConfig.xLog, xLog);
000668        AtomicStore(&sqlite3GlobalConfig.pLogArg, pLogArg);
000669        break;
000670      }
000671  
000672      /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
000673      ** can be changed at start-time using the
000674      ** sqlite3_config(SQLITE_CONFIG_URI,1) or
000675      ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
000676      */
000677      case SQLITE_CONFIG_URI: {
000678        /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
000679        ** argument of type int. If non-zero, then URI handling is globally
000680        ** enabled. If the parameter is zero, then URI handling is globally
000681        ** disabled. */
000682        int bOpenUri = va_arg(ap, int);
000683        AtomicStore(&sqlite3GlobalConfig.bOpenUri, bOpenUri);
000684        break;
000685      }
000686  
000687      case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
000688        /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
000689        ** option takes a single integer argument which is interpreted as a
000690        ** boolean in order to enable or disable the use of covering indices for
000691        ** full table scans in the query optimizer. */
000692        sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
000693        break;
000694      }
000695  
000696  #ifdef SQLITE_ENABLE_SQLLOG
000697      case SQLITE_CONFIG_SQLLOG: {
000698        typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
000699        sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
000700        sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
000701        break;
000702      }
000703  #endif
000704  
000705      case SQLITE_CONFIG_MMAP_SIZE: {
000706        /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
000707        ** integer (sqlite3_int64) values that are the default mmap size limit
000708        ** (the default setting for PRAGMA mmap_size) and the maximum allowed
000709        ** mmap size limit. */
000710        sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
000711        sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
000712        /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
000713        ** negative, then that argument is changed to its compile-time default.
000714        **
000715        ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
000716        ** silently truncated if necessary so that it does not exceed the
000717        ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
000718        ** compile-time option.
000719        */
000720        if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
000721          mxMmap = SQLITE_MAX_MMAP_SIZE;
000722        }
000723        if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
000724        if( szMmap>mxMmap) szMmap = mxMmap;
000725        sqlite3GlobalConfig.mxMmap = mxMmap;
000726        sqlite3GlobalConfig.szMmap = szMmap;
000727        break;
000728      }
000729  
000730  #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
000731      case SQLITE_CONFIG_WIN32_HEAPSIZE: {
000732        /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
000733        ** unsigned integer value that specifies the maximum size of the created
000734        ** heap. */
000735        sqlite3GlobalConfig.nHeap = va_arg(ap, int);
000736        break;
000737      }
000738  #endif
000739  
000740      case SQLITE_CONFIG_PMASZ: {
000741        sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
000742        break;
000743      }
000744  
000745      case SQLITE_CONFIG_STMTJRNL_SPILL: {
000746        sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
000747        break;
000748      }
000749  
000750  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
000751      case SQLITE_CONFIG_SORTERREF_SIZE: {
000752        int iVal = va_arg(ap, int);
000753        if( iVal<0 ){
000754          iVal = SQLITE_DEFAULT_SORTERREF_SIZE;
000755        }
000756        sqlite3GlobalConfig.szSorterRef = (u32)iVal;
000757        break;
000758      }
000759  #endif /* SQLITE_ENABLE_SORTER_REFERENCES */
000760  
000761  #ifndef SQLITE_OMIT_DESERIALIZE
000762      case SQLITE_CONFIG_MEMDB_MAXSIZE: {
000763        sqlite3GlobalConfig.mxMemdbSize = va_arg(ap, sqlite3_int64);
000764        break;
000765      }
000766  #endif /* SQLITE_OMIT_DESERIALIZE */
000767  
000768      case SQLITE_CONFIG_ROWID_IN_VIEW: {
000769        int *pVal = va_arg(ap,int*);
000770  #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
000771        if( 0==*pVal ) sqlite3GlobalConfig.mNoVisibleRowid = TF_NoVisibleRowid;
000772        if( 1==*pVal ) sqlite3GlobalConfig.mNoVisibleRowid = 0;
000773        *pVal = (sqlite3GlobalConfig.mNoVisibleRowid==0);
000774  #else
000775        *pVal = 0;
000776  #endif
000777        break;
000778      }
000779  
000780      default: {
000781        rc = SQLITE_ERROR;
000782        break;
000783      }
000784    }
000785    va_end(ap);
000786    return rc;
000787  }
000788  
000789  /*
000790  ** Set up the lookaside buffers for a database connection.
000791  ** Return SQLITE_OK on success. 
000792  ** If lookaside is already active, return SQLITE_BUSY.
000793  **
000794  ** The sz parameter is the number of bytes in each lookaside slot.
000795  ** The cnt parameter is the number of slots.  If pStart is NULL the
000796  ** space for the lookaside memory is obtained from sqlite3_malloc().
000797  ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
000798  ** the lookaside memory.
000799  */
000800  static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
000801  #ifndef SQLITE_OMIT_LOOKASIDE
000802    void *pStart;
000803    sqlite3_int64 szAlloc = sz*(sqlite3_int64)cnt;
000804    int nBig;   /* Number of full-size slots */
000805    int nSm;    /* Number smaller LOOKASIDE_SMALL-byte slots */
000806   
000807    if( sqlite3LookasideUsed(db,0)>0 ){
000808      return SQLITE_BUSY;
000809    }
000810    /* Free any existing lookaside buffer for this handle before
000811    ** allocating a new one so we don't have to have space for
000812    ** both at the same time.
000813    */
000814    if( db->lookaside.bMalloced ){
000815      sqlite3_free(db->lookaside.pStart);
000816    }
000817    /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
000818    ** than a pointer to be useful.
000819    */
000820    sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
000821    if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
000822    if( cnt<0 ) cnt = 0;
000823    if( sz==0 || cnt==0 ){
000824      sz = 0;
000825      pStart = 0;
000826    }else if( pBuf==0 ){
000827      sqlite3BeginBenignMalloc();
000828      pStart = sqlite3Malloc( szAlloc );  /* IMP: R-61949-35727 */
000829      sqlite3EndBenignMalloc();
000830      if( pStart ) szAlloc = sqlite3MallocSize(pStart);
000831    }else{
000832      pStart = pBuf;
000833    }
000834  #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
000835    if( sz>=LOOKASIDE_SMALL*3 ){
000836      nBig = szAlloc/(3*LOOKASIDE_SMALL+sz);
000837      nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
000838    }else if( sz>=LOOKASIDE_SMALL*2 ){
000839      nBig = szAlloc/(LOOKASIDE_SMALL+sz);
000840      nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
000841    }else
000842  #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
000843    if( sz>0 ){
000844      nBig = szAlloc/sz;
000845      nSm = 0;
000846    }else{
000847      nBig = nSm = 0;
000848    }
000849    db->lookaside.pStart = pStart;
000850    db->lookaside.pInit = 0;
000851    db->lookaside.pFree = 0;
000852    db->lookaside.sz = (u16)sz;
000853    db->lookaside.szTrue = (u16)sz;
000854    if( pStart ){
000855      int i;
000856      LookasideSlot *p;
000857      assert( sz > (int)sizeof(LookasideSlot*) );
000858      p = (LookasideSlot*)pStart;
000859      for(i=0; i<nBig; i++){
000860        p->pNext = db->lookaside.pInit;
000861        db->lookaside.pInit = p;
000862        p = (LookasideSlot*)&((u8*)p)[sz];
000863      }
000864  #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
000865      db->lookaside.pSmallInit = 0;
000866      db->lookaside.pSmallFree = 0;
000867      db->lookaside.pMiddle = p;
000868      for(i=0; i<nSm; i++){
000869        p->pNext = db->lookaside.pSmallInit;
000870        db->lookaside.pSmallInit = p;
000871        p = (LookasideSlot*)&((u8*)p)[LOOKASIDE_SMALL];
000872      }
000873  #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
000874      assert( ((uptr)p)<=szAlloc + (uptr)pStart );
000875      db->lookaside.pEnd = p;
000876      db->lookaside.bDisable = 0;
000877      db->lookaside.bMalloced = pBuf==0 ?1:0;
000878      db->lookaside.nSlot = nBig+nSm;
000879    }else{
000880      db->lookaside.pStart = 0;
000881  #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
000882      db->lookaside.pSmallInit = 0;
000883      db->lookaside.pSmallFree = 0;
000884      db->lookaside.pMiddle = 0;
000885  #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
000886      db->lookaside.pEnd = 0;
000887      db->lookaside.bDisable = 1;
000888      db->lookaside.sz = 0;
000889      db->lookaside.bMalloced = 0;
000890      db->lookaside.nSlot = 0;
000891    }
000892    db->lookaside.pTrueEnd = db->lookaside.pEnd;
000893    assert( sqlite3LookasideUsed(db,0)==0 );
000894  #endif /* SQLITE_OMIT_LOOKASIDE */
000895    return SQLITE_OK;
000896  }
000897  
000898  /*
000899  ** Return the mutex associated with a database connection.
000900  */
000901  sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
000902  #ifdef SQLITE_ENABLE_API_ARMOR
000903    if( !sqlite3SafetyCheckOk(db) ){
000904      (void)SQLITE_MISUSE_BKPT;
000905      return 0;
000906    }
000907  #endif
000908    return db->mutex;
000909  }
000910  
000911  /*
000912  ** Free up as much memory as we can from the given database
000913  ** connection.
000914  */
000915  int sqlite3_db_release_memory(sqlite3 *db){
000916    int i;
000917  
000918  #ifdef SQLITE_ENABLE_API_ARMOR
000919    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
000920  #endif
000921    sqlite3_mutex_enter(db->mutex);
000922    sqlite3BtreeEnterAll(db);
000923    for(i=0; i<db->nDb; i++){
000924      Btree *pBt = db->aDb[i].pBt;
000925      if( pBt ){
000926        Pager *pPager = sqlite3BtreePager(pBt);
000927        sqlite3PagerShrink(pPager);
000928      }
000929    }
000930    sqlite3BtreeLeaveAll(db);
000931    sqlite3_mutex_leave(db->mutex);
000932    return SQLITE_OK;
000933  }
000934  
000935  /*
000936  ** Flush any dirty pages in the pager-cache for any attached database
000937  ** to disk.
000938  */
000939  int sqlite3_db_cacheflush(sqlite3 *db){
000940    int i;
000941    int rc = SQLITE_OK;
000942    int bSeenBusy = 0;
000943  
000944  #ifdef SQLITE_ENABLE_API_ARMOR
000945    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
000946  #endif
000947    sqlite3_mutex_enter(db->mutex);
000948    sqlite3BtreeEnterAll(db);
000949    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
000950      Btree *pBt = db->aDb[i].pBt;
000951      if( pBt && sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
000952        Pager *pPager = sqlite3BtreePager(pBt);
000953        rc = sqlite3PagerFlush(pPager);
000954        if( rc==SQLITE_BUSY ){
000955          bSeenBusy = 1;
000956          rc = SQLITE_OK;
000957        }
000958      }
000959    }
000960    sqlite3BtreeLeaveAll(db);
000961    sqlite3_mutex_leave(db->mutex);
000962    return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
000963  }
000964  
000965  /*
000966  ** Configuration settings for an individual database connection
000967  */
000968  int sqlite3_db_config(sqlite3 *db, int op, ...){
000969    va_list ap;
000970    int rc;
000971  
000972  #ifdef SQLITE_ENABLE_API_ARMOR
000973    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
000974  #endif
000975    sqlite3_mutex_enter(db->mutex);
000976    va_start(ap, op);
000977    switch( op ){
000978      case SQLITE_DBCONFIG_MAINDBNAME: {
000979        /* IMP: R-06824-28531 */
000980        /* IMP: R-36257-52125 */
000981        db->aDb[0].zDbSName = va_arg(ap,char*);
000982        rc = SQLITE_OK;
000983        break;
000984      }
000985      case SQLITE_DBCONFIG_LOOKASIDE: {
000986        void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
000987        int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
000988        int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
000989        rc = setupLookaside(db, pBuf, sz, cnt);
000990        break;
000991      }
000992      default: {
000993        static const struct {
000994          int op;      /* The opcode */
000995          u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
000996        } aFlagOp[] = {
000997          { SQLITE_DBCONFIG_ENABLE_FKEY,           SQLITE_ForeignKeys    },
000998          { SQLITE_DBCONFIG_ENABLE_TRIGGER,        SQLITE_EnableTrigger  },
000999          { SQLITE_DBCONFIG_ENABLE_VIEW,           SQLITE_EnableView     },
001000          { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer  },
001001          { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension  },
001002          { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE,      SQLITE_NoCkptOnClose  },
001003          { SQLITE_DBCONFIG_ENABLE_QPSG,           SQLITE_EnableQPSG     },
001004          { SQLITE_DBCONFIG_TRIGGER_EQP,           SQLITE_TriggerEQP     },
001005          { SQLITE_DBCONFIG_RESET_DATABASE,        SQLITE_ResetDatabase  },
001006          { SQLITE_DBCONFIG_DEFENSIVE,             SQLITE_Defensive      },
001007          { SQLITE_DBCONFIG_WRITABLE_SCHEMA,       SQLITE_WriteSchema|
001008                                                   SQLITE_NoSchemaError  },
001009          { SQLITE_DBCONFIG_LEGACY_ALTER_TABLE,    SQLITE_LegacyAlter    },
001010          { SQLITE_DBCONFIG_DQS_DDL,               SQLITE_DqsDDL         },
001011          { SQLITE_DBCONFIG_DQS_DML,               SQLITE_DqsDML         },
001012          { SQLITE_DBCONFIG_LEGACY_FILE_FORMAT,    SQLITE_LegacyFileFmt  },
001013          { SQLITE_DBCONFIG_TRUSTED_SCHEMA,        SQLITE_TrustedSchema  },
001014          { SQLITE_DBCONFIG_STMT_SCANSTATUS,       SQLITE_StmtScanStatus },
001015          { SQLITE_DBCONFIG_REVERSE_SCANORDER,     SQLITE_ReverseOrder   },
001016        };
001017        unsigned int i;
001018        rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
001019        for(i=0; i<ArraySize(aFlagOp); i++){
001020          if( aFlagOp[i].op==op ){
001021            int onoff = va_arg(ap, int);
001022            int *pRes = va_arg(ap, int*);
001023            u64 oldFlags = db->flags;
001024            if( onoff>0 ){
001025              db->flags |= aFlagOp[i].mask;
001026            }else if( onoff==0 ){
001027              db->flags &= ~(u64)aFlagOp[i].mask;
001028            }
001029            if( oldFlags!=db->flags ){
001030              sqlite3ExpirePreparedStatements(db, 0);
001031            }
001032            if( pRes ){
001033              *pRes = (db->flags & aFlagOp[i].mask)!=0;
001034            }
001035            rc = SQLITE_OK;
001036            break;
001037          }
001038        }
001039        break;
001040      }
001041    }
001042    va_end(ap);
001043    sqlite3_mutex_leave(db->mutex);
001044    return rc;
001045  }
001046  
001047  /*
001048  ** This is the default collating function named "BINARY" which is always
001049  ** available.
001050  */
001051  static int binCollFunc(
001052    void *NotUsed,
001053    int nKey1, const void *pKey1,
001054    int nKey2, const void *pKey2
001055  ){
001056    int rc, n;
001057    UNUSED_PARAMETER(NotUsed);
001058    n = nKey1<nKey2 ? nKey1 : nKey2;
001059    /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
001060    ** strings byte by byte using the memcmp() function from the standard C
001061    ** library. */
001062    assert( pKey1 && pKey2 );
001063    rc = memcmp(pKey1, pKey2, n);
001064    if( rc==0 ){
001065      rc = nKey1 - nKey2;
001066    }
001067    return rc;
001068  }
001069  
001070  /*
001071  ** This is the collating function named "RTRIM" which is always
001072  ** available.  Ignore trailing spaces.
001073  */
001074  static int rtrimCollFunc(
001075    void *pUser,
001076    int nKey1, const void *pKey1,
001077    int nKey2, const void *pKey2
001078  ){
001079    const u8 *pK1 = (const u8*)pKey1;
001080    const u8 *pK2 = (const u8*)pKey2;
001081    while( nKey1 && pK1[nKey1-1]==' ' ) nKey1--;
001082    while( nKey2 && pK2[nKey2-1]==' ' ) nKey2--;
001083    return binCollFunc(pUser, nKey1, pKey1, nKey2, pKey2);
001084  }
001085  
001086  /*
001087  ** Return true if CollSeq is the default built-in BINARY.
001088  */
001089  int sqlite3IsBinary(const CollSeq *p){
001090    assert( p==0 || p->xCmp!=binCollFunc || strcmp(p->zName,"BINARY")==0 );
001091    return p==0 || p->xCmp==binCollFunc;
001092  }
001093  
001094  /*
001095  ** Another built-in collating sequence: NOCASE.
001096  **
001097  ** This collating sequence is intended to be used for "case independent
001098  ** comparison". SQLite's knowledge of upper and lower case equivalents
001099  ** extends only to the 26 characters used in the English language.
001100  **
001101  ** At the moment there is only a UTF-8 implementation.
001102  */
001103  static int nocaseCollatingFunc(
001104    void *NotUsed,
001105    int nKey1, const void *pKey1,
001106    int nKey2, const void *pKey2
001107  ){
001108    int r = sqlite3StrNICmp(
001109        (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
001110    UNUSED_PARAMETER(NotUsed);
001111    if( 0==r ){
001112      r = nKey1-nKey2;
001113    }
001114    return r;
001115  }
001116  
001117  /*
001118  ** Return the ROWID of the most recent insert
001119  */
001120  sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
001121  #ifdef SQLITE_ENABLE_API_ARMOR
001122    if( !sqlite3SafetyCheckOk(db) ){
001123      (void)SQLITE_MISUSE_BKPT;
001124      return 0;
001125    }
001126  #endif
001127    return db->lastRowid;
001128  }
001129  
001130  /*
001131  ** Set the value returned by the sqlite3_last_insert_rowid() API function.
001132  */
001133  void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
001134  #ifdef SQLITE_ENABLE_API_ARMOR
001135    if( !sqlite3SafetyCheckOk(db) ){
001136      (void)SQLITE_MISUSE_BKPT;
001137      return;
001138    }
001139  #endif
001140    sqlite3_mutex_enter(db->mutex);
001141    db->lastRowid = iRowid;
001142    sqlite3_mutex_leave(db->mutex);
001143  }
001144  
001145  /*
001146  ** Return the number of changes in the most recent call to sqlite3_exec().
001147  */
001148  sqlite3_int64 sqlite3_changes64(sqlite3 *db){
001149  #ifdef SQLITE_ENABLE_API_ARMOR
001150    if( !sqlite3SafetyCheckOk(db) ){
001151      (void)SQLITE_MISUSE_BKPT;
001152      return 0;
001153    }
001154  #endif
001155    return db->nChange;
001156  }
001157  int sqlite3_changes(sqlite3 *db){
001158    return (int)sqlite3_changes64(db);
001159  }
001160  
001161  /*
001162  ** Return the number of changes since the database handle was opened.
001163  */
001164  sqlite3_int64 sqlite3_total_changes64(sqlite3 *db){
001165  #ifdef SQLITE_ENABLE_API_ARMOR
001166    if( !sqlite3SafetyCheckOk(db) ){
001167      (void)SQLITE_MISUSE_BKPT;
001168      return 0;
001169    }
001170  #endif
001171    return db->nTotalChange;
001172  }
001173  int sqlite3_total_changes(sqlite3 *db){
001174    return (int)sqlite3_total_changes64(db);
001175  }
001176  
001177  /*
001178  ** Close all open savepoints. This function only manipulates fields of the
001179  ** database handle object, it does not close any savepoints that may be open
001180  ** at the b-tree/pager level.
001181  */
001182  void sqlite3CloseSavepoints(sqlite3 *db){
001183    while( db->pSavepoint ){
001184      Savepoint *pTmp = db->pSavepoint;
001185      db->pSavepoint = pTmp->pNext;
001186      sqlite3DbFree(db, pTmp);
001187    }
001188    db->nSavepoint = 0;
001189    db->nStatement = 0;
001190    db->isTransactionSavepoint = 0;
001191  }
001192  
001193  /*
001194  ** Invoke the destructor function associated with FuncDef p, if any. Except,
001195  ** if this is not the last copy of the function, do not invoke it. Multiple
001196  ** copies of a single function are created when create_function() is called
001197  ** with SQLITE_ANY as the encoding.
001198  */
001199  static void functionDestroy(sqlite3 *db, FuncDef *p){
001200    FuncDestructor *pDestructor;
001201    assert( (p->funcFlags & SQLITE_FUNC_BUILTIN)==0 );
001202    pDestructor = p->u.pDestructor;
001203    if( pDestructor ){
001204      pDestructor->nRef--;
001205      if( pDestructor->nRef==0 ){
001206        pDestructor->xDestroy(pDestructor->pUserData);
001207        sqlite3DbFree(db, pDestructor);
001208      }
001209    }
001210  }
001211  
001212  /*
001213  ** Disconnect all sqlite3_vtab objects that belong to database connection
001214  ** db. This is called when db is being closed.
001215  */
001216  static void disconnectAllVtab(sqlite3 *db){
001217  #ifndef SQLITE_OMIT_VIRTUALTABLE
001218    int i;
001219    HashElem *p;
001220    sqlite3BtreeEnterAll(db);
001221    for(i=0; i<db->nDb; i++){
001222      Schema *pSchema = db->aDb[i].pSchema;
001223      if( pSchema ){
001224        for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
001225          Table *pTab = (Table *)sqliteHashData(p);
001226          if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
001227        }
001228      }
001229    }
001230    for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
001231      Module *pMod = (Module *)sqliteHashData(p);
001232      if( pMod->pEpoTab ){
001233        sqlite3VtabDisconnect(db, pMod->pEpoTab);
001234      }
001235    }
001236    sqlite3VtabUnlockList(db);
001237    sqlite3BtreeLeaveAll(db);
001238  #else
001239    UNUSED_PARAMETER(db);
001240  #endif
001241  }
001242  
001243  /*
001244  ** Return TRUE if database connection db has unfinalized prepared
001245  ** statements or unfinished sqlite3_backup objects. 
001246  */
001247  static int connectionIsBusy(sqlite3 *db){
001248    int j;
001249    assert( sqlite3_mutex_held(db->mutex) );
001250    if( db->pVdbe ) return 1;
001251    for(j=0; j<db->nDb; j++){
001252      Btree *pBt = db->aDb[j].pBt;
001253      if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
001254    }
001255    return 0;
001256  }
001257  
001258  /*
001259  ** Close an existing SQLite database
001260  */
001261  static int sqlite3Close(sqlite3 *db, int forceZombie){
001262    if( !db ){
001263      /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
001264      ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
001265      return SQLITE_OK;
001266    }
001267    if( !sqlite3SafetyCheckSickOrOk(db) ){
001268      return SQLITE_MISUSE_BKPT;
001269    }
001270    sqlite3_mutex_enter(db->mutex);
001271    if( db->mTrace & SQLITE_TRACE_CLOSE ){
001272      db->trace.xV2(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
001273    }
001274  
001275    /* Force xDisconnect calls on all virtual tables */
001276    disconnectAllVtab(db);
001277  
001278    /* If a transaction is open, the disconnectAllVtab() call above
001279    ** will not have called the xDisconnect() method on any virtual
001280    ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
001281    ** call will do so. We need to do this before the check for active
001282    ** SQL statements below, as the v-table implementation may be storing
001283    ** some prepared statements internally.
001284    */
001285    sqlite3VtabRollback(db);
001286  
001287    /* Legacy behavior (sqlite3_close() behavior) is to return
001288    ** SQLITE_BUSY if the connection can not be closed immediately.
001289    */
001290    if( !forceZombie && connectionIsBusy(db) ){
001291      sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
001292         "statements or unfinished backups");
001293      sqlite3_mutex_leave(db->mutex);
001294      return SQLITE_BUSY;
001295    }
001296  
001297  #ifdef SQLITE_ENABLE_SQLLOG
001298    if( sqlite3GlobalConfig.xSqllog ){
001299      /* Closing the handle. Fourth parameter is passed the value 2. */
001300      sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
001301    }
001302  #endif
001303  
001304    while( db->pDbData ){
001305      DbClientData *p = db->pDbData;
001306      db->pDbData = p->pNext;
001307      assert( p->pData!=0 );
001308      if( p->xDestructor ) p->xDestructor(p->pData);
001309      sqlite3_free(p);
001310    }
001311  
001312    /* Convert the connection into a zombie and then close it.
001313    */
001314    db->eOpenState = SQLITE_STATE_ZOMBIE;
001315    sqlite3LeaveMutexAndCloseZombie(db);
001316    return SQLITE_OK;
001317  }
001318  
001319  /*
001320  ** Return the transaction state for a single databse, or the maximum
001321  ** transaction state over all attached databases if zSchema is null.
001322  */
001323  int sqlite3_txn_state(sqlite3 *db, const char *zSchema){
001324    int iDb, nDb;
001325    int iTxn = -1;
001326  #ifdef SQLITE_ENABLE_API_ARMOR
001327    if( !sqlite3SafetyCheckOk(db) ){
001328      (void)SQLITE_MISUSE_BKPT;
001329      return -1;
001330    }
001331  #endif
001332    sqlite3_mutex_enter(db->mutex);
001333    if( zSchema ){
001334      nDb = iDb = sqlite3FindDbName(db, zSchema);
001335      if( iDb<0 ) nDb--;
001336    }else{
001337      iDb = 0;
001338      nDb = db->nDb-1;
001339    }
001340    for(; iDb<=nDb; iDb++){
001341      Btree *pBt = db->aDb[iDb].pBt;
001342      int x = pBt!=0 ? sqlite3BtreeTxnState(pBt) : SQLITE_TXN_NONE;
001343      if( x>iTxn ) iTxn = x;
001344    }
001345    sqlite3_mutex_leave(db->mutex);
001346    return iTxn;
001347  }
001348  
001349  /*
001350  ** Two variations on the public interface for closing a database
001351  ** connection. The sqlite3_close() version returns SQLITE_BUSY and
001352  ** leaves the connection open if there are unfinalized prepared
001353  ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
001354  ** version forces the connection to become a zombie if there are
001355  ** unclosed resources, and arranges for deallocation when the last
001356  ** prepare statement or sqlite3_backup closes.
001357  */
001358  int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
001359  int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
001360  
001361  
001362  /*
001363  ** Close the mutex on database connection db.
001364  **
001365  ** Furthermore, if database connection db is a zombie (meaning that there
001366  ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
001367  ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
001368  ** finished, then free all resources.
001369  */
001370  void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
001371    HashElem *i;                    /* Hash table iterator */
001372    int j;
001373  
001374    /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
001375    ** or if the connection has not yet been closed by sqlite3_close_v2(),
001376    ** then just leave the mutex and return.
001377    */
001378    if( db->eOpenState!=SQLITE_STATE_ZOMBIE || connectionIsBusy(db) ){
001379      sqlite3_mutex_leave(db->mutex);
001380      return;
001381    }
001382  
001383    /* If we reach this point, it means that the database connection has
001384    ** closed all sqlite3_stmt and sqlite3_backup objects and has been
001385    ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
001386    ** go ahead and free all resources.
001387    */
001388  
001389    /* If a transaction is open, roll it back. This also ensures that if
001390    ** any database schemas have been modified by an uncommitted transaction
001391    ** they are reset. And that the required b-tree mutex is held to make
001392    ** the pager rollback and schema reset an atomic operation. */
001393    sqlite3RollbackAll(db, SQLITE_OK);
001394  
001395    /* Free any outstanding Savepoint structures. */
001396    sqlite3CloseSavepoints(db);
001397  
001398    /* Close all database connections */
001399    for(j=0; j<db->nDb; j++){
001400      struct Db *pDb = &db->aDb[j];
001401      if( pDb->pBt ){
001402        sqlite3BtreeClose(pDb->pBt);
001403        pDb->pBt = 0;
001404        if( j!=1 ){
001405          pDb->pSchema = 0;
001406        }
001407      }
001408    }
001409    /* Clear the TEMP schema separately and last */
001410    if( db->aDb[1].pSchema ){
001411      sqlite3SchemaClear(db->aDb[1].pSchema);
001412    }
001413    sqlite3VtabUnlockList(db);
001414  
001415    /* Free up the array of auxiliary databases */
001416    sqlite3CollapseDatabaseArray(db);
001417    assert( db->nDb<=2 );
001418    assert( db->aDb==db->aDbStatic );
001419  
001420    /* Tell the code in notify.c that the connection no longer holds any
001421    ** locks and does not require any further unlock-notify callbacks.
001422    */
001423    sqlite3ConnectionClosed(db);
001424  
001425    for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
001426      FuncDef *pNext, *p;
001427      p = sqliteHashData(i);
001428      do{
001429        functionDestroy(db, p);
001430        pNext = p->pNext;
001431        sqlite3DbFree(db, p);
001432        p = pNext;
001433      }while( p );
001434    }
001435    sqlite3HashClear(&db->aFunc);
001436    for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
001437      CollSeq *pColl = (CollSeq *)sqliteHashData(i);
001438      /* Invoke any destructors registered for collation sequence user data. */
001439      for(j=0; j<3; j++){
001440        if( pColl[j].xDel ){
001441          pColl[j].xDel(pColl[j].pUser);
001442        }
001443      }
001444      sqlite3DbFree(db, pColl);
001445    }
001446    sqlite3HashClear(&db->aCollSeq);
001447  #ifndef SQLITE_OMIT_VIRTUALTABLE
001448    for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
001449      Module *pMod = (Module *)sqliteHashData(i);
001450      sqlite3VtabEponymousTableClear(db, pMod);
001451      sqlite3VtabModuleUnref(db, pMod);
001452    }
001453    sqlite3HashClear(&db->aModule);
001454  #endif
001455  
001456    sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
001457    sqlite3ValueFree(db->pErr);
001458    sqlite3CloseExtensions(db);
001459  #if SQLITE_USER_AUTHENTICATION
001460    sqlite3_free(db->auth.zAuthUser);
001461    sqlite3_free(db->auth.zAuthPW);
001462  #endif
001463  
001464    db->eOpenState = SQLITE_STATE_ERROR;
001465  
001466    /* The temp-database schema is allocated differently from the other schema
001467    ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
001468    ** So it needs to be freed here. Todo: Why not roll the temp schema into
001469    ** the same sqliteMalloc() as the one that allocates the database
001470    ** structure?
001471    */
001472    sqlite3DbFree(db, db->aDb[1].pSchema);
001473    if( db->xAutovacDestr ){
001474      db->xAutovacDestr(db->pAutovacPagesArg);
001475    }
001476    sqlite3_mutex_leave(db->mutex);
001477    db->eOpenState = SQLITE_STATE_CLOSED;
001478    sqlite3_mutex_free(db->mutex);
001479    assert( sqlite3LookasideUsed(db,0)==0 );
001480    if( db->lookaside.bMalloced ){
001481      sqlite3_free(db->lookaside.pStart);
001482    }
001483    sqlite3_free(db);
001484  }
001485  
001486  /*
001487  ** Rollback all database files.  If tripCode is not SQLITE_OK, then
001488  ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
001489  ** breaker") and made to return tripCode if there are any further
001490  ** attempts to use that cursor.  Read cursors remain open and valid
001491  ** but are "saved" in case the table pages are moved around.
001492  */
001493  void sqlite3RollbackAll(sqlite3 *db, int tripCode){
001494    int i;
001495    int inTrans = 0;
001496    int schemaChange;
001497    assert( sqlite3_mutex_held(db->mutex) );
001498    sqlite3BeginBenignMalloc();
001499  
001500    /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
001501    ** This is important in case the transaction being rolled back has
001502    ** modified the database schema. If the b-tree mutexes are not taken
001503    ** here, then another shared-cache connection might sneak in between
001504    ** the database rollback and schema reset, which can cause false
001505    ** corruption reports in some cases.  */
001506    sqlite3BtreeEnterAll(db);
001507    schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
001508  
001509    for(i=0; i<db->nDb; i++){
001510      Btree *p = db->aDb[i].pBt;
001511      if( p ){
001512        if( sqlite3BtreeTxnState(p)==SQLITE_TXN_WRITE ){
001513          inTrans = 1;
001514        }
001515        sqlite3BtreeRollback(p, tripCode, !schemaChange);
001516      }
001517    }
001518    sqlite3VtabRollback(db);
001519    sqlite3EndBenignMalloc();
001520  
001521    if( schemaChange ){
001522      sqlite3ExpirePreparedStatements(db, 0);
001523      sqlite3ResetAllSchemasOfConnection(db);
001524    }
001525    sqlite3BtreeLeaveAll(db);
001526  
001527    /* Any deferred constraint violations have now been resolved. */
001528    db->nDeferredCons = 0;
001529    db->nDeferredImmCons = 0;
001530    db->flags &= ~(u64)(SQLITE_DeferFKs|SQLITE_CorruptRdOnly);
001531  
001532    /* If one has been configured, invoke the rollback-hook callback */
001533    if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
001534      db->xRollbackCallback(db->pRollbackArg);
001535    }
001536  }
001537  
001538  /*
001539  ** Return a static string containing the name corresponding to the error code
001540  ** specified in the argument.
001541  */
001542  #if defined(SQLITE_NEED_ERR_NAME)
001543  const char *sqlite3ErrName(int rc){
001544    const char *zName = 0;
001545    int i, origRc = rc;
001546    for(i=0; i<2 && zName==0; i++, rc &= 0xff){
001547      switch( rc ){
001548        case SQLITE_OK:                 zName = "SQLITE_OK";                break;
001549        case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
001550        case SQLITE_ERROR_SNAPSHOT:     zName = "SQLITE_ERROR_SNAPSHOT";    break;
001551        case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
001552        case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
001553        case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
001554        case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
001555        case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
001556        case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
001557        case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
001558        case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
001559        case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
001560        case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
001561        case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
001562        case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
001563        case SQLITE_READONLY_CANTINIT:  zName = "SQLITE_READONLY_CANTINIT"; break;
001564        case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
001565        case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
001566        case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break;
001567        case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
001568        case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
001569        case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
001570        case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
001571        case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
001572        case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
001573        case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
001574        case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
001575        case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
001576        case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
001577        case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
001578        case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
001579        case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
001580        case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
001581        case SQLITE_IOERR_CHECKRESERVEDLOCK:
001582                                  zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
001583        case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
001584        case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
001585        case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
001586        case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
001587        case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
001588        case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
001589        case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
001590        case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
001591        case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
001592        case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
001593        case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
001594        case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
001595        case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
001596        case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
001597        case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
001598        case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
001599        case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
001600        case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
001601        case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
001602        case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
001603        case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
001604        case SQLITE_CANTOPEN_SYMLINK:   zName = "SQLITE_CANTOPEN_SYMLINK";  break;
001605        case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
001606        case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
001607        case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
001608        case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
001609        case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
001610        case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
001611        case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
001612        case SQLITE_CONSTRAINT_FOREIGNKEY:
001613                                  zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
001614        case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
001615        case SQLITE_CONSTRAINT_PRIMARYKEY:
001616                                  zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
001617        case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
001618        case SQLITE_CONSTRAINT_COMMITHOOK:
001619                                  zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
001620        case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
001621        case SQLITE_CONSTRAINT_FUNCTION:
001622                                  zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
001623        case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
001624        case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
001625        case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
001626        case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
001627        case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
001628        case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
001629        case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
001630        case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
001631        case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
001632        case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
001633        case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
001634        case SQLITE_NOTICE_RECOVER_ROLLBACK:
001635                                  zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
001636        case SQLITE_NOTICE_RBU:         zName = "SQLITE_NOTICE_RBU"; break;
001637        case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
001638        case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
001639        case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
001640      }
001641    }
001642    if( zName==0 ){
001643      static char zBuf[50];
001644      sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
001645      zName = zBuf;
001646    }
001647    return zName;
001648  }
001649  #endif
001650  
001651  /*
001652  ** Return a static string that describes the kind of error specified in the
001653  ** argument.
001654  */
001655  const char *sqlite3ErrStr(int rc){
001656    static const char* const aMsg[] = {
001657      /* SQLITE_OK          */ "not an error",
001658      /* SQLITE_ERROR       */ "SQL logic error",
001659      /* SQLITE_INTERNAL    */ 0,
001660      /* SQLITE_PERM        */ "access permission denied",
001661      /* SQLITE_ABORT       */ "query aborted",
001662      /* SQLITE_BUSY        */ "database is locked",
001663      /* SQLITE_LOCKED      */ "database table is locked",
001664      /* SQLITE_NOMEM       */ "out of memory",
001665      /* SQLITE_READONLY    */ "attempt to write a readonly database",
001666      /* SQLITE_INTERRUPT   */ "interrupted",
001667      /* SQLITE_IOERR       */ "disk I/O error",
001668      /* SQLITE_CORRUPT     */ "database disk image is malformed",
001669      /* SQLITE_NOTFOUND    */ "unknown operation",
001670      /* SQLITE_FULL        */ "database or disk is full",
001671      /* SQLITE_CANTOPEN    */ "unable to open database file",
001672      /* SQLITE_PROTOCOL    */ "locking protocol",
001673      /* SQLITE_EMPTY       */ 0,
001674      /* SQLITE_SCHEMA      */ "database schema has changed",
001675      /* SQLITE_TOOBIG      */ "string or blob too big",
001676      /* SQLITE_CONSTRAINT  */ "constraint failed",
001677      /* SQLITE_MISMATCH    */ "datatype mismatch",
001678      /* SQLITE_MISUSE      */ "bad parameter or other API misuse",
001679  #ifdef SQLITE_DISABLE_LFS
001680      /* SQLITE_NOLFS       */ "large file support is disabled",
001681  #else
001682      /* SQLITE_NOLFS       */ 0,
001683  #endif
001684      /* SQLITE_AUTH        */ "authorization denied",
001685      /* SQLITE_FORMAT      */ 0,
001686      /* SQLITE_RANGE       */ "column index out of range",
001687      /* SQLITE_NOTADB      */ "file is not a database",
001688      /* SQLITE_NOTICE      */ "notification message",
001689      /* SQLITE_WARNING     */ "warning message",
001690    };
001691    const char *zErr = "unknown error";
001692    switch( rc ){
001693      case SQLITE_ABORT_ROLLBACK: {
001694        zErr = "abort due to ROLLBACK";
001695        break;
001696      }
001697      case SQLITE_ROW: {
001698        zErr = "another row available";
001699        break;
001700      }
001701      case SQLITE_DONE: {
001702        zErr = "no more rows available";
001703        break;
001704      }
001705      default: {
001706        rc &= 0xff;
001707        if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
001708          zErr = aMsg[rc];
001709        }
001710        break;
001711      }
001712    }
001713    return zErr;
001714  }
001715  
001716  /*
001717  ** This routine implements a busy callback that sleeps and tries
001718  ** again until a timeout value is reached.  The timeout value is
001719  ** an integer number of milliseconds passed in as the first
001720  ** argument.
001721  **
001722  ** Return non-zero to retry the lock.  Return zero to stop trying
001723  ** and cause SQLite to return SQLITE_BUSY.
001724  */
001725  static int sqliteDefaultBusyCallback(
001726    void *ptr,               /* Database connection */
001727    int count                /* Number of times table has been busy */
001728  ){
001729  #if SQLITE_OS_WIN || !defined(HAVE_NANOSLEEP) || HAVE_NANOSLEEP
001730    /* This case is for systems that have support for sleeping for fractions of
001731    ** a second.  Examples:  All windows systems, unix systems with nanosleep() */
001732    static const u8 delays[] =
001733       { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
001734    static const u8 totals[] =
001735       { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
001736  # define NDELAY ArraySize(delays)
001737    sqlite3 *db = (sqlite3 *)ptr;
001738    int tmout = db->busyTimeout;
001739    int delay, prior;
001740  
001741    assert( count>=0 );
001742    if( count < NDELAY ){
001743      delay = delays[count];
001744      prior = totals[count];
001745    }else{
001746      delay = delays[NDELAY-1];
001747      prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
001748    }
001749    if( prior + delay > tmout ){
001750      delay = tmout - prior;
001751      if( delay<=0 ) return 0;
001752    }
001753    sqlite3OsSleep(db->pVfs, delay*1000);
001754    return 1;
001755  #else
001756    /* This case for unix systems that lack usleep() support.  Sleeping
001757    ** must be done in increments of whole seconds */
001758    sqlite3 *db = (sqlite3 *)ptr;
001759    int tmout = ((sqlite3 *)ptr)->busyTimeout;
001760    if( (count+1)*1000 > tmout ){
001761      return 0;
001762    }
001763    sqlite3OsSleep(db->pVfs, 1000000);
001764    return 1;
001765  #endif
001766  }
001767  
001768  /*
001769  ** Invoke the given busy handler.
001770  **
001771  ** This routine is called when an operation failed to acquire a
001772  ** lock on VFS file pFile.
001773  **
001774  ** If this routine returns non-zero, the lock is retried.  If it
001775  ** returns 0, the operation aborts with an SQLITE_BUSY error.
001776  */
001777  int sqlite3InvokeBusyHandler(BusyHandler *p){
001778    int rc;
001779    if( p->xBusyHandler==0 || p->nBusy<0 ) return 0;
001780    rc = p->xBusyHandler(p->pBusyArg, p->nBusy);
001781    if( rc==0 ){
001782      p->nBusy = -1;
001783    }else{
001784      p->nBusy++;
001785    }
001786    return rc;
001787  }
001788  
001789  /*
001790  ** This routine sets the busy callback for an Sqlite database to the
001791  ** given callback function with the given argument.
001792  */
001793  int sqlite3_busy_handler(
001794    sqlite3 *db,
001795    int (*xBusy)(void*,int),
001796    void *pArg
001797  ){
001798  #ifdef SQLITE_ENABLE_API_ARMOR
001799    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
001800  #endif
001801    sqlite3_mutex_enter(db->mutex);
001802    db->busyHandler.xBusyHandler = xBusy;
001803    db->busyHandler.pBusyArg = pArg;
001804    db->busyHandler.nBusy = 0;
001805    db->busyTimeout = 0;
001806    sqlite3_mutex_leave(db->mutex);
001807    return SQLITE_OK;
001808  }
001809  
001810  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
001811  /*
001812  ** This routine sets the progress callback for an Sqlite database to the
001813  ** given callback function with the given argument. The progress callback will
001814  ** be invoked every nOps opcodes.
001815  */
001816  void sqlite3_progress_handler(
001817    sqlite3 *db,
001818    int nOps,
001819    int (*xProgress)(void*),
001820    void *pArg
001821  ){
001822  #ifdef SQLITE_ENABLE_API_ARMOR
001823    if( !sqlite3SafetyCheckOk(db) ){
001824      (void)SQLITE_MISUSE_BKPT;
001825      return;
001826    }
001827  #endif
001828    sqlite3_mutex_enter(db->mutex);
001829    if( nOps>0 ){
001830      db->xProgress = xProgress;
001831      db->nProgressOps = (unsigned)nOps;
001832      db->pProgressArg = pArg;
001833    }else{
001834      db->xProgress = 0;
001835      db->nProgressOps = 0;
001836      db->pProgressArg = 0;
001837    }
001838    sqlite3_mutex_leave(db->mutex);
001839  }
001840  #endif
001841  
001842  
001843  /*
001844  ** This routine installs a default busy handler that waits for the
001845  ** specified number of milliseconds before returning 0.
001846  */
001847  int sqlite3_busy_timeout(sqlite3 *db, int ms){
001848  #ifdef SQLITE_ENABLE_API_ARMOR
001849    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
001850  #endif
001851    if( ms>0 ){
001852      sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
001853                               (void*)db);
001854      db->busyTimeout = ms;
001855    }else{
001856      sqlite3_busy_handler(db, 0, 0);
001857    }
001858    return SQLITE_OK;
001859  }
001860  
001861  /*
001862  ** Cause any pending operation to stop at its earliest opportunity.
001863  */
001864  void sqlite3_interrupt(sqlite3 *db){
001865  #ifdef SQLITE_ENABLE_API_ARMOR
001866    if( !sqlite3SafetyCheckOk(db)
001867     && (db==0 || db->eOpenState!=SQLITE_STATE_ZOMBIE)
001868    ){
001869      (void)SQLITE_MISUSE_BKPT;
001870      return;
001871    }
001872  #endif
001873    AtomicStore(&db->u1.isInterrupted, 1);
001874  }
001875  
001876  /*
001877  ** Return true or false depending on whether or not an interrupt is
001878  ** pending on connection db.
001879  */
001880  int sqlite3_is_interrupted(sqlite3 *db){
001881  #ifdef SQLITE_ENABLE_API_ARMOR
001882    if( !sqlite3SafetyCheckOk(db)
001883     && (db==0 || db->eOpenState!=SQLITE_STATE_ZOMBIE)
001884    ){
001885      (void)SQLITE_MISUSE_BKPT;
001886      return 0;
001887    }
001888  #endif
001889    return AtomicLoad(&db->u1.isInterrupted)!=0;
001890  }
001891  
001892  /*
001893  ** This function is exactly the same as sqlite3_create_function(), except
001894  ** that it is designed to be called by internal code. The difference is
001895  ** that if a malloc() fails in sqlite3_create_function(), an error code
001896  ** is returned and the mallocFailed flag cleared.
001897  */
001898  int sqlite3CreateFunc(
001899    sqlite3 *db,
001900    const char *zFunctionName,
001901    int nArg,
001902    int enc,
001903    void *pUserData,
001904    void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
001905    void (*xStep)(sqlite3_context*,int,sqlite3_value **),
001906    void (*xFinal)(sqlite3_context*),
001907    void (*xValue)(sqlite3_context*),
001908    void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
001909    FuncDestructor *pDestructor
001910  ){
001911    FuncDef *p;
001912    int extraFlags;
001913  
001914    assert( sqlite3_mutex_held(db->mutex) );
001915    assert( xValue==0 || xSFunc==0 );
001916    if( zFunctionName==0                /* Must have a valid name */
001917     || (xSFunc!=0 && xFinal!=0)        /* Not both xSFunc and xFinal */
001918     || ((xFinal==0)!=(xStep==0))       /* Both or neither of xFinal and xStep */
001919     || ((xValue==0)!=(xInverse==0))    /* Both or neither of xValue, xInverse */
001920     || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG)
001921     || (255<sqlite3Strlen30(zFunctionName))
001922    ){
001923      return SQLITE_MISUSE_BKPT;
001924    }
001925  
001926    assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
001927    assert( SQLITE_FUNC_DIRECT==SQLITE_DIRECTONLY );
001928    extraFlags = enc &  (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY|
001929                         SQLITE_SUBTYPE|SQLITE_INNOCUOUS|SQLITE_RESULT_SUBTYPE);
001930    enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
001931  
001932    /* The SQLITE_INNOCUOUS flag is the same bit as SQLITE_FUNC_UNSAFE.  But
001933    ** the meaning is inverted.  So flip the bit. */
001934    assert( SQLITE_FUNC_UNSAFE==SQLITE_INNOCUOUS );
001935    extraFlags ^= SQLITE_FUNC_UNSAFE;  /* tag-20230109-1 */
001936  
001937   
001938  #ifndef SQLITE_OMIT_UTF16
001939    /* If SQLITE_UTF16 is specified as the encoding type, transform this
001940    ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
001941    ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
001942    **
001943    ** If SQLITE_ANY is specified, add three versions of the function
001944    ** to the hash table.
001945    */
001946    switch( enc ){
001947      case SQLITE_UTF16:
001948        enc = SQLITE_UTF16NATIVE;
001949        break;
001950      case SQLITE_ANY: {
001951        int rc;
001952        rc = sqlite3CreateFunc(db, zFunctionName, nArg,
001953             (SQLITE_UTF8|extraFlags)^SQLITE_FUNC_UNSAFE, /* tag-20230109-1 */
001954             pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
001955        if( rc==SQLITE_OK ){
001956          rc = sqlite3CreateFunc(db, zFunctionName, nArg,
001957               (SQLITE_UTF16LE|extraFlags)^SQLITE_FUNC_UNSAFE, /* tag-20230109-1*/
001958               pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
001959        }
001960        if( rc!=SQLITE_OK ){
001961          return rc;
001962        }
001963        enc = SQLITE_UTF16BE;
001964        break;
001965      }
001966      case SQLITE_UTF8:
001967      case SQLITE_UTF16LE:
001968      case SQLITE_UTF16BE:
001969        break;
001970      default:
001971        enc = SQLITE_UTF8;
001972        break;
001973    }
001974  #else
001975    enc = SQLITE_UTF8;
001976  #endif
001977   
001978    /* Check if an existing function is being overridden or deleted. If so,
001979    ** and there are active VMs, then return SQLITE_BUSY. If a function
001980    ** is being overridden/deleted but there are no active VMs, allow the
001981    ** operation to continue but invalidate all precompiled statements.
001982    */
001983    p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
001984    if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){
001985      if( db->nVdbeActive ){
001986        sqlite3ErrorWithMsg(db, SQLITE_BUSY,
001987          "unable to delete/modify user-function due to active statements");
001988        assert( !db->mallocFailed );
001989        return SQLITE_BUSY;
001990      }else{
001991        sqlite3ExpirePreparedStatements(db, 0);
001992      }
001993    }else if( xSFunc==0 && xFinal==0 ){
001994      /* Trying to delete a function that does not exist.  This is a no-op.
001995      ** https://sqlite.org/forum/forumpost/726219164b */
001996      return SQLITE_OK;
001997    }
001998  
001999    p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
002000    assert(p || db->mallocFailed);
002001    if( !p ){
002002      return SQLITE_NOMEM_BKPT;
002003    }
002004  
002005    /* If an older version of the function with a configured destructor is
002006    ** being replaced invoke the destructor function here. */
002007    functionDestroy(db, p);
002008  
002009    if( pDestructor ){
002010      pDestructor->nRef++;
002011    }
002012    p->u.pDestructor = pDestructor;
002013    p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
002014    testcase( p->funcFlags & SQLITE_DETERMINISTIC );
002015    testcase( p->funcFlags & SQLITE_DIRECTONLY );
002016    p->xSFunc = xSFunc ? xSFunc : xStep;
002017    p->xFinalize = xFinal;
002018    p->xValue = xValue;
002019    p->xInverse = xInverse;
002020    p->pUserData = pUserData;
002021    p->nArg = (u16)nArg;
002022    return SQLITE_OK;
002023  }
002024  
002025  /*
002026  ** Worker function used by utf-8 APIs that create new functions:
002027  **
002028  **    sqlite3_create_function()
002029  **    sqlite3_create_function_v2()
002030  **    sqlite3_create_window_function()
002031  */
002032  static int createFunctionApi(
002033    sqlite3 *db,
002034    const char *zFunc,
002035    int nArg,
002036    int enc,
002037    void *p,
002038    void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
002039    void (*xStep)(sqlite3_context*,int,sqlite3_value**),
002040    void (*xFinal)(sqlite3_context*),
002041    void (*xValue)(sqlite3_context*),
002042    void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
002043    void(*xDestroy)(void*)
002044  ){
002045    int rc = SQLITE_ERROR;
002046    FuncDestructor *pArg = 0;
002047  
002048  #ifdef SQLITE_ENABLE_API_ARMOR
002049    if( !sqlite3SafetyCheckOk(db) ){
002050      return SQLITE_MISUSE_BKPT;
002051    }
002052  #endif
002053    sqlite3_mutex_enter(db->mutex);
002054    if( xDestroy ){
002055      pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor));
002056      if( !pArg ){
002057        sqlite3OomFault(db);
002058        xDestroy(p);
002059        goto out;
002060      }
002061      pArg->nRef = 0;
002062      pArg->xDestroy = xDestroy;
002063      pArg->pUserData = p;
002064    }
002065    rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p,
002066        xSFunc, xStep, xFinal, xValue, xInverse, pArg
002067    );
002068    if( pArg && pArg->nRef==0 ){
002069      assert( rc!=SQLITE_OK || (xStep==0 && xFinal==0) );
002070      xDestroy(p);
002071      sqlite3_free(pArg);
002072    }
002073  
002074   out:
002075    rc = sqlite3ApiExit(db, rc);
002076    sqlite3_mutex_leave(db->mutex);
002077    return rc;
002078  }
002079  
002080  /*
002081  ** Create new user functions.
002082  */
002083  int sqlite3_create_function(
002084    sqlite3 *db,
002085    const char *zFunc,
002086    int nArg,
002087    int enc,
002088    void *p,
002089    void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
002090    void (*xStep)(sqlite3_context*,int,sqlite3_value **),
002091    void (*xFinal)(sqlite3_context*)
002092  ){
002093    return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
002094                                      xFinal, 0, 0, 0);
002095  }
002096  int sqlite3_create_function_v2(
002097    sqlite3 *db,
002098    const char *zFunc,
002099    int nArg,
002100    int enc,
002101    void *p,
002102    void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
002103    void (*xStep)(sqlite3_context*,int,sqlite3_value **),
002104    void (*xFinal)(sqlite3_context*),
002105    void (*xDestroy)(void *)
002106  ){
002107    return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
002108                                      xFinal, 0, 0, xDestroy);
002109  }
002110  int sqlite3_create_window_function(
002111    sqlite3 *db,
002112    const char *zFunc,
002113    int nArg,
002114    int enc,
002115    void *p,
002116    void (*xStep)(sqlite3_context*,int,sqlite3_value **),
002117    void (*xFinal)(sqlite3_context*),
002118    void (*xValue)(sqlite3_context*),
002119    void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
002120    void (*xDestroy)(void *)
002121  ){
002122    return createFunctionApi(db, zFunc, nArg, enc, p, 0, xStep,
002123                                      xFinal, xValue, xInverse, xDestroy);
002124  }
002125  
002126  #ifndef SQLITE_OMIT_UTF16
002127  int sqlite3_create_function16(
002128    sqlite3 *db,
002129    const void *zFunctionName,
002130    int nArg,
002131    int eTextRep,
002132    void *p,
002133    void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
002134    void (*xStep)(sqlite3_context*,int,sqlite3_value**),
002135    void (*xFinal)(sqlite3_context*)
002136  ){
002137    int rc;
002138    char *zFunc8;
002139  
002140  #ifdef SQLITE_ENABLE_API_ARMOR
002141    if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
002142  #endif
002143    sqlite3_mutex_enter(db->mutex);
002144    assert( !db->mallocFailed );
002145    zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
002146    rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0,0,0);
002147    sqlite3DbFree(db, zFunc8);
002148    rc = sqlite3ApiExit(db, rc);
002149    sqlite3_mutex_leave(db->mutex);
002150    return rc;
002151  }
002152  #endif
002153  
002154  
002155  /*
002156  ** The following is the implementation of an SQL function that always
002157  ** fails with an error message stating that the function is used in the
002158  ** wrong context.  The sqlite3_overload_function() API might construct
002159  ** SQL function that use this routine so that the functions will exist
002160  ** for name resolution but are actually overloaded by the xFindFunction
002161  ** method of virtual tables.
002162  */
002163  static void sqlite3InvalidFunction(
002164    sqlite3_context *context,  /* The function calling context */
002165    int NotUsed,               /* Number of arguments to the function */
002166    sqlite3_value **NotUsed2   /* Value of each argument */
002167  ){
002168    const char *zName = (const char*)sqlite3_user_data(context);
002169    char *zErr;
002170    UNUSED_PARAMETER2(NotUsed, NotUsed2);
002171    zErr = sqlite3_mprintf(
002172        "unable to use function %s in the requested context", zName);
002173    sqlite3_result_error(context, zErr, -1);
002174    sqlite3_free(zErr);
002175  }
002176  
002177  /*
002178  ** Declare that a function has been overloaded by a virtual table.
002179  **
002180  ** If the function already exists as a regular global function, then
002181  ** this routine is a no-op.  If the function does not exist, then create
002182  ** a new one that always throws a run-time error. 
002183  **
002184  ** When virtual tables intend to provide an overloaded function, they
002185  ** should call this routine to make sure the global function exists.
002186  ** A global function must exist in order for name resolution to work
002187  ** properly.
002188  */
002189  int sqlite3_overload_function(
002190    sqlite3 *db,
002191    const char *zName,
002192    int nArg
002193  ){
002194    int rc;
002195    char *zCopy;
002196  
002197  #ifdef SQLITE_ENABLE_API_ARMOR
002198    if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
002199      return SQLITE_MISUSE_BKPT;
002200    }
002201  #endif
002202    sqlite3_mutex_enter(db->mutex);
002203    rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0;
002204    sqlite3_mutex_leave(db->mutex);
002205    if( rc ) return SQLITE_OK;
002206    zCopy = sqlite3_mprintf("%s", zName);
002207    if( zCopy==0 ) return SQLITE_NOMEM;
002208    return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8,
002209                             zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free);
002210  }
002211  
002212  #ifndef SQLITE_OMIT_TRACE
002213  /*
002214  ** Register a trace function.  The pArg from the previously registered trace
002215  ** is returned. 
002216  **
002217  ** A NULL trace function means that no tracing is executes.  A non-NULL
002218  ** trace is a pointer to a function that is invoked at the start of each
002219  ** SQL statement.
002220  */
002221  #ifndef SQLITE_OMIT_DEPRECATED
002222  void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
002223    void *pOld;
002224  
002225  #ifdef SQLITE_ENABLE_API_ARMOR
002226    if( !sqlite3SafetyCheckOk(db) ){
002227      (void)SQLITE_MISUSE_BKPT;
002228      return 0;
002229    }
002230  #endif
002231    sqlite3_mutex_enter(db->mutex);
002232    pOld = db->pTraceArg;
002233    db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
002234    db->trace.xLegacy = xTrace;
002235    db->pTraceArg = pArg;
002236    sqlite3_mutex_leave(db->mutex);
002237    return pOld;
002238  }
002239  #endif /* SQLITE_OMIT_DEPRECATED */
002240  
002241  /* Register a trace callback using the version-2 interface.
002242  */
002243  int sqlite3_trace_v2(
002244    sqlite3 *db,                               /* Trace this connection */
002245    unsigned mTrace,                           /* Mask of events to be traced */
002246    int(*xTrace)(unsigned,void*,void*,void*),  /* Callback to invoke */
002247    void *pArg                                 /* Context */
002248  ){
002249  #ifdef SQLITE_ENABLE_API_ARMOR
002250    if( !sqlite3SafetyCheckOk(db) ){
002251      return SQLITE_MISUSE_BKPT;
002252    }
002253  #endif
002254    sqlite3_mutex_enter(db->mutex);
002255    if( mTrace==0 ) xTrace = 0;
002256    if( xTrace==0 ) mTrace = 0;
002257    db->mTrace = mTrace;
002258    db->trace.xV2 = xTrace;
002259    db->pTraceArg = pArg;
002260    sqlite3_mutex_leave(db->mutex);
002261    return SQLITE_OK;
002262  }
002263  
002264  #ifndef SQLITE_OMIT_DEPRECATED
002265  /*
002266  ** Register a profile function.  The pArg from the previously registered
002267  ** profile function is returned. 
002268  **
002269  ** A NULL profile function means that no profiling is executes.  A non-NULL
002270  ** profile is a pointer to a function that is invoked at the conclusion of
002271  ** each SQL statement that is run.
002272  */
002273  void *sqlite3_profile(
002274    sqlite3 *db,
002275    void (*xProfile)(void*,const char*,sqlite_uint64),
002276    void *pArg
002277  ){
002278    void *pOld;
002279  
002280  #ifdef SQLITE_ENABLE_API_ARMOR
002281    if( !sqlite3SafetyCheckOk(db) ){
002282      (void)SQLITE_MISUSE_BKPT;
002283      return 0;
002284    }
002285  #endif
002286    sqlite3_mutex_enter(db->mutex);
002287    pOld = db->pProfileArg;
002288    db->xProfile = xProfile;
002289    db->pProfileArg = pArg;
002290    db->mTrace &= SQLITE_TRACE_NONLEGACY_MASK;
002291    if( db->xProfile ) db->mTrace |= SQLITE_TRACE_XPROFILE;
002292    sqlite3_mutex_leave(db->mutex);
002293    return pOld;
002294  }
002295  #endif /* SQLITE_OMIT_DEPRECATED */
002296  #endif /* SQLITE_OMIT_TRACE */
002297  
002298  /*
002299  ** Register a function to be invoked when a transaction commits.
002300  ** If the invoked function returns non-zero, then the commit becomes a
002301  ** rollback.
002302  */
002303  void *sqlite3_commit_hook(
002304    sqlite3 *db,              /* Attach the hook to this database */
002305    int (*xCallback)(void*),  /* Function to invoke on each commit */
002306    void *pArg                /* Argument to the function */
002307  ){
002308    void *pOld;
002309  
002310  #ifdef SQLITE_ENABLE_API_ARMOR
002311    if( !sqlite3SafetyCheckOk(db) ){
002312      (void)SQLITE_MISUSE_BKPT;
002313      return 0;
002314    }
002315  #endif
002316    sqlite3_mutex_enter(db->mutex);
002317    pOld = db->pCommitArg;
002318    db->xCommitCallback = xCallback;
002319    db->pCommitArg = pArg;
002320    sqlite3_mutex_leave(db->mutex);
002321    return pOld;
002322  }
002323  
002324  /*
002325  ** Register a callback to be invoked each time a row is updated,
002326  ** inserted or deleted using this database connection.
002327  */
002328  void *sqlite3_update_hook(
002329    sqlite3 *db,              /* Attach the hook to this database */
002330    void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
002331    void *pArg                /* Argument to the function */
002332  ){
002333    void *pRet;
002334  
002335  #ifdef SQLITE_ENABLE_API_ARMOR
002336    if( !sqlite3SafetyCheckOk(db) ){
002337      (void)SQLITE_MISUSE_BKPT;
002338      return 0;
002339    }
002340  #endif
002341    sqlite3_mutex_enter(db->mutex);
002342    pRet = db->pUpdateArg;
002343    db->xUpdateCallback = xCallback;
002344    db->pUpdateArg = pArg;
002345    sqlite3_mutex_leave(db->mutex);
002346    return pRet;
002347  }
002348  
002349  /*
002350  ** Register a callback to be invoked each time a transaction is rolled
002351  ** back by this database connection.
002352  */
002353  void *sqlite3_rollback_hook(
002354    sqlite3 *db,              /* Attach the hook to this database */
002355    void (*xCallback)(void*), /* Callback function */
002356    void *pArg                /* Argument to the function */
002357  ){
002358    void *pRet;
002359  
002360  #ifdef SQLITE_ENABLE_API_ARMOR
002361    if( !sqlite3SafetyCheckOk(db) ){
002362      (void)SQLITE_MISUSE_BKPT;
002363      return 0;
002364    }
002365  #endif
002366    sqlite3_mutex_enter(db->mutex);
002367    pRet = db->pRollbackArg;
002368    db->xRollbackCallback = xCallback;
002369    db->pRollbackArg = pArg;
002370    sqlite3_mutex_leave(db->mutex);
002371    return pRet;
002372  }
002373  
002374  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
002375  /*
002376  ** Register a callback to be invoked each time a row is updated,
002377  ** inserted or deleted using this database connection.
002378  */
002379  void *sqlite3_preupdate_hook(
002380    sqlite3 *db,              /* Attach the hook to this database */
002381    void(*xCallback)(         /* Callback function */
002382      void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
002383    void *pArg                /* First callback argument */
002384  ){
002385    void *pRet;
002386  
002387  #ifdef SQLITE_ENABLE_API_ARMOR
002388    if( db==0 ){
002389      return 0;
002390    }
002391  #endif
002392    sqlite3_mutex_enter(db->mutex);
002393    pRet = db->pPreUpdateArg;
002394    db->xPreUpdateCallback = xCallback;
002395    db->pPreUpdateArg = pArg;
002396    sqlite3_mutex_leave(db->mutex);
002397    return pRet;
002398  }
002399  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
002400  
002401  /*
002402  ** Register a function to be invoked prior to each autovacuum that
002403  ** determines the number of pages to vacuum.
002404  */
002405  int sqlite3_autovacuum_pages(
002406    sqlite3 *db,                 /* Attach the hook to this database */
002407    unsigned int (*xCallback)(void*,const char*,u32,u32,u32),
002408    void *pArg,                  /* Argument to the function */
002409    void (*xDestructor)(void*)   /* Destructor for pArg */
002410  ){
002411  #ifdef SQLITE_ENABLE_API_ARMOR
002412    if( !sqlite3SafetyCheckOk(db) ){
002413      if( xDestructor ) xDestructor(pArg);
002414      return SQLITE_MISUSE_BKPT;
002415    }
002416  #endif
002417    sqlite3_mutex_enter(db->mutex);
002418    if( db->xAutovacDestr ){
002419      db->xAutovacDestr(db->pAutovacPagesArg);
002420    }
002421    db->xAutovacPages = xCallback;
002422    db->pAutovacPagesArg = pArg;
002423    db->xAutovacDestr = xDestructor;
002424    sqlite3_mutex_leave(db->mutex);
002425    return SQLITE_OK;
002426  }
002427  
002428  
002429  #ifndef SQLITE_OMIT_WAL
002430  /*
002431  ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
002432  ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
002433  ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
002434  ** wal_autocheckpoint()).
002435  */
002436  int sqlite3WalDefaultHook(
002437    void *pClientData,     /* Argument */
002438    sqlite3 *db,           /* Connection */
002439    const char *zDb,       /* Database */
002440    int nFrame             /* Size of WAL */
002441  ){
002442    if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
002443      sqlite3BeginBenignMalloc();
002444      sqlite3_wal_checkpoint(db, zDb);
002445      sqlite3EndBenignMalloc();
002446    }
002447    return SQLITE_OK;
002448  }
002449  #endif /* SQLITE_OMIT_WAL */
002450  
002451  /*
002452  ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
002453  ** a database after committing a transaction if there are nFrame or
002454  ** more frames in the log file. Passing zero or a negative value as the
002455  ** nFrame parameter disables automatic checkpoints entirely.
002456  **
002457  ** The callback registered by this function replaces any existing callback
002458  ** registered using sqlite3_wal_hook(). Likewise, registering a callback
002459  ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
002460  ** configured by this function.
002461  */
002462  int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
002463  #ifdef SQLITE_OMIT_WAL
002464    UNUSED_PARAMETER(db);
002465    UNUSED_PARAMETER(nFrame);
002466  #else
002467  #ifdef SQLITE_ENABLE_API_ARMOR
002468    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
002469  #endif
002470    if( nFrame>0 ){
002471      sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
002472    }else{
002473      sqlite3_wal_hook(db, 0, 0);
002474    }
002475  #endif
002476    return SQLITE_OK;
002477  }
002478  
002479  /*
002480  ** Register a callback to be invoked each time a transaction is written
002481  ** into the write-ahead-log by this database connection.
002482  */
002483  void *sqlite3_wal_hook(
002484    sqlite3 *db,                    /* Attach the hook to this db handle */
002485    int(*xCallback)(void *, sqlite3*, const char*, int),
002486    void *pArg                      /* First argument passed to xCallback() */
002487  ){
002488  #ifndef SQLITE_OMIT_WAL
002489    void *pRet;
002490  #ifdef SQLITE_ENABLE_API_ARMOR
002491    if( !sqlite3SafetyCheckOk(db) ){
002492      (void)SQLITE_MISUSE_BKPT;
002493      return 0;
002494    }
002495  #endif
002496    sqlite3_mutex_enter(db->mutex);
002497    pRet = db->pWalArg;
002498    db->xWalCallback = xCallback;
002499    db->pWalArg = pArg;
002500    sqlite3_mutex_leave(db->mutex);
002501    return pRet;
002502  #else
002503    return 0;
002504  #endif
002505  }
002506  
002507  /*
002508  ** Checkpoint database zDb.
002509  */
002510  int sqlite3_wal_checkpoint_v2(
002511    sqlite3 *db,                    /* Database handle */
002512    const char *zDb,                /* Name of attached database (or NULL) */
002513    int eMode,                      /* SQLITE_CHECKPOINT_* value */
002514    int *pnLog,                     /* OUT: Size of WAL log in frames */
002515    int *pnCkpt                     /* OUT: Total number of frames checkpointed */
002516  ){
002517  #ifdef SQLITE_OMIT_WAL
002518    return SQLITE_OK;
002519  #else
002520    int rc;                         /* Return code */
002521    int iDb;                        /* Schema to checkpoint */
002522  
002523  #ifdef SQLITE_ENABLE_API_ARMOR
002524    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
002525  #endif
002526  
002527    /* Initialize the output variables to -1 in case an error occurs. */
002528    if( pnLog ) *pnLog = -1;
002529    if( pnCkpt ) *pnCkpt = -1;
002530  
002531    assert( SQLITE_CHECKPOINT_PASSIVE==0 );
002532    assert( SQLITE_CHECKPOINT_FULL==1 );
002533    assert( SQLITE_CHECKPOINT_RESTART==2 );
002534    assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
002535    if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
002536      /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
002537      ** mode: */
002538      return SQLITE_MISUSE_BKPT;
002539    }
002540  
002541    sqlite3_mutex_enter(db->mutex);
002542    if( zDb && zDb[0] ){
002543      iDb = sqlite3FindDbName(db, zDb);
002544    }else{
002545      iDb = SQLITE_MAX_DB;   /* This means process all schemas */
002546    }
002547    if( iDb<0 ){
002548      rc = SQLITE_ERROR;
002549      sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
002550    }else{
002551      db->busyHandler.nBusy = 0;
002552      rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
002553      sqlite3Error(db, rc);
002554    }
002555    rc = sqlite3ApiExit(db, rc);
002556  
002557    /* If there are no active statements, clear the interrupt flag at this
002558    ** point.  */
002559    if( db->nVdbeActive==0 ){
002560      AtomicStore(&db->u1.isInterrupted, 0);
002561    }
002562  
002563    sqlite3_mutex_leave(db->mutex);
002564    return rc;
002565  #endif
002566  }
002567  
002568  
002569  /*
002570  ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
002571  ** to contains a zero-length string, all attached databases are
002572  ** checkpointed.
002573  */
002574  int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
002575    /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
002576    ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
002577    return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
002578  }
002579  
002580  #ifndef SQLITE_OMIT_WAL
002581  /*
002582  ** Run a checkpoint on database iDb. This is a no-op if database iDb is
002583  ** not currently open in WAL mode.
002584  **
002585  ** If a transaction is open on the database being checkpointed, this
002586  ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
002587  ** an error occurs while running the checkpoint, an SQLite error code is
002588  ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
002589  **
002590  ** The mutex on database handle db should be held by the caller. The mutex
002591  ** associated with the specific b-tree being checkpointed is taken by
002592  ** this function while the checkpoint is running.
002593  **
002594  ** If iDb is passed SQLITE_MAX_DB then all attached databases are
002595  ** checkpointed. If an error is encountered it is returned immediately -
002596  ** no attempt is made to checkpoint any remaining databases.
002597  **
002598  ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
002599  ** or TRUNCATE.
002600  */
002601  int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
002602    int rc = SQLITE_OK;             /* Return code */
002603    int i;                          /* Used to iterate through attached dbs */
002604    int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
002605  
002606    assert( sqlite3_mutex_held(db->mutex) );
002607    assert( !pnLog || *pnLog==-1 );
002608    assert( !pnCkpt || *pnCkpt==-1 );
002609    testcase( iDb==SQLITE_MAX_ATTACHED ); /* See forum post a006d86f72 */
002610    testcase( iDb==SQLITE_MAX_DB );
002611  
002612    for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
002613      if( i==iDb || iDb==SQLITE_MAX_DB ){
002614        rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
002615        pnLog = 0;
002616        pnCkpt = 0;
002617        if( rc==SQLITE_BUSY ){
002618          bBusy = 1;
002619          rc = SQLITE_OK;
002620        }
002621      }
002622    }
002623  
002624    return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
002625  }
002626  #endif /* SQLITE_OMIT_WAL */
002627  
002628  /*
002629  ** This function returns true if main-memory should be used instead of
002630  ** a temporary file for transient pager files and statement journals.
002631  ** The value returned depends on the value of db->temp_store (runtime
002632  ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
002633  ** following table describes the relationship between these two values
002634  ** and this functions return value.
002635  **
002636  **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
002637  **   -----------------     --------------     ------------------------------
002638  **   0                     any                file      (return 0)
002639  **   1                     1                  file      (return 0)
002640  **   1                     2                  memory    (return 1)
002641  **   1                     0                  file      (return 0)
002642  **   2                     1                  file      (return 0)
002643  **   2                     2                  memory    (return 1)
002644  **   2                     0                  memory    (return 1)
002645  **   3                     any                memory    (return 1)
002646  */
002647  int sqlite3TempInMemory(const sqlite3 *db){
002648  #if SQLITE_TEMP_STORE==1
002649    return ( db->temp_store==2 );
002650  #endif
002651  #if SQLITE_TEMP_STORE==2
002652    return ( db->temp_store!=1 );
002653  #endif
002654  #if SQLITE_TEMP_STORE==3
002655    UNUSED_PARAMETER(db);
002656    return 1;
002657  #endif
002658  #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
002659    UNUSED_PARAMETER(db);
002660    return 0;
002661  #endif
002662  }
002663  
002664  /*
002665  ** Return UTF-8 encoded English language explanation of the most recent
002666  ** error.
002667  */
002668  const char *sqlite3_errmsg(sqlite3 *db){
002669    const char *z;
002670    if( !db ){
002671      return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
002672    }
002673    if( !sqlite3SafetyCheckSickOrOk(db) ){
002674      return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
002675    }
002676    sqlite3_mutex_enter(db->mutex);
002677    if( db->mallocFailed ){
002678      z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
002679    }else{
002680      testcase( db->pErr==0 );
002681      z = db->errCode ? (char*)sqlite3_value_text(db->pErr) : 0;
002682      assert( !db->mallocFailed );
002683      if( z==0 ){
002684        z = sqlite3ErrStr(db->errCode);
002685      }
002686    }
002687    sqlite3_mutex_leave(db->mutex);
002688    return z;
002689  }
002690  
002691  /*
002692  ** Return the byte offset of the most recent error
002693  */
002694  int sqlite3_error_offset(sqlite3 *db){
002695    int iOffset = -1;
002696    if( db && sqlite3SafetyCheckSickOrOk(db) && db->errCode ){
002697      sqlite3_mutex_enter(db->mutex);
002698      iOffset = db->errByteOffset;
002699      sqlite3_mutex_leave(db->mutex);
002700    }
002701    return iOffset;
002702  }
002703  
002704  #ifndef SQLITE_OMIT_UTF16
002705  /*
002706  ** Return UTF-16 encoded English language explanation of the most recent
002707  ** error.
002708  */
002709  const void *sqlite3_errmsg16(sqlite3 *db){
002710    static const u16 outOfMem[] = {
002711      'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
002712    };
002713    static const u16 misuse[] = {
002714      'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
002715      'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
002716      'm', 'i', 's', 'u', 's', 'e', 0
002717    };
002718  
002719    const void *z;
002720    if( !db ){
002721      return (void *)outOfMem;
002722    }
002723    if( !sqlite3SafetyCheckSickOrOk(db) ){
002724      return (void *)misuse;
002725    }
002726    sqlite3_mutex_enter(db->mutex);
002727    if( db->mallocFailed ){
002728      z = (void *)outOfMem;
002729    }else{
002730      z = sqlite3_value_text16(db->pErr);
002731      if( z==0 ){
002732        sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
002733        z = sqlite3_value_text16(db->pErr);
002734      }
002735      /* A malloc() may have failed within the call to sqlite3_value_text16()
002736      ** above. If this is the case, then the db->mallocFailed flag needs to
002737      ** be cleared before returning. Do this directly, instead of via
002738      ** sqlite3ApiExit(), to avoid setting the database handle error message.
002739      */
002740      sqlite3OomClear(db);
002741    }
002742    sqlite3_mutex_leave(db->mutex);
002743    return z;
002744  }
002745  #endif /* SQLITE_OMIT_UTF16 */
002746  
002747  /*
002748  ** Return the most recent error code generated by an SQLite routine. If NULL is
002749  ** passed to this function, we assume a malloc() failed during sqlite3_open().
002750  */
002751  int sqlite3_errcode(sqlite3 *db){
002752    if( db && !sqlite3SafetyCheckSickOrOk(db) ){
002753      return SQLITE_MISUSE_BKPT;
002754    }
002755    if( !db || db->mallocFailed ){
002756      return SQLITE_NOMEM_BKPT;
002757    }
002758    return db->errCode & db->errMask;
002759  }
002760  int sqlite3_extended_errcode(sqlite3 *db){
002761    if( db && !sqlite3SafetyCheckSickOrOk(db) ){
002762      return SQLITE_MISUSE_BKPT;
002763    }
002764    if( !db || db->mallocFailed ){
002765      return SQLITE_NOMEM_BKPT;
002766    }
002767    return db->errCode;
002768  }
002769  int sqlite3_system_errno(sqlite3 *db){
002770    return db ? db->iSysErrno : 0;
002771  } 
002772  
002773  /*
002774  ** Return a string that describes the kind of error specified in the
002775  ** argument.  For now, this simply calls the internal sqlite3ErrStr()
002776  ** function.
002777  */
002778  const char *sqlite3_errstr(int rc){
002779    return sqlite3ErrStr(rc);
002780  }
002781  
002782  /*
002783  ** Create a new collating function for database "db".  The name is zName
002784  ** and the encoding is enc.
002785  */
002786  static int createCollation(
002787    sqlite3* db,
002788    const char *zName,
002789    u8 enc,
002790    void* pCtx,
002791    int(*xCompare)(void*,int,const void*,int,const void*),
002792    void(*xDel)(void*)
002793  ){
002794    CollSeq *pColl;
002795    int enc2;
002796   
002797    assert( sqlite3_mutex_held(db->mutex) );
002798  
002799    /* If SQLITE_UTF16 is specified as the encoding type, transform this
002800    ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
002801    ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
002802    */
002803    enc2 = enc;
002804    testcase( enc2==SQLITE_UTF16 );
002805    testcase( enc2==SQLITE_UTF16_ALIGNED );
002806    if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
002807      enc2 = SQLITE_UTF16NATIVE;
002808    }
002809    if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
002810      return SQLITE_MISUSE_BKPT;
002811    }
002812  
002813    /* Check if this call is removing or replacing an existing collation
002814    ** sequence. If so, and there are active VMs, return busy. If there
002815    ** are no active VMs, invalidate any pre-compiled statements.
002816    */
002817    pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
002818    if( pColl && pColl->xCmp ){
002819      if( db->nVdbeActive ){
002820        sqlite3ErrorWithMsg(db, SQLITE_BUSY,
002821          "unable to delete/modify collation sequence due to active statements");
002822        return SQLITE_BUSY;
002823      }
002824      sqlite3ExpirePreparedStatements(db, 0);
002825  
002826      /* If collation sequence pColl was created directly by a call to
002827      ** sqlite3_create_collation, and not generated by synthCollSeq(),
002828      ** then any copies made by synthCollSeq() need to be invalidated.
002829      ** Also, collation destructor - CollSeq.xDel() - function may need
002830      ** to be called.
002831      */
002832      if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
002833        CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
002834        int j;
002835        for(j=0; j<3; j++){
002836          CollSeq *p = &aColl[j];
002837          if( p->enc==pColl->enc ){
002838            if( p->xDel ){
002839              p->xDel(p->pUser);
002840            }
002841            p->xCmp = 0;
002842          }
002843        }
002844      }
002845    }
002846  
002847    pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
002848    if( pColl==0 ) return SQLITE_NOMEM_BKPT;
002849    pColl->xCmp = xCompare;
002850    pColl->pUser = pCtx;
002851    pColl->xDel = xDel;
002852    pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
002853    sqlite3Error(db, SQLITE_OK);
002854    return SQLITE_OK;
002855  }
002856  
002857  
002858  /*
002859  ** This array defines hard upper bounds on limit values.  The
002860  ** initializer must be kept in sync with the SQLITE_LIMIT_*
002861  ** #defines in sqlite3.h.
002862  */
002863  static const int aHardLimit[] = {
002864    SQLITE_MAX_LENGTH,
002865    SQLITE_MAX_SQL_LENGTH,
002866    SQLITE_MAX_COLUMN,
002867    SQLITE_MAX_EXPR_DEPTH,
002868    SQLITE_MAX_COMPOUND_SELECT,
002869    SQLITE_MAX_VDBE_OP,
002870    SQLITE_MAX_FUNCTION_ARG,
002871    SQLITE_MAX_ATTACHED,
002872    SQLITE_MAX_LIKE_PATTERN_LENGTH,
002873    SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
002874    SQLITE_MAX_TRIGGER_DEPTH,
002875    SQLITE_MAX_WORKER_THREADS,
002876  };
002877  
002878  /*
002879  ** Make sure the hard limits are set to reasonable values
002880  */
002881  #if SQLITE_MAX_LENGTH<100
002882  # error SQLITE_MAX_LENGTH must be at least 100
002883  #endif
002884  #if SQLITE_MAX_SQL_LENGTH<100
002885  # error SQLITE_MAX_SQL_LENGTH must be at least 100
002886  #endif
002887  #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
002888  # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
002889  #endif
002890  #if SQLITE_MAX_COMPOUND_SELECT<2
002891  # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
002892  #endif
002893  #if SQLITE_MAX_VDBE_OP<40
002894  # error SQLITE_MAX_VDBE_OP must be at least 40
002895  #endif
002896  #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
002897  # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
002898  #endif
002899  #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
002900  # error SQLITE_MAX_ATTACHED must be between 0 and 125
002901  #endif
002902  #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
002903  # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
002904  #endif
002905  #if SQLITE_MAX_COLUMN>32767
002906  # error SQLITE_MAX_COLUMN must not exceed 32767
002907  #endif
002908  #if SQLITE_MAX_TRIGGER_DEPTH<1
002909  # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
002910  #endif
002911  #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
002912  # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
002913  #endif
002914  
002915  
002916  /*
002917  ** Change the value of a limit.  Report the old value.
002918  ** If an invalid limit index is supplied, report -1.
002919  ** Make no changes but still report the old value if the
002920  ** new limit is negative.
002921  **
002922  ** A new lower limit does not shrink existing constructs.
002923  ** It merely prevents new constructs that exceed the limit
002924  ** from forming.
002925  */
002926  int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
002927    int oldLimit;
002928  
002929  #ifdef SQLITE_ENABLE_API_ARMOR
002930    if( !sqlite3SafetyCheckOk(db) ){
002931      (void)SQLITE_MISUSE_BKPT;
002932      return -1;
002933    }
002934  #endif
002935  
002936    /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
002937    ** there is a hard upper bound set at compile-time by a C preprocessor
002938    ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
002939    ** "_MAX_".)
002940    */
002941    assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
002942    assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
002943    assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
002944    assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
002945    assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
002946    assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
002947    assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
002948    assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
002949    assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
002950                                                 SQLITE_MAX_LIKE_PATTERN_LENGTH );
002951    assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
002952    assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
002953    assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
002954    assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
002955  
002956  
002957    if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
002958      return -1;
002959    }
002960    oldLimit = db->aLimit[limitId];
002961    if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
002962      if( newLimit>aHardLimit[limitId] ){
002963        newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
002964      }else if( newLimit<1 && limitId==SQLITE_LIMIT_LENGTH ){
002965        newLimit = 1;
002966      }
002967      db->aLimit[limitId] = newLimit;
002968    }
002969    return oldLimit;                     /* IMP: R-53341-35419 */
002970  }
002971  
002972  /*
002973  ** This function is used to parse both URIs and non-URI filenames passed by the
002974  ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
002975  ** URIs specified as part of ATTACH statements.
002976  **
002977  ** The first argument to this function is the name of the VFS to use (or
002978  ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
002979  ** query parameter. The second argument contains the URI (or non-URI filename)
002980  ** itself. When this function is called the *pFlags variable should contain
002981  ** the default flags to open the database handle with. The value stored in
002982  ** *pFlags may be updated before returning if the URI filename contains
002983  ** "cache=xxx" or "mode=xxx" query parameters.
002984  **
002985  ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
002986  ** the VFS that should be used to open the database file. *pzFile is set to
002987  ** point to a buffer containing the name of the file to open.  The value
002988  ** stored in *pzFile is a database name acceptable to sqlite3_uri_parameter()
002989  ** and is in the same format as names created using sqlite3_create_filename().
002990  ** The caller must invoke sqlite3_free_filename() (not sqlite3_free()!) on
002991  ** the value returned in *pzFile to avoid a memory leak.
002992  **
002993  ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
002994  ** may be set to point to a buffer containing an English language error
002995  ** message. It is the responsibility of the caller to eventually release
002996  ** this buffer by calling sqlite3_free().
002997  */
002998  int sqlite3ParseUri(
002999    const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
003000    const char *zUri,               /* Nul-terminated URI to parse */
003001    unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
003002    sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
003003    char **pzFile,                  /* OUT: Filename component of URI */
003004    char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
003005  ){
003006    int rc = SQLITE_OK;
003007    unsigned int flags = *pFlags;
003008    const char *zVfs = zDefaultVfs;
003009    char *zFile;
003010    char c;
003011    int nUri = sqlite3Strlen30(zUri);
003012  
003013    assert( *pzErrMsg==0 );
003014  
003015    if( ((flags & SQLITE_OPEN_URI)                     /* IMP: R-48725-32206 */
003016         || AtomicLoad(&sqlite3GlobalConfig.bOpenUri)) /* IMP: R-51689-46548 */
003017     && nUri>=5 && memcmp(zUri, "file:", 5)==0         /* IMP: R-57884-37496 */
003018    ){
003019      char *zOpt;
003020      int eState;                   /* Parser state when parsing URI */
003021      int iIn;                      /* Input character index */
003022      int iOut = 0;                 /* Output character index */
003023      u64 nByte = nUri+8;           /* Bytes of space to allocate */
003024  
003025      /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
003026      ** method that there may be extra parameters following the file-name.  */
003027      flags |= SQLITE_OPEN_URI;
003028  
003029      for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
003030      zFile = sqlite3_malloc64(nByte);
003031      if( !zFile ) return SQLITE_NOMEM_BKPT;
003032  
003033      memset(zFile, 0, 4);  /* 4-byte of 0x00 is the start of DB name marker */
003034      zFile += 4;
003035  
003036      iIn = 5;
003037  #ifdef SQLITE_ALLOW_URI_AUTHORITY
003038      if( strncmp(zUri+5, "///", 3)==0 ){
003039        iIn = 7;
003040        /* The following condition causes URIs with five leading / characters
003041        ** like file://///host/path to be converted into UNCs like //host/path.
003042        ** The correct URI for that UNC has only two or four leading / characters
003043        ** file://host/path or file:////host/path.  But 5 leading slashes is a
003044        ** common error, we are told, so we handle it as a special case. */
003045        if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
003046      }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
003047        iIn = 16;
003048      }
003049  #else
003050      /* Discard the scheme and authority segments of the URI. */
003051      if( zUri[5]=='/' && zUri[6]=='/' ){
003052        iIn = 7;
003053        while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
003054        if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
003055          *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
003056              iIn-7, &zUri[7]);
003057          rc = SQLITE_ERROR;
003058          goto parse_uri_out;
003059        }
003060      }
003061  #endif
003062  
003063      /* Copy the filename and any query parameters into the zFile buffer.
003064      ** Decode %HH escape codes along the way.
003065      **
003066      ** Within this loop, variable eState may be set to 0, 1 or 2, depending
003067      ** on the parsing context. As follows:
003068      **
003069      **   0: Parsing file-name.
003070      **   1: Parsing name section of a name=value query parameter.
003071      **   2: Parsing value section of a name=value query parameter.
003072      */
003073      eState = 0;
003074      while( (c = zUri[iIn])!=0 && c!='#' ){
003075        iIn++;
003076        if( c=='%'
003077         && sqlite3Isxdigit(zUri[iIn])
003078         && sqlite3Isxdigit(zUri[iIn+1])
003079        ){
003080          int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
003081          octet += sqlite3HexToInt(zUri[iIn++]);
003082  
003083          assert( octet>=0 && octet<256 );
003084          if( octet==0 ){
003085  #ifndef SQLITE_ENABLE_URI_00_ERROR
003086            /* This branch is taken when "%00" appears within the URI. In this
003087            ** case we ignore all text in the remainder of the path, name or
003088            ** value currently being parsed. So ignore the current character
003089            ** and skip to the next "?", "=" or "&", as appropriate. */
003090            while( (c = zUri[iIn])!=0 && c!='#'
003091                && (eState!=0 || c!='?')
003092                && (eState!=1 || (c!='=' && c!='&'))
003093                && (eState!=2 || c!='&')
003094            ){
003095              iIn++;
003096            }
003097            continue;
003098  #else
003099            /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
003100            *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
003101            rc = SQLITE_ERROR;
003102            goto parse_uri_out;
003103  #endif
003104          }
003105          c = octet;
003106        }else if( eState==1 && (c=='&' || c=='=') ){
003107          if( zFile[iOut-1]==0 ){
003108            /* An empty option name. Ignore this option altogether. */
003109            while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
003110            continue;
003111          }
003112          if( c=='&' ){
003113            zFile[iOut++] = '\0';
003114          }else{
003115            eState = 2;
003116          }
003117          c = 0;
003118        }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
003119          c = 0;
003120          eState = 1;
003121        }
003122        zFile[iOut++] = c;
003123      }
003124      if( eState==1 ) zFile[iOut++] = '\0';
003125      memset(zFile+iOut, 0, 4); /* end-of-options + empty journal filenames */
003126  
003127      /* Check if there were any options specified that should be interpreted
003128      ** here. Options that are interpreted here include "vfs" and those that
003129      ** correspond to flags that may be passed to the sqlite3_open_v2()
003130      ** method. */
003131      zOpt = &zFile[sqlite3Strlen30(zFile)+1];
003132      while( zOpt[0] ){
003133        int nOpt = sqlite3Strlen30(zOpt);
003134        char *zVal = &zOpt[nOpt+1];
003135        int nVal = sqlite3Strlen30(zVal);
003136  
003137        if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
003138          zVfs = zVal;
003139        }else{
003140          struct OpenMode {
003141            const char *z;
003142            int mode;
003143          } *aMode = 0;
003144          char *zModeType = 0;
003145          int mask = 0;
003146          int limit = 0;
003147  
003148          if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
003149            static struct OpenMode aCacheMode[] = {
003150              { "shared",  SQLITE_OPEN_SHAREDCACHE },
003151              { "private", SQLITE_OPEN_PRIVATECACHE },
003152              { 0, 0 }
003153            };
003154  
003155            mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
003156            aMode = aCacheMode;
003157            limit = mask;
003158            zModeType = "cache";
003159          }
003160          if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
003161            static struct OpenMode aOpenMode[] = {
003162              { "ro",  SQLITE_OPEN_READONLY },
003163              { "rw",  SQLITE_OPEN_READWRITE },
003164              { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
003165              { "memory", SQLITE_OPEN_MEMORY },
003166              { 0, 0 }
003167            };
003168  
003169            mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
003170                     | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
003171            aMode = aOpenMode;
003172            limit = mask & flags;
003173            zModeType = "access";
003174          }
003175  
003176          if( aMode ){
003177            int i;
003178            int mode = 0;
003179            for(i=0; aMode[i].z; i++){
003180              const char *z = aMode[i].z;
003181              if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
003182                mode = aMode[i].mode;
003183                break;
003184              }
003185            }
003186            if( mode==0 ){
003187              *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
003188              rc = SQLITE_ERROR;
003189              goto parse_uri_out;
003190            }
003191            if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
003192              *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
003193                                          zModeType, zVal);
003194              rc = SQLITE_PERM;
003195              goto parse_uri_out;
003196            }
003197            flags = (flags & ~mask) | mode;
003198          }
003199        }
003200  
003201        zOpt = &zVal[nVal+1];
003202      }
003203  
003204    }else{
003205      zFile = sqlite3_malloc64(nUri+8);
003206      if( !zFile ) return SQLITE_NOMEM_BKPT;
003207      memset(zFile, 0, 4);
003208      zFile += 4;
003209      if( nUri ){
003210        memcpy(zFile, zUri, nUri);
003211      }
003212      memset(zFile+nUri, 0, 4);
003213      flags &= ~SQLITE_OPEN_URI;
003214    }
003215  
003216    *ppVfs = sqlite3_vfs_find(zVfs);
003217    if( *ppVfs==0 ){
003218      *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
003219      rc = SQLITE_ERROR;
003220    }
003221   parse_uri_out:
003222    if( rc!=SQLITE_OK ){
003223      sqlite3_free_filename(zFile);
003224      zFile = 0;
003225    }
003226    *pFlags = flags;
003227    *pzFile = zFile;
003228    return rc;
003229  }
003230  
003231  /*
003232  ** This routine does the core work of extracting URI parameters from a
003233  ** database filename for the sqlite3_uri_parameter() interface.
003234  */
003235  static const char *uriParameter(const char *zFilename, const char *zParam){
003236    zFilename += sqlite3Strlen30(zFilename) + 1;
003237    while( ALWAYS(zFilename!=0) && zFilename[0] ){
003238      int x = strcmp(zFilename, zParam);
003239      zFilename += sqlite3Strlen30(zFilename) + 1;
003240      if( x==0 ) return zFilename;
003241      zFilename += sqlite3Strlen30(zFilename) + 1;
003242    }
003243    return 0;
003244  }
003245  
003246  
003247  
003248  /*
003249  ** This routine does the work of opening a database on behalf of
003250  ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename" 
003251  ** is UTF-8 encoded.
003252  */
003253  static int openDatabase(
003254    const char *zFilename, /* Database filename UTF-8 encoded */
003255    sqlite3 **ppDb,        /* OUT: Returned database handle */
003256    unsigned int flags,    /* Operational flags */
003257    const char *zVfs       /* Name of the VFS to use */
003258  ){
003259    sqlite3 *db;                    /* Store allocated handle here */
003260    int rc;                         /* Return code */
003261    int isThreadsafe;               /* True for threadsafe connections */
003262    char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
003263    char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
003264    int i;                          /* Loop counter */
003265  
003266  #ifdef SQLITE_ENABLE_API_ARMOR
003267    if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
003268  #endif
003269    *ppDb = 0;
003270  #ifndef SQLITE_OMIT_AUTOINIT
003271    rc = sqlite3_initialize();
003272    if( rc ) return rc;
003273  #endif
003274  
003275    if( sqlite3GlobalConfig.bCoreMutex==0 ){
003276      isThreadsafe = 0;
003277    }else if( flags & SQLITE_OPEN_NOMUTEX ){
003278      isThreadsafe = 0;
003279    }else if( flags & SQLITE_OPEN_FULLMUTEX ){
003280      isThreadsafe = 1;
003281    }else{
003282      isThreadsafe = sqlite3GlobalConfig.bFullMutex;
003283    }
003284  
003285    if( flags & SQLITE_OPEN_PRIVATECACHE ){
003286      flags &= ~SQLITE_OPEN_SHAREDCACHE;
003287    }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
003288      flags |= SQLITE_OPEN_SHAREDCACHE;
003289    }
003290  
003291    /* Remove harmful bits from the flags parameter
003292    **
003293    ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
003294    ** dealt with in the previous code block.  Besides these, the only
003295    ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
003296    ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
003297    ** SQLITE_OPEN_PRIVATECACHE, SQLITE_OPEN_EXRESCODE, and some reserved
003298    ** bits.  Silently mask off all other flags.
003299    */
003300    flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
003301                 SQLITE_OPEN_EXCLUSIVE |
003302                 SQLITE_OPEN_MAIN_DB |
003303                 SQLITE_OPEN_TEMP_DB |
003304                 SQLITE_OPEN_TRANSIENT_DB |
003305                 SQLITE_OPEN_MAIN_JOURNAL |
003306                 SQLITE_OPEN_TEMP_JOURNAL |
003307                 SQLITE_OPEN_SUBJOURNAL |
003308                 SQLITE_OPEN_SUPER_JOURNAL |
003309                 SQLITE_OPEN_NOMUTEX |
003310                 SQLITE_OPEN_FULLMUTEX |
003311                 SQLITE_OPEN_WAL
003312               );
003313  
003314    /* Allocate the sqlite data structure */
003315    db = sqlite3MallocZero( sizeof(sqlite3) );
003316    if( db==0 ) goto opendb_out;
003317    if( isThreadsafe
003318  #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
003319     || sqlite3GlobalConfig.bCoreMutex
003320  #endif
003321    ){
003322      db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
003323      if( db->mutex==0 ){
003324        sqlite3_free(db);
003325        db = 0;
003326        goto opendb_out;
003327      }
003328      if( isThreadsafe==0 ){
003329        sqlite3MutexWarnOnContention(db->mutex);
003330      }
003331    }
003332    sqlite3_mutex_enter(db->mutex);
003333    db->errMask = (flags & SQLITE_OPEN_EXRESCODE)!=0 ? 0xffffffff : 0xff;
003334    db->nDb = 2;
003335    db->eOpenState = SQLITE_STATE_BUSY;
003336    db->aDb = db->aDbStatic;
003337    db->lookaside.bDisable = 1;
003338    db->lookaside.sz = 0;
003339  
003340    assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
003341    memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
003342    db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
003343    db->autoCommit = 1;
003344    db->nextAutovac = -1;
003345    db->szMmap = sqlite3GlobalConfig.szMmap;
003346    db->nextPagesize = 0;
003347    db->init.azInit = sqlite3StdType; /* Any array of string ptrs will do */
003348  #ifdef SQLITE_ENABLE_SORTER_MMAP
003349    /* Beginning with version 3.37.0, using the VFS xFetch() API to memory-map
003350    ** the temporary files used to do external sorts (see code in vdbesort.c)
003351    ** is disabled. It can still be used either by defining
003352    ** SQLITE_ENABLE_SORTER_MMAP at compile time or by using the
003353    ** SQLITE_TESTCTRL_SORTER_MMAP test-control at runtime. */
003354    db->nMaxSorterMmap = 0x7FFFFFFF;
003355  #endif
003356    db->flags |= SQLITE_ShortColNames
003357                   | SQLITE_EnableTrigger
003358                   | SQLITE_EnableView
003359                   | SQLITE_CacheSpill
003360  #if !defined(SQLITE_TRUSTED_SCHEMA) || SQLITE_TRUSTED_SCHEMA+0!=0
003361                   | SQLITE_TrustedSchema
003362  #endif
003363  /* The SQLITE_DQS compile-time option determines the default settings
003364  ** for SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML.
003365  **
003366  **    SQLITE_DQS     SQLITE_DBCONFIG_DQS_DDL    SQLITE_DBCONFIG_DQS_DML
003367  **    ----------     -----------------------    -----------------------
003368  **     undefined               on                          on
003369  **         3                   on                          on
003370  **         2                   on                         off
003371  **         1                  off                          on
003372  **         0                  off                         off
003373  **
003374  ** Legacy behavior is 3 (double-quoted string literals are allowed anywhere)
003375  ** and so that is the default.  But developers are encouraged to use
003376  ** -DSQLITE_DQS=0 (best) or -DSQLITE_DQS=1 (second choice) if possible.
003377  */
003378  #if !defined(SQLITE_DQS)
003379  # define SQLITE_DQS 3
003380  #endif
003381  #if (SQLITE_DQS&1)==1
003382                   | SQLITE_DqsDML
003383  #endif
003384  #if (SQLITE_DQS&2)==2
003385                   | SQLITE_DqsDDL
003386  #endif
003387  
003388  #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
003389                   | SQLITE_AutoIndex
003390  #endif
003391  #if SQLITE_DEFAULT_CKPTFULLFSYNC
003392                   | SQLITE_CkptFullFSync
003393  #endif
003394  #if SQLITE_DEFAULT_FILE_FORMAT<4
003395                   | SQLITE_LegacyFileFmt
003396  #endif
003397  #ifdef SQLITE_ENABLE_LOAD_EXTENSION
003398                   | SQLITE_LoadExtension
003399  #endif
003400  #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
003401                   | SQLITE_RecTriggers
003402  #endif
003403  #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
003404                   | SQLITE_ForeignKeys
003405  #endif
003406  #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
003407                   | SQLITE_ReverseOrder
003408  #endif
003409  #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
003410                   | SQLITE_CellSizeCk
003411  #endif
003412  #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
003413                   | SQLITE_Fts3Tokenizer
003414  #endif
003415  #if defined(SQLITE_ENABLE_QPSG)
003416                   | SQLITE_EnableQPSG
003417  #endif
003418  #if defined(SQLITE_DEFAULT_DEFENSIVE)
003419                   | SQLITE_Defensive
003420  #endif
003421  #if defined(SQLITE_DEFAULT_LEGACY_ALTER_TABLE)
003422                   | SQLITE_LegacyAlter
003423  #endif
003424  #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
003425                   | SQLITE_StmtScanStatus
003426  #endif
003427        ;
003428    sqlite3HashInit(&db->aCollSeq);
003429  #ifndef SQLITE_OMIT_VIRTUALTABLE
003430    sqlite3HashInit(&db->aModule);
003431  #endif
003432  
003433    /* Add the default collation sequence BINARY. BINARY works for both UTF-8
003434    ** and UTF-16, so add a version for each to avoid any unnecessary
003435    ** conversions. The only error that can occur here is a malloc() failure.
003436    **
003437    ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
003438    ** functions:
003439    */
003440    createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
003441    createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
003442    createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
003443    createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
003444    createCollation(db, "RTRIM", SQLITE_UTF8, 0, rtrimCollFunc, 0);
003445    if( db->mallocFailed ){
003446      goto opendb_out;
003447    }
003448  
003449  #if SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL)
003450    /* Process magic filenames ":localStorage:" and ":sessionStorage:" */
003451    if( zFilename && zFilename[0]==':' ){
003452      if( strcmp(zFilename, ":localStorage:")==0 ){
003453        zFilename = "file:local?vfs=kvvfs";
003454        flags |= SQLITE_OPEN_URI;
003455      }else if( strcmp(zFilename, ":sessionStorage:")==0 ){
003456        zFilename = "file:session?vfs=kvvfs";
003457        flags |= SQLITE_OPEN_URI;
003458      }
003459    }
003460  #endif /* SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL) */
003461  
003462    /* Parse the filename/URI argument
003463    **
003464    ** Only allow sensible combinations of bits in the flags argument. 
003465    ** Throw an error if any non-sense combination is used.  If we
003466    ** do not block illegal combinations here, it could trigger
003467    ** assert() statements in deeper layers.  Sensible combinations
003468    ** are:
003469    **
003470    **  1:  SQLITE_OPEN_READONLY
003471    **  2:  SQLITE_OPEN_READWRITE
003472    **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
003473    */
003474    db->openFlags = flags;
003475    assert( SQLITE_OPEN_READONLY  == 0x01 );
003476    assert( SQLITE_OPEN_READWRITE == 0x02 );
003477    assert( SQLITE_OPEN_CREATE    == 0x04 );
003478    testcase( (1<<(flags&7))==0x02 ); /* READONLY */
003479    testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
003480    testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
003481    if( ((1<<(flags&7)) & 0x46)==0 ){
003482      rc = SQLITE_MISUSE_BKPT;  /* IMP: R-18321-05872 */
003483    }else{
003484      rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
003485    }
003486    if( rc!=SQLITE_OK ){
003487      if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
003488      sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
003489      sqlite3_free(zErrMsg);
003490      goto opendb_out;
003491    }
003492    assert( db->pVfs!=0 );
003493  #if SQLITE_OS_KV || defined(SQLITE_OS_KV_OPTIONAL)
003494    if( sqlite3_stricmp(db->pVfs->zName, "kvvfs")==0 ){
003495      db->temp_store = 2;
003496    }
003497  #endif
003498  
003499    /* Open the backend database driver */
003500    rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
003501                          flags | SQLITE_OPEN_MAIN_DB);
003502    if( rc!=SQLITE_OK ){
003503      if( rc==SQLITE_IOERR_NOMEM ){
003504        rc = SQLITE_NOMEM_BKPT;
003505      }
003506      sqlite3Error(db, rc);
003507      goto opendb_out;
003508    }
003509    sqlite3BtreeEnter(db->aDb[0].pBt);
003510    db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
003511    if( !db->mallocFailed ){
003512      sqlite3SetTextEncoding(db, SCHEMA_ENC(db));
003513    }
003514    sqlite3BtreeLeave(db->aDb[0].pBt);
003515    db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
003516  
003517    /* The default safety_level for the main database is FULL; for the temp
003518    ** database it is OFF. This matches the pager layer defaults. 
003519    */
003520    db->aDb[0].zDbSName = "main";
003521    db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
003522    db->aDb[1].zDbSName = "temp";
003523    db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
003524  
003525    db->eOpenState = SQLITE_STATE_OPEN;
003526    if( db->mallocFailed ){
003527      goto opendb_out;
003528    }
003529  
003530    /* Register all built-in functions, but do not attempt to read the
003531    ** database schema yet. This is delayed until the first time the database
003532    ** is accessed.
003533    */
003534    sqlite3Error(db, SQLITE_OK);
003535    sqlite3RegisterPerConnectionBuiltinFunctions(db);
003536    rc = sqlite3_errcode(db);
003537  
003538  
003539    /* Load compiled-in extensions */
003540    for(i=0; rc==SQLITE_OK && i<ArraySize(sqlite3BuiltinExtensions); i++){
003541      rc = sqlite3BuiltinExtensions[i](db);
003542    }
003543  
003544    /* Load automatic extensions - extensions that have been registered
003545    ** using the sqlite3_automatic_extension() API.
003546    */
003547    if( rc==SQLITE_OK ){
003548      sqlite3AutoLoadExtensions(db);
003549      rc = sqlite3_errcode(db);
003550      if( rc!=SQLITE_OK ){
003551        goto opendb_out;
003552      }
003553    }
003554  
003555  #ifdef SQLITE_ENABLE_INTERNAL_FUNCTIONS
003556    /* Testing use only!!! The -DSQLITE_ENABLE_INTERNAL_FUNCTIONS=1 compile-time
003557    ** option gives access to internal functions by default. 
003558    ** Testing use only!!! */
003559    db->mDbFlags |= DBFLAG_InternalFunc;
003560  #endif
003561  
003562    /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
003563    ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
003564    ** mode.  Doing nothing at all also makes NORMAL the default.
003565    */
003566  #ifdef SQLITE_DEFAULT_LOCKING_MODE
003567    db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
003568    sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
003569                            SQLITE_DEFAULT_LOCKING_MODE);
003570  #endif
003571  
003572    if( rc ) sqlite3Error(db, rc);
003573  
003574    /* Enable the lookaside-malloc subsystem */
003575    setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
003576                          sqlite3GlobalConfig.nLookaside);
003577  
003578    sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
003579  
003580  opendb_out:
003581    if( db ){
003582      assert( db->mutex!=0 || isThreadsafe==0
003583             || sqlite3GlobalConfig.bFullMutex==0 );
003584      sqlite3_mutex_leave(db->mutex);
003585    }
003586    rc = sqlite3_errcode(db);
003587    assert( db!=0 || (rc&0xff)==SQLITE_NOMEM );
003588    if( (rc&0xff)==SQLITE_NOMEM ){
003589      sqlite3_close(db);
003590      db = 0;
003591    }else if( rc!=SQLITE_OK ){
003592      db->eOpenState = SQLITE_STATE_SICK;
003593    }
003594    *ppDb = db;
003595  #ifdef SQLITE_ENABLE_SQLLOG
003596    if( sqlite3GlobalConfig.xSqllog ){
003597      /* Opening a db handle. Fourth parameter is passed 0. */
003598      void *pArg = sqlite3GlobalConfig.pSqllogArg;
003599      sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
003600    }
003601  #endif
003602    sqlite3_free_filename(zOpen);
003603    return rc;
003604  }
003605  
003606  
003607  /*
003608  ** Open a new database handle.
003609  */
003610  int sqlite3_open(
003611    const char *zFilename,
003612    sqlite3 **ppDb
003613  ){
003614    return openDatabase(zFilename, ppDb,
003615                        SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
003616  }
003617  int sqlite3_open_v2(
003618    const char *filename,   /* Database filename (UTF-8) */
003619    sqlite3 **ppDb,         /* OUT: SQLite db handle */
003620    int flags,              /* Flags */
003621    const char *zVfs        /* Name of VFS module to use */
003622  ){
003623    return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
003624  }
003625  
003626  #ifndef SQLITE_OMIT_UTF16
003627  /*
003628  ** Open a new database handle.
003629  */
003630  int sqlite3_open16(
003631    const void *zFilename,
003632    sqlite3 **ppDb
003633  ){
003634    char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
003635    sqlite3_value *pVal;
003636    int rc;
003637  
003638  #ifdef SQLITE_ENABLE_API_ARMOR
003639    if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
003640  #endif
003641    *ppDb = 0;
003642  #ifndef SQLITE_OMIT_AUTOINIT
003643    rc = sqlite3_initialize();
003644    if( rc ) return rc;
003645  #endif
003646    if( zFilename==0 ) zFilename = "\000\000";
003647    pVal = sqlite3ValueNew(0);
003648    sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
003649    zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
003650    if( zFilename8 ){
003651      rc = openDatabase(zFilename8, ppDb,
003652                        SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
003653      assert( *ppDb || rc==SQLITE_NOMEM );
003654      if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
003655        SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
003656      }
003657    }else{
003658      rc = SQLITE_NOMEM_BKPT;
003659    }
003660    sqlite3ValueFree(pVal);
003661  
003662    return rc & 0xff;
003663  }
003664  #endif /* SQLITE_OMIT_UTF16 */
003665  
003666  /*
003667  ** Register a new collation sequence with the database handle db.
003668  */
003669  int sqlite3_create_collation(
003670    sqlite3* db,
003671    const char *zName,
003672    int enc,
003673    void* pCtx,
003674    int(*xCompare)(void*,int,const void*,int,const void*)
003675  ){
003676    return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
003677  }
003678  
003679  /*
003680  ** Register a new collation sequence with the database handle db.
003681  */
003682  int sqlite3_create_collation_v2(
003683    sqlite3* db,
003684    const char *zName,
003685    int enc,
003686    void* pCtx,
003687    int(*xCompare)(void*,int,const void*,int,const void*),
003688    void(*xDel)(void*)
003689  ){
003690    int rc;
003691  
003692  #ifdef SQLITE_ENABLE_API_ARMOR
003693    if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
003694  #endif
003695    sqlite3_mutex_enter(db->mutex);
003696    assert( !db->mallocFailed );
003697    rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
003698    rc = sqlite3ApiExit(db, rc);
003699    sqlite3_mutex_leave(db->mutex);
003700    return rc;
003701  }
003702  
003703  #ifndef SQLITE_OMIT_UTF16
003704  /*
003705  ** Register a new collation sequence with the database handle db.
003706  */
003707  int sqlite3_create_collation16(
003708    sqlite3* db,
003709    const void *zName,
003710    int enc,
003711    void* pCtx,
003712    int(*xCompare)(void*,int,const void*,int,const void*)
003713  ){
003714    int rc = SQLITE_OK;
003715    char *zName8;
003716  
003717  #ifdef SQLITE_ENABLE_API_ARMOR
003718    if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
003719  #endif
003720    sqlite3_mutex_enter(db->mutex);
003721    assert( !db->mallocFailed );
003722    zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
003723    if( zName8 ){
003724      rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
003725      sqlite3DbFree(db, zName8);
003726    }
003727    rc = sqlite3ApiExit(db, rc);
003728    sqlite3_mutex_leave(db->mutex);
003729    return rc;
003730  }
003731  #endif /* SQLITE_OMIT_UTF16 */
003732  
003733  /*
003734  ** Register a collation sequence factory callback with the database handle
003735  ** db. Replace any previously installed collation sequence factory.
003736  */
003737  int sqlite3_collation_needed(
003738    sqlite3 *db,
003739    void *pCollNeededArg,
003740    void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
003741  ){
003742  #ifdef SQLITE_ENABLE_API_ARMOR
003743    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
003744  #endif
003745    sqlite3_mutex_enter(db->mutex);
003746    db->xCollNeeded = xCollNeeded;
003747    db->xCollNeeded16 = 0;
003748    db->pCollNeededArg = pCollNeededArg;
003749    sqlite3_mutex_leave(db->mutex);
003750    return SQLITE_OK;
003751  }
003752  
003753  #ifndef SQLITE_OMIT_UTF16
003754  /*
003755  ** Register a collation sequence factory callback with the database handle
003756  ** db. Replace any previously installed collation sequence factory.
003757  */
003758  int sqlite3_collation_needed16(
003759    sqlite3 *db,
003760    void *pCollNeededArg,
003761    void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
003762  ){
003763  #ifdef SQLITE_ENABLE_API_ARMOR
003764    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
003765  #endif
003766    sqlite3_mutex_enter(db->mutex);
003767    db->xCollNeeded = 0;
003768    db->xCollNeeded16 = xCollNeeded16;
003769    db->pCollNeededArg = pCollNeededArg;
003770    sqlite3_mutex_leave(db->mutex);
003771    return SQLITE_OK;
003772  }
003773  #endif /* SQLITE_OMIT_UTF16 */
003774  
003775  /*
003776  ** Find existing client data.
003777  */
003778  void *sqlite3_get_clientdata(sqlite3 *db, const char *zName){
003779    DbClientData *p;
003780    sqlite3_mutex_enter(db->mutex);
003781    for(p=db->pDbData; p; p=p->pNext){
003782      if( strcmp(p->zName, zName)==0 ){
003783        void *pResult = p->pData;
003784        sqlite3_mutex_leave(db->mutex);
003785        return pResult;
003786      }
003787    }
003788    sqlite3_mutex_leave(db->mutex);
003789    return 0;
003790  }
003791  
003792  /*
003793  ** Add new client data to a database connection.
003794  */
003795  int sqlite3_set_clientdata(
003796    sqlite3 *db,                   /* Attach client data to this connection */
003797    const char *zName,             /* Name of the client data */
003798    void *pData,                   /* The client data itself */
003799    void (*xDestructor)(void*)     /* Destructor */
003800  ){
003801    DbClientData *p, **pp;
003802    sqlite3_mutex_enter(db->mutex);
003803    pp = &db->pDbData;
003804    for(p=db->pDbData; p && strcmp(p->zName,zName); p=p->pNext){
003805      pp = &p->pNext;
003806    }
003807    if( p ){
003808      assert( p->pData!=0 );
003809      if( p->xDestructor ) p->xDestructor(p->pData);
003810      if( pData==0 ){
003811        *pp = p->pNext;
003812        sqlite3_free(p);
003813        sqlite3_mutex_leave(db->mutex);
003814        return SQLITE_OK;
003815      }
003816    }else if( pData==0 ){
003817      sqlite3_mutex_leave(db->mutex);
003818      return SQLITE_OK;
003819    }else{
003820      size_t n = strlen(zName);
003821      p = sqlite3_malloc64( sizeof(DbClientData)+n+1 );
003822      if( p==0 ){
003823        if( xDestructor ) xDestructor(pData);
003824        sqlite3_mutex_leave(db->mutex);
003825        return SQLITE_NOMEM;
003826      }
003827      memcpy(p->zName, zName, n+1);
003828      p->pNext = db->pDbData;
003829      db->pDbData = p;
003830    }
003831    p->pData = pData;
003832    p->xDestructor = xDestructor;
003833    sqlite3_mutex_leave(db->mutex);
003834    return SQLITE_OK;
003835  }
003836  
003837  
003838  #ifndef SQLITE_OMIT_DEPRECATED
003839  /*
003840  ** This function is now an anachronism. It used to be used to recover from a
003841  ** malloc() failure, but SQLite now does this automatically.
003842  */
003843  int sqlite3_global_recover(void){
003844    return SQLITE_OK;
003845  }
003846  #endif
003847  
003848  /*
003849  ** Test to see whether or not the database connection is in autocommit
003850  ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
003851  ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
003852  ** by the next COMMIT or ROLLBACK.
003853  */
003854  int sqlite3_get_autocommit(sqlite3 *db){
003855  #ifdef SQLITE_ENABLE_API_ARMOR
003856    if( !sqlite3SafetyCheckOk(db) ){
003857      (void)SQLITE_MISUSE_BKPT;
003858      return 0;
003859    }
003860  #endif
003861    return db->autoCommit;
003862  }
003863  
003864  /*
003865  ** The following routines are substitutes for constants SQLITE_CORRUPT,
003866  ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
003867  ** constants.  They serve two purposes:
003868  **
003869  **   1.  Serve as a convenient place to set a breakpoint in a debugger
003870  **       to detect when version error conditions occurs.
003871  **
003872  **   2.  Invoke sqlite3_log() to provide the source code location where
003873  **       a low-level error is first detected.
003874  */
003875  int sqlite3ReportError(int iErr, int lineno, const char *zType){
003876    sqlite3_log(iErr, "%s at line %d of [%.10s]",
003877                zType, lineno, 20+sqlite3_sourceid());
003878    return iErr;
003879  }
003880  int sqlite3CorruptError(int lineno){
003881    testcase( sqlite3GlobalConfig.xLog!=0 );
003882    return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
003883  }
003884  int sqlite3MisuseError(int lineno){
003885    testcase( sqlite3GlobalConfig.xLog!=0 );
003886    return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
003887  }
003888  int sqlite3CantopenError(int lineno){
003889    testcase( sqlite3GlobalConfig.xLog!=0 );
003890    return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
003891  }
003892  #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
003893  int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
003894    char zMsg[100];
003895    sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
003896    testcase( sqlite3GlobalConfig.xLog!=0 );
003897    return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
003898  }
003899  #endif
003900  #ifdef SQLITE_DEBUG
003901  int sqlite3NomemError(int lineno){
003902    testcase( sqlite3GlobalConfig.xLog!=0 );
003903    return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
003904  }
003905  int sqlite3IoerrnomemError(int lineno){
003906    testcase( sqlite3GlobalConfig.xLog!=0 );
003907    return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
003908  }
003909  #endif
003910  
003911  #ifndef SQLITE_OMIT_DEPRECATED
003912  /*
003913  ** This is a convenience routine that makes sure that all thread-specific
003914  ** data for this thread has been deallocated.
003915  **
003916  ** SQLite no longer uses thread-specific data so this routine is now a
003917  ** no-op.  It is retained for historical compatibility.
003918  */
003919  void sqlite3_thread_cleanup(void){
003920  }
003921  #endif
003922  
003923  /*
003924  ** Return meta information about a specific column of a database table.
003925  ** See comment in sqlite3.h (sqlite.h.in) for details.
003926  */
003927  int sqlite3_table_column_metadata(
003928    sqlite3 *db,                /* Connection handle */
003929    const char *zDbName,        /* Database name or NULL */
003930    const char *zTableName,     /* Table name */
003931    const char *zColumnName,    /* Column name */
003932    char const **pzDataType,    /* OUTPUT: Declared data type */
003933    char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
003934    int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
003935    int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
003936    int *pAutoinc               /* OUTPUT: True if column is auto-increment */
003937  ){
003938    int rc;
003939    char *zErrMsg = 0;
003940    Table *pTab = 0;
003941    Column *pCol = 0;
003942    int iCol = 0;
003943    char const *zDataType = 0;
003944    char const *zCollSeq = 0;
003945    int notnull = 0;
003946    int primarykey = 0;
003947    int autoinc = 0;
003948  
003949  
003950  #ifdef SQLITE_ENABLE_API_ARMOR
003951    if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
003952      return SQLITE_MISUSE_BKPT;
003953    }
003954  #endif
003955  
003956    /* Ensure the database schema has been loaded */
003957    sqlite3_mutex_enter(db->mutex);
003958    sqlite3BtreeEnterAll(db);
003959    rc = sqlite3Init(db, &zErrMsg);
003960    if( SQLITE_OK!=rc ){
003961      goto error_out;
003962    }
003963  
003964    /* Locate the table in question */
003965    pTab = sqlite3FindTable(db, zTableName, zDbName);
003966    if( !pTab || IsView(pTab) ){
003967      pTab = 0;
003968      goto error_out;
003969    }
003970  
003971    /* Find the column for which info is requested */
003972    if( zColumnName==0 ){
003973      /* Query for existence of table only */
003974    }else{
003975      for(iCol=0; iCol<pTab->nCol; iCol++){
003976        pCol = &pTab->aCol[iCol];
003977        if( 0==sqlite3StrICmp(pCol->zCnName, zColumnName) ){
003978          break;
003979        }
003980      }
003981      if( iCol==pTab->nCol ){
003982        if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
003983          iCol = pTab->iPKey;
003984          pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
003985        }else{
003986          pTab = 0;
003987          goto error_out;
003988        }
003989      }
003990    }
003991  
003992    /* The following block stores the meta information that will be returned
003993    ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
003994    ** and autoinc. At this point there are two possibilities:
003995    **
003996    **     1. The specified column name was rowid", "oid" or "_rowid_"
003997    **        and there is no explicitly declared IPK column.
003998    **
003999    **     2. The table is not a view and the column name identified an
004000    **        explicitly declared column. Copy meta information from *pCol.
004001    */
004002    if( pCol ){
004003      zDataType = sqlite3ColumnType(pCol,0);
004004      zCollSeq = sqlite3ColumnColl(pCol);
004005      notnull = pCol->notNull!=0;
004006      primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
004007      autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
004008    }else{
004009      zDataType = "INTEGER";
004010      primarykey = 1;
004011    }
004012    if( !zCollSeq ){
004013      zCollSeq = sqlite3StrBINARY;
004014    }
004015  
004016  error_out:
004017    sqlite3BtreeLeaveAll(db);
004018  
004019    /* Whether the function call succeeded or failed, set the output parameters
004020    ** to whatever their local counterparts contain. If an error did occur,
004021    ** this has the effect of zeroing all output parameters.
004022    */
004023    if( pzDataType ) *pzDataType = zDataType;
004024    if( pzCollSeq ) *pzCollSeq = zCollSeq;
004025    if( pNotNull ) *pNotNull = notnull;
004026    if( pPrimaryKey ) *pPrimaryKey = primarykey;
004027    if( pAutoinc ) *pAutoinc = autoinc;
004028  
004029    if( SQLITE_OK==rc && !pTab ){
004030      sqlite3DbFree(db, zErrMsg);
004031      zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
004032          zColumnName);
004033      rc = SQLITE_ERROR;
004034    }
004035    sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
004036    sqlite3DbFree(db, zErrMsg);
004037    rc = sqlite3ApiExit(db, rc);
004038    sqlite3_mutex_leave(db->mutex);
004039    return rc;
004040  }
004041  
004042  /*
004043  ** Sleep for a little while.  Return the amount of time slept.
004044  */
004045  int sqlite3_sleep(int ms){
004046    sqlite3_vfs *pVfs;
004047    int rc;
004048    pVfs = sqlite3_vfs_find(0);
004049    if( pVfs==0 ) return 0;
004050  
004051    /* This function works in milliseconds, but the underlying OsSleep()
004052    ** API uses microseconds. Hence the 1000's.
004053    */
004054    rc = (sqlite3OsSleep(pVfs, ms<0 ? 0 : 1000*ms)/1000);
004055    return rc;
004056  }
004057  
004058  /*
004059  ** Enable or disable the extended result codes.
004060  */
004061  int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
004062  #ifdef SQLITE_ENABLE_API_ARMOR
004063    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
004064  #endif
004065    sqlite3_mutex_enter(db->mutex);
004066    db->errMask = onoff ? 0xffffffff : 0xff;
004067    sqlite3_mutex_leave(db->mutex);
004068    return SQLITE_OK;
004069  }
004070  
004071  /*
004072  ** Invoke the xFileControl method on a particular database.
004073  */
004074  int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
004075    int rc = SQLITE_ERROR;
004076    Btree *pBtree;
004077  
004078  #ifdef SQLITE_ENABLE_API_ARMOR
004079    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
004080  #endif
004081    sqlite3_mutex_enter(db->mutex);
004082    pBtree = sqlite3DbNameToBtree(db, zDbName);
004083    if( pBtree ){
004084      Pager *pPager;
004085      sqlite3_file *fd;
004086      sqlite3BtreeEnter(pBtree);
004087      pPager = sqlite3BtreePager(pBtree);
004088      assert( pPager!=0 );
004089      fd = sqlite3PagerFile(pPager);
004090      assert( fd!=0 );
004091      if( op==SQLITE_FCNTL_FILE_POINTER ){
004092        *(sqlite3_file**)pArg = fd;
004093        rc = SQLITE_OK;
004094      }else if( op==SQLITE_FCNTL_VFS_POINTER ){
004095        *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
004096        rc = SQLITE_OK;
004097      }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
004098        *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
004099        rc = SQLITE_OK;
004100      }else if( op==SQLITE_FCNTL_DATA_VERSION ){
004101        *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager);
004102        rc = SQLITE_OK;
004103      }else if( op==SQLITE_FCNTL_RESERVE_BYTES ){
004104        int iNew = *(int*)pArg;
004105        *(int*)pArg = sqlite3BtreeGetRequestedReserve(pBtree);
004106        if( iNew>=0 && iNew<=255 ){
004107          sqlite3BtreeSetPageSize(pBtree, 0, iNew, 0);
004108        }
004109        rc = SQLITE_OK;
004110      }else if( op==SQLITE_FCNTL_RESET_CACHE ){
004111        sqlite3BtreeClearCache(pBtree);
004112        rc = SQLITE_OK;
004113      }else{
004114        int nSave = db->busyHandler.nBusy;
004115        rc = sqlite3OsFileControl(fd, op, pArg);
004116        db->busyHandler.nBusy = nSave;
004117      }
004118      sqlite3BtreeLeave(pBtree);
004119    }
004120    sqlite3_mutex_leave(db->mutex);
004121    return rc;
004122  }
004123  
004124  /*
004125  ** Interface to the testing logic.
004126  */
004127  int sqlite3_test_control(int op, ...){
004128    int rc = 0;
004129  #ifdef SQLITE_UNTESTABLE
004130    UNUSED_PARAMETER(op);
004131  #else
004132    va_list ap;
004133    va_start(ap, op);
004134    switch( op ){
004135  
004136      /*
004137      ** Save the current state of the PRNG.
004138      */
004139      case SQLITE_TESTCTRL_PRNG_SAVE: {
004140        sqlite3PrngSaveState();
004141        break;
004142      }
004143  
004144      /*
004145      ** Restore the state of the PRNG to the last state saved using
004146      ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
004147      ** this verb acts like PRNG_RESET.
004148      */
004149      case SQLITE_TESTCTRL_PRNG_RESTORE: {
004150        sqlite3PrngRestoreState();
004151        break;
004152      }
004153  
004154      /*  sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, int x, sqlite3 *db);
004155      **
004156      ** Control the seed for the pseudo-random number generator (PRNG) that
004157      ** is built into SQLite.  Cases:
004158      **
004159      **    x!=0 && db!=0       Seed the PRNG to the current value of the
004160      **                        schema cookie in the main database for db, or
004161      **                        x if the schema cookie is zero.  This case
004162      **                        is convenient to use with database fuzzers
004163      **                        as it allows the fuzzer some control over the
004164      **                        the PRNG seed.
004165      **
004166      **    x!=0 && db==0       Seed the PRNG to the value of x.
004167      **
004168      **    x==0 && db==0       Revert to default behavior of using the
004169      **                        xRandomness method on the primary VFS.
004170      **
004171      ** This test-control also resets the PRNG so that the new seed will
004172      ** be used for the next call to sqlite3_randomness().
004173      */
004174  #ifndef SQLITE_OMIT_WSD
004175      case SQLITE_TESTCTRL_PRNG_SEED: {
004176        int x = va_arg(ap, int);
004177        int y;
004178        sqlite3 *db = va_arg(ap, sqlite3*);
004179        assert( db==0 || db->aDb[0].pSchema!=0 );
004180        if( db && (y = db->aDb[0].pSchema->schema_cookie)!=0 ){ x = y; }
004181        sqlite3Config.iPrngSeed = x;
004182        sqlite3_randomness(0,0);
004183        break;
004184      }
004185  #endif
004186  
004187      /*  sqlite3_test_control(SQLITE_TESTCTRL_FK_NO_ACTION, sqlite3 *db, int b);
004188      **
004189      ** If b is true, then activate the SQLITE_FkNoAction setting.  If b is
004190      ** false then clearn that setting.  If the SQLITE_FkNoAction setting is
004191      ** abled, all foreign key ON DELETE and ON UPDATE actions behave as if
004192      ** they were NO ACTION, regardless of how they are defined.
004193      **
004194      ** NB:  One must usually run "PRAGMA writable_schema=RESET" after
004195      ** using this test-control, before it will take full effect.  failing
004196      ** to reset the schema can result in some unexpected behavior.
004197      */
004198      case SQLITE_TESTCTRL_FK_NO_ACTION: {
004199        sqlite3 *db = va_arg(ap, sqlite3*);
004200        int b = va_arg(ap, int);
004201        if( b ){
004202          db->flags |= SQLITE_FkNoAction;
004203        }else{
004204          db->flags &= ~SQLITE_FkNoAction;
004205        }
004206        break;
004207      }
004208  
004209      /*
004210      **  sqlite3_test_control(BITVEC_TEST, size, program)
004211      **
004212      ** Run a test against a Bitvec object of size.  The program argument
004213      ** is an array of integers that defines the test.  Return -1 on a
004214      ** memory allocation error, 0 on success, or non-zero for an error.
004215      ** See the sqlite3BitvecBuiltinTest() for additional information.
004216      */
004217      case SQLITE_TESTCTRL_BITVEC_TEST: {
004218        int sz = va_arg(ap, int);
004219        int *aProg = va_arg(ap, int*);
004220        rc = sqlite3BitvecBuiltinTest(sz, aProg);
004221        break;
004222      }
004223  
004224      /*
004225      **  sqlite3_test_control(FAULT_INSTALL, xCallback)
004226      **
004227      ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
004228      ** if xCallback is not NULL.
004229      **
004230      ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
004231      ** is called immediately after installing the new callback and the return
004232      ** value from sqlite3FaultSim(0) becomes the return from
004233      ** sqlite3_test_control().
004234      */
004235      case SQLITE_TESTCTRL_FAULT_INSTALL: {
004236        /* A bug in MSVC prevents it from understanding pointers to functions
004237        ** types in the second argument to va_arg().  Work around the problem
004238        ** using a typedef.
004239        ** http://support.microsoft.com/kb/47961  <-- dead hyperlink
004240        ** Search at http://web.archive.org/ to find the 2015-03-16 archive
004241        ** of the link above to see the original text.
004242        ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
004243        */
004244        typedef int(*sqlite3FaultFuncType)(int);
004245        sqlite3GlobalConfig.xTestCallback = va_arg(ap, sqlite3FaultFuncType);
004246        rc = sqlite3FaultSim(0);
004247        break;
004248      }
004249  
004250      /*
004251      **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
004252      **
004253      ** Register hooks to call to indicate which malloc() failures
004254      ** are benign.
004255      */
004256      case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
004257        typedef void (*void_function)(void);
004258        void_function xBenignBegin;
004259        void_function xBenignEnd;
004260        xBenignBegin = va_arg(ap, void_function);
004261        xBenignEnd = va_arg(ap, void_function);
004262        sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
004263        break;
004264      }
004265  
004266      /*
004267      **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
004268      **
004269      ** Set the PENDING byte to the value in the argument, if X>0.
004270      ** Make no changes if X==0.  Return the value of the pending byte
004271      ** as it existing before this routine was called.
004272      **
004273      ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
004274      ** an incompatible database file format.  Changing the PENDING byte
004275      ** while any database connection is open results in undefined and
004276      ** deleterious behavior.
004277      */
004278      case SQLITE_TESTCTRL_PENDING_BYTE: {
004279        rc = PENDING_BYTE;
004280  #ifndef SQLITE_OMIT_WSD
004281        {
004282          unsigned int newVal = va_arg(ap, unsigned int);
004283          if( newVal ) sqlite3PendingByte = newVal;
004284        }
004285  #endif
004286        break;
004287      }
004288  
004289      /*
004290      **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
004291      **
004292      ** This action provides a run-time test to see whether or not
004293      ** assert() was enabled at compile-time.  If X is true and assert()
004294      ** is enabled, then the return value is true.  If X is true and
004295      ** assert() is disabled, then the return value is zero.  If X is
004296      ** false and assert() is enabled, then the assertion fires and the
004297      ** process aborts.  If X is false and assert() is disabled, then the
004298      ** return value is zero.
004299      */
004300      case SQLITE_TESTCTRL_ASSERT: {
004301        volatile int x = 0;
004302        assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
004303        rc = x;
004304  #if defined(SQLITE_DEBUG)
004305        /* Invoke these debugging routines so that the compiler does not
004306        ** issue "defined but not used" warnings. */
004307        if( x==9999 ){
004308          sqlite3ShowExpr(0);
004309          sqlite3ShowExpr(0);
004310          sqlite3ShowExprList(0);
004311          sqlite3ShowIdList(0);
004312          sqlite3ShowSrcList(0);
004313          sqlite3ShowWith(0);
004314          sqlite3ShowUpsert(0);
004315  #ifndef SQLITE_OMIT_TRIGGER
004316          sqlite3ShowTriggerStep(0);
004317          sqlite3ShowTriggerStepList(0);
004318          sqlite3ShowTrigger(0);
004319          sqlite3ShowTriggerList(0);
004320  #endif
004321  #ifndef SQLITE_OMIT_WINDOWFUNC
004322          sqlite3ShowWindow(0);
004323          sqlite3ShowWinFunc(0);
004324  #endif
004325          sqlite3ShowSelect(0);
004326        }
004327  #endif
004328        break;
004329      }
004330  
004331  
004332      /*
004333      **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
004334      **
004335      ** This action provides a run-time test to see how the ALWAYS and
004336      ** NEVER macros were defined at compile-time.
004337      **
004338      ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
004339      **
004340      ** The recommended test is X==2.  If the return value is 2, that means
004341      ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
004342      ** default setting.  If the return value is 1, then ALWAYS() is either
004343      ** hard-coded to true or else it asserts if its argument is false.
004344      ** The first behavior (hard-coded to true) is the case if
004345      ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
004346      ** behavior (assert if the argument to ALWAYS() is false) is the case if
004347      ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
004348      **
004349      ** The run-time test procedure might look something like this:
004350      **
004351      **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
004352      **      // ALWAYS() and NEVER() are no-op pass-through macros
004353      **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
004354      **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
004355      **    }else{
004356      **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
004357      **    }
004358      */
004359      case SQLITE_TESTCTRL_ALWAYS: {
004360        int x = va_arg(ap,int);
004361        rc = x ? ALWAYS(x) : 0;
004362        break;
004363      }
004364  
004365      /*
004366      **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
004367      **
004368      ** The integer returned reveals the byte-order of the computer on which
004369      ** SQLite is running:
004370      **
004371      **       1     big-endian,    determined at run-time
004372      **      10     little-endian, determined at run-time
004373      **  432101     big-endian,    determined at compile-time
004374      **  123410     little-endian, determined at compile-time
004375      */
004376      case SQLITE_TESTCTRL_BYTEORDER: {
004377        rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
004378        break;
004379      }
004380  
004381      /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
004382      **
004383      ** Enable or disable various optimizations for testing purposes.  The
004384      ** argument N is a bitmask of optimizations to be disabled.  For normal
004385      ** operation N should be 0.  The idea is that a test program (like the
004386      ** SQL Logic Test or SLT test module) can run the same SQL multiple times
004387      ** with various optimizations disabled to verify that the same answer
004388      ** is obtained in every case.
004389      */
004390      case SQLITE_TESTCTRL_OPTIMIZATIONS: {
004391        sqlite3 *db = va_arg(ap, sqlite3*);
004392        db->dbOptFlags = va_arg(ap, u32);
004393        break;
004394      }
004395  
004396      /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, onoff, xAlt);
004397      **
004398      ** If parameter onoff is 1, subsequent calls to localtime() fail.
004399      ** If 2, then invoke xAlt() instead of localtime().  If 0, normal
004400      ** processing.
004401      **
004402      ** xAlt arguments are void pointers, but they really want to be:
004403      **
004404      **    int xAlt(const time_t*, struct tm*);
004405      **
004406      ** xAlt should write results in to struct tm object of its 2nd argument
004407      ** and return zero on success, or return non-zero on failure.
004408      */
004409      case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
004410        sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
004411        if( sqlite3GlobalConfig.bLocaltimeFault==2 ){
004412          typedef int(*sqlite3LocaltimeType)(const void*,void*);
004413          sqlite3GlobalConfig.xAltLocaltime = va_arg(ap, sqlite3LocaltimeType);
004414        }else{
004415          sqlite3GlobalConfig.xAltLocaltime = 0;
004416        }
004417        break;
004418      }
004419  
004420      /*   sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, sqlite3*);
004421      **
004422      ** Toggle the ability to use internal functions on or off for
004423      ** the database connection given in the argument.
004424      */
004425      case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: {
004426        sqlite3 *db = va_arg(ap, sqlite3*);
004427        db->mDbFlags ^= DBFLAG_InternalFunc;
004428        break;
004429      }
004430  
004431      /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
004432      **
004433      ** Set or clear a flag that indicates that the database file is always well-
004434      ** formed and never corrupt.  This flag is clear by default, indicating that
004435      ** database files might have arbitrary corruption.  Setting the flag during
004436      ** testing causes certain assert() statements in the code to be activated
004437      ** that demonstrate invariants on well-formed database files.
004438      */
004439      case SQLITE_TESTCTRL_NEVER_CORRUPT: {
004440        sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
004441        break;
004442      }
004443  
004444      /*   sqlite3_test_control(SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS, int);
004445      **
004446      ** Set or clear a flag that causes SQLite to verify that type, name,
004447      ** and tbl_name fields of the sqlite_schema table.  This is normally
004448      ** on, but it is sometimes useful to turn it off for testing.
004449      **
004450      ** 2020-07-22:  Disabling EXTRA_SCHEMA_CHECKS also disables the
004451      ** verification of rootpage numbers when parsing the schema.  This
004452      ** is useful to make it easier to reach strange internal error states
004453      ** during testing.  The EXTRA_SCHEMA_CHECKS setting is always enabled
004454      ** in production.
004455      */
004456      case SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS: {
004457        sqlite3GlobalConfig.bExtraSchemaChecks = va_arg(ap, int);
004458        break;
004459      }
004460  
004461      /* Set the threshold at which OP_Once counters reset back to zero.
004462      ** By default this is 0x7ffffffe (over 2 billion), but that value is
004463      ** too big to test in a reasonable amount of time, so this control is
004464      ** provided to set a small and easily reachable reset value.
004465      */
004466      case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
004467        sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
004468        break;
004469      }
004470  
004471      /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
004472      **
004473      ** Set the VDBE coverage callback function to xCallback with context
004474      ** pointer ptr.
004475      */
004476      case SQLITE_TESTCTRL_VDBE_COVERAGE: {
004477  #ifdef SQLITE_VDBE_COVERAGE
004478        typedef void (*branch_callback)(void*,unsigned int,
004479                                        unsigned char,unsigned char);
004480        sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
004481        sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
004482  #endif
004483        break;
004484      }
004485  
004486      /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
004487      case SQLITE_TESTCTRL_SORTER_MMAP: {
004488        sqlite3 *db = va_arg(ap, sqlite3*);
004489        db->nMaxSorterMmap = va_arg(ap, int);
004490        break;
004491      }
004492  
004493      /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
004494      **
004495      ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
004496      ** not.
004497      */
004498      case SQLITE_TESTCTRL_ISINIT: {
004499        if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
004500        break;
004501      }
004502  
004503      /*  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
004504      **
004505      ** This test control is used to create imposter tables.  "db" is a pointer
004506      ** to the database connection.  dbName is the database name (ex: "main" or
004507      ** "temp") which will receive the imposter.  "onOff" turns imposter mode on
004508      ** or off.  "tnum" is the root page of the b-tree to which the imposter
004509      ** table should connect.
004510      **
004511      ** Enable imposter mode only when the schema has already been parsed.  Then
004512      ** run a single CREATE TABLE statement to construct the imposter table in
004513      ** the parsed schema.  Then turn imposter mode back off again.
004514      **
004515      ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
004516      ** the schema to be reparsed the next time it is needed.  This has the
004517      ** effect of erasing all imposter tables.
004518      */
004519      case SQLITE_TESTCTRL_IMPOSTER: {
004520        sqlite3 *db = va_arg(ap, sqlite3*);
004521        int iDb;
004522        sqlite3_mutex_enter(db->mutex);
004523        iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
004524        if( iDb>=0 ){
004525          db->init.iDb = iDb;
004526          db->init.busy = db->init.imposterTable = va_arg(ap,int);
004527          db->init.newTnum = va_arg(ap,int);
004528          if( db->init.busy==0 && db->init.newTnum>0 ){
004529            sqlite3ResetAllSchemasOfConnection(db);
004530          }
004531        }
004532        sqlite3_mutex_leave(db->mutex);
004533        break;
004534      }
004535  
004536  #if defined(YYCOVERAGE)
004537      /*  sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
004538      **
004539      ** This test control (only available when SQLite is compiled with
004540      ** -DYYCOVERAGE) writes a report onto "out" that shows all
004541      ** state/lookahead combinations in the parser state machine
004542      ** which are never exercised.  If any state is missed, make the
004543      ** return code SQLITE_ERROR.
004544      */
004545      case SQLITE_TESTCTRL_PARSER_COVERAGE: {
004546        FILE *out = va_arg(ap, FILE*);
004547        if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
004548        break;
004549      }
004550  #endif /* defined(YYCOVERAGE) */
004551  
004552      /*  sqlite3_test_control(SQLITE_TESTCTRL_RESULT_INTREAL, sqlite3_context*);
004553      **
004554      ** This test-control causes the most recent sqlite3_result_int64() value
004555      ** to be interpreted as a MEM_IntReal instead of as an MEM_Int.  Normally,
004556      ** MEM_IntReal values only arise during an INSERT operation of integer
004557      ** values into a REAL column, so they can be challenging to test.  This
004558      ** test-control enables us to write an intreal() SQL function that can
004559      ** inject an intreal() value at arbitrary places in an SQL statement,
004560      ** for testing purposes.
004561      */
004562      case SQLITE_TESTCTRL_RESULT_INTREAL: {
004563        sqlite3_context *pCtx = va_arg(ap, sqlite3_context*);
004564        sqlite3ResultIntReal(pCtx);
004565        break;
004566      }
004567  
004568      /*  sqlite3_test_control(SQLITE_TESTCTRL_SEEK_COUNT,
004569      **    sqlite3 *db,    // Database connection
004570      **    u64 *pnSeek     // Write seek count here
004571      **  );
004572      **
004573      ** This test-control queries the seek-counter on the "main" database
004574      ** file.  The seek-counter is written into *pnSeek and is then reset.
004575      ** The seek-count is only available if compiled with SQLITE_DEBUG.
004576      */
004577      case SQLITE_TESTCTRL_SEEK_COUNT: {
004578        sqlite3 *db = va_arg(ap, sqlite3*);
004579        u64 *pn = va_arg(ap, sqlite3_uint64*);
004580        *pn = sqlite3BtreeSeekCount(db->aDb->pBt);
004581        (void)db;  /* Silence harmless unused variable warning */
004582        break;
004583      }
004584  
004585      /*  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, op, ptr)
004586      **
004587      **  "ptr" is a pointer to a u32. 
004588      **
004589      **   op==0       Store the current sqlite3TreeTrace in *ptr
004590      **   op==1       Set sqlite3TreeTrace to the value *ptr
004591      **   op==2       Store the current sqlite3WhereTrace in *ptr
004592      **   op==3       Set sqlite3WhereTrace to the value *ptr
004593      */
004594      case SQLITE_TESTCTRL_TRACEFLAGS: {
004595         int opTrace = va_arg(ap, int);
004596         u32 *ptr = va_arg(ap, u32*);
004597         switch( opTrace ){
004598           case 0:   *ptr = sqlite3TreeTrace;      break;
004599           case 1:   sqlite3TreeTrace = *ptr;      break;
004600           case 2:   *ptr = sqlite3WhereTrace;     break;
004601           case 3:   sqlite3WhereTrace = *ptr;     break;
004602         }
004603         break;
004604      }
004605  
004606      /* sqlite3_test_control(SQLITE_TESTCTRL_LOGEST,
004607      **      double fIn,     // Input value
004608      **      int *pLogEst,   // sqlite3LogEstFromDouble(fIn)
004609      **      u64 *pInt,      // sqlite3LogEstToInt(*pLogEst)
004610      **      int *pLogEst2   // sqlite3LogEst(*pInt)
004611      ** );
004612      **
004613      ** Test access for the LogEst conversion routines.
004614      */
004615      case SQLITE_TESTCTRL_LOGEST: {
004616        double rIn = va_arg(ap, double);
004617        LogEst rLogEst = sqlite3LogEstFromDouble(rIn);
004618        int *pI1 = va_arg(ap,int*);
004619        u64 *pU64 = va_arg(ap,u64*);
004620        int *pI2 = va_arg(ap,int*);
004621        *pI1 = rLogEst;
004622        *pU64 = sqlite3LogEstToInt(rLogEst);
004623        *pI2 = sqlite3LogEst(*pU64);
004624        break;
004625      }
004626  
004627  #if !defined(SQLITE_OMIT_WSD)
004628      /* sqlite3_test_control(SQLITE_TESTCTRL_USELONGDOUBLE, int X);
004629      **
004630      **   X<0     Make no changes to the bUseLongDouble.  Just report value.
004631      **   X==0    Disable bUseLongDouble
004632      **   X==1    Enable bUseLongDouble
004633      **   X>=2    Set bUseLongDouble to its default value for this platform
004634      */
004635      case SQLITE_TESTCTRL_USELONGDOUBLE: {
004636        int b = va_arg(ap, int);
004637        if( b>=2 ) b = hasHighPrecisionDouble(b);
004638        if( b>=0 ) sqlite3Config.bUseLongDouble = b>0;
004639        rc = sqlite3Config.bUseLongDouble!=0;
004640        break;
004641      }
004642  #endif
004643  
004644  
004645  #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
004646      /* sqlite3_test_control(SQLITE_TESTCTRL_TUNE, id, *piValue)
004647      **
004648      ** If "id" is an integer between 1 and SQLITE_NTUNE then set the value
004649      ** of the id-th tuning parameter to *piValue.  If "id" is between -1
004650      ** and -SQLITE_NTUNE, then write the current value of the (-id)-th
004651      ** tuning parameter into *piValue.
004652      **
004653      ** Tuning parameters are for use during transient development builds,
004654      ** to help find the best values for constants in the query planner.
004655      ** Access tuning parameters using the Tuning(ID) macro.  Set the
004656      ** parameters in the CLI using ".testctrl tune ID VALUE".
004657      **
004658      ** Transient use only.  Tuning parameters should not be used in
004659      ** checked-in code.
004660      */
004661      case SQLITE_TESTCTRL_TUNE: {
004662        int id = va_arg(ap, int);
004663        int *piValue = va_arg(ap, int*);
004664        if( id>0 && id<=SQLITE_NTUNE ){
004665          Tuning(id) = *piValue;
004666        }else if( id<0 && id>=-SQLITE_NTUNE ){
004667          *piValue = Tuning(-id);
004668        }else{
004669          rc = SQLITE_NOTFOUND;
004670        }
004671        break;
004672      }
004673  #endif
004674  
004675      /* sqlite3_test_control(SQLITE_TESTCTRL_JSON_SELFCHECK, &onOff);
004676      **
004677      ** Activate or deactivate validation of JSONB that is generated from
004678      ** text.  Off by default, as the validation is slow.  Validation is
004679      ** only available if compiled using SQLITE_DEBUG.
004680      **
004681      ** If onOff is initially 1, then turn it on.  If onOff is initially
004682      ** off, turn it off.  If onOff is initially -1, then change onOff
004683      ** to be the current setting.
004684      */
004685      case SQLITE_TESTCTRL_JSON_SELFCHECK: {
004686  #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
004687        int *pOnOff = va_arg(ap, int*);
004688        if( *pOnOff<0 ){
004689          *pOnOff = sqlite3Config.bJsonSelfcheck;
004690        }else{
004691          sqlite3Config.bJsonSelfcheck = (u8)((*pOnOff)&0xff);
004692        }
004693  #endif
004694        break;
004695      }
004696    }
004697    va_end(ap);
004698  #endif /* SQLITE_UNTESTABLE */
004699    return rc;
004700  }
004701  
004702  /*
004703  ** The Pager stores the Database filename, Journal filename, and WAL filename
004704  ** consecutively in memory, in that order.  The database filename is prefixed
004705  ** by four zero bytes.  Locate the start of the database filename by searching
004706  ** backwards for the first byte following four consecutive zero bytes.
004707  **
004708  ** This only works if the filename passed in was obtained from the Pager.
004709  */
004710  static const char *databaseName(const char *zName){
004711    while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
004712      zName--;
004713    }
004714    return zName;
004715  }
004716  
004717  /*
004718  ** Append text z[] to the end of p[].  Return a pointer to the first
004719  ** character after then zero terminator on the new text in p[].
004720  */
004721  static char *appendText(char *p, const char *z){
004722    size_t n = strlen(z);
004723    memcpy(p, z, n+1);
004724    return p+n+1;
004725  }
004726  
004727  /*
004728  ** Allocate memory to hold names for a database, journal file, WAL file,
004729  ** and query parameters.  The pointer returned is valid for use by
004730  ** sqlite3_filename_database() and sqlite3_uri_parameter() and related
004731  ** functions.
004732  **
004733  ** Memory layout must be compatible with that generated by the pager
004734  ** and expected by sqlite3_uri_parameter() and databaseName().
004735  */
004736  const char *sqlite3_create_filename(
004737    const char *zDatabase,
004738    const char *zJournal,
004739    const char *zWal,
004740    int nParam,
004741    const char **azParam
004742  ){
004743    sqlite3_int64 nByte;
004744    int i;
004745    char *pResult, *p;
004746    nByte = strlen(zDatabase) + strlen(zJournal) + strlen(zWal) + 10;
004747    for(i=0; i<nParam*2; i++){
004748      nByte += strlen(azParam[i])+1;
004749    }
004750    pResult = p = sqlite3_malloc64( nByte );
004751    if( p==0 ) return 0;
004752    memset(p, 0, 4);
004753    p += 4;
004754    p = appendText(p, zDatabase);
004755    for(i=0; i<nParam*2; i++){
004756      p = appendText(p, azParam[i]);
004757    }
004758    *(p++) = 0;
004759    p = appendText(p, zJournal);
004760    p = appendText(p, zWal);
004761    *(p++) = 0;
004762    *(p++) = 0;
004763    assert( (sqlite3_int64)(p - pResult)==nByte );
004764    return pResult + 4;
004765  }
004766  
004767  /*
004768  ** Free memory obtained from sqlite3_create_filename().  It is a severe
004769  ** error to call this routine with any parameter other than a pointer
004770  ** previously obtained from sqlite3_create_filename() or a NULL pointer.
004771  */
004772  void sqlite3_free_filename(const char *p){
004773    if( p==0 ) return;
004774    p = databaseName(p);
004775    sqlite3_free((char*)p - 4);
004776  }
004777  
004778  
004779  /*
004780  ** This is a utility routine, useful to VFS implementations, that checks
004781  ** to see if a database file was a URI that contained a specific query
004782  ** parameter, and if so obtains the value of the query parameter.
004783  **
004784  ** The zFilename argument is the filename pointer passed into the xOpen()
004785  ** method of a VFS implementation.  The zParam argument is the name of the
004786  ** query parameter we seek.  This routine returns the value of the zParam
004787  ** parameter if it exists.  If the parameter does not exist, this routine
004788  ** returns a NULL pointer.
004789  */
004790  const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
004791    if( zFilename==0 || zParam==0 ) return 0;
004792    zFilename = databaseName(zFilename);
004793    return uriParameter(zFilename, zParam);
004794  }
004795  
004796  /*
004797  ** Return a pointer to the name of Nth query parameter of the filename.
004798  */
004799  const char *sqlite3_uri_key(const char *zFilename, int N){
004800    if( zFilename==0 || N<0 ) return 0;
004801    zFilename = databaseName(zFilename);
004802    zFilename += sqlite3Strlen30(zFilename) + 1;
004803    while( ALWAYS(zFilename) && zFilename[0] && (N--)>0 ){
004804      zFilename += sqlite3Strlen30(zFilename) + 1;
004805      zFilename += sqlite3Strlen30(zFilename) + 1;
004806    }
004807    return zFilename[0] ? zFilename : 0;
004808  }
004809  
004810  /*
004811  ** Return a boolean value for a query parameter.
004812  */
004813  int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
004814    const char *z = sqlite3_uri_parameter(zFilename, zParam);
004815    bDflt = bDflt!=0;
004816    return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
004817  }
004818  
004819  /*
004820  ** Return a 64-bit integer value for a query parameter.
004821  */
004822  sqlite3_int64 sqlite3_uri_int64(
004823    const char *zFilename,    /* Filename as passed to xOpen */
004824    const char *zParam,       /* URI parameter sought */
004825    sqlite3_int64 bDflt       /* return if parameter is missing */
004826  ){
004827    const char *z = sqlite3_uri_parameter(zFilename, zParam);
004828    sqlite3_int64 v;
004829    if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
004830      bDflt = v;
004831    }
004832    return bDflt;
004833  }
004834  
004835  /*
004836  ** Translate a filename that was handed to a VFS routine into the corresponding
004837  ** database, journal, or WAL file.
004838  **
004839  ** It is an error to pass this routine a filename string that was not
004840  ** passed into the VFS from the SQLite core.  Doing so is similar to
004841  ** passing free() a pointer that was not obtained from malloc() - it is
004842  ** an error that we cannot easily detect but that will likely cause memory
004843  ** corruption.
004844  */
004845  const char *sqlite3_filename_database(const char *zFilename){
004846    if( zFilename==0 ) return 0;
004847    return databaseName(zFilename);
004848  }
004849  const char *sqlite3_filename_journal(const char *zFilename){
004850    if( zFilename==0 ) return 0;
004851    zFilename = databaseName(zFilename);
004852    zFilename += sqlite3Strlen30(zFilename) + 1;
004853    while( ALWAYS(zFilename) && zFilename[0] ){
004854      zFilename += sqlite3Strlen30(zFilename) + 1;
004855      zFilename += sqlite3Strlen30(zFilename) + 1;
004856    }
004857    return zFilename + 1;
004858  }
004859  const char *sqlite3_filename_wal(const char *zFilename){
004860  #ifdef SQLITE_OMIT_WAL
004861    return 0;
004862  #else
004863    zFilename = sqlite3_filename_journal(zFilename);
004864    if( zFilename ) zFilename += sqlite3Strlen30(zFilename) + 1;
004865    return zFilename;
004866  #endif
004867  }
004868  
004869  /*
004870  ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
004871  */
004872  Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
004873    int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
004874    return iDb<0 ? 0 : db->aDb[iDb].pBt;
004875  }
004876  
004877  /*
004878  ** Return the name of the N-th database schema.  Return NULL if N is out
004879  ** of range.
004880  */
004881  const char *sqlite3_db_name(sqlite3 *db, int N){
004882  #ifdef SQLITE_ENABLE_API_ARMOR
004883    if( !sqlite3SafetyCheckOk(db) ){
004884      (void)SQLITE_MISUSE_BKPT;
004885      return 0;
004886    }
004887  #endif
004888    if( N<0 || N>=db->nDb ){
004889      return 0;
004890    }else{
004891      return db->aDb[N].zDbSName;
004892    }
004893  }
004894  
004895  /*
004896  ** Return the filename of the database associated with a database
004897  ** connection.
004898  */
004899  const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
004900    Btree *pBt;
004901  #ifdef SQLITE_ENABLE_API_ARMOR
004902    if( !sqlite3SafetyCheckOk(db) ){
004903      (void)SQLITE_MISUSE_BKPT;
004904      return 0;
004905    }
004906  #endif
004907    pBt = sqlite3DbNameToBtree(db, zDbName);
004908    return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
004909  }
004910  
004911  /*
004912  ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
004913  ** no such database exists.
004914  */
004915  int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
004916    Btree *pBt;
004917  #ifdef SQLITE_ENABLE_API_ARMOR
004918    if( !sqlite3SafetyCheckOk(db) ){
004919      (void)SQLITE_MISUSE_BKPT;
004920      return -1;
004921    }
004922  #endif
004923    pBt = sqlite3DbNameToBtree(db, zDbName);
004924    return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
004925  }
004926  
004927  #ifdef SQLITE_ENABLE_SNAPSHOT
004928  /*
004929  ** Obtain a snapshot handle for the snapshot of database zDb currently
004930  ** being read by handle db.
004931  */
004932  int sqlite3_snapshot_get(
004933    sqlite3 *db,
004934    const char *zDb,
004935    sqlite3_snapshot **ppSnapshot
004936  ){
004937    int rc = SQLITE_ERROR;
004938  #ifndef SQLITE_OMIT_WAL
004939  
004940  #ifdef SQLITE_ENABLE_API_ARMOR
004941    if( !sqlite3SafetyCheckOk(db) ){
004942      return SQLITE_MISUSE_BKPT;
004943    }
004944  #endif
004945    sqlite3_mutex_enter(db->mutex);
004946  
004947    if( db->autoCommit==0 ){
004948      int iDb = sqlite3FindDbName(db, zDb);
004949      if( iDb==0 || iDb>1 ){
004950        Btree *pBt = db->aDb[iDb].pBt;
004951        if( SQLITE_TXN_WRITE!=sqlite3BtreeTxnState(pBt) ){
004952          rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
004953          if( rc==SQLITE_OK ){
004954            rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
004955          }
004956        }
004957      }
004958    }
004959  
004960    sqlite3_mutex_leave(db->mutex);
004961  #endif   /* SQLITE_OMIT_WAL */
004962    return rc;
004963  }
004964  
004965  /*
004966  ** Open a read-transaction on the snapshot identified by pSnapshot.
004967  */
004968  int sqlite3_snapshot_open(
004969    sqlite3 *db,
004970    const char *zDb,
004971    sqlite3_snapshot *pSnapshot
004972  ){
004973    int rc = SQLITE_ERROR;
004974  #ifndef SQLITE_OMIT_WAL
004975  
004976  #ifdef SQLITE_ENABLE_API_ARMOR
004977    if( !sqlite3SafetyCheckOk(db) ){
004978      return SQLITE_MISUSE_BKPT;
004979    }
004980  #endif
004981    sqlite3_mutex_enter(db->mutex);
004982    if( db->autoCommit==0 ){
004983      int iDb;
004984      iDb = sqlite3FindDbName(db, zDb);
004985      if( iDb==0 || iDb>1 ){
004986        Btree *pBt = db->aDb[iDb].pBt;
004987        if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE ){
004988          Pager *pPager = sqlite3BtreePager(pBt);
004989          int bUnlock = 0;
004990          if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_NONE ){
004991            if( db->nVdbeActive==0 ){
004992              rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot);
004993              if( rc==SQLITE_OK ){
004994                bUnlock = 1;
004995                rc = sqlite3BtreeCommit(pBt);
004996              }
004997            }
004998          }else{
004999            rc = SQLITE_OK;
005000          }
005001          if( rc==SQLITE_OK ){
005002            rc = sqlite3PagerSnapshotOpen(pPager, pSnapshot);
005003          }
005004          if( rc==SQLITE_OK ){
005005            rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
005006            sqlite3PagerSnapshotOpen(pPager, 0);
005007          }
005008          if( bUnlock ){
005009            sqlite3PagerSnapshotUnlock(pPager);
005010          }
005011        }
005012      }
005013    }
005014  
005015    sqlite3_mutex_leave(db->mutex);
005016  #endif   /* SQLITE_OMIT_WAL */
005017    return rc;
005018  }
005019  
005020  /*
005021  ** Recover as many snapshots as possible from the wal file associated with
005022  ** schema zDb of database db.
005023  */
005024  int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
005025    int rc = SQLITE_ERROR;
005026  #ifndef SQLITE_OMIT_WAL
005027    int iDb;
005028  
005029  #ifdef SQLITE_ENABLE_API_ARMOR
005030    if( !sqlite3SafetyCheckOk(db) ){
005031      return SQLITE_MISUSE_BKPT;
005032    }
005033  #endif
005034  
005035    sqlite3_mutex_enter(db->mutex);
005036    iDb = sqlite3FindDbName(db, zDb);
005037    if( iDb==0 || iDb>1 ){
005038      Btree *pBt = db->aDb[iDb].pBt;
005039      if( SQLITE_TXN_NONE==sqlite3BtreeTxnState(pBt) ){
005040        rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
005041        if( rc==SQLITE_OK ){
005042          rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
005043          sqlite3BtreeCommit(pBt);
005044        }
005045      }
005046    }
005047    sqlite3_mutex_leave(db->mutex);
005048  #endif   /* SQLITE_OMIT_WAL */
005049    return rc;
005050  }
005051  
005052  /*
005053  ** Free a snapshot handle obtained from sqlite3_snapshot_get().
005054  */
005055  void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
005056    sqlite3_free(pSnapshot);
005057  }
005058  #endif /* SQLITE_ENABLE_SNAPSHOT */
005059  
005060  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
005061  /*
005062  ** Given the name of a compile-time option, return true if that option
005063  ** was used and false if not.
005064  **
005065  ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
005066  ** is not required for a match.
005067  */
005068  int sqlite3_compileoption_used(const char *zOptName){
005069    int i, n;
005070    int nOpt;
005071    const char **azCompileOpt;
005072  
005073  #ifdef SQLITE_ENABLE_API_ARMOR
005074    if( zOptName==0 ){
005075      (void)SQLITE_MISUSE_BKPT;
005076      return 0;
005077    }
005078  #endif
005079  
005080    azCompileOpt = sqlite3CompileOptions(&nOpt);
005081  
005082    if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
005083    n = sqlite3Strlen30(zOptName);
005084  
005085    /* Since nOpt is normally in single digits, a linear search is
005086    ** adequate. No need for a binary search. */
005087    for(i=0; i<nOpt; i++){
005088      if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
005089       && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
005090      ){
005091        return 1;
005092      }
005093    }
005094    return 0;
005095  }
005096  
005097  /*
005098  ** Return the N-th compile-time option string.  If N is out of range,
005099  ** return a NULL pointer.
005100  */
005101  const char *sqlite3_compileoption_get(int N){
005102    int nOpt;
005103    const char **azCompileOpt;
005104    azCompileOpt = sqlite3CompileOptions(&nOpt);
005105    if( N>=0 && N<nOpt ){
005106      return azCompileOpt[N];
005107    }
005108    return 0;
005109  }
005110  #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */