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