xref: /sqlite-3.40.0/src/main.c (revision 52d5d474)
175897234Sdrh /*
2b19a2bc6Sdrh ** 2001 September 15
375897234Sdrh **
4b19a2bc6Sdrh ** The author disclaims copyright to this source code.  In place of
5b19a2bc6Sdrh ** a legal notice, here is a blessing:
675897234Sdrh **
7b19a2bc6Sdrh **    May you do good and not evil.
8b19a2bc6Sdrh **    May you find forgiveness for yourself and forgive others.
9b19a2bc6Sdrh **    May you share freely, never taking more than you give.
1075897234Sdrh **
1175897234Sdrh *************************************************************************
1275897234Sdrh ** Main file for the SQLite library.  The routines in this file
1375897234Sdrh ** implement the programmer interface to the library.  Routines in
1475897234Sdrh ** other files are for internal use by SQLite and should not be
1575897234Sdrh ** accessed by users of the library.
1675897234Sdrh */
1775897234Sdrh #include "sqliteInt.h"
1858f1c8b7Sdrh 
19820a9069Sdrh #ifdef SQLITE_ENABLE_FTS3
20820a9069Sdrh # include "fts3.h"
21820a9069Sdrh #endif
2258f1c8b7Sdrh #ifdef SQLITE_ENABLE_RTREE
2358f1c8b7Sdrh # include "rtree.h"
2458f1c8b7Sdrh #endif
2521540ae4Sdan #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
261c826650Sdanielk1977 # include "sqliteicu.h"
271c826650Sdanielk1977 #endif
2820e34f91Sdrh 
2920e34f91Sdrh /*
3020e34f91Sdrh ** This is an extension initializer that is a no-op and always
3120e34f91Sdrh ** succeeds, except that it fails if the fault-simulation is set
3220e34f91Sdrh ** to 500.
3320e34f91Sdrh */
sqlite3TestExtInit(sqlite3 * db)3420e34f91Sdrh static int sqlite3TestExtInit(sqlite3 *db){
3520e34f91Sdrh   (void)db;
3620e34f91Sdrh   return sqlite3FaultSim(500);
3720e34f91Sdrh }
3820e34f91Sdrh 
3920e34f91Sdrh 
4020e34f91Sdrh /*
4120e34f91Sdrh ** Forward declarations of external module initializer functions
4220e34f91Sdrh ** for modules that need them.
4320e34f91Sdrh */
4420e34f91Sdrh #ifdef SQLITE_ENABLE_FTS1
4520e34f91Sdrh int sqlite3Fts1Init(sqlite3*);
4620e34f91Sdrh #endif
4720e34f91Sdrh #ifdef SQLITE_ENABLE_FTS2
4820e34f91Sdrh int sqlite3Fts2Init(sqlite3*);
4920e34f91Sdrh #endif
5020e34f91Sdrh #ifdef SQLITE_ENABLE_FTS5
5120e34f91Sdrh int sqlite3Fts5Init(sqlite3*);
5220e34f91Sdrh #endif
53c6603af7Sdrh #ifdef SQLITE_ENABLE_STMTVTAB
54c6603af7Sdrh int sqlite3StmtVtabInit(sqlite3*);
55f00f530bSdrh #endif
5620e34f91Sdrh 
5720e34f91Sdrh /*
5820e34f91Sdrh ** An array of pointers to extension initializer functions for
5920e34f91Sdrh ** built-in extensions.
6020e34f91Sdrh */
6120e34f91Sdrh static int (*const sqlite3BuiltinExtensions[])(sqlite3*) = {
6220e34f91Sdrh #ifdef SQLITE_ENABLE_FTS1
6320e34f91Sdrh   sqlite3Fts1Init,
64c306e08aSdrh #endif
6520e34f91Sdrh #ifdef SQLITE_ENABLE_FTS2
6620e34f91Sdrh   sqlite3Fts2Init,
6720e34f91Sdrh #endif
6820e34f91Sdrh #ifdef SQLITE_ENABLE_FTS3
6920e34f91Sdrh   sqlite3Fts3Init,
7020e34f91Sdrh #endif
7120e34f91Sdrh #ifdef SQLITE_ENABLE_FTS5
7220e34f91Sdrh   sqlite3Fts5Init,
7320e34f91Sdrh #endif
7420e34f91Sdrh #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
7520e34f91Sdrh   sqlite3IcuInit,
7620e34f91Sdrh #endif
7720e34f91Sdrh #ifdef SQLITE_ENABLE_RTREE
7820e34f91Sdrh   sqlite3RtreeInit,
7920e34f91Sdrh #endif
8020e34f91Sdrh #ifdef SQLITE_ENABLE_DBPAGE_VTAB
8120e34f91Sdrh   sqlite3DbpageRegister,
8220e34f91Sdrh #endif
8320e34f91Sdrh #ifdef SQLITE_ENABLE_DBSTAT_VTAB
8420e34f91Sdrh   sqlite3DbstatRegister,
8520e34f91Sdrh #endif
8620e34f91Sdrh   sqlite3TestExtInit,
879dbf96bdSdrh #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
889dbf96bdSdrh   sqlite3JsonTableFunctions,
8920e34f91Sdrh #endif
9020e34f91Sdrh #ifdef SQLITE_ENABLE_STMTVTAB
9120e34f91Sdrh   sqlite3StmtVtabInit,
9220e34f91Sdrh #endif
9320e34f91Sdrh #ifdef SQLITE_ENABLE_BYTECODE_VTAB
9420e34f91Sdrh   sqlite3VdbeBytecodeVtabInit,
9520e34f91Sdrh #endif
9620e34f91Sdrh };
9775897234Sdrh 
98b3190c15Sdrh #ifndef SQLITE_AMALGAMATION
999f129f46Sdrh /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
1009f129f46Sdrh ** contains the text of SQLITE_VERSION macro.
1019f129f46Sdrh */
10224b03fd0Sdanielk1977 const char sqlite3_version[] = SQLITE_VERSION;
103b3190c15Sdrh #endif
1049f129f46Sdrh 
1059f129f46Sdrh /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
1069f129f46Sdrh ** a pointer to the to the sqlite3_version[] string constant.
1079f129f46Sdrh */
sqlite3_libversion(void)1084aec8b65Sdrh const char *sqlite3_libversion(void){ return sqlite3_version; }
1099f129f46Sdrh 
110c6aa3815Sdrh /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
1119f129f46Sdrh ** pointer to a string constant whose value is the same as the
112c6aa3815Sdrh ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
113c6aa3815Sdrh ** an edited copy of the amalgamation, then the last four characters of
114c6aa3815Sdrh ** the hash might be different from SQLITE_SOURCE_ID.
1159f129f46Sdrh */
sqlite3_sourceid(void)11647baebc2Sdrh const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
1179f129f46Sdrh 
1189f129f46Sdrh /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
1199f129f46Sdrh ** returns an integer equal to SQLITE_VERSION_NUMBER.
1209f129f46Sdrh */
sqlite3_libversion_number(void)12199ba19eaSdanielk1977 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
1229f129f46Sdrh 
1235dc2bcdaSdrh /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
124b8a45bbdSdrh ** zero if and only if SQLite was compiled with mutexing code omitted due to
1259f129f46Sdrh ** the SQLITE_THREADSAFE compile-time option being set to 0.
1269f129f46Sdrh */
sqlite3_threadsafe(void)127b67e8bf0Sdrh int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
128b217a57eSdrh 
12934cf2583Smistachkin /*
13034cf2583Smistachkin ** When compiling the test fixture or with debugging enabled (on Win32),
13134cf2583Smistachkin ** this variable being set to non-zero will cause OSTRACE macros to emit
13234cf2583Smistachkin ** extra diagnostic information.
13334cf2583Smistachkin */
134fb383e92Smistachkin #ifdef SQLITE_HAVE_OS_TRACE
13534cf2583Smistachkin # ifndef SQLITE_DEBUG_OS_TRACE
13634cf2583Smistachkin #   define SQLITE_DEBUG_OS_TRACE 0
13734cf2583Smistachkin # endif
13834cf2583Smistachkin   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
13934cf2583Smistachkin #endif
14034cf2583Smistachkin 
141e265b084Sdrh #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
142b217a57eSdrh /*
143b0603416Sdrh ** If the following function pointer is not NULL and if
144b0603416Sdrh ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
145b0603416Sdrh ** I/O active are written using this function.  These messages
146b0603416Sdrh ** are intended for debugging activity only.
147b0603416Sdrh */
1489871a933Smistachkin SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
149e265b084Sdrh #endif
150b0603416Sdrh 
151b0603416Sdrh /*
152a16313e5Sdrh ** If the following global variable points to a string which is the
153a16313e5Sdrh ** name of a directory, then that directory will be used to store
154a16313e5Sdrh ** temporary files.
155a16313e5Sdrh **
156a16313e5Sdrh ** See also the "PRAGMA temp_store_directory" SQL command.
157a16313e5Sdrh */
158a16313e5Sdrh char *sqlite3_temp_directory = 0;
159a16313e5Sdrh 
160c5499befSdrh /*
161a112d140Smistachkin ** If the following global variable points to a string which is the
162a112d140Smistachkin ** name of a directory, then that directory will be used to store
163a112d140Smistachkin ** all database files specified with a relative pathname.
164a112d140Smistachkin **
165a112d140Smistachkin ** See also the "PRAGMA data_store_directory" SQL command.
166a112d140Smistachkin */
167a112d140Smistachkin char *sqlite3_data_directory = 0;
168a112d140Smistachkin 
169a112d140Smistachkin /*
17040257ffdSdrh ** Initialize SQLite.
17140257ffdSdrh **
17240257ffdSdrh ** This routine must be called to initialize the memory allocation,
17393ed56d9Sdrh ** VFS, and mutex subsystems prior to doing any serious work with
17440257ffdSdrh ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
17540257ffdSdrh ** this routine will be called automatically by key routines such as
17640257ffdSdrh ** sqlite3_open().
17740257ffdSdrh **
17840257ffdSdrh ** This routine is a no-op except on its very first call for the process,
17940257ffdSdrh ** or for the first call after a call to sqlite3_shutdown.
18093ed56d9Sdrh **
18193ed56d9Sdrh ** The first thread to call this routine runs the initialization to
18293ed56d9Sdrh ** completion.  If subsequent threads call this routine before the first
18393ed56d9Sdrh ** thread has finished the initialization process, then the subsequent
18493ed56d9Sdrh ** threads must block until the first thread finishes with the initialization.
18593ed56d9Sdrh **
18693ed56d9Sdrh ** The first thread might call this routine recursively.  Recursive
18793ed56d9Sdrh ** calls to this routine should not block, of course.  Otherwise the
18893ed56d9Sdrh ** initialization process would never complete.
18993ed56d9Sdrh **
19093ed56d9Sdrh ** Let X be the first thread to enter this routine.  Let Y be some other
19193ed56d9Sdrh ** thread.  Then while the initial invocation of this routine by X is
19293ed56d9Sdrh ** incomplete, it is required that:
19393ed56d9Sdrh **
19493ed56d9Sdrh **    *  Calls to this routine from Y must block until the outer-most
19593ed56d9Sdrh **       call by X completes.
19693ed56d9Sdrh **
19793ed56d9Sdrh **    *  Recursive calls to this routine from thread X return immediately
19893ed56d9Sdrh **       without blocking.
19940257ffdSdrh */
sqlite3_initialize(void)20040257ffdSdrh int sqlite3_initialize(void){
201067b92baSdrh   MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )      /* The main static mutex */
20293ed56d9Sdrh   int rc;                                      /* Result code */
203ab80be99Sdrh #ifdef SQLITE_EXTRA_INIT
204ab80be99Sdrh   int bRunExtraInit = 0;                       /* Extra initialization needed */
205ab80be99Sdrh #endif
20671bc31c6Sdanielk1977 
207075c23afSdanielk1977 #ifdef SQLITE_OMIT_WSD
208a8f83bfcSdanielk1977   rc = sqlite3_wsd_init(4096, 24);
209075c23afSdanielk1977   if( rc!=SQLITE_OK ){
210075c23afSdanielk1977     return rc;
211075c23afSdanielk1977   }
212075c23afSdanielk1977 #endif
213075c23afSdanielk1977 
2142b4905c8Sdrh   /* If the following assert() fails on some obscure processor/compiler
2152b4905c8Sdrh   ** combination, the work-around is to set the correct pointer
2162b4905c8Sdrh   ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
2172b4905c8Sdrh   assert( SQLITE_PTRSIZE==sizeof(char*) );
2182b4905c8Sdrh 
21993ed56d9Sdrh   /* If SQLite is already completely initialized, then this call
22093ed56d9Sdrh   ** to sqlite3_initialize() should be a no-op.  But the initialization
22193ed56d9Sdrh   ** must be complete.  So isInit must not be set until the very end
22293ed56d9Sdrh   ** of this routine.
22393ed56d9Sdrh   */
224ffd3fd0cSdrh   if( sqlite3GlobalConfig.isInit ){
225ffd3fd0cSdrh     sqlite3MemoryBarrier();
226ffd3fd0cSdrh     return SQLITE_OK;
227ffd3fd0cSdrh   }
22871bc31c6Sdanielk1977 
22993ed56d9Sdrh   /* Make sure the mutex subsystem is initialized.  If unable to
23093ed56d9Sdrh   ** initialize the mutex subsystem, return early with the error.
23193ed56d9Sdrh   ** If the system is so sick that we are unable to allocate a mutex,
23293ed56d9Sdrh   ** there is not much SQLite is going to be able to do.
23393ed56d9Sdrh   **
23493ed56d9Sdrh   ** The mutex subsystem must take care of serializing its own
23593ed56d9Sdrh   ** initialization.
23693ed56d9Sdrh   */
237d025174fSdanielk1977   rc = sqlite3MutexInit();
23893ed56d9Sdrh   if( rc ) return rc;
23971bc31c6Sdanielk1977 
24071bc31c6Sdanielk1977   /* Initialize the malloc() system and the recursive pInitMutex mutex.
241ccb2113aSdrh   ** This operation is protected by the STATIC_MAIN mutex.  Note that
24293ed56d9Sdrh   ** MutexAlloc() is called for a static mutex prior to initializing the
24393ed56d9Sdrh   ** malloc subsystem - this implies that the allocation of a static
24493ed56d9Sdrh   ** mutex must not require support from the malloc subsystem.
24571bc31c6Sdanielk1977   */
246067b92baSdrh   MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
247067b92baSdrh   sqlite3_mutex_enter(pMainMtx);
248e1ab2193Sdan   sqlite3GlobalConfig.isMutexInit = 1;
249075c23afSdanielk1977   if( !sqlite3GlobalConfig.isMallocInit ){
25071bc31c6Sdanielk1977     rc = sqlite3MallocInit();
25171bc31c6Sdanielk1977   }
25271bc31c6Sdanielk1977   if( rc==SQLITE_OK ){
253075c23afSdanielk1977     sqlite3GlobalConfig.isMallocInit = 1;
254075c23afSdanielk1977     if( !sqlite3GlobalConfig.pInitMutex ){
2559ac06509Sdrh       sqlite3GlobalConfig.pInitMutex =
2569ac06509Sdrh            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
257075c23afSdanielk1977       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
258fad3039cSmistachkin         rc = SQLITE_NOMEM_BKPT;
25971bc31c6Sdanielk1977       }
26071bc31c6Sdanielk1977     }
26177eb5bb6Sdanielk1977   }
26277eb5bb6Sdanielk1977   if( rc==SQLITE_OK ){
263075c23afSdanielk1977     sqlite3GlobalConfig.nRefInitMutex++;
26471bc31c6Sdanielk1977   }
265067b92baSdrh   sqlite3_mutex_leave(pMainMtx);
26693ed56d9Sdrh 
267e1ab2193Sdan   /* If rc is not SQLITE_OK at this point, then either the malloc
268e1ab2193Sdan   ** subsystem could not be initialized or the system failed to allocate
269e1ab2193Sdan   ** the pInitMutex mutex. Return an error in either case.  */
27040257ffdSdrh   if( rc!=SQLITE_OK ){
27171bc31c6Sdanielk1977     return rc;
27240257ffdSdrh   }
27371bc31c6Sdanielk1977 
27493ed56d9Sdrh   /* Do the rest of the initialization under the recursive mutex so
27593ed56d9Sdrh   ** that we will be able to handle recursive calls into
27693ed56d9Sdrh   ** sqlite3_initialize().  The recursive calls normally come through
27793ed56d9Sdrh   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
27893ed56d9Sdrh   ** recursive calls might also be possible.
279f759bb83Sdrh   **
280f759bb83Sdrh   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
281f759bb83Sdrh   ** to the xInit method, so the xInit method need not be threadsafe.
282f759bb83Sdrh   **
283f759bb83Sdrh   ** The following mutex is what serializes access to the appdef pcache xInit
284f759bb83Sdrh   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
285f759bb83Sdrh   ** call to sqlite3PcacheInitialize().
28671bc31c6Sdanielk1977   */
287075c23afSdanielk1977   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
288502b4e00Sdanielk1977   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
289502b4e00Sdanielk1977     sqlite3GlobalConfig.inProgress = 1;
2905e3cefe3Sdrh #ifdef SQLITE_ENABLE_SQLLOG
291d83f7ca1Sdan     {
2925e3cefe3Sdrh       extern void sqlite3_init_sqllog(void);
2935e3cefe3Sdrh       sqlite3_init_sqllog();
294d83f7ca1Sdan     }
295d83f7ca1Sdan #endif
29680738d9cSdrh     memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
29780738d9cSdrh     sqlite3RegisterBuiltinFunctions();
298e1ab2193Sdan     if( sqlite3GlobalConfig.isPCacheInit==0 ){
2998c0a791aSdanielk1977       rc = sqlite3PcacheInitialize();
300e1ab2193Sdan     }
3010bf9f7bcSdrh     if( rc==SQLITE_OK ){
302e1ab2193Sdan       sqlite3GlobalConfig.isPCacheInit = 1;
3033d6e060bSdan       rc = sqlite3OsInit();
3040bf9f7bcSdrh     }
3058d889afcSdrh #ifndef SQLITE_OMIT_DESERIALIZE
306ac442f41Sdrh     if( rc==SQLITE_OK ){
307ac442f41Sdrh       rc = sqlite3MemdbInit();
308ac442f41Sdrh     }
309ac442f41Sdrh #endif
3100bf9f7bcSdrh     if( rc==SQLITE_OK ){
3115b775295Sdanielk1977       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
3125b775295Sdanielk1977           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
313c4842889Sdrh       sqlite3MemoryBarrier();
3140bf9f7bcSdrh       sqlite3GlobalConfig.isInit = 1;
315ab80be99Sdrh #ifdef SQLITE_EXTRA_INIT
316ab80be99Sdrh       bRunExtraInit = 1;
317ab80be99Sdrh #endif
3188c0a791aSdanielk1977     }
319502b4e00Sdanielk1977     sqlite3GlobalConfig.inProgress = 0;
32040257ffdSdrh   }
321075c23afSdanielk1977   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
322dfb7b37dSshane 
32393ed56d9Sdrh   /* Go back under the static mutex and clean up the recursive
32493ed56d9Sdrh   ** mutex to prevent a resource leak.
32593ed56d9Sdrh   */
326067b92baSdrh   sqlite3_mutex_enter(pMainMtx);
327075c23afSdanielk1977   sqlite3GlobalConfig.nRefInitMutex--;
328075c23afSdanielk1977   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
329075c23afSdanielk1977     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
330075c23afSdanielk1977     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
331075c23afSdanielk1977     sqlite3GlobalConfig.pInitMutex = 0;
33293ed56d9Sdrh   }
333067b92baSdrh   sqlite3_mutex_leave(pMainMtx);
33493ed56d9Sdrh 
33593ed56d9Sdrh   /* The following is just a sanity check to make sure SQLite has
33693ed56d9Sdrh   ** been compiled correctly.  It is important to run this code, but
33793ed56d9Sdrh   ** we don't want to run it too often and soak up CPU cycles for no
33893ed56d9Sdrh   ** reason.  So we run it once during initialization.
33993ed56d9Sdrh   */
340dfb7b37dSshane #ifndef NDEBUG
341fbd60f82Sshane #ifndef SQLITE_OMIT_FLOATING_POINT
342dfb7b37dSshane   /* This section of code's only "output" is via assert() statements. */
343dfb7b37dSshane   if( rc==SQLITE_OK ){
344dfb7b37dSshane     u64 x = (((u64)1)<<63)-1;
345dfb7b37dSshane     double y;
346dfb7b37dSshane     assert(sizeof(x)==8);
347dfb7b37dSshane     assert(sizeof(x)==sizeof(y));
348dfb7b37dSshane     memcpy(&y, &x, 8);
349dfb7b37dSshane     assert( sqlite3IsNaN(y) );
350dfb7b37dSshane   }
351dfb7b37dSshane #endif
352fbd60f82Sshane #endif
353dfb7b37dSshane 
354e4cf0b31Sdrh   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
355e4cf0b31Sdrh   ** compile-time option.
356e4cf0b31Sdrh   */
357e4cf0b31Sdrh #ifdef SQLITE_EXTRA_INIT
358ab80be99Sdrh   if( bRunExtraInit ){
359c7f94629Sdrh     int SQLITE_EXTRA_INIT(const char*);
360c7f94629Sdrh     rc = SQLITE_EXTRA_INIT(0);
361e4cf0b31Sdrh   }
362e4cf0b31Sdrh #endif
363e4cf0b31Sdrh 
36440257ffdSdrh   return rc;
36540257ffdSdrh }
36640257ffdSdrh 
36740257ffdSdrh /*
36840257ffdSdrh ** Undo the effects of sqlite3_initialize().  Must not be called while
36940257ffdSdrh ** there are outstanding database connections or memory allocations or
37040257ffdSdrh ** while any part of SQLite is otherwise in use in any thread.  This
371d1a2440dSdrh ** routine is not threadsafe.  But it is safe to invoke this routine
372d1a2440dSdrh ** on when SQLite is already shut down.  If SQLite is already shut down
373d1a2440dSdrh ** when this routine is invoked, then this routine is a harmless no-op.
37440257ffdSdrh */
sqlite3_shutdown(void)37540257ffdSdrh int sqlite3_shutdown(void){
376054450f0Smistachkin #ifdef SQLITE_OMIT_WSD
377054450f0Smistachkin   int rc = sqlite3_wsd_init(4096, 24);
378054450f0Smistachkin   if( rc!=SQLITE_OK ){
379054450f0Smistachkin     return rc;
380054450f0Smistachkin   }
381054450f0Smistachkin #endif
382054450f0Smistachkin 
383d1a2440dSdrh   if( sqlite3GlobalConfig.isInit ){
3849797706cSdrh #ifdef SQLITE_EXTRA_SHUTDOWN
3859797706cSdrh     void SQLITE_EXTRA_SHUTDOWN(void);
3869797706cSdrh     SQLITE_EXTRA_SHUTDOWN();
3879797706cSdrh #endif
38840257ffdSdrh     sqlite3_os_end();
389bb77b753Sdrh     sqlite3_reset_auto_extension();
390075c23afSdanielk1977     sqlite3GlobalConfig.isInit = 0;
391d1a2440dSdrh   }
392e1ab2193Sdan   if( sqlite3GlobalConfig.isPCacheInit ){
393e1ab2193Sdan     sqlite3PcacheShutdown();
394e1ab2193Sdan     sqlite3GlobalConfig.isPCacheInit = 0;
395e1ab2193Sdan   }
396e1ab2193Sdan   if( sqlite3GlobalConfig.isMallocInit ){
397e1ab2193Sdan     sqlite3MallocEnd();
398e1ab2193Sdan     sqlite3GlobalConfig.isMallocInit = 0;
39986f89871Smistachkin 
40086f89871Smistachkin #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
40186f89871Smistachkin     /* The heap subsystem has now been shutdown and these values are supposed
40286f89871Smistachkin     ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
40386f89871Smistachkin     ** which would rely on that heap subsystem; therefore, make sure these
40486f89871Smistachkin     ** values cannot refer to heap memory that was just invalidated when the
40586f89871Smistachkin     ** heap subsystem was shutdown.  This is only done if the current call to
40686f89871Smistachkin     ** this function resulted in the heap subsystem actually being shutdown.
40786f89871Smistachkin     */
40886f89871Smistachkin     sqlite3_data_directory = 0;
40986f89871Smistachkin     sqlite3_temp_directory = 0;
41086f89871Smistachkin #endif
411e1ab2193Sdan   }
412e1ab2193Sdan   if( sqlite3GlobalConfig.isMutexInit ){
413e1ab2193Sdan     sqlite3MutexEnd();
414e1ab2193Sdan     sqlite3GlobalConfig.isMutexInit = 0;
415e1ab2193Sdan   }
416e1ab2193Sdan 
41740257ffdSdrh   return SQLITE_OK;
41840257ffdSdrh }
41940257ffdSdrh 
42040257ffdSdrh /*
42140257ffdSdrh ** This API allows applications to modify the global configuration of
42240257ffdSdrh ** the SQLite library at run-time.
42340257ffdSdrh **
42440257ffdSdrh ** This routine should only be called when there are no outstanding
42540257ffdSdrh ** database connections or memory allocations.  This routine is not
42640257ffdSdrh ** threadsafe.  Failure to heed these warnings can lead to unpredictable
42740257ffdSdrh ** behavior.
42840257ffdSdrh */
sqlite3_config(int op,...)42940257ffdSdrh int sqlite3_config(int op, ...){
43040257ffdSdrh   va_list ap;
43140257ffdSdrh   int rc = SQLITE_OK;
43240257ffdSdrh 
43340257ffdSdrh   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
43440257ffdSdrh   ** the SQLite library is in use. */
435413c3d36Sdrh   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
43640257ffdSdrh 
43740257ffdSdrh   va_start(ap, op);
43840257ffdSdrh   switch( op ){
43918472fa7Sdrh 
44018472fa7Sdrh     /* Mutex configuration options are only available in a threadsafe
44118472fa7Sdrh     ** compile.
44218472fa7Sdrh     */
443d1dcb234Sdrh #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0  /* IMP: R-54466-46756 */
44440257ffdSdrh     case SQLITE_CONFIG_SINGLETHREAD: {
445682a6ef6Sdrh       /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
446682a6ef6Sdrh       ** Single-thread. */
447682a6ef6Sdrh       sqlite3GlobalConfig.bCoreMutex = 0;  /* Disable mutex on core */
448682a6ef6Sdrh       sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
44940257ffdSdrh       break;
45040257ffdSdrh     }
451d1dcb234Sdrh #endif
452d1dcb234Sdrh #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
45340257ffdSdrh     case SQLITE_CONFIG_MULTITHREAD: {
454682a6ef6Sdrh       /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
455682a6ef6Sdrh       ** Multi-thread. */
456682a6ef6Sdrh       sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
457682a6ef6Sdrh       sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
45840257ffdSdrh       break;
45940257ffdSdrh     }
460d1dcb234Sdrh #endif
461d1dcb234Sdrh #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
46240257ffdSdrh     case SQLITE_CONFIG_SERIALIZED: {
463682a6ef6Sdrh       /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
464682a6ef6Sdrh       ** Serialized. */
465682a6ef6Sdrh       sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
466682a6ef6Sdrh       sqlite3GlobalConfig.bFullMutex = 1;  /* Enable mutex on connections */
46740257ffdSdrh       break;
46840257ffdSdrh     }
469d1dcb234Sdrh #endif
470d1dcb234Sdrh #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
47118472fa7Sdrh     case SQLITE_CONFIG_MUTEX: {
47218472fa7Sdrh       /* Specify an alternative mutex implementation */
47318472fa7Sdrh       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
47418472fa7Sdrh       break;
47518472fa7Sdrh     }
476d1dcb234Sdrh #endif
477d1dcb234Sdrh #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
47818472fa7Sdrh     case SQLITE_CONFIG_GETMUTEX: {
47918472fa7Sdrh       /* Retrieve the current mutex implementation */
48018472fa7Sdrh       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
48118472fa7Sdrh       break;
48218472fa7Sdrh     }
48318472fa7Sdrh #endif
48418472fa7Sdrh 
48540257ffdSdrh     case SQLITE_CONFIG_MALLOC: {
4865279d343Sdrh       /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
4875279d343Sdrh       ** single argument which is a pointer to an instance of the
4885279d343Sdrh       ** sqlite3_mem_methods structure. The argument specifies alternative
4895279d343Sdrh       ** low-level memory allocation routines to be used in place of the memory
4905279d343Sdrh       ** allocation routines built into SQLite. */
491075c23afSdanielk1977       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
49240257ffdSdrh       break;
49340257ffdSdrh     }
49433589797Sdrh     case SQLITE_CONFIG_GETMALLOC: {
4955279d343Sdrh       /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
4965279d343Sdrh       ** single argument which is a pointer to an instance of the
4975279d343Sdrh       ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
4985279d343Sdrh       ** filled with the currently defined memory allocation routines. */
499075c23afSdanielk1977       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
500075c23afSdanielk1977       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
50133589797Sdrh       break;
50233589797Sdrh     }
503fec00eabSdrh     case SQLITE_CONFIG_MEMSTATUS: {
5045279d343Sdrh       /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
5055279d343Sdrh       ** single argument of type int, interpreted as a boolean, which enables
5065279d343Sdrh       ** or disables the collection of memory allocation statistics. */
5075279d343Sdrh       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
50840257ffdSdrh       break;
50940257ffdSdrh     }
510b2a0f75cSdrh     case SQLITE_CONFIG_SMALL_MALLOC: {
511b2a0f75cSdrh       sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
51233589797Sdrh       break;
51333589797Sdrh     }
51433589797Sdrh     case SQLITE_CONFIG_PAGECACHE: {
51515427279Sdrh       /* EVIDENCE-OF: R-18761-36601 There are three arguments to
51615427279Sdrh       ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
51715427279Sdrh       ** the size of each page cache line (sz), and the number of cache lines
51815427279Sdrh       ** (N). */
519075c23afSdanielk1977       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
520075c23afSdanielk1977       sqlite3GlobalConfig.szPage = va_arg(ap, int);
521075c23afSdanielk1977       sqlite3GlobalConfig.nPage = va_arg(ap, int);
52233589797Sdrh       break;
52333589797Sdrh     }
524def6889dSdrh     case SQLITE_CONFIG_PCACHE_HDRSZ: {
5255279d343Sdrh       /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
5265279d343Sdrh       ** a single parameter which is a pointer to an integer and writes into
5275279d343Sdrh       ** that integer the number of extra bytes per page required for each page
5285279d343Sdrh       ** in SQLITE_CONFIG_PAGECACHE. */
529def6889dSdrh       *va_arg(ap, int*) =
530def6889dSdrh           sqlite3HeaderSizeBtree() +
531def6889dSdrh           sqlite3HeaderSizePcache() +
532def6889dSdrh           sqlite3HeaderSizePcache1();
533def6889dSdrh       break;
534def6889dSdrh     }
5355099be5eSdanielk1977 
536bc2ca9ebSdanielk1977     case SQLITE_CONFIG_PCACHE: {
53722e21ff4Sdan       /* no-op */
53822e21ff4Sdan       break;
53922e21ff4Sdan     }
54022e21ff4Sdan     case SQLITE_CONFIG_GETPCACHE: {
54122e21ff4Sdan       /* now an error */
54222e21ff4Sdan       rc = SQLITE_ERROR;
543bc2ca9ebSdanielk1977       break;
544bc2ca9ebSdanielk1977     }
545bc2ca9ebSdanielk1977 
54622e21ff4Sdan     case SQLITE_CONFIG_PCACHE2: {
5475279d343Sdrh       /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
5485279d343Sdrh       ** single argument which is a pointer to an sqlite3_pcache_methods2
5495279d343Sdrh       ** object. This object specifies the interface to a custom page cache
5505279d343Sdrh       ** implementation. */
55122e21ff4Sdan       sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
55222e21ff4Sdan       break;
55322e21ff4Sdan     }
55422e21ff4Sdan     case SQLITE_CONFIG_GETPCACHE2: {
5555279d343Sdrh       /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
5565279d343Sdrh       ** single argument which is a pointer to an sqlite3_pcache_methods2
5575279d343Sdrh       ** object. SQLite copies of the current page cache implementation into
5585279d343Sdrh       ** that object. */
55922e21ff4Sdan       if( sqlite3GlobalConfig.pcache2.xInit==0 ){
560b232c232Sdrh         sqlite3PCacheSetDefault();
561b232c232Sdrh       }
56222e21ff4Sdan       *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
563b232c232Sdrh       break;
564b232c232Sdrh     }
565b232c232Sdrh 
5668790b6e8Sdrh /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
5678790b6e8Sdrh ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
5688790b6e8Sdrh ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
5695d414839Sdrh #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
57033589797Sdrh     case SQLITE_CONFIG_HEAP: {
5715279d343Sdrh       /* EVIDENCE-OF: R-19854-42126 There are three arguments to
5725279d343Sdrh       ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
5733ba689d8Sdrh       ** number of bytes in the memory buffer, and the minimum allocation size.
5743ba689d8Sdrh       */
575075c23afSdanielk1977       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
576075c23afSdanielk1977       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
577075c23afSdanielk1977       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
5785099be5eSdanielk1977 
579a6ec892bSshaneh       if( sqlite3GlobalConfig.mnReq<1 ){
580a6ec892bSshaneh         sqlite3GlobalConfig.mnReq = 1;
581a6ec892bSshaneh       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
582a6ec892bSshaneh         /* cap min request size at 2^12 */
583a6ec892bSshaneh         sqlite3GlobalConfig.mnReq = (1<<12);
584a6ec892bSshaneh       }
585a6ec892bSshaneh 
586075c23afSdanielk1977       if( sqlite3GlobalConfig.pHeap==0 ){
5878790b6e8Sdrh         /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
5888790b6e8Sdrh         ** is NULL, then SQLite reverts to using its default memory allocator
5898790b6e8Sdrh         ** (the system malloc() implementation), undoing any prior invocation of
5908790b6e8Sdrh         ** SQLITE_CONFIG_MALLOC.
5918790b6e8Sdrh         **
5928790b6e8Sdrh         ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
5938790b6e8Sdrh         ** revert to its default implementation when sqlite3_initialize() is run
5948a42cbd3Sdrh         */
595075c23afSdanielk1977         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
5968a42cbd3Sdrh       }else{
5978790b6e8Sdrh         /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
5988790b6e8Sdrh         ** alternative memory allocator is engaged to handle all of SQLites
5998790b6e8Sdrh         ** memory allocation needs. */
6005099be5eSdanielk1977 #ifdef SQLITE_ENABLE_MEMSYS3
601075c23afSdanielk1977         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
6028a42cbd3Sdrh #endif
6038a42cbd3Sdrh #ifdef SQLITE_ENABLE_MEMSYS5
604075c23afSdanielk1977         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
6058a42cbd3Sdrh #endif
6068a42cbd3Sdrh       }
6075099be5eSdanielk1977       break;
6085099be5eSdanielk1977     }
6095d414839Sdrh #endif
6105099be5eSdanielk1977 
611633e6d57Sdrh     case SQLITE_CONFIG_LOOKASIDE: {
612075c23afSdanielk1977       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
613075c23afSdanielk1977       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
614633e6d57Sdrh       break;
615633e6d57Sdrh     }
6163f280701Sdrh 
617037933b8Smistachkin     /* Record a pointer to the logger function and its first argument.
6183f280701Sdrh     ** The default is NULL.  Logging is disabled if the function pointer is
6193f280701Sdrh     ** NULL.
6203f280701Sdrh     */
6213f280701Sdrh     case SQLITE_CONFIG_LOG: {
622dc97a8cdSshaneh       /* MSVC is picky about pulling func ptrs from va lists.
623dc97a8cdSshaneh       ** http://support.microsoft.com/kb/47961
624dc97a8cdSshaneh       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
625dc97a8cdSshaneh       */
626dc97a8cdSshaneh       typedef void(*LOGFUNC_t)(void*,int,const char*);
627dc97a8cdSshaneh       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
6283f280701Sdrh       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
6293f280701Sdrh       break;
6303f280701Sdrh     }
631633e6d57Sdrh 
63200729cbaSdrh     /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
63300729cbaSdrh     ** can be changed at start-time using the
63400729cbaSdrh     ** sqlite3_config(SQLITE_CONFIG_URI,1) or
63500729cbaSdrh     ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
63600729cbaSdrh     */
637cd74b611Sdan     case SQLITE_CONFIG_URI: {
6384d9f188fSdrh       /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
6394d9f188fSdrh       ** argument of type int. If non-zero, then URI handling is globally
6404d9f188fSdrh       ** enabled. If the parameter is zero, then URI handling is globally
6414d9f188fSdrh       ** disabled. */
642cd74b611Sdan       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
643cd74b611Sdan       break;
644cd74b611Sdan     }
645cd74b611Sdan 
646de9a7b8aSdrh     case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
6474d9f188fSdrh       /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
6484d9f188fSdrh       ** option takes a single integer argument which is interpreted as a
6494d9f188fSdrh       ** boolean in order to enable or disable the use of covering indices for
6504d9f188fSdrh       ** full table scans in the query optimizer. */
651de9a7b8aSdrh       sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
652de9a7b8aSdrh       break;
653de9a7b8aSdrh     }
654de9a7b8aSdrh 
655ac455939Sdan #ifdef SQLITE_ENABLE_SQLLOG
656ac455939Sdan     case SQLITE_CONFIG_SQLLOG: {
657ac455939Sdan       typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
658ac455939Sdan       sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
659ac455939Sdan       sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
660ac455939Sdan       break;
661ac455939Sdan     }
662ac455939Sdan #endif
663ac455939Sdan 
6649b4c59faSdrh     case SQLITE_CONFIG_MMAP_SIZE: {
6654d9f188fSdrh       /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
6664d9f188fSdrh       ** integer (sqlite3_int64) values that are the default mmap size limit
6674d9f188fSdrh       ** (the default setting for PRAGMA mmap_size) and the maximum allowed
6684d9f188fSdrh       ** mmap size limit. */
6699b4c59faSdrh       sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
670a1f42c7cSdrh       sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
6714d9f188fSdrh       /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
6728790b6e8Sdrh       ** negative, then that argument is changed to its compile-time default.
6738790b6e8Sdrh       **
6748790b6e8Sdrh       ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
6758790b6e8Sdrh       ** silently truncated if necessary so that it does not exceed the
6768790b6e8Sdrh       ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
6778790b6e8Sdrh       ** compile-time option.
6788790b6e8Sdrh       */
6793ba689d8Sdrh       if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
6803ba689d8Sdrh         mxMmap = SQLITE_MAX_MMAP_SIZE;
6813ba689d8Sdrh       }
6829b4c59faSdrh       if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
6839b4c59faSdrh       if( szMmap>mxMmap) szMmap = mxMmap;
6844d9f188fSdrh       sqlite3GlobalConfig.mxMmap = mxMmap;
6859b4c59faSdrh       sqlite3GlobalConfig.szMmap = szMmap;
686a1f42c7cSdrh       break;
687a1f42c7cSdrh     }
688a1f42c7cSdrh 
6894d9f188fSdrh #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
690af8641bdSmistachkin     case SQLITE_CONFIG_WIN32_HEAPSIZE: {
6914d9f188fSdrh       /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
6924d9f188fSdrh       ** unsigned integer value that specifies the maximum size of the created
6934d9f188fSdrh       ** heap. */
694ac1f1045Smistachkin       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
695ac1f1045Smistachkin       break;
696ac1f1045Smistachkin     }
697ac1f1045Smistachkin #endif
698ac1f1045Smistachkin 
6993bd1791dSdrh     case SQLITE_CONFIG_PMASZ: {
7003bd1791dSdrh       sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
7013bd1791dSdrh       break;
7023bd1791dSdrh     }
7033bd1791dSdrh 
7048c71a98cSdrh     case SQLITE_CONFIG_STMTJRNL_SPILL: {
7058c71a98cSdrh       sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
7068c71a98cSdrh       break;
7078c71a98cSdrh     }
7088c71a98cSdrh 
7092e3a5a81Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES
710bbade8d1Sdrh     case SQLITE_CONFIG_SORTERREF_SIZE: {
7112e3a5a81Sdan       int iVal = va_arg(ap, int);
7122e3a5a81Sdan       if( iVal<0 ){
7132e3a5a81Sdan         iVal = SQLITE_DEFAULT_SORTERREF_SIZE;
7142e3a5a81Sdan       }
7152e3a5a81Sdan       sqlite3GlobalConfig.szSorterRef = (u32)iVal;
7162e3a5a81Sdan       break;
7172e3a5a81Sdan     }
718bbade8d1Sdrh #endif /* SQLITE_ENABLE_SORTER_REFERENCES */
7192e3a5a81Sdan 
7208d889afcSdrh #ifndef SQLITE_OMIT_DESERIALIZE
72123a88595Sdrh     case SQLITE_CONFIG_MEMDB_MAXSIZE: {
72223a88595Sdrh       sqlite3GlobalConfig.mxMemdbSize = va_arg(ap, sqlite3_int64);
72323a88595Sdrh       break;
72423a88595Sdrh     }
7258d889afcSdrh #endif /* SQLITE_OMIT_DESERIALIZE */
72623a88595Sdrh 
72740257ffdSdrh     default: {
72840257ffdSdrh       rc = SQLITE_ERROR;
72940257ffdSdrh       break;
73040257ffdSdrh     }
73140257ffdSdrh   }
73240257ffdSdrh   va_end(ap);
73340257ffdSdrh   return rc;
73440257ffdSdrh }
73540257ffdSdrh 
73640257ffdSdrh /*
737633e6d57Sdrh ** Set up the lookaside buffers for a database connection.
738633e6d57Sdrh ** Return SQLITE_OK on success.
739633e6d57Sdrh ** If lookaside is already active, return SQLITE_BUSY.
740e9d1c720Sdrh **
741e9d1c720Sdrh ** The sz parameter is the number of bytes in each lookaside slot.
742e9d1c720Sdrh ** The cnt parameter is the number of slots.  If pStart is NULL the
743e9d1c720Sdrh ** space for the lookaside memory is obtained from sqlite3_malloc().
744e9d1c720Sdrh ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
745e9d1c720Sdrh ** the lookaside memory.
746633e6d57Sdrh */
setupLookaside(sqlite3 * db,void * pBuf,int sz,int cnt)747e9d1c720Sdrh static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
7487877d9afSdrh #ifndef SQLITE_OMIT_LOOKASIDE
749633e6d57Sdrh   void *pStart;
750115d663cSnumist   sqlite3_int64 szAlloc = sz*(sqlite3_int64)cnt;
751e6068027Sdrh   int nBig;   /* Number of full-size slots */
752cf014f6cSdrh   int nSm;    /* Number smaller LOOKASIDE_SMALL-byte slots */
75352fb8e19Sdrh 
75452fb8e19Sdrh   if( sqlite3LookasideUsed(db,0)>0 ){
755633e6d57Sdrh     return SQLITE_BUSY;
756633e6d57Sdrh   }
757f71f89e8Sshane   /* Free any existing lookaside buffer for this handle before
758f71f89e8Sshane   ** allocating a new one so we don't have to have space for
759f71f89e8Sshane   ** both at the same time.
760f71f89e8Sshane   */
761f71f89e8Sshane   if( db->lookaside.bMalloced ){
762f71f89e8Sshane     sqlite3_free(db->lookaside.pStart);
763f71f89e8Sshane   }
76461a4bd5cSdrh   /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
76561a4bd5cSdrh   ** than a pointer to be useful.
766f71f89e8Sshane   */
76761a4bd5cSdrh   sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
7681d34fdecSdrh   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
769633e6d57Sdrh   if( cnt<0 ) cnt = 0;
770f71f89e8Sshane   if( sz==0 || cnt==0 ){
771f71f89e8Sshane     sz = 0;
772f71f89e8Sshane     pStart = 0;
773f71f89e8Sshane   }else if( pBuf==0 ){
774633e6d57Sdrh     sqlite3BeginBenignMalloc();
775115d663cSnumist     pStart = sqlite3Malloc( szAlloc );  /* IMP: R-61949-35727 */
776633e6d57Sdrh     sqlite3EndBenignMalloc();
777e6068027Sdrh     if( pStart ) szAlloc = sqlite3MallocSize(pStart);
778e9d1c720Sdrh   }else{
779e9d1c720Sdrh     pStart = pBuf;
780e9d1c720Sdrh   }
781cf014f6cSdrh #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
782cf014f6cSdrh   if( sz>=LOOKASIDE_SMALL*3 ){
783cf014f6cSdrh     nBig = szAlloc/(3*LOOKASIDE_SMALL+sz);
784cf014f6cSdrh     nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
785cf014f6cSdrh   }else if( sz>=LOOKASIDE_SMALL*2 ){
786cf014f6cSdrh     nBig = szAlloc/(LOOKASIDE_SMALL+sz);
787cf014f6cSdrh     nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
788e6068027Sdrh   }else
789cf014f6cSdrh #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
790e6068027Sdrh   if( sz>0 ){
791e6068027Sdrh     nBig = szAlloc/sz;
792e6068027Sdrh     nSm = 0;
793e6068027Sdrh   }else{
794e6068027Sdrh     nBig = nSm = 0;
795e6068027Sdrh   }
7964cfb22f7Sdrh   db->lookaside.pStart = pStart;
79752fb8e19Sdrh   db->lookaside.pInit = 0;
7984cfb22f7Sdrh   db->lookaside.pFree = 0;
7991bd10f8aSdrh   db->lookaside.sz = (u16)sz;
80031f69626Sdrh   db->lookaside.szTrue = (u16)sz;
801633e6d57Sdrh   if( pStart ){
802633e6d57Sdrh     int i;
803633e6d57Sdrh     LookasideSlot *p;
804de467985Sdrh     assert( sz > (int)sizeof(LookasideSlot*) );
805633e6d57Sdrh     p = (LookasideSlot*)pStart;
806e6068027Sdrh     for(i=0; i<nBig; i++){
80752fb8e19Sdrh       p->pNext = db->lookaside.pInit;
80852fb8e19Sdrh       db->lookaside.pInit = p;
809633e6d57Sdrh       p = (LookasideSlot*)&((u8*)p)[sz];
810633e6d57Sdrh     }
811cf014f6cSdrh #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
812cf014f6cSdrh     db->lookaside.pSmallInit = 0;
813cf014f6cSdrh     db->lookaside.pSmallFree = 0;
814115d663cSnumist     db->lookaside.pMiddle = p;
815e6068027Sdrh     for(i=0; i<nSm; i++){
816cf014f6cSdrh       p->pNext = db->lookaside.pSmallInit;
817cf014f6cSdrh       db->lookaside.pSmallInit = p;
818cf014f6cSdrh       p = (LookasideSlot*)&((u8*)p)[LOOKASIDE_SMALL];
819115d663cSnumist     }
820cf014f6cSdrh #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
821e6068027Sdrh     assert( ((uptr)p)<=szAlloc + (uptr)pStart );
822633e6d57Sdrh     db->lookaside.pEnd = p;
8234a642b60Sdrh     db->lookaside.bDisable = 0;
824f71f89e8Sshane     db->lookaside.bMalloced = pBuf==0 ?1:0;
825e6068027Sdrh     db->lookaside.nSlot = nBig+nSm;
8264cfb22f7Sdrh   }else{
827376860baSdrh     db->lookaside.pStart = 0;
828cf014f6cSdrh #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
829cf014f6cSdrh     db->lookaside.pSmallInit = 0;
830cf014f6cSdrh     db->lookaside.pSmallFree = 0;
831376860baSdrh     db->lookaside.pMiddle = 0;
832cf014f6cSdrh #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
833376860baSdrh     db->lookaside.pEnd = 0;
8344a642b60Sdrh     db->lookaside.bDisable = 1;
83531f69626Sdrh     db->lookaside.sz = 0;
836f71f89e8Sshane     db->lookaside.bMalloced = 0;
83752fb8e19Sdrh     db->lookaside.nSlot = 0;
838633e6d57Sdrh   }
839376860baSdrh   db->lookaside.pTrueEnd = db->lookaside.pEnd;
840e6068027Sdrh   assert( sqlite3LookasideUsed(db,0)==0 );
8417877d9afSdrh #endif /* SQLITE_OMIT_LOOKASIDE */
842633e6d57Sdrh   return SQLITE_OK;
843633e6d57Sdrh }
844633e6d57Sdrh 
845633e6d57Sdrh /*
8464413d0e9Sdrh ** Return the mutex associated with a database connection.
8474413d0e9Sdrh */
sqlite3_db_mutex(sqlite3 * db)8484413d0e9Sdrh sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
8499ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
8509ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ){
8519ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
8529ca95730Sdrh     return 0;
8539ca95730Sdrh   }
8549ca95730Sdrh #endif
8554413d0e9Sdrh   return db->mutex;
8564413d0e9Sdrh }
8574413d0e9Sdrh 
8584413d0e9Sdrh /*
85909419b4bSdrh ** Free up as much memory as we can from the given database
86009419b4bSdrh ** connection.
86109419b4bSdrh */
sqlite3_db_release_memory(sqlite3 * db)86209419b4bSdrh int sqlite3_db_release_memory(sqlite3 *db){
86309419b4bSdrh   int i;
8649ca95730Sdrh 
8659ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
8669ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
8679ca95730Sdrh #endif
868d9bb3a97Sdan   sqlite3_mutex_enter(db->mutex);
86909419b4bSdrh   sqlite3BtreeEnterAll(db);
87009419b4bSdrh   for(i=0; i<db->nDb; i++){
87109419b4bSdrh     Btree *pBt = db->aDb[i].pBt;
87209419b4bSdrh     if( pBt ){
87309419b4bSdrh       Pager *pPager = sqlite3BtreePager(pBt);
87409419b4bSdrh       sqlite3PagerShrink(pPager);
87509419b4bSdrh     }
87609419b4bSdrh   }
87709419b4bSdrh   sqlite3BtreeLeaveAll(db);
878d9bb3a97Sdan   sqlite3_mutex_leave(db->mutex);
87909419b4bSdrh   return SQLITE_OK;
88009419b4bSdrh }
88109419b4bSdrh 
88209419b4bSdrh /*
8836fa255fdSdan ** Flush any dirty pages in the pager-cache for any attached database
8846fa255fdSdan ** to disk.
8856fa255fdSdan */
sqlite3_db_cacheflush(sqlite3 * db)8866fa255fdSdan int sqlite3_db_cacheflush(sqlite3 *db){
8876fa255fdSdan   int i;
8886fa255fdSdan   int rc = SQLITE_OK;
8896fa255fdSdan   int bSeenBusy = 0;
8906fa255fdSdan 
8916fa255fdSdan #ifdef SQLITE_ENABLE_API_ARMOR
8926fa255fdSdan   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
8936fa255fdSdan #endif
8946fa255fdSdan   sqlite3_mutex_enter(db->mutex);
8956fa255fdSdan   sqlite3BtreeEnterAll(db);
8966fa255fdSdan   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
8976fa255fdSdan     Btree *pBt = db->aDb[i].pBt;
89899744fa4Sdrh     if( pBt && sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
8996fa255fdSdan       Pager *pPager = sqlite3BtreePager(pBt);
9006fa255fdSdan       rc = sqlite3PagerFlush(pPager);
9016fa255fdSdan       if( rc==SQLITE_BUSY ){
9026fa255fdSdan         bSeenBusy = 1;
9036fa255fdSdan         rc = SQLITE_OK;
9046fa255fdSdan       }
9056fa255fdSdan     }
9066fa255fdSdan   }
9076fa255fdSdan   sqlite3BtreeLeaveAll(db);
9086fa255fdSdan   sqlite3_mutex_leave(db->mutex);
9096fa255fdSdan   return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
9106fa255fdSdan }
9116fa255fdSdan 
9126fa255fdSdan /*
913633e6d57Sdrh ** Configuration settings for an individual database connection
914633e6d57Sdrh */
sqlite3_db_config(sqlite3 * db,int op,...)915633e6d57Sdrh int sqlite3_db_config(sqlite3 *db, int op, ...){
916633e6d57Sdrh   va_list ap;
9176480aad4Sdrh   int rc;
9187383f5a7Sdrh   sqlite3_mutex_enter(db->mutex);
919633e6d57Sdrh   va_start(ap, op);
920633e6d57Sdrh   switch( op ){
921da84dcaeSdrh     case SQLITE_DBCONFIG_MAINDBNAME: {
922749e4a9fSdrh       /* IMP: R-06824-28531 */
923749e4a9fSdrh       /* IMP: R-36257-52125 */
924da84dcaeSdrh       db->aDb[0].zDbSName = va_arg(ap,char*);
925da84dcaeSdrh       rc = SQLITE_OK;
926da84dcaeSdrh       break;
927da84dcaeSdrh     }
928e9d1c720Sdrh     case SQLITE_DBCONFIG_LOOKASIDE: {
9298b2b2e67Sdrh       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
9309dd55f51Sdrh       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
9319dd55f51Sdrh       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
932e9d1c720Sdrh       rc = setupLookaside(db, pBuf, sz, cnt);
933633e6d57Sdrh       break;
934633e6d57Sdrh     }
9356480aad4Sdrh     default: {
936e83cafd2Sdrh       static const struct {
937e83cafd2Sdrh         int op;      /* The opcode */
938e83cafd2Sdrh         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
939e83cafd2Sdrh       } aFlagOp[] = {
940e83cafd2Sdrh         { SQLITE_DBCONFIG_ENABLE_FKEY,           SQLITE_ForeignKeys    },
941e83cafd2Sdrh         { SQLITE_DBCONFIG_ENABLE_TRIGGER,        SQLITE_EnableTrigger  },
94211d88e68Sdrh         { SQLITE_DBCONFIG_ENABLE_VIEW,           SQLITE_EnableView     },
943d42908fbSdrh         { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer  },
944191dd061Sdrh         { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension  },
945298af023Sdan         { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE,      SQLITE_NoCkptOnClose  },
946169dd928Sdrh         { SQLITE_DBCONFIG_ENABLE_QPSG,           SQLITE_EnableQPSG     },
94736e31c69Sdrh         { SQLITE_DBCONFIG_TRIGGER_EQP,           SQLITE_TriggerEQP     },
9487df01196Sdrh         { SQLITE_DBCONFIG_RESET_DATABASE,        SQLITE_ResetDatabase  },
949a296cda0Sdrh         { SQLITE_DBCONFIG_DEFENSIVE,             SQLITE_Defensive      },
950346f4e26Sdrh         { SQLITE_DBCONFIG_WRITABLE_SCHEMA,       SQLITE_WriteSchema|
951346f4e26Sdrh                                                  SQLITE_NoSchemaError  },
9520a6873bfSdrh         { SQLITE_DBCONFIG_LEGACY_ALTER_TABLE,    SQLITE_LegacyAlter    },
953d0ff601cSdrh         { SQLITE_DBCONFIG_DQS_DDL,               SQLITE_DqsDDL         },
954d0ff601cSdrh         { SQLITE_DBCONFIG_DQS_DML,               SQLITE_DqsDML         },
95566c48907Sdrh         { SQLITE_DBCONFIG_LEGACY_FILE_FORMAT,    SQLITE_LegacyFileFmt  },
956b77da374Sdrh         { SQLITE_DBCONFIG_TRUSTED_SCHEMA,        SQLITE_TrustedSchema  },
957e83cafd2Sdrh       };
95858ad580fSdrh       unsigned int i;
9599dd55f51Sdrh       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
960e83cafd2Sdrh       for(i=0; i<ArraySize(aFlagOp); i++){
961e83cafd2Sdrh         if( aFlagOp[i].op==op ){
962e83cafd2Sdrh           int onoff = va_arg(ap, int);
963e83cafd2Sdrh           int *pRes = va_arg(ap, int*);
96470d5dfbaSdrh           u64 oldFlags = db->flags;
965e83cafd2Sdrh           if( onoff>0 ){
966e83cafd2Sdrh             db->flags |= aFlagOp[i].mask;
967e83cafd2Sdrh           }else if( onoff==0 ){
968d5b44d60Sdrh             db->flags &= ~(u64)aFlagOp[i].mask;
969e83cafd2Sdrh           }
970e83cafd2Sdrh           if( oldFlags!=db->flags ){
971ba968dbfSdrh             sqlite3ExpirePreparedStatements(db, 0);
972e83cafd2Sdrh           }
973e83cafd2Sdrh           if( pRes ){
974e83cafd2Sdrh             *pRes = (db->flags & aFlagOp[i].mask)!=0;
975e83cafd2Sdrh           }
976e83cafd2Sdrh           rc = SQLITE_OK;
977e83cafd2Sdrh           break;
978e83cafd2Sdrh         }
979e83cafd2Sdrh       }
9806480aad4Sdrh       break;
9816480aad4Sdrh     }
982633e6d57Sdrh   }
983633e6d57Sdrh   va_end(ap);
9847383f5a7Sdrh   sqlite3_mutex_leave(db->mutex);
985633e6d57Sdrh   return rc;
986633e6d57Sdrh }
987633e6d57Sdrh 
9889b5adfa2Sdrh /*
989d3d39e93Sdrh ** This is the default collating function named "BINARY" which is always
990d3d39e93Sdrh ** available.
991d3d39e93Sdrh */
binCollFunc(void * NotUsed,int nKey1,const void * pKey1,int nKey2,const void * pKey2)9922c336549Sdanielk1977 static int binCollFunc(
993821afa44Sdrh   void *NotUsed,
994d3d39e93Sdrh   int nKey1, const void *pKey1,
995d3d39e93Sdrh   int nKey2, const void *pKey2
996d3d39e93Sdrh ){
997d3d39e93Sdrh   int rc, n;
998821afa44Sdrh   UNUSED_PARAMETER(NotUsed);
999d3d39e93Sdrh   n = nKey1<nKey2 ? nKey1 : nKey2;
10005e3b49bcSdrh   /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
10015e3b49bcSdrh   ** strings byte by byte using the memcmp() function from the standard C
10025e3b49bcSdrh   ** library. */
100321766c0cSdan   assert( pKey1 && pKey2 );
1004d3d39e93Sdrh   rc = memcmp(pKey1, pKey2, n);
1005d3d39e93Sdrh   if( rc==0 ){
1006d3d39e93Sdrh     rc = nKey1 - nKey2;
1007d3d39e93Sdrh   }
1008d3d39e93Sdrh   return rc;
1009d3d39e93Sdrh }
1010d3d39e93Sdrh 
1011d3d39e93Sdrh /*
1012821afa44Sdrh ** This is the collating function named "RTRIM" which is always
1013821afa44Sdrh ** available.  Ignore trailing spaces.
1014821afa44Sdrh */
rtrimCollFunc(void * pUser,int nKey1,const void * pKey1,int nKey2,const void * pKey2)1015821afa44Sdrh static int rtrimCollFunc(
1016821afa44Sdrh   void *pUser,
1017821afa44Sdrh   int nKey1, const void *pKey1,
1018821afa44Sdrh   int nKey2, const void *pKey2
1019821afa44Sdrh ){
1020821afa44Sdrh   const u8 *pK1 = (const u8*)pKey1;
1021821afa44Sdrh   const u8 *pK2 = (const u8*)pKey2;
1022821afa44Sdrh   while( nKey1 && pK1[nKey1-1]==' ' ) nKey1--;
1023821afa44Sdrh   while( nKey2 && pK2[nKey2-1]==' ' ) nKey2--;
1024821afa44Sdrh   return binCollFunc(pUser, nKey1, pKey1, nKey2, pKey2);
1025821afa44Sdrh }
1026821afa44Sdrh 
1027821afa44Sdrh /*
1028bcd15938Sdrh ** Return true if CollSeq is the default built-in BINARY.
1029bcd15938Sdrh */
sqlite3IsBinary(const CollSeq * p)1030bcd15938Sdrh int sqlite3IsBinary(const CollSeq *p){
1031821afa44Sdrh   assert( p==0 || p->xCmp!=binCollFunc || strcmp(p->zName,"BINARY")==0 );
1032821afa44Sdrh   return p==0 || p->xCmp==binCollFunc;
1033bcd15938Sdrh }
1034bcd15938Sdrh 
1035bcd15938Sdrh /*
1036dc1bdc4fSdanielk1977 ** Another built-in collating sequence: NOCASE.
1037dc1bdc4fSdanielk1977 **
1038f7b5496eSdrh ** This collating sequence is intended to be used for "case independent
1039dc1bdc4fSdanielk1977 ** comparison". SQLite's knowledge of upper and lower case equivalents
1040dc1bdc4fSdanielk1977 ** extends only to the 26 characters used in the English language.
1041dc1bdc4fSdanielk1977 **
1042dc1bdc4fSdanielk1977 ** At the moment there is only a UTF-8 implementation.
10430202b29eSdanielk1977 */
nocaseCollatingFunc(void * NotUsed,int nKey1,const void * pKey1,int nKey2,const void * pKey2)10440202b29eSdanielk1977 static int nocaseCollatingFunc(
10450202b29eSdanielk1977   void *NotUsed,
10460202b29eSdanielk1977   int nKey1, const void *pKey1,
10470202b29eSdanielk1977   int nKey2, const void *pKey2
10480202b29eSdanielk1977 ){
10490202b29eSdanielk1977   int r = sqlite3StrNICmp(
1050208f80a7Sdrh       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
105162c14b34Sdanielk1977   UNUSED_PARAMETER(NotUsed);
10520202b29eSdanielk1977   if( 0==r ){
10530202b29eSdanielk1977     r = nKey1-nKey2;
10540202b29eSdanielk1977   }
10550202b29eSdanielk1977   return r;
10560202b29eSdanielk1977 }
10570202b29eSdanielk1977 
10580202b29eSdanielk1977 /*
1059af9ff33aSdrh ** Return the ROWID of the most recent insert
1060af9ff33aSdrh */
sqlite3_last_insert_rowid(sqlite3 * db)10619bb575fdSdrh sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
10629ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
10639ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ){
10649ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
10659ca95730Sdrh     return 0;
10669ca95730Sdrh   }
10679ca95730Sdrh #endif
1068af9ff33aSdrh   return db->lastRowid;
1069af9ff33aSdrh }
1070af9ff33aSdrh 
1071af9ff33aSdrh /*
10729c58b63cSdan ** Set the value returned by the sqlite3_last_insert_rowid() API function.
10739c58b63cSdan */
sqlite3_set_last_insert_rowid(sqlite3 * db,sqlite3_int64 iRowid)10749c58b63cSdan void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
10759c58b63cSdan #ifdef SQLITE_ENABLE_API_ARMOR
10769c58b63cSdan   if( !sqlite3SafetyCheckOk(db) ){
10779c58b63cSdan     (void)SQLITE_MISUSE_BKPT;
10789c58b63cSdan     return;
10799c58b63cSdan   }
10809c58b63cSdan #endif
10819c58b63cSdan   sqlite3_mutex_enter(db->mutex);
10829c58b63cSdan   db->lastRowid = iRowid;
10839c58b63cSdan   sqlite3_mutex_leave(db->mutex);
10849c58b63cSdan }
10859c58b63cSdan 
10869c58b63cSdan /*
108724b03fd0Sdanielk1977 ** Return the number of changes in the most recent call to sqlite3_exec().
1088c8d30ac1Sdrh */
sqlite3_changes64(sqlite3 * db)10892c718873Sdan sqlite3_int64 sqlite3_changes64(sqlite3 *db){
10909ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
10919ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ){
10929ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
10939ca95730Sdrh     return 0;
10949ca95730Sdrh   }
10959ca95730Sdrh #endif
1096c8d30ac1Sdrh   return db->nChange;
1097c8d30ac1Sdrh }
sqlite3_changes(sqlite3 * db)10982c718873Sdan int sqlite3_changes(sqlite3 *db){
10992c718873Sdan   return (int)sqlite3_changes64(db);
11002c718873Sdan }
1101c8d30ac1Sdrh 
1102f146a776Srdc /*
1103b28af71aSdanielk1977 ** Return the number of changes since the database handle was opened.
1104f146a776Srdc */
sqlite3_total_changes64(sqlite3 * db)11052c718873Sdan sqlite3_int64 sqlite3_total_changes64(sqlite3 *db){
11069ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
11079ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ){
11089ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
11099ca95730Sdrh     return 0;
11109ca95730Sdrh   }
11119ca95730Sdrh #endif
1112b28af71aSdanielk1977   return db->nTotalChange;
1113b0c374ffSrdc }
sqlite3_total_changes(sqlite3 * db)11142c718873Sdan int sqlite3_total_changes(sqlite3 *db){
11152c718873Sdan   return (int)sqlite3_total_changes64(db);
11162c718873Sdan }
1117b0c374ffSrdc 
1118c8d30ac1Sdrh /*
1119fd7f0452Sdanielk1977 ** Close all open savepoints. This function only manipulates fields of the
1120fd7f0452Sdanielk1977 ** database handle object, it does not close any savepoints that may be open
1121fd7f0452Sdanielk1977 ** at the b-tree/pager level.
1122fd7f0452Sdanielk1977 */
sqlite3CloseSavepoints(sqlite3 * db)1123fd7f0452Sdanielk1977 void sqlite3CloseSavepoints(sqlite3 *db){
1124fd7f0452Sdanielk1977   while( db->pSavepoint ){
1125fd7f0452Sdanielk1977     Savepoint *pTmp = db->pSavepoint;
1126fd7f0452Sdanielk1977     db->pSavepoint = pTmp->pNext;
1127fd7f0452Sdanielk1977     sqlite3DbFree(db, pTmp);
1128fd7f0452Sdanielk1977   }
1129fd7f0452Sdanielk1977   db->nSavepoint = 0;
1130bd43455cSdanielk1977   db->nStatement = 0;
1131fd7f0452Sdanielk1977   db->isTransactionSavepoint = 0;
1132fd7f0452Sdanielk1977 }
1133fd7f0452Sdanielk1977 
1134fd7f0452Sdanielk1977 /*
1135d2199f0fSdan ** Invoke the destructor function associated with FuncDef p, if any. Except,
1136d2199f0fSdan ** if this is not the last copy of the function, do not invoke it. Multiple
1137d2199f0fSdan ** copies of a single function are created when create_function() is called
1138d2199f0fSdan ** with SQLITE_ANY as the encoding.
1139d2199f0fSdan */
functionDestroy(sqlite3 * db,FuncDef * p)1140d2199f0fSdan static void functionDestroy(sqlite3 *db, FuncDef *p){
1141f9751074Sdrh   FuncDestructor *pDestructor;
1142f9751074Sdrh   assert( (p->funcFlags & SQLITE_FUNC_BUILTIN)==0 );
1143f9751074Sdrh   pDestructor = p->u.pDestructor;
1144d2199f0fSdan   if( pDestructor ){
1145d2199f0fSdan     pDestructor->nRef--;
1146d2199f0fSdan     if( pDestructor->nRef==0 ){
1147d2199f0fSdan       pDestructor->xDestroy(pDestructor->pUserData);
1148d2199f0fSdan       sqlite3DbFree(db, pDestructor);
1149d2199f0fSdan     }
1150d2199f0fSdan   }
1151d2199f0fSdan }
1152d2199f0fSdan 
1153d2199f0fSdan /*
1154bba02a95Sdan ** Disconnect all sqlite3_vtab objects that belong to database connection
1155bba02a95Sdan ** db. This is called when db is being closed.
1156bba02a95Sdan */
disconnectAllVtab(sqlite3 * db)1157bba02a95Sdan static void disconnectAllVtab(sqlite3 *db){
1158bba02a95Sdan #ifndef SQLITE_OMIT_VIRTUALTABLE
1159bba02a95Sdan   int i;
116051be3873Sdrh   HashElem *p;
1161bba02a95Sdan   sqlite3BtreeEnterAll(db);
1162bba02a95Sdan   for(i=0; i<db->nDb; i++){
1163bba02a95Sdan     Schema *pSchema = db->aDb[i].pSchema;
11646389a7b0Smistachkin     if( pSchema ){
1165bba02a95Sdan       for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
1166bba02a95Sdan         Table *pTab = (Table *)sqliteHashData(p);
1167bba02a95Sdan         if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
1168bba02a95Sdan       }
1169bba02a95Sdan     }
1170bba02a95Sdan   }
117151be3873Sdrh   for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
117251be3873Sdrh     Module *pMod = (Module *)sqliteHashData(p);
117351be3873Sdrh     if( pMod->pEpoTab ){
117451be3873Sdrh       sqlite3VtabDisconnect(db, pMod->pEpoTab);
117551be3873Sdrh     }
117651be3873Sdrh   }
1177d88e521fSdan   sqlite3VtabUnlockList(db);
1178bba02a95Sdan   sqlite3BtreeLeaveAll(db);
1179bba02a95Sdan #else
1180bba02a95Sdan   UNUSED_PARAMETER(db);
1181bba02a95Sdan #endif
1182bba02a95Sdan }
1183bba02a95Sdan 
1184bba02a95Sdan /*
1185167cd6abSdrh ** Return TRUE if database connection db has unfinalized prepared
1186167cd6abSdrh ** statements or unfinished sqlite3_backup objects.
1187167cd6abSdrh */
connectionIsBusy(sqlite3 * db)1188167cd6abSdrh static int connectionIsBusy(sqlite3 *db){
1189167cd6abSdrh   int j;
1190167cd6abSdrh   assert( sqlite3_mutex_held(db->mutex) );
1191167cd6abSdrh   if( db->pVdbe ) return 1;
1192167cd6abSdrh   for(j=0; j<db->nDb; j++){
1193167cd6abSdrh     Btree *pBt = db->aDb[j].pBt;
1194167cd6abSdrh     if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
1195167cd6abSdrh   }
1196167cd6abSdrh   return 0;
1197167cd6abSdrh }
1198167cd6abSdrh 
1199167cd6abSdrh /*
120050e5dadfSdrh ** Close an existing SQLite database
120150e5dadfSdrh */
sqlite3Close(sqlite3 * db,int forceZombie)1202167cd6abSdrh static int sqlite3Close(sqlite3 *db, int forceZombie){
12035c4c7787Sdanielk1977   if( !db ){
1204ddb17caeSdrh     /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
1205ddb17caeSdrh     ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
120696d81f99Sdanielk1977     return SQLITE_OK;
12075c4c7787Sdanielk1977   }
12087e8b848aSdrh   if( !sqlite3SafetyCheckSickOrOk(db) ){
1209413c3d36Sdrh     return SQLITE_MISUSE_BKPT;
1210e35ee196Sdanielk1977   }
1211605264d2Sdrh   sqlite3_mutex_enter(db->mutex);
12123d2a529dSdrh   if( db->mTrace & SQLITE_TRACE_CLOSE ){
121308b92086Sdrh     db->trace.xV2(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
12143d2a529dSdrh   }
1215e35ee196Sdanielk1977 
1216bba02a95Sdan   /* Force xDisconnect calls on all virtual tables */
1217bba02a95Sdan   disconnectAllVtab(db);
1218a04a34ffSdanielk1977 
1219bba02a95Sdan   /* If a transaction is open, the disconnectAllVtab() call above
122001256832Sdanielk1977   ** will not have called the xDisconnect() method on any virtual
122101256832Sdanielk1977   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
122201256832Sdanielk1977   ** call will do so. We need to do this before the check for active
122301256832Sdanielk1977   ** SQL statements below, as the v-table implementation may be storing
122401256832Sdanielk1977   ** some prepared statements internally.
122501256832Sdanielk1977   */
122667430817Sdan   sqlite3VtabRollback(db);
122701256832Sdanielk1977 
1228167cd6abSdrh   /* Legacy behavior (sqlite3_close() behavior) is to return
1229167cd6abSdrh   ** SQLITE_BUSY if the connection can not be closed immediately.
1230167cd6abSdrh   */
1231167cd6abSdrh   if( !forceZombie && connectionIsBusy(db) ){
123213f40da3Sdrh     sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
1233167cd6abSdrh        "statements or unfinished backups");
123427641703Sdrh     sqlite3_mutex_leave(db->mutex);
123596d81f99Sdanielk1977     return SQLITE_BUSY;
123696d81f99Sdanielk1977   }
1237e0048400Sdanielk1977 
1238ac455939Sdan #ifdef SQLITE_ENABLE_SQLLOG
1239ac455939Sdan   if( sqlite3GlobalConfig.xSqllog ){
124071ba10d3Sdan     /* Closing the handle. Fourth parameter is passed the value 2. */
124171ba10d3Sdan     sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
1242ac455939Sdan   }
1243ac455939Sdan #endif
1244ac455939Sdan 
1245167cd6abSdrh   /* Convert the connection into a zombie and then close it.
12464245c405Sdrh   */
12475f9de6ecSdrh   db->eOpenState = SQLITE_STATE_ZOMBIE;
12484245c405Sdrh   sqlite3LeaveMutexAndCloseZombie(db);
12494245c405Sdrh   return SQLITE_OK;
125094e92032Sdrh }
125194e92032Sdrh 
1252167cd6abSdrh /*
125399744fa4Sdrh ** Return the transaction state for a single databse, or the maximum
125499744fa4Sdrh ** transaction state over all attached databases if zSchema is null.
125599744fa4Sdrh */
sqlite3_txn_state(sqlite3 * db,const char * zSchema)125699744fa4Sdrh int sqlite3_txn_state(sqlite3 *db, const char *zSchema){
125799744fa4Sdrh   int iDb, nDb;
125899744fa4Sdrh   int iTxn = -1;
125999744fa4Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
126099744fa4Sdrh   if( !sqlite3SafetyCheckOk(db) ){
126199744fa4Sdrh     (void)SQLITE_MISUSE_BKPT;
126299744fa4Sdrh     return -1;
126399744fa4Sdrh   }
126499744fa4Sdrh #endif
126599744fa4Sdrh   sqlite3_mutex_enter(db->mutex);
126699744fa4Sdrh   if( zSchema ){
126799744fa4Sdrh     nDb = iDb = sqlite3FindDbName(db, zSchema);
126899744fa4Sdrh     if( iDb<0 ) nDb--;
126999744fa4Sdrh   }else{
127099744fa4Sdrh     iDb = 0;
127199744fa4Sdrh     nDb = db->nDb-1;
127299744fa4Sdrh   }
127399744fa4Sdrh   for(; iDb<=nDb; iDb++){
127499744fa4Sdrh     Btree *pBt = db->aDb[iDb].pBt;
127599744fa4Sdrh     int x = pBt!=0 ? sqlite3BtreeTxnState(pBt) : SQLITE_TXN_NONE;
127699744fa4Sdrh     if( x>iTxn ) iTxn = x;
127799744fa4Sdrh   }
127899744fa4Sdrh   sqlite3_mutex_leave(db->mutex);
127999744fa4Sdrh   return iTxn;
128099744fa4Sdrh }
128199744fa4Sdrh 
128299744fa4Sdrh /*
1283167cd6abSdrh ** Two variations on the public interface for closing a database
1284167cd6abSdrh ** connection. The sqlite3_close() version returns SQLITE_BUSY and
12851d6d737cSdrh ** leaves the connection open if there are unfinalized prepared
1286167cd6abSdrh ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
1287167cd6abSdrh ** version forces the connection to become a zombie if there are
1288167cd6abSdrh ** unclosed resources, and arranges for deallocation when the last
1289167cd6abSdrh ** prepare statement or sqlite3_backup closes.
1290167cd6abSdrh */
sqlite3_close(sqlite3 * db)1291167cd6abSdrh int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
sqlite3_close_v2(sqlite3 * db)1292167cd6abSdrh int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
1293167cd6abSdrh 
12944245c405Sdrh 
12954245c405Sdrh /*
12964245c405Sdrh ** Close the mutex on database connection db.
12974245c405Sdrh **
12984245c405Sdrh ** Furthermore, if database connection db is a zombie (meaning that there
1299167cd6abSdrh ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
1300167cd6abSdrh ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
1301167cd6abSdrh ** finished, then free all resources.
13024245c405Sdrh */
sqlite3LeaveMutexAndCloseZombie(sqlite3 * db)13034245c405Sdrh void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
13044245c405Sdrh   HashElem *i;                    /* Hash table iterator */
13054245c405Sdrh   int j;
13064245c405Sdrh 
13074245c405Sdrh   /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
1308167cd6abSdrh   ** or if the connection has not yet been closed by sqlite3_close_v2(),
1309167cd6abSdrh   ** then just leave the mutex and return.
13104245c405Sdrh   */
13115f9de6ecSdrh   if( db->eOpenState!=SQLITE_STATE_ZOMBIE || connectionIsBusy(db) ){
13120410302eSdanielk1977     sqlite3_mutex_leave(db->mutex);
13134245c405Sdrh     return;
13140410302eSdanielk1977   }
13150410302eSdanielk1977 
13164245c405Sdrh   /* If we reach this point, it means that the database connection has
13174245c405Sdrh   ** closed all sqlite3_stmt and sqlite3_backup objects and has been
131848864df9Smistachkin   ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
13194245c405Sdrh   ** go ahead and free all resources.
13204245c405Sdrh   */
1321311019beSdanielk1977 
1322617dc860Sdan   /* If a transaction is open, roll it back. This also ensures that if
1323617dc860Sdan   ** any database schemas have been modified by an uncommitted transaction
1324617dc860Sdan   ** they are reset. And that the required b-tree mutex is held to make
1325617dc860Sdan   ** the pager rollback and schema reset an atomic operation. */
1326617dc860Sdan   sqlite3RollbackAll(db, SQLITE_OK);
1327617dc860Sdan 
132870a8ca3cSdrh   /* Free any outstanding Savepoint structures. */
132970a8ca3cSdrh   sqlite3CloseSavepoints(db);
133070a8ca3cSdrh 
13315efb3145Sdrh   /* Close all database connections */
1332001bbcbbSdrh   for(j=0; j<db->nDb; j++){
13334d189ca4Sdrh     struct Db *pDb = &db->aDb[j];
13344d189ca4Sdrh     if( pDb->pBt ){
1335ebdb81ddSdrh       sqlite3BtreeClose(pDb->pBt);
1336ebdb81ddSdrh       pDb->pBt = 0;
1337ebdb81ddSdrh       if( j!=1 ){
1338311019beSdanielk1977         pDb->pSchema = 0;
1339311019beSdanielk1977       }
1340113088ecSdrh     }
1341001bbcbbSdrh   }
13425efb3145Sdrh   /* Clear the TEMP schema separately and last */
13435efb3145Sdrh   if( db->aDb[1].pSchema ){
13445efb3145Sdrh     sqlite3SchemaClear(db->aDb[1].pSchema);
13455efb3145Sdrh   }
13465efb3145Sdrh   sqlite3VtabUnlockList(db);
1347bba02a95Sdan 
13485efb3145Sdrh   /* Free up the array of auxiliary databases */
13495efb3145Sdrh   sqlite3CollapseDatabaseArray(db);
1350bba02a95Sdan   assert( db->nDb<=2 );
1351bba02a95Sdan   assert( db->aDb==db->aDbStatic );
1352404ca075Sdanielk1977 
1353404ca075Sdanielk1977   /* Tell the code in notify.c that the connection no longer holds any
1354404ca075Sdanielk1977   ** locks and does not require any further unlock-notify callbacks.
1355404ca075Sdanielk1977   */
1356404ca075Sdanielk1977   sqlite3ConnectionClosed(db);
1357404ca075Sdanielk1977 
135880738d9cSdrh   for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
135980738d9cSdrh     FuncDef *pNext, *p;
136080738d9cSdrh     p = sqliteHashData(i);
136180738d9cSdrh     do{
1362d2199f0fSdan       functionDestroy(db, p);
136370a8ca3cSdrh       pNext = p->pNext;
136470a8ca3cSdrh       sqlite3DbFree(db, p);
136570a8ca3cSdrh       p = pNext;
136680738d9cSdrh     }while( p );
13678e0a2f90Sdrh   }
136880738d9cSdrh   sqlite3HashClear(&db->aFunc);
1369d8123366Sdanielk1977   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
1370466be56bSdanielk1977     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
1371a9808b31Sdanielk1977     /* Invoke any destructors registered for collation sequence user data. */
1372a9808b31Sdanielk1977     for(j=0; j<3; j++){
1373a9808b31Sdanielk1977       if( pColl[j].xDel ){
1374a9808b31Sdanielk1977         pColl[j].xDel(pColl[j].pUser);
1375a9808b31Sdanielk1977       }
1376a9808b31Sdanielk1977     }
1377633e6d57Sdrh     sqlite3DbFree(db, pColl);
1378466be56bSdanielk1977   }
1379d8123366Sdanielk1977   sqlite3HashClear(&db->aCollSeq);
1380b9bb7c18Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
1381d1ab1ba5Sdanielk1977   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
1382d1ab1ba5Sdanielk1977     Module *pMod = (Module *)sqliteHashData(i);
138351be3873Sdrh     sqlite3VtabEponymousTableClear(db, pMod);
1384cc5979dbSdrh     sqlite3VtabModuleUnref(db, pMod);
1385d1ab1ba5Sdanielk1977   }
1386b9bb7c18Sdrh   sqlite3HashClear(&db->aModule);
1387b9bb7c18Sdrh #endif
1388466be56bSdanielk1977 
138913f40da3Sdrh   sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
1390bfd6cce5Sdanielk1977   sqlite3ValueFree(db->pErr);
1391f1952c5dSdrh   sqlite3CloseExtensions(db);
1392d4530979Sdrh #if SQLITE_USER_AUTHENTICATION
1393d4530979Sdrh   sqlite3_free(db->auth.zAuthUser);
1394d4530979Sdrh   sqlite3_free(db->auth.zAuthPW);
1395d4530979Sdrh #endif
139696d81f99Sdanielk1977 
13975f9de6ecSdrh   db->eOpenState = SQLITE_STATE_ERROR;
1398311019beSdanielk1977 
1399311019beSdanielk1977   /* The temp-database schema is allocated differently from the other schema
1400311019beSdanielk1977   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
1401311019beSdanielk1977   ** So it needs to be freed here. Todo: Why not roll the temp schema into
1402311019beSdanielk1977   ** the same sqliteMalloc() as the one that allocates the database
1403311019beSdanielk1977   ** structure?
1404311019beSdanielk1977   */
1405633e6d57Sdrh   sqlite3DbFree(db, db->aDb[1].pSchema);
14061bbfc674Sdrh   if( db->xAutovacDestr ){
14071bbfc674Sdrh     db->xAutovacDestr(db->pAutovacPagesArg);
14081bbfc674Sdrh   }
1409605264d2Sdrh   sqlite3_mutex_leave(db->mutex);
14105f9de6ecSdrh   db->eOpenState = SQLITE_STATE_CLOSED;
1411605264d2Sdrh   sqlite3_mutex_free(db->mutex);
141252fb8e19Sdrh   assert( sqlite3LookasideUsed(db,0)==0 );
1413e9d1c720Sdrh   if( db->lookaside.bMalloced ){
1414633e6d57Sdrh     sqlite3_free(db->lookaside.pStart);
1415e9d1c720Sdrh   }
141617435752Sdrh   sqlite3_free(db);
141775897234Sdrh }
141875897234Sdrh 
141975897234Sdrh /*
14200f198a74Sdrh ** Rollback all database files.  If tripCode is not SQLITE_OK, then
142147b7fc78Sdrh ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
14220f198a74Sdrh ** breaker") and made to return tripCode if there are any further
142347b7fc78Sdrh ** attempts to use that cursor.  Read cursors remain open and valid
142447b7fc78Sdrh ** but are "saved" in case the table pages are moved around.
1425001bbcbbSdrh */
sqlite3RollbackAll(sqlite3 * db,int tripCode)14260f198a74Sdrh void sqlite3RollbackAll(sqlite3 *db, int tripCode){
1427001bbcbbSdrh   int i;
1428f3f06bb3Sdanielk1977   int inTrans = 0;
142947b7fc78Sdrh   int schemaChange;
1430e30f4426Sdrh   assert( sqlite3_mutex_held(db->mutex) );
14312d1d86fbSdanielk1977   sqlite3BeginBenignMalloc();
1432617dc860Sdan 
1433617dc860Sdan   /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
1434617dc860Sdan   ** This is important in case the transaction being rolled back has
1435617dc860Sdan   ** modified the database schema. If the b-tree mutexes are not taken
1436617dc860Sdan   ** here, then another shared-cache connection might sneak in between
1437617dc860Sdan   ** the database rollback and schema reset, which can cause false
1438617dc860Sdan   ** corruption reports in some cases.  */
1439cd7b91a7Sdan   sqlite3BtreeEnterAll(db);
14408257aa8dSdrh   schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
1441617dc860Sdan 
1442001bbcbbSdrh   for(i=0; i<db->nDb; i++){
14430f198a74Sdrh     Btree *p = db->aDb[i].pBt;
14440f198a74Sdrh     if( p ){
144599744fa4Sdrh       if( sqlite3BtreeTxnState(p)==SQLITE_TXN_WRITE ){
1446f3f06bb3Sdanielk1977         inTrans = 1;
1447f3f06bb3Sdanielk1977       }
144847b7fc78Sdrh       sqlite3BtreeRollback(p, tripCode, !schemaChange);
1449001bbcbbSdrh     }
1450001bbcbbSdrh   }
1451a298e90dSdanielk1977   sqlite3VtabRollback(db);
14522d1d86fbSdanielk1977   sqlite3EndBenignMalloc();
1453ae72d982Sdanielk1977 
14547f32dc94Sdrh   if( schemaChange ){
1455ba968dbfSdrh     sqlite3ExpirePreparedStatements(db, 0);
145681028a45Sdrh     sqlite3ResetAllSchemasOfConnection(db);
1457001bbcbbSdrh   }
1458cd7b91a7Sdan   sqlite3BtreeLeaveAll(db);
1459001bbcbbSdrh 
14601da40a38Sdan   /* Any deferred constraint violations have now been resolved. */
14611da40a38Sdan   db->nDeferredCons = 0;
1462648e2643Sdrh   db->nDeferredImmCons = 0;
146346c425b4Sdrh   db->flags &= ~(u64)(SQLITE_DeferFKs|SQLITE_CorruptRdOnly);
14641da40a38Sdan 
146571fd80bfSdanielk1977   /* If one has been configured, invoke the rollback-hook callback */
1466f3f06bb3Sdanielk1977   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
146771fd80bfSdanielk1977     db->xRollbackCallback(db->pRollbackArg);
146871fd80bfSdanielk1977   }
146971fd80bfSdanielk1977 }
147071fd80bfSdanielk1977 
1471001bbcbbSdrh /*
1472f2c1c99fSmistachkin ** Return a static string containing the name corresponding to the error code
1473f2c1c99fSmistachkin ** specified in the argument.
1474f2c1c99fSmistachkin */
14755824d44bSmistachkin #if defined(SQLITE_NEED_ERR_NAME)
sqlite3ErrName(int rc)1476f2c1c99fSmistachkin const char *sqlite3ErrName(int rc){
1477f2c1c99fSmistachkin   const char *zName = 0;
147810269dc6Smistachkin   int i, origRc = rc;
1479f2c1c99fSmistachkin   for(i=0; i<2 && zName==0; i++, rc &= 0xff){
1480f2c1c99fSmistachkin     switch( rc ){
1481f2c1c99fSmistachkin       case SQLITE_OK:                 zName = "SQLITE_OK";                break;
1482f2c1c99fSmistachkin       case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
14838d4b7a3fSdan       case SQLITE_ERROR_SNAPSHOT:     zName = "SQLITE_ERROR_SNAPSHOT";    break;
1484f2c1c99fSmistachkin       case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
1485f2c1c99fSmistachkin       case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
1486f2c1c99fSmistachkin       case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
1487e84d8d32Smistachkin       case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
1488f2c1c99fSmistachkin       case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
1489e84d8d32Smistachkin       case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
1490f73819afSdan       case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
1491f2c1c99fSmistachkin       case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
1492f2c1c99fSmistachkin       case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
1493f2c1c99fSmistachkin       case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
1494f2c1c99fSmistachkin       case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
1495e84d8d32Smistachkin       case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
14967e45e3a5Sdrh       case SQLITE_READONLY_CANTINIT:  zName = "SQLITE_READONLY_CANTINIT"; break;
1497e84d8d32Smistachkin       case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
1498091a81b9Smistachkin       case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
1499a688ca5eSdan       case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break;
1500f2c1c99fSmistachkin       case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
1501f2c1c99fSmistachkin       case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
1502e84d8d32Smistachkin       case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
1503e84d8d32Smistachkin       case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
1504e84d8d32Smistachkin       case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
1505e84d8d32Smistachkin       case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
1506e84d8d32Smistachkin       case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
1507e84d8d32Smistachkin       case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
1508e84d8d32Smistachkin       case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
1509e84d8d32Smistachkin       case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
1510e84d8d32Smistachkin       case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
1511e84d8d32Smistachkin       case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
1512e84d8d32Smistachkin       case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
1513e84d8d32Smistachkin       case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
1514e84d8d32Smistachkin       case SQLITE_IOERR_CHECKRESERVEDLOCK:
1515e84d8d32Smistachkin                                 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
1516e84d8d32Smistachkin       case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
1517e84d8d32Smistachkin       case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
1518e84d8d32Smistachkin       case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
1519e84d8d32Smistachkin       case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
1520e84d8d32Smistachkin       case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
1521e84d8d32Smistachkin       case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
1522e84d8d32Smistachkin       case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
1523e84d8d32Smistachkin       case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
1524e84d8d32Smistachkin       case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
1525e84d8d32Smistachkin       case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
152616a2e7a0Smistachkin       case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
1527d95a3d35Smistachkin       case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
1528f2c1c99fSmistachkin       case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
1529e84d8d32Smistachkin       case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
1530f2c1c99fSmistachkin       case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
1531f2c1c99fSmistachkin       case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
1532f2c1c99fSmistachkin       case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
1533e84d8d32Smistachkin       case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
1534e84d8d32Smistachkin       case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
1535e84d8d32Smistachkin       case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
1536d95a3d35Smistachkin       case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
15373c161e07Smistachkin       case SQLITE_CANTOPEN_SYMLINK:   zName = "SQLITE_CANTOPEN_SYMLINK";  break;
1538f2c1c99fSmistachkin       case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
1539f2c1c99fSmistachkin       case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
1540f2c1c99fSmistachkin       case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
1541f2c1c99fSmistachkin       case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
1542f2c1c99fSmistachkin       case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
1543f2c1c99fSmistachkin       case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
1544f2c1c99fSmistachkin       case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
1545f2c1c99fSmistachkin       case SQLITE_CONSTRAINT_FOREIGNKEY:
1546f2c1c99fSmistachkin                                 zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
1547f2c1c99fSmistachkin       case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
1548f2c1c99fSmistachkin       case SQLITE_CONSTRAINT_PRIMARYKEY:
1549f2c1c99fSmistachkin                                 zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
1550f2c1c99fSmistachkin       case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
1551f2c1c99fSmistachkin       case SQLITE_CONSTRAINT_COMMITHOOK:
1552f2c1c99fSmistachkin                                 zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
1553f2c1c99fSmistachkin       case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
1554f2c1c99fSmistachkin       case SQLITE_CONSTRAINT_FUNCTION:
1555f2c1c99fSmistachkin                                 zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
1556f9c8ce3cSdrh       case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
1557f2c1c99fSmistachkin       case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
1558f2c1c99fSmistachkin       case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
1559f2c1c99fSmistachkin       case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
1560f2c1c99fSmistachkin       case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
1561f2c1c99fSmistachkin       case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
1562f2c1c99fSmistachkin       case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
1563f2c1c99fSmistachkin       case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
1564f2c1c99fSmistachkin       case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
1565f2c1c99fSmistachkin       case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
1566e84d8d32Smistachkin       case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
1567e84d8d32Smistachkin       case SQLITE_NOTICE_RECOVER_ROLLBACK:
1568e84d8d32Smistachkin                                 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
1569f2c1c99fSmistachkin       case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
15708d56e205Sdrh       case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
1571f2c1c99fSmistachkin       case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
1572f2c1c99fSmistachkin     }
1573f2c1c99fSmistachkin   }
157410269dc6Smistachkin   if( zName==0 ){
157510269dc6Smistachkin     static char zBuf[50];
157610269dc6Smistachkin     sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
157710269dc6Smistachkin     zName = zBuf;
157810269dc6Smistachkin   }
1579f2c1c99fSmistachkin   return zName;
1580f2c1c99fSmistachkin }
158110269dc6Smistachkin #endif
1582f2c1c99fSmistachkin 
1583f2c1c99fSmistachkin /*
1584c22bd47dSdrh ** Return a static string that describes the kind of error specified in the
1585c22bd47dSdrh ** argument.
1586247be43dSdrh */
sqlite3ErrStr(int rc)1587f20b21c8Sdanielk1977 const char *sqlite3ErrStr(int rc){
158851c7d864Sdrh   static const char* const aMsg[] = {
158951c7d864Sdrh     /* SQLITE_OK          */ "not an error",
1590a690ff36Sdrh     /* SQLITE_ERROR       */ "SQL logic error",
159151c7d864Sdrh     /* SQLITE_INTERNAL    */ 0,
159251c7d864Sdrh     /* SQLITE_PERM        */ "access permission denied",
1593ff4fa772Sdrh     /* SQLITE_ABORT       */ "query aborted",
159451c7d864Sdrh     /* SQLITE_BUSY        */ "database is locked",
159551c7d864Sdrh     /* SQLITE_LOCKED      */ "database table is locked",
159651c7d864Sdrh     /* SQLITE_NOMEM       */ "out of memory",
159751c7d864Sdrh     /* SQLITE_READONLY    */ "attempt to write a readonly database",
159851c7d864Sdrh     /* SQLITE_INTERRUPT   */ "interrupted",
159951c7d864Sdrh     /* SQLITE_IOERR       */ "disk I/O error",
160051c7d864Sdrh     /* SQLITE_CORRUPT     */ "database disk image is malformed",
16010b52b7d0Sdrh     /* SQLITE_NOTFOUND    */ "unknown operation",
160251c7d864Sdrh     /* SQLITE_FULL        */ "database or disk is full",
160351c7d864Sdrh     /* SQLITE_CANTOPEN    */ "unable to open database file",
16040dc7b74fSdan     /* SQLITE_PROTOCOL    */ "locking protocol",
1605e75be1aeSdrh     /* SQLITE_EMPTY       */ 0,
160651c7d864Sdrh     /* SQLITE_SCHEMA      */ "database schema has changed",
16074c8555fdSdrh     /* SQLITE_TOOBIG      */ "string or blob too big",
160851c7d864Sdrh     /* SQLITE_CONSTRAINT  */ "constraint failed",
160951c7d864Sdrh     /* SQLITE_MISMATCH    */ "datatype mismatch",
1610ff4fa772Sdrh     /* SQLITE_MISUSE      */ "bad parameter or other API misuse",
1611e75be1aeSdrh #ifdef SQLITE_DISABLE_LFS
161251c7d864Sdrh     /* SQLITE_NOLFS       */ "large file support is disabled",
1613e75be1aeSdrh #else
1614e75be1aeSdrh     /* SQLITE_NOLFS       */ 0,
1615e75be1aeSdrh #endif
161651c7d864Sdrh     /* SQLITE_AUTH        */ "authorization denied",
1617e75be1aeSdrh     /* SQLITE_FORMAT      */ 0,
1618ff4fa772Sdrh     /* SQLITE_RANGE       */ "column index out of range",
1619ff4fa772Sdrh     /* SQLITE_NOTADB      */ "file is not a database",
16202a86110aSmistachkin     /* SQLITE_NOTICE      */ "notification message",
16212a86110aSmistachkin     /* SQLITE_WARNING     */ "warning message",
162251c7d864Sdrh   };
162321021a5cSdrh   const char *zErr = "unknown error";
162421021a5cSdrh   switch( rc ){
162521021a5cSdrh     case SQLITE_ABORT_ROLLBACK: {
162621021a5cSdrh       zErr = "abort due to ROLLBACK";
162721021a5cSdrh       break;
1628247be43dSdrh     }
16292a86110aSmistachkin     case SQLITE_ROW: {
16302a86110aSmistachkin       zErr = "another row available";
16312a86110aSmistachkin       break;
16322a86110aSmistachkin     }
16332a86110aSmistachkin     case SQLITE_DONE: {
16342a86110aSmistachkin       zErr = "no more rows available";
16352a86110aSmistachkin       break;
16362a86110aSmistachkin     }
163721021a5cSdrh     default: {
163821021a5cSdrh       rc &= 0xff;
163921021a5cSdrh       if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
164021021a5cSdrh         zErr = aMsg[rc];
164121021a5cSdrh       }
164221021a5cSdrh       break;
164321021a5cSdrh     }
164421021a5cSdrh   }
164521021a5cSdrh   return zErr;
1646247be43dSdrh }
1647247be43dSdrh 
1648247be43dSdrh /*
16492dfbbcafSdrh ** This routine implements a busy callback that sleeps and tries
16502dfbbcafSdrh ** again until a timeout value is reached.  The timeout value is
16512dfbbcafSdrh ** an integer number of milliseconds passed in as the first
16522dfbbcafSdrh ** argument.
1653f0119b2eSdrh **
1654f0119b2eSdrh ** Return non-zero to retry the lock.  Return zero to stop trying
1655f0119b2eSdrh ** and cause SQLite to return SQLITE_BUSY.
16562dfbbcafSdrh */
sqliteDefaultBusyCallback(void * ptr,int count)1657daffd0e5Sdrh static int sqliteDefaultBusyCallback(
165897903fefSdrh   void *ptr,               /* Database connection */
16598714de97Sdan   int count                /* Number of times table has been busy */
16602dfbbcafSdrh ){
16610ede9ebeSdrh #if SQLITE_OS_WIN || HAVE_USLEEP
1662f0119b2eSdrh   /* This case is for systems that have support for sleeping for fractions of
1663f0119b2eSdrh   ** a second.  Examples:  All windows systems, unix systems with usleep() */
1664ee570fa4Sdrh   static const u8 delays[] =
1665ee570fa4Sdrh      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
1666ee570fa4Sdrh   static const u8 totals[] =
1667ee570fa4Sdrh      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
1668fcd71b60Sdrh # define NDELAY ArraySize(delays)
1669b4b47411Sdanielk1977   sqlite3 *db = (sqlite3 *)ptr;
1670f0119b2eSdrh   int tmout = db->busyTimeout;
167197903fefSdrh   int delay, prior;
16722dfbbcafSdrh 
1673ee570fa4Sdrh   assert( count>=0 );
1674ee570fa4Sdrh   if( count < NDELAY ){
1675ee570fa4Sdrh     delay = delays[count];
1676ee570fa4Sdrh     prior = totals[count];
1677d1bec47aSdrh   }else{
1678d1bec47aSdrh     delay = delays[NDELAY-1];
167968cb6192Sdrh     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
16802dfbbcafSdrh   }
1681f0119b2eSdrh   if( prior + delay > tmout ){
1682f0119b2eSdrh     delay = tmout - prior;
16832dfbbcafSdrh     if( delay<=0 ) return 0;
16842dfbbcafSdrh   }
16852a6bdf6dSdanielk1977   sqlite3OsSleep(db->pVfs, delay*1000);
16862dfbbcafSdrh   return 1;
16872dfbbcafSdrh #else
1688f0119b2eSdrh   /* This case for unix systems that lack usleep() support.  Sleeping
1689f0119b2eSdrh   ** must be done in increments of whole seconds */
1690482ea18fSdrh   sqlite3 *db = (sqlite3 *)ptr;
1691f0119b2eSdrh   int tmout = ((sqlite3 *)ptr)->busyTimeout;
1692f0119b2eSdrh   if( (count+1)*1000 > tmout ){
16932dfbbcafSdrh     return 0;
16942dfbbcafSdrh   }
1695482ea18fSdrh   sqlite3OsSleep(db->pVfs, 1000000);
16962dfbbcafSdrh   return 1;
16972dfbbcafSdrh #endif
16982dfbbcafSdrh }
16992dfbbcafSdrh 
17002dfbbcafSdrh /*
1701a4afb65cSdrh ** Invoke the given busy handler.
1702a4afb65cSdrh **
1703f0119b2eSdrh ** This routine is called when an operation failed to acquire a
1704f0119b2eSdrh ** lock on VFS file pFile.
1705f0119b2eSdrh **
1706a4afb65cSdrh ** If this routine returns non-zero, the lock is retried.  If it
1707a4afb65cSdrh ** returns 0, the operation aborts with an SQLITE_BUSY error.
1708a4afb65cSdrh */
sqlite3InvokeBusyHandler(BusyHandler * p)1709783e159eSdrh int sqlite3InvokeBusyHandler(BusyHandler *p){
1710a4afb65cSdrh   int rc;
171180262896Sdrh   if( p->xBusyHandler==0 || p->nBusy<0 ) return 0;
171280262896Sdrh   rc = p->xBusyHandler(p->pBusyArg, p->nBusy);
1713a4afb65cSdrh   if( rc==0 ){
1714a4afb65cSdrh     p->nBusy = -1;
1715a4afb65cSdrh   }else{
1716a4afb65cSdrh     p->nBusy++;
1717a4afb65cSdrh   }
1718a4afb65cSdrh   return rc;
1719a4afb65cSdrh }
1720a4afb65cSdrh 
1721a4afb65cSdrh /*
17222dfbbcafSdrh ** This routine sets the busy callback for an Sqlite database to the
17232dfbbcafSdrh ** given callback function with the given argument.
17242dfbbcafSdrh */
sqlite3_busy_handler(sqlite3 * db,int (* xBusy)(void *,int),void * pArg)1725f9d64d2cSdanielk1977 int sqlite3_busy_handler(
1726f9d64d2cSdanielk1977   sqlite3 *db,
17272a764eb0Sdanielk1977   int (*xBusy)(void*,int),
17282dfbbcafSdrh   void *pArg
17292dfbbcafSdrh ){
17309ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
173196c707a3Sdrh   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
17329ca95730Sdrh #endif
1733e30f4426Sdrh   sqlite3_mutex_enter(db->mutex);
173480262896Sdrh   db->busyHandler.xBusyHandler = xBusy;
173580262896Sdrh   db->busyHandler.pBusyArg = pArg;
1736a4afb65cSdrh   db->busyHandler.nBusy = 0;
1737c0c7b5eeSdrh   db->busyTimeout = 0;
1738e30f4426Sdrh   sqlite3_mutex_leave(db->mutex);
1739f9d64d2cSdanielk1977   return SQLITE_OK;
17402dfbbcafSdrh }
17412dfbbcafSdrh 
1742348bb5d6Sdanielk1977 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1743348bb5d6Sdanielk1977 /*
1744348bb5d6Sdanielk1977 ** This routine sets the progress callback for an Sqlite database to the
1745348bb5d6Sdanielk1977 ** given callback function with the given argument. The progress callback will
1746348bb5d6Sdanielk1977 ** be invoked every nOps opcodes.
1747348bb5d6Sdanielk1977 */
sqlite3_progress_handler(sqlite3 * db,int nOps,int (* xProgress)(void *),void * pArg)174824b03fd0Sdanielk1977 void sqlite3_progress_handler(
17499bb575fdSdrh   sqlite3 *db,
1750348bb5d6Sdanielk1977   int nOps,
1751348bb5d6Sdanielk1977   int (*xProgress)(void*),
1752348bb5d6Sdanielk1977   void *pArg
1753348bb5d6Sdanielk1977 ){
17549ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
17559ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ){
17569ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
17579ca95730Sdrh     return;
17589ca95730Sdrh   }
17599ca95730Sdrh #endif
1760e30f4426Sdrh   sqlite3_mutex_enter(db->mutex);
1761348bb5d6Sdanielk1977   if( nOps>0 ){
1762348bb5d6Sdanielk1977     db->xProgress = xProgress;
17638f8c65f7Sdrh     db->nProgressOps = (unsigned)nOps;
1764348bb5d6Sdanielk1977     db->pProgressArg = pArg;
1765348bb5d6Sdanielk1977   }else{
1766348bb5d6Sdanielk1977     db->xProgress = 0;
1767348bb5d6Sdanielk1977     db->nProgressOps = 0;
1768348bb5d6Sdanielk1977     db->pProgressArg = 0;
1769348bb5d6Sdanielk1977   }
1770e30f4426Sdrh   sqlite3_mutex_leave(db->mutex);
1771348bb5d6Sdanielk1977 }
1772348bb5d6Sdanielk1977 #endif
1773348bb5d6Sdanielk1977 
1774348bb5d6Sdanielk1977 
17752dfbbcafSdrh /*
17762dfbbcafSdrh ** This routine installs a default busy handler that waits for the
17772dfbbcafSdrh ** specified number of milliseconds before returning 0.
17782dfbbcafSdrh */
sqlite3_busy_timeout(sqlite3 * db,int ms)1779f9d64d2cSdanielk1977 int sqlite3_busy_timeout(sqlite3 *db, int ms){
17809ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
17819ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
17829ca95730Sdrh #endif
17832dfbbcafSdrh   if( ms>0 ){
1784f0119b2eSdrh     sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
1785f0119b2eSdrh                              (void*)db);
1786c0c7b5eeSdrh     db->busyTimeout = ms;
17872dfbbcafSdrh   }else{
178824b03fd0Sdanielk1977     sqlite3_busy_handler(db, 0, 0);
17892dfbbcafSdrh   }
1790f9d64d2cSdanielk1977   return SQLITE_OK;
17912dfbbcafSdrh }
17924c504391Sdrh 
17934c504391Sdrh /*
17944c504391Sdrh ** Cause any pending operation to stop at its earliest opportunity.
17954c504391Sdrh */
sqlite3_interrupt(sqlite3 * db)17969bb575fdSdrh void sqlite3_interrupt(sqlite3 *db){
17979ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
17985f9de6ecSdrh   if( !sqlite3SafetyCheckOk(db) && (db==0 || db->eOpenState!=SQLITE_STATE_ZOMBIE) ){
17999ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
18009ca95730Sdrh     return;
18019ca95730Sdrh   }
18029ca95730Sdrh #endif
1803892edb69Sdan   AtomicStore(&db->u1.isInterrupted, 1);
18044c504391Sdrh }
1805fa86c412Sdrh 
1806fa86c412Sdrh 
1807fa86c412Sdrh /*
1808771151b6Sdanielk1977 ** This function is exactly the same as sqlite3_create_function(), except
1809771151b6Sdanielk1977 ** that it is designed to be called by internal code. The difference is
1810771151b6Sdanielk1977 ** that if a malloc() fails in sqlite3_create_function(), an error code
1811771151b6Sdanielk1977 ** is returned and the mallocFailed flag cleared.
1812fa86c412Sdrh */
sqlite3CreateFunc(sqlite3 * db,const char * zFunctionName,int nArg,int enc,void * pUserData,void (* xSFunc)(sqlite3_context *,int,sqlite3_value **),void (* xStep)(sqlite3_context *,int,sqlite3_value **),void (* xFinal)(sqlite3_context *),void (* xValue)(sqlite3_context *),void (* xInverse)(sqlite3_context *,int,sqlite3_value **),FuncDestructor * pDestructor)1813771151b6Sdanielk1977 int sqlite3CreateFunc(
18146590493dSdanielk1977   sqlite3 *db,
18156590493dSdanielk1977   const char *zFunctionName,
18166590493dSdanielk1977   int nArg,
1817d8123366Sdanielk1977   int enc,
18186590493dSdanielk1977   void *pUserData,
18192d80151fSdrh   void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
18206590493dSdanielk1977   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
1821d2199f0fSdan   void (*xFinal)(sqlite3_context*),
1822660af939Sdan   void (*xValue)(sqlite3_context*),
1823660af939Sdan   void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
1824d2199f0fSdan   FuncDestructor *pDestructor
18258e0a2f90Sdrh ){
18260bce8354Sdrh   FuncDef *p;
18274a8ee3dfSdrh   int extraFlags;
18286590493dSdanielk1977 
1829e30f4426Sdrh   assert( sqlite3_mutex_held(db->mutex) );
18301e80ace4Sdrh   assert( xValue==0 || xSFunc==0 );
18311e80ace4Sdrh   if( zFunctionName==0                /* Must have a valid name */
18321e80ace4Sdrh    || (xSFunc!=0 && xFinal!=0)        /* Not both xSFunc and xFinal */
18331e80ace4Sdrh    || ((xFinal==0)!=(xStep==0))       /* Both or neither of xFinal and xStep */
18341e80ace4Sdrh    || ((xValue==0)!=(xInverse==0))    /* Both or neither of xValue, xInverse */
18351e80ace4Sdrh    || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG)
18367d4c94bcSdrh    || (255<sqlite3Strlen30(zFunctionName))
18371e80ace4Sdrh   ){
1838413c3d36Sdrh     return SQLITE_MISUSE_BKPT;
18396590493dSdanielk1977   }
18406590493dSdanielk1977 
18414a8ee3dfSdrh   assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
184242d2fce7Sdrh   assert( SQLITE_FUNC_DIRECT==SQLITE_DIRECTONLY );
1843c4ad8499Sdrh   extraFlags = enc &  (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY|
1844c4ad8499Sdrh                        SQLITE_SUBTYPE|SQLITE_INNOCUOUS);
18454a8ee3dfSdrh   enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
18464a8ee3dfSdrh 
18474be621e1Sdrh   /* The SQLITE_INNOCUOUS flag is the same bit as SQLITE_FUNC_UNSAFE.  But
18484be621e1Sdrh   ** the meaning is inverted.  So flip the bit. */
18494be621e1Sdrh   assert( SQLITE_FUNC_UNSAFE==SQLITE_INNOCUOUS );
18504be621e1Sdrh   extraFlags ^= SQLITE_FUNC_UNSAFE;
18514be621e1Sdrh 
18524be621e1Sdrh 
185393758c8dSdanielk1977 #ifndef SQLITE_OMIT_UTF16
1854d8123366Sdanielk1977   /* If SQLITE_UTF16 is specified as the encoding type, transform this
1855d8123366Sdanielk1977   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
1856d8123366Sdanielk1977   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
1857d8123366Sdanielk1977   **
1858d8123366Sdanielk1977   ** If SQLITE_ANY is specified, add three versions of the function
1859d8123366Sdanielk1977   ** to the hash table.
1860d8123366Sdanielk1977   */
186162f560f8Sdrh   switch( enc ){
186262f560f8Sdrh     case SQLITE_UTF16:
1863d8123366Sdanielk1977       enc = SQLITE_UTF16NATIVE;
186462f560f8Sdrh       break;
186562f560f8Sdrh     case SQLITE_ANY: {
1866d8123366Sdanielk1977       int rc;
186779d5bc80Sdrh       rc = sqlite3CreateFunc(db, zFunctionName, nArg,
186879d5bc80Sdrh            (SQLITE_UTF8|extraFlags)^SQLITE_FUNC_UNSAFE,
1869660af939Sdan            pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
1870e30f4426Sdrh       if( rc==SQLITE_OK ){
187179d5bc80Sdrh         rc = sqlite3CreateFunc(db, zFunctionName, nArg,
187279d5bc80Sdrh              (SQLITE_UTF16LE|extraFlags)^SQLITE_FUNC_UNSAFE,
1873660af939Sdan              pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
1874e30f4426Sdrh       }
1875e30f4426Sdrh       if( rc!=SQLITE_OK ){
1876e30f4426Sdrh         return rc;
1877e30f4426Sdrh       }
1878d8123366Sdanielk1977       enc = SQLITE_UTF16BE;
187962f560f8Sdrh       break;
188062f560f8Sdrh     }
188162f560f8Sdrh     case SQLITE_UTF8:
188262f560f8Sdrh     case SQLITE_UTF16LE:
188362f560f8Sdrh     case SQLITE_UTF16BE:
188462f560f8Sdrh       break;
188562f560f8Sdrh     default:
188662f560f8Sdrh       enc = SQLITE_UTF8;
188762f560f8Sdrh       break;
1888d8123366Sdanielk1977   }
188993758c8dSdanielk1977 #else
189093758c8dSdanielk1977   enc = SQLITE_UTF8;
189193758c8dSdanielk1977 #endif
1892d8123366Sdanielk1977 
18939636c4e1Sdanielk1977   /* Check if an existing function is being overridden or deleted. If so,
18949636c4e1Sdanielk1977   ** and there are active VMs, then return SQLITE_BUSY. If a function
18959636c4e1Sdanielk1977   ** is being overridden/deleted but there are no active VMs, allow the
18969636c4e1Sdanielk1977   ** operation to continue but invalidate all precompiled statements.
18979636c4e1Sdanielk1977   */
189880738d9cSdrh   p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
1899c7bf5716Sdrh   if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){
19004f7d3a5fSdrh     if( db->nVdbeActive ){
190113f40da3Sdrh       sqlite3ErrorWithMsg(db, SQLITE_BUSY,
1902b309becdSdrh         "unable to delete/modify user-function due to active statements");
190317435752Sdrh       assert( !db->mallocFailed );
19049636c4e1Sdanielk1977       return SQLITE_BUSY;
19059636c4e1Sdanielk1977     }else{
1906ba968dbfSdrh       sqlite3ExpirePreparedStatements(db, 0);
19079636c4e1Sdanielk1977     }
1908ba39ca40Sdrh   }else if( xSFunc==0 && xFinal==0 ){
1909ba39ca40Sdrh     /* Trying to delete a function that does not exist.  This is a no-op.
1910ba39ca40Sdrh     ** https://sqlite.org/forum/forumpost/726219164b */
1911ba39ca40Sdrh     return SQLITE_OK;
19129636c4e1Sdanielk1977   }
19139636c4e1Sdanielk1977 
191480738d9cSdrh   p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
1915fa18beceSdanielk1977   assert(p || db->mallocFailed);
1916fa18beceSdanielk1977   if( !p ){
1917fad3039cSmistachkin     return SQLITE_NOMEM_BKPT;
1918fa18beceSdanielk1977   }
1919d2199f0fSdan 
1920d2199f0fSdan   /* If an older version of the function with a configured destructor is
1921d2199f0fSdan   ** being replaced invoke the destructor function here. */
1922d2199f0fSdan   functionDestroy(db, p);
1923d2199f0fSdan 
1924d2199f0fSdan   if( pDestructor ){
1925d2199f0fSdan     pDestructor->nRef++;
1926d2199f0fSdan   }
192780738d9cSdrh   p->u.pDestructor = pDestructor;
19284a8ee3dfSdrh   p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
19294a8ee3dfSdrh   testcase( p->funcFlags & SQLITE_DETERMINISTIC );
193042d2fce7Sdrh   testcase( p->funcFlags & SQLITE_DIRECTONLY );
19312d80151fSdrh   p->xSFunc = xSFunc ? xSFunc : xStep;
19326590493dSdanielk1977   p->xFinalize = xFinal;
1933660af939Sdan   p->xValue = xValue;
1934660af939Sdan   p->xInverse = xInverse;
19351350b030Sdrh   p->pUserData = pUserData;
19361bd10f8aSdrh   p->nArg = (u16)nArg;
19376590493dSdanielk1977   return SQLITE_OK;
19386590493dSdanielk1977 }
1939771151b6Sdanielk1977 
1940771151b6Sdanielk1977 /*
1941660af939Sdan ** Worker function used by utf-8 APIs that create new functions:
1942660af939Sdan **
1943660af939Sdan **    sqlite3_create_function()
1944660af939Sdan **    sqlite3_create_function_v2()
1945660af939Sdan **    sqlite3_create_window_function()
1946771151b6Sdanielk1977 */
createFunctionApi(sqlite3 * db,const char * zFunc,int nArg,int enc,void * p,void (* xSFunc)(sqlite3_context *,int,sqlite3_value **),void (* xStep)(sqlite3_context *,int,sqlite3_value **),void (* xFinal)(sqlite3_context *),void (* xValue)(sqlite3_context *),void (* xInverse)(sqlite3_context *,int,sqlite3_value **),void (* xDestroy)(void *))1947660af939Sdan static int createFunctionApi(
1948d2199f0fSdan   sqlite3 *db,
1949d2199f0fSdan   const char *zFunc,
1950d2199f0fSdan   int nArg,
1951d2199f0fSdan   int enc,
1952d2199f0fSdan   void *p,
19532d80151fSdrh   void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
1954d2199f0fSdan   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
1955d2199f0fSdan   void (*xFinal)(sqlite3_context*),
1956660af939Sdan   void (*xValue)(sqlite3_context*),
1957660af939Sdan   void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
1958d2199f0fSdan   void(*xDestroy)(void*)
1959d2199f0fSdan ){
1960bd2aaf9aSshaneh   int rc = SQLITE_ERROR;
1961d2199f0fSdan   FuncDestructor *pArg = 0;
19629ca95730Sdrh 
19639ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
19649ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ){
19659ca95730Sdrh     return SQLITE_MISUSE_BKPT;
19669ca95730Sdrh   }
19679ca95730Sdrh #endif
1968d2199f0fSdan   sqlite3_mutex_enter(db->mutex);
1969d2199f0fSdan   if( xDestroy ){
197092011847Sdrh     pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor));
19719508daa9Sdan     if( !pArg ){
197292011847Sdrh       sqlite3OomFault(db);
19739508daa9Sdan       xDestroy(p);
19749508daa9Sdan       goto out;
19759508daa9Sdan     }
197692011847Sdrh     pArg->nRef = 0;
1977d2199f0fSdan     pArg->xDestroy = xDestroy;
1978d2199f0fSdan     pArg->pUserData = p;
1979d2199f0fSdan   }
1980660af939Sdan   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p,
1981660af939Sdan       xSFunc, xStep, xFinal, xValue, xInverse, pArg
1982660af939Sdan   );
1983d2199f0fSdan   if( pArg && pArg->nRef==0 ){
19848eed5847Sdan     assert( rc!=SQLITE_OK || (xStep==0 && xFinal==0) );
19859508daa9Sdan     xDestroy(p);
198692011847Sdrh     sqlite3_free(pArg);
1987d2199f0fSdan   }
1988d2199f0fSdan 
1989d2199f0fSdan  out:
1990e30f4426Sdrh   rc = sqlite3ApiExit(db, rc);
1991e30f4426Sdrh   sqlite3_mutex_leave(db->mutex);
1992e30f4426Sdrh   return rc;
1993771151b6Sdanielk1977 }
1994771151b6Sdanielk1977 
1995660af939Sdan /*
1996660af939Sdan ** Create new user functions.
1997660af939Sdan */
sqlite3_create_function(sqlite3 * db,const char * zFunc,int nArg,int enc,void * p,void (* xSFunc)(sqlite3_context *,int,sqlite3_value **),void (* xStep)(sqlite3_context *,int,sqlite3_value **),void (* xFinal)(sqlite3_context *))1998660af939Sdan int sqlite3_create_function(
1999660af939Sdan   sqlite3 *db,
2000660af939Sdan   const char *zFunc,
2001660af939Sdan   int nArg,
2002660af939Sdan   int enc,
2003660af939Sdan   void *p,
2004660af939Sdan   void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
2005660af939Sdan   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
2006660af939Sdan   void (*xFinal)(sqlite3_context*)
2007660af939Sdan ){
2008660af939Sdan   return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
2009660af939Sdan                                     xFinal, 0, 0, 0);
2010660af939Sdan }
sqlite3_create_function_v2(sqlite3 * db,const char * zFunc,int nArg,int enc,void * p,void (* xSFunc)(sqlite3_context *,int,sqlite3_value **),void (* xStep)(sqlite3_context *,int,sqlite3_value **),void (* xFinal)(sqlite3_context *),void (* xDestroy)(void *))2011660af939Sdan int sqlite3_create_function_v2(
2012660af939Sdan   sqlite3 *db,
2013660af939Sdan   const char *zFunc,
2014660af939Sdan   int nArg,
2015660af939Sdan   int enc,
2016660af939Sdan   void *p,
2017660af939Sdan   void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
2018660af939Sdan   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
2019660af939Sdan   void (*xFinal)(sqlite3_context*),
2020660af939Sdan   void (*xDestroy)(void *)
2021660af939Sdan ){
2022660af939Sdan   return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
2023660af939Sdan                                     xFinal, 0, 0, xDestroy);
2024660af939Sdan }
sqlite3_create_window_function(sqlite3 * db,const char * zFunc,int nArg,int enc,void * p,void (* xStep)(sqlite3_context *,int,sqlite3_value **),void (* xFinal)(sqlite3_context *),void (* xValue)(sqlite3_context *),void (* xInverse)(sqlite3_context *,int,sqlite3_value **),void (* xDestroy)(void *))2025660af939Sdan int sqlite3_create_window_function(
2026660af939Sdan   sqlite3 *db,
2027660af939Sdan   const char *zFunc,
2028660af939Sdan   int nArg,
2029660af939Sdan   int enc,
2030660af939Sdan   void *p,
2031660af939Sdan   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
2032660af939Sdan   void (*xFinal)(sqlite3_context*),
2033660af939Sdan   void (*xValue)(sqlite3_context*),
2034660af939Sdan   void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
2035660af939Sdan   void (*xDestroy)(void *)
2036660af939Sdan ){
2037660af939Sdan   return createFunctionApi(db, zFunc, nArg, enc, p, 0, xStep,
2038660af939Sdan                                     xFinal, xValue, xInverse, xDestroy);
2039660af939Sdan }
2040660af939Sdan 
204193758c8dSdanielk1977 #ifndef SQLITE_OMIT_UTF16
sqlite3_create_function16(sqlite3 * db,const void * zFunctionName,int nArg,int eTextRep,void * p,void (* xSFunc)(sqlite3_context *,int,sqlite3_value **),void (* xStep)(sqlite3_context *,int,sqlite3_value **),void (* xFinal)(sqlite3_context *))20426590493dSdanielk1977 int sqlite3_create_function16(
20436590493dSdanielk1977   sqlite3 *db,
20446590493dSdanielk1977   const void *zFunctionName,
20456590493dSdanielk1977   int nArg,
20466590493dSdanielk1977   int eTextRep,
2047771151b6Sdanielk1977   void *p,
20482d80151fSdrh   void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
20496590493dSdanielk1977   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
20506590493dSdanielk1977   void (*xFinal)(sqlite3_context*)
20516590493dSdanielk1977 ){
20526590493dSdanielk1977   int rc;
2053af9a7c22Sdrh   char *zFunc8;
20549ca95730Sdrh 
20559ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
20569ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
20579ca95730Sdrh #endif
2058e30f4426Sdrh   sqlite3_mutex_enter(db->mutex);
205917435752Sdrh   assert( !db->mallocFailed );
2060b7dca7d7Sdan   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
2061660af939Sdan   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0,0,0);
2062633e6d57Sdrh   sqlite3DbFree(db, zFunc8);
2063e30f4426Sdrh   rc = sqlite3ApiExit(db, rc);
2064e30f4426Sdrh   sqlite3_mutex_leave(db->mutex);
2065e30f4426Sdrh   return rc;
20668e0a2f90Sdrh }
206793758c8dSdanielk1977 #endif
2068c9b84a1fSdrh 
2069b7481e70Sdrh 
2070b7481e70Sdrh /*
207192011847Sdrh ** The following is the implementation of an SQL function that always
207292011847Sdrh ** fails with an error message stating that the function is used in the
207392011847Sdrh ** wrong context.  The sqlite3_overload_function() API might construct
207492011847Sdrh ** SQL function that use this routine so that the functions will exist
207592011847Sdrh ** for name resolution but are actually overloaded by the xFindFunction
207692011847Sdrh ** method of virtual tables.
207792011847Sdrh */
sqlite3InvalidFunction(sqlite3_context * context,int NotUsed,sqlite3_value ** NotUsed2)207892011847Sdrh static void sqlite3InvalidFunction(
207992011847Sdrh   sqlite3_context *context,  /* The function calling context */
208092011847Sdrh   int NotUsed,               /* Number of arguments to the function */
208192011847Sdrh   sqlite3_value **NotUsed2   /* Value of each argument */
208292011847Sdrh ){
208392011847Sdrh   const char *zName = (const char*)sqlite3_user_data(context);
208492011847Sdrh   char *zErr;
208592011847Sdrh   UNUSED_PARAMETER2(NotUsed, NotUsed2);
208692011847Sdrh   zErr = sqlite3_mprintf(
208792011847Sdrh       "unable to use function %s in the requested context", zName);
208892011847Sdrh   sqlite3_result_error(context, zErr, -1);
208992011847Sdrh   sqlite3_free(zErr);
209092011847Sdrh }
209192011847Sdrh 
209292011847Sdrh /*
2093b7481e70Sdrh ** Declare that a function has been overloaded by a virtual table.
2094b7481e70Sdrh **
2095b7481e70Sdrh ** If the function already exists as a regular global function, then
2096b7481e70Sdrh ** this routine is a no-op.  If the function does not exist, then create
2097b7481e70Sdrh ** a new one that always throws a run-time error.
2098b7481e70Sdrh **
2099b7481e70Sdrh ** When virtual tables intend to provide an overloaded function, they
2100b7481e70Sdrh ** should call this routine to make sure the global function exists.
2101b7481e70Sdrh ** A global function must exist in order for name resolution to work
2102b7481e70Sdrh ** properly.
2103b7481e70Sdrh */
sqlite3_overload_function(sqlite3 * db,const char * zName,int nArg)2104b7481e70Sdrh int sqlite3_overload_function(
2105b7481e70Sdrh   sqlite3 *db,
2106b7481e70Sdrh   const char *zName,
2107b7481e70Sdrh   int nArg
2108b7481e70Sdrh ){
210992011847Sdrh   int rc;
211092011847Sdrh   char *zCopy;
21119ca95730Sdrh 
21129ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
21139ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
21149ca95730Sdrh     return SQLITE_MISUSE_BKPT;
21159ca95730Sdrh   }
21169ca95730Sdrh #endif
2117e30f4426Sdrh   sqlite3_mutex_enter(db->mutex);
211892011847Sdrh   rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0;
2119e30f4426Sdrh   sqlite3_mutex_leave(db->mutex);
212092011847Sdrh   if( rc ) return SQLITE_OK;
212192011847Sdrh   zCopy = sqlite3_mprintf(zName);
212292011847Sdrh   if( zCopy==0 ) return SQLITE_NOMEM;
212392011847Sdrh   return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8,
212492011847Sdrh                            zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free);
2125b7481e70Sdrh }
2126b7481e70Sdrh 
212719e2d37fSdrh #ifndef SQLITE_OMIT_TRACE
2128c9b84a1fSdrh /*
212918de4824Sdrh ** Register a trace function.  The pArg from the previously registered trace
213018de4824Sdrh ** is returned.
213118de4824Sdrh **
213218de4824Sdrh ** A NULL trace function means that no tracing is executes.  A non-NULL
213318de4824Sdrh ** trace is a pointer to a function that is invoked at the start of each
213419e2d37fSdrh ** SQL statement.
213518de4824Sdrh */
21363d2a529dSdrh #ifndef SQLITE_OMIT_DEPRECATED
sqlite3_trace(sqlite3 * db,void (* xTrace)(void *,const char *),void * pArg)21379bb575fdSdrh void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
2138e30f4426Sdrh   void *pOld;
21399ca95730Sdrh 
21409ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
21419ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ){
21429ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
21439ca95730Sdrh     return 0;
21449ca95730Sdrh   }
21459ca95730Sdrh #endif
2146e30f4426Sdrh   sqlite3_mutex_enter(db->mutex);
2147e30f4426Sdrh   pOld = db->pTraceArg;
21481637a517Sdrh   db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
214908b92086Sdrh   db->trace.xLegacy = xTrace;
215018de4824Sdrh   db->pTraceArg = pArg;
2151e30f4426Sdrh   sqlite3_mutex_leave(db->mutex);
215218de4824Sdrh   return pOld;
21530d1a643aSdrh }
21543d2a529dSdrh #endif /* SQLITE_OMIT_DEPRECATED */
21553d2a529dSdrh 
21563d2a529dSdrh /* Register a trace callback using the version-2 interface.
21573d2a529dSdrh */
sqlite3_trace_v2(sqlite3 * db,unsigned mTrace,int (* xTrace)(unsigned,void *,void *,void *),void * pArg)21583d2a529dSdrh int sqlite3_trace_v2(
21593d2a529dSdrh   sqlite3 *db,                               /* Trace this connection */
2160fca760c8Sdrh   unsigned mTrace,                           /* Mask of events to be traced */
2161fca760c8Sdrh   int(*xTrace)(unsigned,void*,void*,void*),  /* Callback to invoke */
21623d2a529dSdrh   void *pArg                                 /* Context */
21633d2a529dSdrh ){
21643d2a529dSdrh #ifdef SQLITE_ENABLE_API_ARMOR
21653d2a529dSdrh   if( !sqlite3SafetyCheckOk(db) ){
2166283a85caSmistachkin     return SQLITE_MISUSE_BKPT;
21673d2a529dSdrh   }
21683d2a529dSdrh #endif
21693d2a529dSdrh   sqlite3_mutex_enter(db->mutex);
2170fb82820aSdrh   if( mTrace==0 ) xTrace = 0;
2171fb82820aSdrh   if( xTrace==0 ) mTrace = 0;
21723d2a529dSdrh   db->mTrace = mTrace;
217308b92086Sdrh   db->trace.xV2 = xTrace;
21743d2a529dSdrh   db->pTraceArg = pArg;
21753d2a529dSdrh   sqlite3_mutex_leave(db->mutex);
21763d2a529dSdrh   return SQLITE_OK;
21773d2a529dSdrh }
21783d2a529dSdrh 
2179087ec072Sdrh #ifndef SQLITE_OMIT_DEPRECATED
218019e2d37fSdrh /*
218119e2d37fSdrh ** Register a profile function.  The pArg from the previously registered
218219e2d37fSdrh ** profile function is returned.
218319e2d37fSdrh **
218419e2d37fSdrh ** A NULL profile function means that no profiling is executes.  A non-NULL
218519e2d37fSdrh ** profile is a pointer to a function that is invoked at the conclusion of
218619e2d37fSdrh ** each SQL statement that is run.
218719e2d37fSdrh */
sqlite3_profile(sqlite3 * db,void (* xProfile)(void *,const char *,sqlite_uint64),void * pArg)218819e2d37fSdrh void *sqlite3_profile(
218919e2d37fSdrh   sqlite3 *db,
219019e2d37fSdrh   void (*xProfile)(void*,const char*,sqlite_uint64),
219119e2d37fSdrh   void *pArg
219219e2d37fSdrh ){
2193e30f4426Sdrh   void *pOld;
21949ca95730Sdrh 
21959ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
21969ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ){
21979ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
21989ca95730Sdrh     return 0;
21999ca95730Sdrh   }
22009ca95730Sdrh #endif
2201e30f4426Sdrh   sqlite3_mutex_enter(db->mutex);
2202e30f4426Sdrh   pOld = db->pProfileArg;
220319e2d37fSdrh   db->xProfile = xProfile;
220419e2d37fSdrh   db->pProfileArg = pArg;
220504c6747aSdrh   db->mTrace &= SQLITE_TRACE_NONLEGACY_MASK;
220604c6747aSdrh   if( db->xProfile ) db->mTrace |= SQLITE_TRACE_XPROFILE;
2207e30f4426Sdrh   sqlite3_mutex_leave(db->mutex);
220819e2d37fSdrh   return pOld;
220919e2d37fSdrh }
2210087ec072Sdrh #endif /* SQLITE_OMIT_DEPRECATED */
221119e2d37fSdrh #endif /* SQLITE_OMIT_TRACE */
2212b0208ccaSpaul 
2213cd565fd1Sdrh /*
2214cd565fd1Sdrh ** Register a function to be invoked when a transaction commits.
221571fd80bfSdanielk1977 ** If the invoked function returns non-zero, then the commit becomes a
2216aa940eacSdrh ** rollback.
2217aa940eacSdrh */
sqlite3_commit_hook(sqlite3 * db,int (* xCallback)(void *),void * pArg)221824b03fd0Sdanielk1977 void *sqlite3_commit_hook(
22199bb575fdSdrh   sqlite3 *db,              /* Attach the hook to this database */
2220aa940eacSdrh   int (*xCallback)(void*),  /* Function to invoke on each commit */
2221aa940eacSdrh   void *pArg                /* Argument to the function */
2222aa940eacSdrh ){
2223e30f4426Sdrh   void *pOld;
22249ca95730Sdrh 
22259ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
22269ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ){
22279ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
22289ca95730Sdrh     return 0;
22299ca95730Sdrh   }
22309ca95730Sdrh #endif
2231e30f4426Sdrh   sqlite3_mutex_enter(db->mutex);
2232e30f4426Sdrh   pOld = db->pCommitArg;
2233aa940eacSdrh   db->xCommitCallback = xCallback;
2234aa940eacSdrh   db->pCommitArg = pArg;
2235e30f4426Sdrh   sqlite3_mutex_leave(db->mutex);
2236aa940eacSdrh   return pOld;
2237aa940eacSdrh }
2238aa940eacSdrh 
223994eb6a14Sdanielk1977 /*
224094eb6a14Sdanielk1977 ** Register a callback to be invoked each time a row is updated,
224194eb6a14Sdanielk1977 ** inserted or deleted using this database connection.
224294eb6a14Sdanielk1977 */
sqlite3_update_hook(sqlite3 * db,void (* xCallback)(void *,int,char const *,char const *,sqlite_int64),void * pArg)224371fd80bfSdanielk1977 void *sqlite3_update_hook(
224494eb6a14Sdanielk1977   sqlite3 *db,              /* Attach the hook to this database */
224594eb6a14Sdanielk1977   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
224694eb6a14Sdanielk1977   void *pArg                /* Argument to the function */
224794eb6a14Sdanielk1977 ){
2248e30f4426Sdrh   void *pRet;
22499ca95730Sdrh 
22509ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
22519ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ){
22529ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
22539ca95730Sdrh     return 0;
22549ca95730Sdrh   }
22559ca95730Sdrh #endif
2256e30f4426Sdrh   sqlite3_mutex_enter(db->mutex);
2257e30f4426Sdrh   pRet = db->pUpdateArg;
225894eb6a14Sdanielk1977   db->xUpdateCallback = xCallback;
225994eb6a14Sdanielk1977   db->pUpdateArg = pArg;
2260e30f4426Sdrh   sqlite3_mutex_leave(db->mutex);
226171fd80bfSdanielk1977   return pRet;
226294eb6a14Sdanielk1977 }
226394eb6a14Sdanielk1977 
226471fd80bfSdanielk1977 /*
226571fd80bfSdanielk1977 ** Register a callback to be invoked each time a transaction is rolled
226671fd80bfSdanielk1977 ** back by this database connection.
226771fd80bfSdanielk1977 */
sqlite3_rollback_hook(sqlite3 * db,void (* xCallback)(void *),void * pArg)226871fd80bfSdanielk1977 void *sqlite3_rollback_hook(
226971fd80bfSdanielk1977   sqlite3 *db,              /* Attach the hook to this database */
227071fd80bfSdanielk1977   void (*xCallback)(void*), /* Callback function */
227171fd80bfSdanielk1977   void *pArg                /* Argument to the function */
227271fd80bfSdanielk1977 ){
2273e30f4426Sdrh   void *pRet;
22749ca95730Sdrh 
22759ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
22769ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ){
22779ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
22789ca95730Sdrh     return 0;
22799ca95730Sdrh   }
22809ca95730Sdrh #endif
2281e30f4426Sdrh   sqlite3_mutex_enter(db->mutex);
2282e30f4426Sdrh   pRet = db->pRollbackArg;
228371fd80bfSdanielk1977   db->xRollbackCallback = xCallback;
228471fd80bfSdanielk1977   db->pRollbackArg = pArg;
2285e30f4426Sdrh   sqlite3_mutex_leave(db->mutex);
228671fd80bfSdanielk1977   return pRet;
228771fd80bfSdanielk1977 }
2288aa940eacSdrh 
22899b1c62d4Sdrh #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
229046c47d46Sdan /*
229146c47d46Sdan ** Register a callback to be invoked each time a row is updated,
229246c47d46Sdan ** inserted or deleted using this database connection.
229346c47d46Sdan */
sqlite3_preupdate_hook(sqlite3 * db,void (* xCallback)(void *,sqlite3 *,int,char const *,char const *,sqlite3_int64,sqlite3_int64),void * pArg)229446c47d46Sdan void *sqlite3_preupdate_hook(
229546c47d46Sdan   sqlite3 *db,              /* Attach the hook to this database */
229646c47d46Sdan   void(*xCallback)(         /* Callback function */
229746c47d46Sdan     void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
229846c47d46Sdan   void *pArg                /* First callback argument */
229946c47d46Sdan ){
230046c47d46Sdan   void *pRet;
230146c47d46Sdan   sqlite3_mutex_enter(db->mutex);
230246c47d46Sdan   pRet = db->pPreUpdateArg;
230346c47d46Sdan   db->xPreUpdateCallback = xCallback;
230446c47d46Sdan   db->pPreUpdateArg = pArg;
230546c47d46Sdan   sqlite3_mutex_leave(db->mutex);
230646c47d46Sdan   return pRet;
230746c47d46Sdan }
23089b1c62d4Sdrh #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
230946c47d46Sdan 
23101bbfc674Sdrh /*
23111bbfc674Sdrh ** Register a function to be invoked prior to each autovacuum that
23121bbfc674Sdrh ** determines the number of pages to vacuum.
23131bbfc674Sdrh */
sqlite3_autovacuum_pages(sqlite3 * db,unsigned int (* xCallback)(void *,const char *,u32,u32,u32),void * pArg,void (* xDestructor)(void *))23141bbfc674Sdrh int sqlite3_autovacuum_pages(
23151bbfc674Sdrh   sqlite3 *db,                 /* Attach the hook to this database */
23161bbfc674Sdrh   unsigned int (*xCallback)(void*,const char*,u32,u32,u32),
23171bbfc674Sdrh   void *pArg,                  /* Argument to the function */
23181bbfc674Sdrh   void (*xDestructor)(void*)   /* Destructor for pArg */
23191bbfc674Sdrh ){
23201bbfc674Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
23211bbfc674Sdrh   if( !sqlite3SafetyCheckOk(db) ){
23221bbfc674Sdrh     if( xDestructor ) xDestructor(pArg);
23231bbfc674Sdrh     return SQLITE_MISUSE_BKPT;
23241bbfc674Sdrh   }
23251bbfc674Sdrh #endif
23261bbfc674Sdrh   sqlite3_mutex_enter(db->mutex);
23271bbfc674Sdrh   if( db->xAutovacDestr ){
23281bbfc674Sdrh     db->xAutovacDestr(db->pAutovacPagesArg);
23291bbfc674Sdrh   }
23301bbfc674Sdrh   db->xAutovacPages = xCallback;
23311bbfc674Sdrh   db->pAutovacPagesArg = pArg;
23321bbfc674Sdrh   db->xAutovacDestr = xDestructor;
23331bbfc674Sdrh   sqlite3_mutex_leave(db->mutex);
23341bbfc674Sdrh   return SQLITE_OK;
23351bbfc674Sdrh }
23361bbfc674Sdrh 
23371bbfc674Sdrh 
2338586b9c8aSdan #ifndef SQLITE_OMIT_WAL
2339586b9c8aSdan /*
2340586b9c8aSdan ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
23415def0843Sdrh ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
23425def0843Sdrh ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
2343b033d8b9Sdrh ** wal_autocheckpoint()).
2344586b9c8aSdan */
sqlite3WalDefaultHook(void * pClientData,sqlite3 * db,const char * zDb,int nFrame)2345b033d8b9Sdrh int sqlite3WalDefaultHook(
23465def0843Sdrh   void *pClientData,     /* Argument */
2347b033d8b9Sdrh   sqlite3 *db,           /* Connection */
23485def0843Sdrh   const char *zDb,       /* Database */
2349b033d8b9Sdrh   int nFrame             /* Size of WAL */
2350b033d8b9Sdrh ){
23515def0843Sdrh   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
2352f5330357Sdrh     sqlite3BeginBenignMalloc();
23535def0843Sdrh     sqlite3_wal_checkpoint(db, zDb);
2354f5330357Sdrh     sqlite3EndBenignMalloc();
23555def0843Sdrh   }
23565def0843Sdrh   return SQLITE_OK;
2357586b9c8aSdan }
2358b033d8b9Sdrh #endif /* SQLITE_OMIT_WAL */
2359586b9c8aSdan 
2360586b9c8aSdan /*
2361586b9c8aSdan ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
2362586b9c8aSdan ** a database after committing a transaction if there are nFrame or
2363586b9c8aSdan ** more frames in the log file. Passing zero or a negative value as the
2364586b9c8aSdan ** nFrame parameter disables automatic checkpoints entirely.
2365586b9c8aSdan **
2366586b9c8aSdan ** The callback registered by this function replaces any existing callback
2367586b9c8aSdan ** registered using sqlite3_wal_hook(). Likewise, registering a callback
2368586b9c8aSdan ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
2369586b9c8aSdan ** configured by this function.
2370586b9c8aSdan */
sqlite3_wal_autocheckpoint(sqlite3 * db,int nFrame)2371586b9c8aSdan int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
2372bd2aaf9aSshaneh #ifdef SQLITE_OMIT_WAL
2373bd2aaf9aSshaneh   UNUSED_PARAMETER(db);
2374bd2aaf9aSshaneh   UNUSED_PARAMETER(nFrame);
2375bd2aaf9aSshaneh #else
23769ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
23779ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
23789ca95730Sdrh #endif
2379586b9c8aSdan   if( nFrame>0 ){
2380b033d8b9Sdrh     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
2381586b9c8aSdan   }else{
2382586b9c8aSdan     sqlite3_wal_hook(db, 0, 0);
2383586b9c8aSdan   }
2384b033d8b9Sdrh #endif
2385586b9c8aSdan   return SQLITE_OK;
2386586b9c8aSdan }
2387586b9c8aSdan 
2388b0208ccaSpaul /*
23898d22a174Sdan ** Register a callback to be invoked each time a transaction is written
23908d22a174Sdan ** into the write-ahead-log by this database connection.
23918d22a174Sdan */
sqlite3_wal_hook(sqlite3 * db,int (* xCallback)(void *,sqlite3 *,const char *,int),void * pArg)2392833bf968Sdrh void *sqlite3_wal_hook(
23938d22a174Sdan   sqlite3 *db,                    /* Attach the hook to this db handle */
23948d22a174Sdan   int(*xCallback)(void *, sqlite3*, const char*, int),
23958d22a174Sdan   void *pArg                      /* First argument passed to xCallback() */
23968d22a174Sdan ){
2397b033d8b9Sdrh #ifndef SQLITE_OMIT_WAL
23988d22a174Sdan   void *pRet;
23999ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
24009ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ){
24019ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
24029ca95730Sdrh     return 0;
24039ca95730Sdrh   }
24049ca95730Sdrh #endif
24058d22a174Sdan   sqlite3_mutex_enter(db->mutex);
24067ed91f23Sdrh   pRet = db->pWalArg;
24077ed91f23Sdrh   db->xWalCallback = xCallback;
24087ed91f23Sdrh   db->pWalArg = pArg;
24098d22a174Sdan   sqlite3_mutex_leave(db->mutex);
24108d22a174Sdan   return pRet;
2411b033d8b9Sdrh #else
2412b033d8b9Sdrh   return 0;
2413b033d8b9Sdrh #endif
24148d22a174Sdan }
24158d22a174Sdan 
24168d22a174Sdan /*
2417cdc1f049Sdan ** Checkpoint database zDb.
2418586b9c8aSdan */
sqlite3_wal_checkpoint_v2(sqlite3 * db,const char * zDb,int eMode,int * pnLog,int * pnCkpt)2419cdc1f049Sdan int sqlite3_wal_checkpoint_v2(
2420cdc1f049Sdan   sqlite3 *db,                    /* Database handle */
2421cdc1f049Sdan   const char *zDb,                /* Name of attached database (or NULL) */
2422cdc1f049Sdan   int eMode,                      /* SQLITE_CHECKPOINT_* value */
2423cdc1f049Sdan   int *pnLog,                     /* OUT: Size of WAL log in frames */
2424cdc1f049Sdan   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
2425cdc1f049Sdan ){
2426b033d8b9Sdrh #ifdef SQLITE_OMIT_WAL
2427b033d8b9Sdrh   return SQLITE_OK;
2428b033d8b9Sdrh #else
2429586b9c8aSdan   int rc;                         /* Return code */
2430099b385dSdrh   int iDb;                        /* Schema to checkpoint */
2431586b9c8aSdan 
24329ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
24339ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
24349ca95730Sdrh #endif
24359ca95730Sdrh 
24369c5e3680Sdan   /* Initialize the output variables to -1 in case an error occurs. */
24379c5e3680Sdan   if( pnLog ) *pnLog = -1;
24389c5e3680Sdan   if( pnCkpt ) *pnCkpt = -1;
24399c5e3680Sdan 
2440f26a1549Sdan   assert( SQLITE_CHECKPOINT_PASSIVE==0 );
2441f26a1549Sdan   assert( SQLITE_CHECKPOINT_FULL==1 );
2442f26a1549Sdan   assert( SQLITE_CHECKPOINT_RESTART==2 );
2443f26a1549Sdan   assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
2444f26a1549Sdan   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
2445bb9a378dSdrh     /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
2446bb9a378dSdrh     ** mode: */
2447cdc1f049Sdan     return SQLITE_MISUSE;
2448cdc1f049Sdan   }
2449cdc1f049Sdan 
2450586b9c8aSdan   sqlite3_mutex_enter(db->mutex);
2451af0cfd36Sdan   if( zDb && zDb[0] ){
2452586b9c8aSdan     iDb = sqlite3FindDbName(db, zDb);
2453099b385dSdrh   }else{
2454099b385dSdrh     iDb = SQLITE_MAX_DB;   /* This means process all schemas */
2455586b9c8aSdan   }
2456586b9c8aSdan   if( iDb<0 ){
2457586b9c8aSdan     rc = SQLITE_ERROR;
245813f40da3Sdrh     sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
2459586b9c8aSdan   }else{
2460976b0033Sdan     db->busyHandler.nBusy = 0;
2461cdc1f049Sdan     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
246213f40da3Sdrh     sqlite3Error(db, rc);
2463586b9c8aSdan   }
2464b033d8b9Sdrh   rc = sqlite3ApiExit(db, rc);
24657fb89906Sdan 
24667fb89906Sdan   /* If there are no active statements, clear the interrupt flag at this
24677fb89906Sdan   ** point.  */
24687fb89906Sdan   if( db->nVdbeActive==0 ){
2469892edb69Sdan     AtomicStore(&db->u1.isInterrupted, 0);
24707fb89906Sdan   }
24717fb89906Sdan 
2472586b9c8aSdan   sqlite3_mutex_leave(db->mutex);
2473b033d8b9Sdrh   return rc;
2474b033d8b9Sdrh #endif
2475586b9c8aSdan }
2476586b9c8aSdan 
2477cdc1f049Sdan 
2478cdc1f049Sdan /*
2479cdc1f049Sdan ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
2480cdc1f049Sdan ** to contains a zero-length string, all attached databases are
2481cdc1f049Sdan ** checkpointed.
2482cdc1f049Sdan */
sqlite3_wal_checkpoint(sqlite3 * db,const char * zDb)2483cdc1f049Sdan int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
2484bb9a378dSdrh   /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
2485bb9a378dSdrh   ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
2486cdc1f049Sdan   return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
2487cdc1f049Sdan }
2488cdc1f049Sdan 
2489b033d8b9Sdrh #ifndef SQLITE_OMIT_WAL
2490586b9c8aSdan /*
2491586b9c8aSdan ** Run a checkpoint on database iDb. This is a no-op if database iDb is
2492586b9c8aSdan ** not currently open in WAL mode.
2493586b9c8aSdan **
24946fcff07fSdan ** If a transaction is open on the database being checkpointed, this
24956fcff07fSdan ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
24966fcff07fSdan ** an error occurs while running the checkpoint, an SQLite error code is
24976fcff07fSdan ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
2498586b9c8aSdan **
2499586b9c8aSdan ** The mutex on database handle db should be held by the caller. The mutex
2500586b9c8aSdan ** associated with the specific b-tree being checkpointed is taken by
2501586b9c8aSdan ** this function while the checkpoint is running.
25026fcff07fSdan **
2503099b385dSdrh ** If iDb is passed SQLITE_MAX_DB then all attached databases are
25046fcff07fSdan ** checkpointed. If an error is encountered it is returned immediately -
25056fcff07fSdan ** no attempt is made to checkpoint any remaining databases.
2506a58f26f9Sdan **
25077834551cSdan ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
25087834551cSdan ** or TRUNCATE.
2509586b9c8aSdan */
sqlite3Checkpoint(sqlite3 * db,int iDb,int eMode,int * pnLog,int * pnCkpt)2510cdc1f049Sdan int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
25116fcff07fSdan   int rc = SQLITE_OK;             /* Return code */
25126fcff07fSdan   int i;                          /* Used to iterate through attached dbs */
2513f2b8dd58Sdan   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
2514586b9c8aSdan 
2515586b9c8aSdan   assert( sqlite3_mutex_held(db->mutex) );
25169c5e3680Sdan   assert( !pnLog || *pnLog==-1 );
25179c5e3680Sdan   assert( !pnCkpt || *pnCkpt==-1 );
2518662a1426Sdrh   testcase( iDb==SQLITE_MAX_ATTACHED ); /* See forum post a006d86f72 */
2519662a1426Sdrh   testcase( iDb==SQLITE_MAX_DB );
2520586b9c8aSdan 
25216fcff07fSdan   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
2522099b385dSdrh     if( i==iDb || iDb==SQLITE_MAX_DB ){
2523cdc1f049Sdan       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
2524f2b8dd58Sdan       pnLog = 0;
2525f2b8dd58Sdan       pnCkpt = 0;
2526f2b8dd58Sdan       if( rc==SQLITE_BUSY ){
2527f2b8dd58Sdan         bBusy = 1;
2528f2b8dd58Sdan         rc = SQLITE_OK;
2529f2b8dd58Sdan       }
25306fcff07fSdan     }
25316fcff07fSdan   }
2532586b9c8aSdan 
2533f2b8dd58Sdan   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
2534586b9c8aSdan }
2535b033d8b9Sdrh #endif /* SQLITE_OMIT_WAL */
2536586b9c8aSdan 
2537586b9c8aSdan /*
2538d829335eSdanielk1977 ** This function returns true if main-memory should be used instead of
2539d829335eSdanielk1977 ** a temporary file for transient pager files and statement journals.
2540d829335eSdanielk1977 ** The value returned depends on the value of db->temp_store (runtime
2541d829335eSdanielk1977 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
2542d829335eSdanielk1977 ** following table describes the relationship between these two values
2543d829335eSdanielk1977 ** and this functions return value.
2544d829335eSdanielk1977 **
2545d829335eSdanielk1977 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
2546d829335eSdanielk1977 **   -----------------     --------------     ------------------------------
2547d829335eSdanielk1977 **   0                     any                file      (return 0)
2548d829335eSdanielk1977 **   1                     1                  file      (return 0)
2549d829335eSdanielk1977 **   1                     2                  memory    (return 1)
2550d829335eSdanielk1977 **   1                     0                  file      (return 0)
2551d829335eSdanielk1977 **   2                     1                  file      (return 0)
2552d829335eSdanielk1977 **   2                     2                  memory    (return 1)
2553d829335eSdanielk1977 **   2                     0                  memory    (return 1)
2554d829335eSdanielk1977 **   3                     any                memory    (return 1)
2555d829335eSdanielk1977 */
sqlite3TempInMemory(const sqlite3 * db)25561c514148Sdrh int sqlite3TempInMemory(const sqlite3 *db){
2557d829335eSdanielk1977 #if SQLITE_TEMP_STORE==1
2558d829335eSdanielk1977   return ( db->temp_store==2 );
2559d829335eSdanielk1977 #endif
2560d829335eSdanielk1977 #if SQLITE_TEMP_STORE==2
2561d829335eSdanielk1977   return ( db->temp_store!=1 );
2562d829335eSdanielk1977 #endif
2563d829335eSdanielk1977 #if SQLITE_TEMP_STORE==3
2564f5ed7ad6Sdrh   UNUSED_PARAMETER(db);
2565d829335eSdanielk1977   return 1;
2566cf697396Sshane #endif
2567cf697396Sshane #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
2568f5ed7ad6Sdrh   UNUSED_PARAMETER(db);
2569d829335eSdanielk1977   return 0;
257060a4b538Sshane #endif
2571d829335eSdanielk1977 }
2572d829335eSdanielk1977 
2573d829335eSdanielk1977 /*
25744ad1713cSdanielk1977 ** Return UTF-8 encoded English language explanation of the most recent
25754ad1713cSdanielk1977 ** error.
25764ad1713cSdanielk1977 */
sqlite3_errmsg(sqlite3 * db)25776622cce3Sdanielk1977 const char *sqlite3_errmsg(sqlite3 *db){
2578c60d0446Sdrh   const char *z;
2579f49661a4Sdrh   if( !db ){
2580fad3039cSmistachkin     return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
25814ad1713cSdanielk1977   }
2582d55d57edSdrh   if( !sqlite3SafetyCheckSickOrOk(db) ){
2583413c3d36Sdrh     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
2584e35ee196Sdanielk1977   }
258527641703Sdrh   sqlite3_mutex_enter(db->mutex);
2586238746a6Sdanielk1977   if( db->mallocFailed ){
2587fad3039cSmistachkin     z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
2588238746a6Sdanielk1977   }else{
2589a3cc007dSdrh     testcase( db->pErr==0 );
2590368bfe8bSdrh     z = db->errCode ? (char*)sqlite3_value_text(db->pErr) : 0;
2591131c8bc0Sdanielk1977     assert( !db->mallocFailed );
2592c60d0446Sdrh     if( z==0 ){
2593c60d0446Sdrh       z = sqlite3ErrStr(db->errCode);
25946622cce3Sdanielk1977     }
2595238746a6Sdanielk1977   }
2596e30f4426Sdrh   sqlite3_mutex_leave(db->mutex);
2597c60d0446Sdrh   return z;
2598bfd6cce5Sdanielk1977 }
25996622cce3Sdanielk1977 
2600f62641e9Sdrh /*
2601f62641e9Sdrh ** Return the byte offset of the most recent error
2602f62641e9Sdrh */
sqlite3_error_offset(sqlite3 * db)2603f62641e9Sdrh int sqlite3_error_offset(sqlite3 *db){
2604f62641e9Sdrh   int iOffset = -1;
26055cec7e1aSdrh   if( db && sqlite3SafetyCheckSickOrOk(db) && db->errCode ){
2606f62641e9Sdrh     sqlite3_mutex_enter(db->mutex);
2607f62641e9Sdrh     iOffset = db->errByteOffset;
2608f62641e9Sdrh     sqlite3_mutex_leave(db->mutex);
2609f62641e9Sdrh   }
2610f62641e9Sdrh   return iOffset;
2611f62641e9Sdrh }
2612f62641e9Sdrh 
26136c62608fSdrh #ifndef SQLITE_OMIT_UTF16
26144ad1713cSdanielk1977 /*
26154ad1713cSdanielk1977 ** Return UTF-16 encoded English language explanation of the most recent
26164ad1713cSdanielk1977 ** error.
26174ad1713cSdanielk1977 */
sqlite3_errmsg16(sqlite3 * db)26186622cce3Sdanielk1977 const void *sqlite3_errmsg16(sqlite3 *db){
26197c5c3cabSdanielk1977   static const u16 outOfMem[] = {
26207c5c3cabSdanielk1977     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
26214ad1713cSdanielk1977   };
26227c5c3cabSdanielk1977   static const u16 misuse[] = {
2623ff4fa772Sdrh     'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
2624ff4fa772Sdrh     'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
2625ff4fa772Sdrh     'm', 'i', 's', 'u', 's', 'e', 0
2626e35ee196Sdanielk1977   };
26274ad1713cSdanielk1977 
2628c60d0446Sdrh   const void *z;
2629ae7fc49dSdanielk1977   if( !db ){
26307c5c3cabSdanielk1977     return (void *)outOfMem;
26316622cce3Sdanielk1977   }
2632d55d57edSdrh   if( !sqlite3SafetyCheckSickOrOk(db) ){
26337c5c3cabSdanielk1977     return (void *)misuse;
2634c60d0446Sdrh   }
2635e30f4426Sdrh   sqlite3_mutex_enter(db->mutex);
2636238746a6Sdanielk1977   if( db->mallocFailed ){
2637238746a6Sdanielk1977     z = (void *)outOfMem;
2638238746a6Sdanielk1977   }else{
2639c60d0446Sdrh     z = sqlite3_value_text16(db->pErr);
2640c60d0446Sdrh     if( z==0 ){
264113f40da3Sdrh       sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
2642c60d0446Sdrh       z = sqlite3_value_text16(db->pErr);
2643c60d0446Sdrh     }
2644131c8bc0Sdanielk1977     /* A malloc() may have failed within the call to sqlite3_value_text16()
2645131c8bc0Sdanielk1977     ** above. If this is the case, then the db->mallocFailed flag needs to
2646131c8bc0Sdanielk1977     ** be cleared before returning. Do this directly, instead of via
2647131c8bc0Sdanielk1977     ** sqlite3ApiExit(), to avoid setting the database handle error message.
2648131c8bc0Sdanielk1977     */
26494a642b60Sdrh     sqlite3OomClear(db);
2650238746a6Sdanielk1977   }
2651e30f4426Sdrh   sqlite3_mutex_leave(db->mutex);
2652c60d0446Sdrh   return z;
2653c60d0446Sdrh }
26546c62608fSdrh #endif /* SQLITE_OMIT_UTF16 */
26556622cce3Sdanielk1977 
2656c60d0446Sdrh /*
26577ddad969Sdanielk1977 ** Return the most recent error code generated by an SQLite routine. If NULL is
26587ddad969Sdanielk1977 ** passed to this function, we assume a malloc() failed during sqlite3_open().
2659c60d0446Sdrh */
sqlite3_errcode(sqlite3 * db)26606622cce3Sdanielk1977 int sqlite3_errcode(sqlite3 *db){
26617c36d077Sdanielk1977   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
2662413c3d36Sdrh     return SQLITE_MISUSE_BKPT;
2663c60d0446Sdrh   }
266401495b99Sdrh   if( !db || db->mallocFailed ){
2665fad3039cSmistachkin     return SQLITE_NOMEM_BKPT;
266601495b99Sdrh   }
26674ac285a1Sdrh   return db->errCode & db->errMask;
26686622cce3Sdanielk1977 }
sqlite3_extended_errcode(sqlite3 * db)266999dfe5ebSdrh int sqlite3_extended_errcode(sqlite3 *db){
267099dfe5ebSdrh   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
2671413c3d36Sdrh     return SQLITE_MISUSE_BKPT;
267299dfe5ebSdrh   }
267399dfe5ebSdrh   if( !db || db->mallocFailed ){
2674fad3039cSmistachkin     return SQLITE_NOMEM_BKPT;
267599dfe5ebSdrh   }
267699dfe5ebSdrh   return db->errCode;
267799dfe5ebSdrh }
sqlite3_system_errno(sqlite3 * db)26781b9f2141Sdrh int sqlite3_system_errno(sqlite3 *db){
26791b9f2141Sdrh   return db ? db->iSysErrno : 0;
26801b9f2141Sdrh }
26816622cce3Sdanielk1977 
26820e819f90Sdrh /*
26835dac8432Smistachkin ** Return a string that describes the kind of error specified in the
26845dac8432Smistachkin ** argument.  For now, this simply calls the internal sqlite3ErrStr()
26855dac8432Smistachkin ** function.
26865dac8432Smistachkin */
sqlite3_errstr(int rc)26875dac8432Smistachkin const char *sqlite3_errstr(int rc){
26885dac8432Smistachkin   return sqlite3ErrStr(rc);
26895dac8432Smistachkin }
26905dac8432Smistachkin 
26915dac8432Smistachkin /*
26920e819f90Sdrh ** Create a new collating function for database "db".  The name is zName
26930e819f90Sdrh ** and the encoding is enc.
26940e819f90Sdrh */
createCollation(sqlite3 * db,const char * zName,u8 enc,void * pCtx,int (* xCompare)(void *,int,const void *,int,const void *),void (* xDel)(void *))26959a30cf65Sdanielk1977 static int createCollation(
26969a30cf65Sdanielk1977   sqlite3* db,
26979a30cf65Sdanielk1977   const char *zName,
2698cea72b2dSshane   u8 enc,
26999a30cf65Sdanielk1977   void* pCtx,
2700a9808b31Sdanielk1977   int(*xCompare)(void*,int,const void*,int,const void*),
2701a9808b31Sdanielk1977   void(*xDel)(void*)
27029a30cf65Sdanielk1977 ){
27039a30cf65Sdanielk1977   CollSeq *pColl;
27047d9bd4e1Sdrh   int enc2;
27059a30cf65Sdanielk1977 
2706e30f4426Sdrh   assert( sqlite3_mutex_held(db->mutex) );
27079a30cf65Sdanielk1977 
27089a30cf65Sdanielk1977   /* If SQLITE_UTF16 is specified as the encoding type, transform this
27099a30cf65Sdanielk1977   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
27109a30cf65Sdanielk1977   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
27119a30cf65Sdanielk1977   */
271251c7d864Sdrh   enc2 = enc;
2713ebb32939Sdanielk1977   testcase( enc2==SQLITE_UTF16 );
2714ebb32939Sdanielk1977   testcase( enc2==SQLITE_UTF16_ALIGNED );
2715ebb32939Sdanielk1977   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
27167d9bd4e1Sdrh     enc2 = SQLITE_UTF16NATIVE;
27179a30cf65Sdanielk1977   }
271851c7d864Sdrh   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
2719413c3d36Sdrh     return SQLITE_MISUSE_BKPT;
27209a30cf65Sdanielk1977   }
27219a30cf65Sdanielk1977 
27229a30cf65Sdanielk1977   /* Check if this call is removing or replacing an existing collation
27239a30cf65Sdanielk1977   ** sequence. If so, and there are active VMs, return busy. If there
27249a30cf65Sdanielk1977   ** are no active VMs, invalidate any pre-compiled statements.
27259a30cf65Sdanielk1977   */
2726c4a64facSdrh   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
27279a30cf65Sdanielk1977   if( pColl && pColl->xCmp ){
27284f7d3a5fSdrh     if( db->nVdbeActive ){
272913f40da3Sdrh       sqlite3ErrorWithMsg(db, SQLITE_BUSY,
2730b309becdSdrh         "unable to delete/modify collation sequence due to active statements");
27319a30cf65Sdanielk1977       return SQLITE_BUSY;
27329a30cf65Sdanielk1977     }
2733ba968dbfSdrh     sqlite3ExpirePreparedStatements(db, 0);
2734a9808b31Sdanielk1977 
2735a9808b31Sdanielk1977     /* If collation sequence pColl was created directly by a call to
2736a9808b31Sdanielk1977     ** sqlite3_create_collation, and not generated by synthCollSeq(),
2737a9808b31Sdanielk1977     ** then any copies made by synthCollSeq() need to be invalidated.
2738a9808b31Sdanielk1977     ** Also, collation destructor - CollSeq.xDel() - function may need
2739a9808b31Sdanielk1977     ** to be called.
2740a9808b31Sdanielk1977     */
2741a9808b31Sdanielk1977     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
2742acbcb7e0Sdrh       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
2743a9808b31Sdanielk1977       int j;
2744a9808b31Sdanielk1977       for(j=0; j<3; j++){
2745a9808b31Sdanielk1977         CollSeq *p = &aColl[j];
2746a9808b31Sdanielk1977         if( p->enc==pColl->enc ){
2747a9808b31Sdanielk1977           if( p->xDel ){
2748a9808b31Sdanielk1977             p->xDel(p->pUser);
2749a9808b31Sdanielk1977           }
2750a9808b31Sdanielk1977           p->xCmp = 0;
2751a9808b31Sdanielk1977         }
2752a9808b31Sdanielk1977       }
2753a9808b31Sdanielk1977     }
27549a30cf65Sdanielk1977   }
27559a30cf65Sdanielk1977 
2756c4a64facSdrh   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
2757fad3039cSmistachkin   if( pColl==0 ) return SQLITE_NOMEM_BKPT;
27589a30cf65Sdanielk1977   pColl->xCmp = xCompare;
27599a30cf65Sdanielk1977   pColl->pUser = pCtx;
2760a9808b31Sdanielk1977   pColl->xDel = xDel;
27611bd10f8aSdrh   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
276213f40da3Sdrh   sqlite3Error(db, SQLITE_OK);
27639a30cf65Sdanielk1977   return SQLITE_OK;
27649a30cf65Sdanielk1977 }
27659a30cf65Sdanielk1977 
27669a30cf65Sdanielk1977 
27676622cce3Sdanielk1977 /*
2768bb4957f8Sdrh ** This array defines hard upper bounds on limit values.  The
2769bb4957f8Sdrh ** initializer must be kept in sync with the SQLITE_LIMIT_*
2770bb4957f8Sdrh ** #defines in sqlite3.h.
2771bb4957f8Sdrh */
2772b1a6c3c1Sdrh static const int aHardLimit[] = {
2773bb4957f8Sdrh   SQLITE_MAX_LENGTH,
2774bb4957f8Sdrh   SQLITE_MAX_SQL_LENGTH,
2775bb4957f8Sdrh   SQLITE_MAX_COLUMN,
2776bb4957f8Sdrh   SQLITE_MAX_EXPR_DEPTH,
2777bb4957f8Sdrh   SQLITE_MAX_COMPOUND_SELECT,
2778bb4957f8Sdrh   SQLITE_MAX_VDBE_OP,
2779bb4957f8Sdrh   SQLITE_MAX_FUNCTION_ARG,
2780bb4957f8Sdrh   SQLITE_MAX_ATTACHED,
2781bb4957f8Sdrh   SQLITE_MAX_LIKE_PATTERN_LENGTH,
27829f959b07Sdrh   SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
2783417168adSdrh   SQLITE_MAX_TRIGGER_DEPTH,
2784111544cbSdrh   SQLITE_MAX_WORKER_THREADS,
2785bb4957f8Sdrh };
2786bb4957f8Sdrh 
2787bb4957f8Sdrh /*
2788bb4957f8Sdrh ** Make sure the hard limits are set to reasonable values
2789bb4957f8Sdrh */
2790bb4957f8Sdrh #if SQLITE_MAX_LENGTH<100
2791bb4957f8Sdrh # error SQLITE_MAX_LENGTH must be at least 100
2792bb4957f8Sdrh #endif
2793bb4957f8Sdrh #if SQLITE_MAX_SQL_LENGTH<100
2794bb4957f8Sdrh # error SQLITE_MAX_SQL_LENGTH must be at least 100
2795bb4957f8Sdrh #endif
2796bb4957f8Sdrh #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
2797bb4957f8Sdrh # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
2798bb4957f8Sdrh #endif
2799bb4957f8Sdrh #if SQLITE_MAX_COMPOUND_SELECT<2
2800bb4957f8Sdrh # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
2801bb4957f8Sdrh #endif
2802bb4957f8Sdrh #if SQLITE_MAX_VDBE_OP<40
2803bb4957f8Sdrh # error SQLITE_MAX_VDBE_OP must be at least 40
2804bb4957f8Sdrh #endif
280580738d9cSdrh #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
280680738d9cSdrh # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
2807bb4957f8Sdrh #endif
2808d08b2798Sdrh #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
2809d08b2798Sdrh # error SQLITE_MAX_ATTACHED must be between 0 and 125
2810bb4957f8Sdrh #endif
2811bb4957f8Sdrh #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
2812bb4957f8Sdrh # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
2813bb4957f8Sdrh #endif
281470a8ca3cSdrh #if SQLITE_MAX_COLUMN>32767
281570a8ca3cSdrh # error SQLITE_MAX_COLUMN must not exceed 32767
281670a8ca3cSdrh #endif
2817417168adSdrh #if SQLITE_MAX_TRIGGER_DEPTH<1
2818417168adSdrh # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
2819417168adSdrh #endif
2820111544cbSdrh #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
2821111544cbSdrh # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
2822111544cbSdrh #endif
2823bb4957f8Sdrh 
2824bb4957f8Sdrh 
2825bb4957f8Sdrh /*
2826bb4957f8Sdrh ** Change the value of a limit.  Report the old value.
2827bb4957f8Sdrh ** If an invalid limit index is supplied, report -1.
2828bb4957f8Sdrh ** Make no changes but still report the old value if the
2829bb4957f8Sdrh ** new limit is negative.
2830bb4957f8Sdrh **
2831bb4957f8Sdrh ** A new lower limit does not shrink existing constructs.
2832bb4957f8Sdrh ** It merely prevents new constructs that exceed the limit
2833bb4957f8Sdrh ** from forming.
2834bb4957f8Sdrh */
sqlite3_limit(sqlite3 * db,int limitId,int newLimit)2835bb4957f8Sdrh int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
2836bb4957f8Sdrh   int oldLimit;
28374e93f5bfSdrh 
28389ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
28399ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ){
28409ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
28419ca95730Sdrh     return -1;
28429ca95730Sdrh   }
28439ca95730Sdrh #endif
28444e93f5bfSdrh 
28454e93f5bfSdrh   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
28464e93f5bfSdrh   ** there is a hard upper bound set at compile-time by a C preprocessor
28474e93f5bfSdrh   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
28484e93f5bfSdrh   ** "_MAX_".)
28494e93f5bfSdrh   */
28504e93f5bfSdrh   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
28514e93f5bfSdrh   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
28524e93f5bfSdrh   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
28534e93f5bfSdrh   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
28544e93f5bfSdrh   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
28554e93f5bfSdrh   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
28564e93f5bfSdrh   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
28574e93f5bfSdrh   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
28584e93f5bfSdrh   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
28594e93f5bfSdrh                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
28604e93f5bfSdrh   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
28614e93f5bfSdrh   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
2862111544cbSdrh   assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
2863111544cbSdrh   assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
28644e93f5bfSdrh 
28654e93f5bfSdrh 
2866521cc849Sdrh   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
2867bb4957f8Sdrh     return -1;
2868bb4957f8Sdrh   }
2869bb4957f8Sdrh   oldLimit = db->aLimit[limitId];
28704e93f5bfSdrh   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
2871f47ce56cSdrh     if( newLimit>aHardLimit[limitId] ){
28724e93f5bfSdrh       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
2873f6a4ef14Sdrh     }else if( newLimit<1 && limitId==SQLITE_LIMIT_LENGTH ){
2874f6a4ef14Sdrh       newLimit = 1;
2875bb4957f8Sdrh     }
2876bb4957f8Sdrh     db->aLimit[limitId] = newLimit;
2877bb4957f8Sdrh   }
28784e93f5bfSdrh   return oldLimit;                     /* IMP: R-53341-35419 */
2879bb4957f8Sdrh }
2880bb4957f8Sdrh 
2881bb4957f8Sdrh /*
2882286ab7c2Sdan ** This function is used to parse both URIs and non-URI filenames passed by the
2883286ab7c2Sdan ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
2884286ab7c2Sdan ** URIs specified as part of ATTACH statements.
2885286ab7c2Sdan **
2886286ab7c2Sdan ** The first argument to this function is the name of the VFS to use (or
2887286ab7c2Sdan ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
2888286ab7c2Sdan ** query parameter. The second argument contains the URI (or non-URI filename)
2889286ab7c2Sdan ** itself. When this function is called the *pFlags variable should contain
2890286ab7c2Sdan ** the default flags to open the database handle with. The value stored in
2891286ab7c2Sdan ** *pFlags may be updated before returning if the URI filename contains
2892286ab7c2Sdan ** "cache=xxx" or "mode=xxx" query parameters.
2893286ab7c2Sdan **
2894286ab7c2Sdan ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
2895286ab7c2Sdan ** the VFS that should be used to open the database file. *pzFile is set to
2896df97d439Sdrh ** point to a buffer containing the name of the file to open.  The value
2897df97d439Sdrh ** stored in *pzFile is a database name acceptable to sqlite3_uri_parameter()
2898df97d439Sdrh ** and is in the same format as names created using sqlite3_create_filename().
2899df97d439Sdrh ** The caller must invoke sqlite3_free_filename() (not sqlite3_free()!) on
2900df97d439Sdrh ** the value returned in *pzFile to avoid a memory leak.
2901286ab7c2Sdan **
2902286ab7c2Sdan ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
2903286ab7c2Sdan ** may be set to point to a buffer containing an English language error
2904286ab7c2Sdan ** message. It is the responsibility of the caller to eventually release
2905286ab7c2Sdan ** this buffer by calling sqlite3_free().
2906cd74b611Sdan */
sqlite3ParseUri(const char * zDefaultVfs,const char * zUri,unsigned int * pFlags,sqlite3_vfs ** ppVfs,char ** pzFile,char ** pzErrMsg)2907cd74b611Sdan int sqlite3ParseUri(
2908cd74b611Sdan   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
2909cd74b611Sdan   const char *zUri,               /* Nul-terminated URI to parse */
2910522c26fbSdrh   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
2911cd74b611Sdan   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
2912cd74b611Sdan   char **pzFile,                  /* OUT: Filename component of URI */
2913cd74b611Sdan   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
2914cd74b611Sdan ){
291578e9dd2bSdan   int rc = SQLITE_OK;
2916522c26fbSdrh   unsigned int flags = *pFlags;
2917cd74b611Sdan   const char *zVfs = zDefaultVfs;
2918cd74b611Sdan   char *zFile;
2919de941c37Sdrh   char c;
2920cd74b611Sdan   int nUri = sqlite3Strlen30(zUri);
2921cd74b611Sdan 
2922cd74b611Sdan   assert( *pzErrMsg==0 );
2923cd74b611Sdan 
29248790b6e8Sdrh   if( ((flags & SQLITE_OPEN_URI)             /* IMP: R-48725-32206 */
29258790b6e8Sdrh             || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
292600729cbaSdrh    && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
2927cd74b611Sdan   ){
29285de15374Sdan     char *zOpt;
2929cd74b611Sdan     int eState;                   /* Parser state when parsing URI */
2930cd74b611Sdan     int iIn;                      /* Input character index */
2931cd74b611Sdan     int iOut = 0;                 /* Output character index */
2932df97d439Sdrh     u64 nByte = nUri+8;           /* Bytes of space to allocate */
2933cd74b611Sdan 
2934286ab7c2Sdan     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
2935286ab7c2Sdan     ** method that there may be extra parameters following the file-name.  */
2936286ab7c2Sdan     flags |= SQLITE_OPEN_URI;
2937286ab7c2Sdan 
2938286ab7c2Sdan     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
2939f3cdcdccSdrh     zFile = sqlite3_malloc64(nByte);
2940fad3039cSmistachkin     if( !zFile ) return SQLITE_NOMEM_BKPT;
2941cd74b611Sdan 
2942df97d439Sdrh     memset(zFile, 0, 4);  /* 4-byte of 0x00 is the start of DB name marker */
2943df97d439Sdrh     zFile += 4;
2944df97d439Sdrh 
2945869c0409Sdrh     iIn = 5;
29464a4b1389Sdrh #ifdef SQLITE_ALLOW_URI_AUTHORITY
29474a4b1389Sdrh     if( strncmp(zUri+5, "///", 3)==0 ){
29484a4b1389Sdrh       iIn = 7;
29494a4b1389Sdrh       /* The following condition causes URIs with five leading / characters
29504a4b1389Sdrh       ** like file://///host/path to be converted into UNCs like //host/path.
29514a4b1389Sdrh       ** The correct URI for that UNC has only two or four leading / characters
29524a4b1389Sdrh       ** file://host/path or file:////host/path.  But 5 leading slashes is a
29534a4b1389Sdrh       ** common error, we are told, so we handle it as a special case. */
29544a4b1389Sdrh       if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
29554a4b1389Sdrh     }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
29564a4b1389Sdrh       iIn = 16;
29574a4b1389Sdrh     }
29584a4b1389Sdrh #else
2959cd74b611Sdan     /* Discard the scheme and authority segments of the URI. */
2960cd74b611Sdan     if( zUri[5]=='/' && zUri[6]=='/' ){
2961cd74b611Sdan       iIn = 7;
2962cd74b611Sdan       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
29633b18a9a3Sdan       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
29643b18a9a3Sdan         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
29653b18a9a3Sdan             iIn-7, &zUri[7]);
29663b18a9a3Sdan         rc = SQLITE_ERROR;
29673b18a9a3Sdan         goto parse_uri_out;
29683b18a9a3Sdan       }
2969cd74b611Sdan     }
2970869c0409Sdrh #endif
2971cd74b611Sdan 
2972cd74b611Sdan     /* Copy the filename and any query parameters into the zFile buffer.
2973cd74b611Sdan     ** Decode %HH escape codes along the way.
2974cd74b611Sdan     **
2975cd74b611Sdan     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
2976cd74b611Sdan     ** on the parsing context. As follows:
2977cd74b611Sdan     **
2978cd74b611Sdan     **   0: Parsing file-name.
2979cd74b611Sdan     **   1: Parsing name section of a name=value query parameter.
2980cd74b611Sdan     **   2: Parsing value section of a name=value query parameter.
2981cd74b611Sdan     */
2982cd74b611Sdan     eState = 0;
2983de941c37Sdrh     while( (c = zUri[iIn])!=0 && c!='#' ){
2984de941c37Sdrh       iIn++;
2985cd74b611Sdan       if( c=='%'
2986cd74b611Sdan        && sqlite3Isxdigit(zUri[iIn])
2987cd74b611Sdan        && sqlite3Isxdigit(zUri[iIn+1])
2988cd74b611Sdan       ){
29896d49e256Sdan         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
29906d49e256Sdan         octet += sqlite3HexToInt(zUri[iIn++]);
2991cd74b611Sdan 
29926d49e256Sdan         assert( octet>=0 && octet<256 );
29936d49e256Sdan         if( octet==0 ){
29945c35e903Sdan #ifndef SQLITE_ENABLE_URI_00_ERROR
29955de15374Sdan           /* This branch is taken when "%00" appears within the URI. In this
29965de15374Sdan           ** case we ignore all text in the remainder of the path, name or
29975de15374Sdan           ** value currently being parsed. So ignore the current character
29985de15374Sdan           ** and skip to the next "?", "=" or "&", as appropriate. */
2999de941c37Sdrh           while( (c = zUri[iIn])!=0 && c!='#'
3000de941c37Sdrh               && (eState!=0 || c!='?')
3001de941c37Sdrh               && (eState!=1 || (c!='=' && c!='&'))
3002de941c37Sdrh               && (eState!=2 || c!='&')
30035de15374Sdan           ){
30045de15374Sdan             iIn++;
3005cd74b611Sdan           }
30065de15374Sdan           continue;
30075c35e903Sdan #else
30085c35e903Sdan           /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
30095c35e903Sdan           *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
30105c35e903Sdan           rc = SQLITE_ERROR;
30115c35e903Sdan           goto parse_uri_out;
30125c35e903Sdan #endif
30135de15374Sdan         }
30146d49e256Sdan         c = octet;
30155de15374Sdan       }else if( eState==1 && (c=='&' || c=='=') ){
30165de15374Sdan         if( zFile[iOut-1]==0 ){
30175de15374Sdan           /* An empty option name. Ignore this option altogether. */
30185de15374Sdan           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
30195de15374Sdan           continue;
30205de15374Sdan         }
30215de15374Sdan         if( c=='&' ){
30225de15374Sdan           zFile[iOut++] = '\0';
30235de15374Sdan         }else{
30245de15374Sdan           eState = 2;
30255de15374Sdan         }
3026cd74b611Sdan         c = 0;
30275de15374Sdan       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
30285de15374Sdan         c = 0;
3029cd74b611Sdan         eState = 1;
3030cd74b611Sdan       }
3031cd74b611Sdan       zFile[iOut++] = c;
3032cd74b611Sdan     }
3033cd74b611Sdan     if( eState==1 ) zFile[iOut++] = '\0';
3034df97d439Sdrh     memset(zFile+iOut, 0, 4); /* end-of-options + empty journal filenames */
3035cd74b611Sdan 
3036cd74b611Sdan     /* Check if there were any options specified that should be interpreted
3037cd74b611Sdan     ** here. Options that are interpreted here include "vfs" and those that
3038cd74b611Sdan     ** correspond to flags that may be passed to the sqlite3_open_v2()
3039cd74b611Sdan     ** method. */
30405de15374Sdan     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
3041cd74b611Sdan     while( zOpt[0] ){
3042cd74b611Sdan       int nOpt = sqlite3Strlen30(zOpt);
3043cd74b611Sdan       char *zVal = &zOpt[nOpt+1];
3044cd74b611Sdan       int nVal = sqlite3Strlen30(zVal);
3045cd74b611Sdan 
3046286ab7c2Sdan       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
3047cd74b611Sdan         zVfs = zVal;
3048cd74b611Sdan       }else{
304978e9dd2bSdan         struct OpenMode {
305078e9dd2bSdan           const char *z;
305178e9dd2bSdan           int mode;
305278e9dd2bSdan         } *aMode = 0;
305345caededSdrh         char *zModeType = 0;
305445caededSdrh         int mask = 0;
305545caededSdrh         int limit = 0;
305678e9dd2bSdan 
3057286ab7c2Sdan         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
305878e9dd2bSdan           static struct OpenMode aCacheMode[] = {
305978e9dd2bSdan             { "shared",  SQLITE_OPEN_SHAREDCACHE },
306078e9dd2bSdan             { "private", SQLITE_OPEN_PRIVATECACHE },
306178e9dd2bSdan             { 0, 0 }
306278e9dd2bSdan           };
306378e9dd2bSdan 
306478e9dd2bSdan           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
306578e9dd2bSdan           aMode = aCacheMode;
306678e9dd2bSdan           limit = mask;
306778e9dd2bSdan           zModeType = "cache";
306878e9dd2bSdan         }
3069286ab7c2Sdan         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
307078e9dd2bSdan           static struct OpenMode aOpenMode[] = {
307178e9dd2bSdan             { "ro",  SQLITE_OPEN_READONLY },
307278e9dd2bSdan             { "rw",  SQLITE_OPEN_READWRITE },
307378e9dd2bSdan             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
30740b8dcfa2Sdan             { "memory", SQLITE_OPEN_MEMORY },
307578e9dd2bSdan             { 0, 0 }
307678e9dd2bSdan           };
307778e9dd2bSdan 
30789c67b2aaSdrh           mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
30799c67b2aaSdrh                    | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
308078e9dd2bSdan           aMode = aOpenMode;
308178e9dd2bSdan           limit = mask & flags;
308278e9dd2bSdan           zModeType = "access";
308378e9dd2bSdan         }
308478e9dd2bSdan 
308578e9dd2bSdan         if( aMode ){
308678e9dd2bSdan           int i;
308778e9dd2bSdan           int mode = 0;
308878e9dd2bSdan           for(i=0; aMode[i].z; i++){
308978e9dd2bSdan             const char *z = aMode[i].z;
3090522c26fbSdrh             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
309178e9dd2bSdan               mode = aMode[i].mode;
309278e9dd2bSdan               break;
3093cd74b611Sdan             }
3094cd74b611Sdan           }
309578e9dd2bSdan           if( mode==0 ){
309678e9dd2bSdan             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
309778e9dd2bSdan             rc = SQLITE_ERROR;
309878e9dd2bSdan             goto parse_uri_out;
309978e9dd2bSdan           }
31009c67b2aaSdrh           if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
3101de941c37Sdrh             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
3102de941c37Sdrh                                         zModeType, zVal);
310378e9dd2bSdan             rc = SQLITE_PERM;
310478e9dd2bSdan             goto parse_uri_out;
310578e9dd2bSdan           }
310678e9dd2bSdan           flags = (flags & ~mask) | mode;
3107cd74b611Sdan         }
3108cd74b611Sdan       }
3109cd74b611Sdan 
3110cd74b611Sdan       zOpt = &zVal[nVal+1];
3111cd74b611Sdan     }
3112cd74b611Sdan 
3113cd74b611Sdan   }else{
3114df97d439Sdrh     zFile = sqlite3_malloc64(nUri+8);
3115fad3039cSmistachkin     if( !zFile ) return SQLITE_NOMEM_BKPT;
3116df97d439Sdrh     memset(zFile, 0, 4);
3117df97d439Sdrh     zFile += 4;
3118895decf6Sdan     if( nUri ){
3119cd74b611Sdan       memcpy(zFile, zUri, nUri);
3120895decf6Sdan     }
3121df97d439Sdrh     memset(zFile+nUri, 0, 4);
31224ab9d254Sdrh     flags &= ~SQLITE_OPEN_URI;
3123cd74b611Sdan   }
3124cd74b611Sdan 
3125cd74b611Sdan   *ppVfs = sqlite3_vfs_find(zVfs);
3126cd74b611Sdan   if( *ppVfs==0 ){
3127cd74b611Sdan     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
312878e9dd2bSdan     rc = SQLITE_ERROR;
312978e9dd2bSdan   }
313078e9dd2bSdan  parse_uri_out:
313178e9dd2bSdan   if( rc!=SQLITE_OK ){
3132df97d439Sdrh     sqlite3_free_filename(zFile);
313378e9dd2bSdan     zFile = 0;
3134cd74b611Sdan   }
3135cd74b611Sdan   *pFlags = flags;
3136cd74b611Sdan   *pzFile = zFile;
313778e9dd2bSdan   return rc;
3138cd74b611Sdan }
3139cd74b611Sdan 
31401eac9660Sdrh /*
31411eac9660Sdrh ** This routine does the core work of extracting URI parameters from a
31421eac9660Sdrh ** database filename for the sqlite3_uri_parameter() interface.
31431eac9660Sdrh */
uriParameter(const char * zFilename,const char * zParam)31441eac9660Sdrh static const char *uriParameter(const char *zFilename, const char *zParam){
31451eac9660Sdrh   zFilename += sqlite3Strlen30(zFilename) + 1;
3146c59ffa8cSdrh   while( ALWAYS(zFilename!=0) && zFilename[0] ){
31471eac9660Sdrh     int x = strcmp(zFilename, zParam);
31481eac9660Sdrh     zFilename += sqlite3Strlen30(zFilename) + 1;
31491eac9660Sdrh     if( x==0 ) return zFilename;
31501eac9660Sdrh     zFilename += sqlite3Strlen30(zFilename) + 1;
31511eac9660Sdrh   }
31521eac9660Sdrh   return 0;
31531eac9660Sdrh }
31541eac9660Sdrh 
3155e5989723Sdrh 
3156cd74b611Sdan 
3157cd74b611Sdan /*
31584ad1713cSdanielk1977 ** This routine does the work of opening a database on behalf of
31594ad1713cSdanielk1977 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
3160ee570fa4Sdrh ** is UTF-8 encoded.
31614ad1713cSdanielk1977 */
openDatabase(const char * zFilename,sqlite3 ** ppDb,unsigned int flags,const char * zVfs)31624ad1713cSdanielk1977 static int openDatabase(
31634ad1713cSdanielk1977   const char *zFilename, /* Database filename UTF-8 encoded */
3164605264d2Sdrh   sqlite3 **ppDb,        /* OUT: Returned database handle */
3165522c26fbSdrh   unsigned int flags,    /* Operational flags */
3166605264d2Sdrh   const char *zVfs       /* Name of the VFS to use */
31674ad1713cSdanielk1977 ){
3168cd74b611Sdan   sqlite3 *db;                    /* Store allocated handle here */
3169cd74b611Sdan   int rc;                         /* Return code */
3170cd74b611Sdan   int isThreadsafe;               /* True for threadsafe connections */
3171cd74b611Sdan   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
3172cd74b611Sdan   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
317320e34f91Sdrh   int i;                          /* Loop counter */
31744ad1713cSdanielk1977 
31759ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
31769ca95730Sdrh   if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
31779ca95730Sdrh #endif
3178e0d0f8eeSdrh   *ppDb = 0;
317940257ffdSdrh #ifndef SQLITE_OMIT_AUTOINIT
318040257ffdSdrh   rc = sqlite3_initialize();
318140257ffdSdrh   if( rc ) return rc;
318240257ffdSdrh #endif
318340257ffdSdrh 
3184039963adSdrh   if( sqlite3GlobalConfig.bCoreMutex==0 ){
31859a6284c1Sdanielk1977     isThreadsafe = 0;
3186039963adSdrh   }else if( flags & SQLITE_OPEN_NOMUTEX ){
3187039963adSdrh     isThreadsafe = 0;
3188039963adSdrh   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
3189039963adSdrh     isThreadsafe = 1;
3190039963adSdrh   }else{
3191039963adSdrh     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
31929a6284c1Sdanielk1977   }
31938385becfSdan 
3194f1f12688Sdrh   if( flags & SQLITE_OPEN_PRIVATECACHE ){
3195f4cfac9dSdrh     flags &= ~SQLITE_OPEN_SHAREDCACHE;
3196f1f12688Sdrh   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
3197f1f12688Sdrh     flags |= SQLITE_OPEN_SHAREDCACHE;
3198f1f12688Sdrh   }
31999a6284c1Sdanielk1977 
3200b25a9f46Sdrh   /* Remove harmful bits from the flags parameter
3201b25a9f46Sdrh   **
3202b25a9f46Sdrh   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
3203b25a9f46Sdrh   ** dealt with in the previous code block.  Besides these, the only
3204b25a9f46Sdrh   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
320503e1b40bSdrh   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
320691acf7d3Sdrh   ** SQLITE_OPEN_PRIVATECACHE, SQLITE_OPEN_EXRESCODE, and some reserved
320791acf7d3Sdrh   ** bits.  Silently mask off all other flags.
3208b25a9f46Sdrh   */
3209a4267dccSdrh   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
3210f6d07c83Sdrh                SQLITE_OPEN_EXCLUSIVE |
3211a4267dccSdrh                SQLITE_OPEN_MAIN_DB |
3212a4267dccSdrh                SQLITE_OPEN_TEMP_DB |
3213a4267dccSdrh                SQLITE_OPEN_TRANSIENT_DB |
3214a4267dccSdrh                SQLITE_OPEN_MAIN_JOURNAL |
3215a4267dccSdrh                SQLITE_OPEN_TEMP_JOURNAL |
3216a4267dccSdrh                SQLITE_OPEN_SUBJOURNAL |
3217ccb2113aSdrh                SQLITE_OPEN_SUPER_JOURNAL |
3218039963adSdrh                SQLITE_OPEN_NOMUTEX |
3219357b5f97Sdrh                SQLITE_OPEN_FULLMUTEX |
3220357b5f97Sdrh                SQLITE_OPEN_WAL
3221a4267dccSdrh              );
3222a4267dccSdrh 
32234ad1713cSdanielk1977   /* Allocate the sqlite data structure */
322417435752Sdrh   db = sqlite3MallocZero( sizeof(sqlite3) );
32254ad1713cSdanielk1977   if( db==0 ) goto opendb_out;
32268385becfSdan   if( isThreadsafe
32278385becfSdan #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
32288385becfSdan    || sqlite3GlobalConfig.bCoreMutex
32298385becfSdan #endif
32308385becfSdan   ){
323159f8c08eSdanielk1977     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
3232605264d2Sdrh     if( db->mutex==0 ){
3233153c62c4Sdrh       sqlite3_free(db);
3234153c62c4Sdrh       db = 0;
3235605264d2Sdrh       goto opendb_out;
3236605264d2Sdrh     }
32378385becfSdan     if( isThreadsafe==0 ){
32388385becfSdan       sqlite3MutexWarnOnContention(db->mutex);
32398385becfSdan     }
324059f8c08eSdanielk1977   }
324127641703Sdrh   sqlite3_mutex_enter(db->mutex);
324291acf7d3Sdrh   db->errMask = (flags & SQLITE_OPEN_EXRESCODE)!=0 ? 0xffffffff : 0xff;
32434ad1713cSdanielk1977   db->nDb = 2;
32445f9de6ecSdrh   db->eOpenState = SQLITE_STATE_BUSY;
32454ad1713cSdanielk1977   db->aDb = db->aDbStatic;
3246c4b1e5e7Sdan   db->lookaside.bDisable = 1;
324731f69626Sdrh   db->lookaside.sz = 0;
3248633e6d57Sdrh 
3249bb4957f8Sdrh   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
3250bb4957f8Sdrh   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
32516b2129aaSdrh   db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
32521d850a72Sdanielk1977   db->autoCommit = 1;
3253ddac25c7Sdrh   db->nextAutovac = -1;
32549b4c59faSdrh   db->szMmap = sqlite3GlobalConfig.szMmap;
3255f653d782Sdanielk1977   db->nextPagesize = 0;
32562a6a72a8Sdrh   db->init.azInit = sqlite3StdType; /* Any array of string ptrs will do */
32570546027cSdan #ifdef SQLITE_ENABLE_SORTER_MMAP
32580546027cSdan   /* Beginning with version 3.37.0, using the VFS xFetch() API to memory-map
32590546027cSdan   ** the temporary files used to do external sorts (see code in vdbesort.c)
32600546027cSdan   ** is disabled. It can still be used either by defining
32610546027cSdan   ** SQLITE_ENABLE_SORTER_MMAP at compile time or by using the
32620546027cSdan   ** SQLITE_TESTCTRL_SORTER_MMAP test-control at runtime. */
32638930c2abSdan   db->nMaxSorterMmap = 0x7FFFFFFF;
32640546027cSdan #endif
32654b50da9cSdrh   db->flags |= SQLITE_ShortColNames
32664b50da9cSdrh                  | SQLITE_EnableTrigger
326711d88e68Sdrh                  | SQLITE_EnableView
32684b50da9cSdrh                  | SQLITE_CacheSpill
3269b77da374Sdrh #if !defined(SQLITE_TRUSTED_SCHEMA) || SQLITE_TRUSTED_SCHEMA+0!=0
3270b77da374Sdrh                  | SQLITE_TrustedSchema
3271b77da374Sdrh #endif
32724b50da9cSdrh /* The SQLITE_DQS compile-time option determines the default settings
32734b50da9cSdrh ** for SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML.
32744b50da9cSdrh **
32754b50da9cSdrh **    SQLITE_DQS     SQLITE_DBCONFIG_DQS_DDL    SQLITE_DBCONFIG_DQS_DML
32764b50da9cSdrh **    ----------     -----------------------    -----------------------
32774b50da9cSdrh **     undefined               on                          on
32784b50da9cSdrh **         3                   on                          on
32794b50da9cSdrh **         2                   on                         off
32804b50da9cSdrh **         1                  off                          on
32814b50da9cSdrh **         0                  off                         off
32824b50da9cSdrh **
32834b50da9cSdrh ** Legacy behavior is 3 (double-quoted string literals are allowed anywhere)
32844b50da9cSdrh ** and so that is the default.  But developers are encouranged to use
32854b50da9cSdrh ** -DSQLITE_DQS=0 (best) or -DSQLITE_DQS=1 (second choice) if possible.
32864b50da9cSdrh */
32874b50da9cSdrh #if !defined(SQLITE_DQS)
32884b50da9cSdrh # define SQLITE_DQS 3
32894b50da9cSdrh #endif
32904b50da9cSdrh #if (SQLITE_DQS&1)==1
3291d0ff601cSdrh                  | SQLITE_DqsDML
32924b50da9cSdrh #endif
32934b50da9cSdrh #if (SQLITE_DQS&2)==2
32944b50da9cSdrh                  | SQLITE_DqsDDL
32954b50da9cSdrh #endif
32964b50da9cSdrh 
32971d1f07dfSdan #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
3298986b3879Sdrh                  | SQLITE_AutoIndex
3299986b3879Sdrh #endif
3300883ad049Sdrh #if SQLITE_DEFAULT_CKPTFULLFSYNC
3301883ad049Sdrh                  | SQLITE_CkptFullFSync
3302883ad049Sdrh #endif
330376fe8032Sdrh #if SQLITE_DEFAULT_FILE_FORMAT<4
330476fe8032Sdrh                  | SQLITE_LegacyFileFmt
330576fe8032Sdrh #endif
330656424db4Sdrh #ifdef SQLITE_ENABLE_LOAD_EXTENSION
330756424db4Sdrh                  | SQLITE_LoadExtension
330856424db4Sdrh #endif
33095bde73c4Sdan #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
33105e1a2788Sdan                  | SQLITE_RecTriggers
331176d462eeSdan #endif
3312a4bfd7fdSdrh #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
3313a4bfd7fdSdrh                  | SQLITE_ForeignKeys
3314a4bfd7fdSdrh #endif
3315f5471925Sdrh #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
3316f5471925Sdrh                  | SQLITE_ReverseOrder
3317f5471925Sdrh #endif
33181421d980Sdrh #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
33191421d980Sdrh                  | SQLITE_CellSizeCk
33201421d980Sdrh #endif
3321d42908fbSdrh #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
3322d42908fbSdrh                  | SQLITE_Fts3Tokenizer
3323d42908fbSdrh #endif
3324169dd928Sdrh #if defined(SQLITE_ENABLE_QPSG)
3325169dd928Sdrh                  | SQLITE_EnableQPSG
3326169dd928Sdrh #endif
33276ab91a7aSdrh #if defined(SQLITE_DEFAULT_DEFENSIVE)
33286ab91a7aSdrh                  | SQLITE_Defensive
33296ab91a7aSdrh #endif
3330e0a8b712Sdrh #if defined(SQLITE_DEFAULT_LEGACY_ALTER_TABLE)
3331e0a8b712Sdrh                  | SQLITE_LegacyAlter
3332e0a8b712Sdrh #endif
333376fe8032Sdrh       ;
3334e61922a6Sdrh   sqlite3HashInit(&db->aCollSeq);
3335b9bb7c18Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
3336e61922a6Sdrh   sqlite3HashInit(&db->aModule);
3337b9bb7c18Sdrh #endif
3338da184236Sdanielk1977 
33390202b29eSdanielk1977   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
33400202b29eSdanielk1977   ** and UTF-16, so add a version for each to avoid any unnecessary
33410202b29eSdanielk1977   ** conversions. The only error that can occur here is a malloc() failure.
33425e3b49bcSdrh   **
33435e3b49bcSdrh   ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
33445e3b49bcSdrh   ** functions:
33450202b29eSdanielk1977   */
3346f19aa5faSdrh   createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
3347f19aa5faSdrh   createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
3348f19aa5faSdrh   createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
33495e3b49bcSdrh   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
3350821afa44Sdrh   createCollation(db, "RTRIM", SQLITE_UTF8, 0, rtrimCollFunc, 0);
335177db4c05Sdrh   if( db->mallocFailed ){
33520202b29eSdanielk1977     goto opendb_out;
33530202b29eSdanielk1977   }
33540202b29eSdanielk1977 
3355c3b6fdaeSdrh #if SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL)
3356c3b6fdaeSdrh   /* Process magic filenames ":localStorage:" and ":sessionStorage:" */
3357c3b6fdaeSdrh   if( zFilename && zFilename[0]==':' ){
3358c3b6fdaeSdrh     if( strcmp(zFilename, ":localStorage:")==0 ){
3359c3b6fdaeSdrh       zFilename = "file:local?vfs=kvvfs";
3360c3b6fdaeSdrh       flags |= SQLITE_OPEN_URI;
3361c3b6fdaeSdrh     }else if( strcmp(zFilename, ":sessionStorage:")==0 ){
3362c3b6fdaeSdrh       zFilename = "file:session?vfs=kvvfs";
3363c3b6fdaeSdrh       flags |= SQLITE_OPEN_URI;
3364c3b6fdaeSdrh     }
3365c3b6fdaeSdrh   }
3366c3b6fdaeSdrh #endif /* SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL) */
3367c3b6fdaeSdrh 
3368ff4fa772Sdrh   /* Parse the filename/URI argument
3369ff4fa772Sdrh   **
3370ff4fa772Sdrh   ** Only allow sensible combinations of bits in the flags argument.
3371ff4fa772Sdrh   ** Throw an error if any non-sense combination is used.  If we
3372ff4fa772Sdrh   ** do not block illegal combinations here, it could trigger
3373ff4fa772Sdrh   ** assert() statements in deeper layers.  Sensible combinations
3374ff4fa772Sdrh   ** are:
3375ff4fa772Sdrh   **
3376ff4fa772Sdrh   **  1:  SQLITE_OPEN_READONLY
3377ff4fa772Sdrh   **  2:  SQLITE_OPEN_READWRITE
3378ff4fa772Sdrh   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
3379ff4fa772Sdrh   */
338019432996Sdan   db->openFlags = flags;
3381ff4fa772Sdrh   assert( SQLITE_OPEN_READONLY  == 0x01 );
3382ff4fa772Sdrh   assert( SQLITE_OPEN_READWRITE == 0x02 );
3383ff4fa772Sdrh   assert( SQLITE_OPEN_CREATE    == 0x04 );
3384ff4fa772Sdrh   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
3385ff4fa772Sdrh   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
3386ff4fa772Sdrh   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
3387ff4fa772Sdrh   if( ((1<<(flags&7)) & 0x46)==0 ){
3388bbf6d432Sdrh     rc = SQLITE_MISUSE_BKPT;  /* IMP: R-18321-05872 */
3389ff4fa772Sdrh   }else{
3390cd74b611Sdan     rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
3391ff4fa772Sdrh   }
3392cd74b611Sdan   if( rc!=SQLITE_OK ){
33934a642b60Sdrh     if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
339413f40da3Sdrh     sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
3395cd74b611Sdan     sqlite3_free(zErrMsg);
3396cd74b611Sdan     goto opendb_out;
3397cd74b611Sdan   }
3398fd608063Sdrh   assert( db->pVfs!=0 );
3399dddec5caSdrh #if SQLITE_OS_KV || defined(SQLITE_OS_KV_OPTIONAL)
3400fd608063Sdrh   if( sqlite3_stricmp(db->pVfs->zName, "kvvfs")==0 ){
3401fd608063Sdrh     db->temp_store = 2;
3402fd608063Sdrh   }
3403fd608063Sdrh #endif
3404cd74b611Sdan 
34054ad1713cSdanielk1977   /* Open the backend database driver */
34063a6d8aecSdan   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
340775c014c3Sdrh                         flags | SQLITE_OPEN_MAIN_DB);
34084ad1713cSdanielk1977   if( rc!=SQLITE_OK ){
340945e60aabSdanielk1977     if( rc==SQLITE_IOERR_NOMEM ){
3410fad3039cSmistachkin       rc = SQLITE_NOMEM_BKPT;
341145e60aabSdanielk1977     }
341213f40da3Sdrh     sqlite3Error(db, rc);
34134ad1713cSdanielk1977     goto opendb_out;
34144ad1713cSdanielk1977   }
34150235a033Sdan   sqlite3BtreeEnter(db->aDb[0].pBt);
341617435752Sdrh   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
341742a630b1Sdrh   if( !db->mallocFailed ){
341842a630b1Sdrh     sqlite3SetTextEncoding(db, SCHEMA_ENC(db));
341942a630b1Sdrh   }
34200235a033Sdan   sqlite3BtreeLeave(db->aDb[0].pBt);
342117435752Sdrh   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
342214db2665Sdanielk1977 
3423e872d513Sdrh   /* The default safety_level for the main database is FULL; for the temp
3424e872d513Sdrh   ** database it is OFF. This matches the pager layer defaults.
342553c0f748Sdanielk1977   */
342669c33826Sdrh   db->aDb[0].zDbSName = "main";
3427c2ae2073Sdrh   db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
342869c33826Sdrh   db->aDb[1].zDbSName = "temp";
3429e872d513Sdrh   db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
343053c0f748Sdanielk1977 
34315f9de6ecSdrh   db->eOpenState = SQLITE_STATE_OPEN;
343217435752Sdrh   if( db->mallocFailed ){
3433832a58a6Sdanielk1977     goto opendb_out;
3434832a58a6Sdanielk1977   }
3435832a58a6Sdanielk1977 
34368e227875Sdanielk1977   /* Register all built-in functions, but do not attempt to read the
34378e227875Sdanielk1977   ** database schema yet. This is delayed until the first time the database
34388e227875Sdanielk1977   ** is accessed.
34398e227875Sdanielk1977   */
344013f40da3Sdrh   sqlite3Error(db, SQLITE_OK);
344180738d9cSdrh   sqlite3RegisterPerConnectionBuiltinFunctions(db);
3442c9e75fb2Sdan   rc = sqlite3_errcode(db);
3443c9e75fb2Sdan 
344420e34f91Sdrh 
344520e34f91Sdrh   /* Load compiled-in extensions */
344620e34f91Sdrh   for(i=0; rc==SQLITE_OK && i<ArraySize(sqlite3BuiltinExtensions); i++){
344720e34f91Sdrh     rc = sqlite3BuiltinExtensions[i](db);
3448c9e75fb2Sdan   }
34494ad1713cSdanielk1977 
34501409be69Sdrh   /* Load automatic extensions - extensions that have been registered
34511409be69Sdrh   ** using the sqlite3_automatic_extension() API.
34521409be69Sdrh   */
3453e5077c12Sdrh   if( rc==SQLITE_OK ){
34547aaa8786Sdrh     sqlite3AutoLoadExtensions(db);
34557aaa8786Sdrh     rc = sqlite3_errcode(db);
34567aaa8786Sdrh     if( rc!=SQLITE_OK ){
3457832a58a6Sdanielk1977       goto opendb_out;
3458832a58a6Sdanielk1977     }
3459e5077c12Sdrh   }
34601409be69Sdrh 
34612a83c100Sdrh #ifdef SQLITE_ENABLE_INTERNAL_FUNCTIONS
34622a83c100Sdrh   /* Testing use only!!! The -DSQLITE_ENABLE_INTERNAL_FUNCTIONS=1 compile-time
34632a83c100Sdrh   ** option gives access to internal functions by default.
34642a83c100Sdrh   ** Testing use only!!! */
34652a83c100Sdrh   db->mDbFlags |= DBFLAG_InternalFunc;
34662a83c100Sdrh #endif
34672a83c100Sdrh 
34688fd5bd36Sdrh   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
34698fd5bd36Sdrh   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
34708fd5bd36Sdrh   ** mode.  Doing nothing at all also makes NORMAL the default.
34718fd5bd36Sdrh   */
34728fd5bd36Sdrh #ifdef SQLITE_DEFAULT_LOCKING_MODE
34738fd5bd36Sdrh   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
34748fd5bd36Sdrh   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
34758fd5bd36Sdrh                           SQLITE_DEFAULT_LOCKING_MODE);
34768fd5bd36Sdrh #endif
34778fd5bd36Sdrh 
347813f40da3Sdrh   if( rc ) sqlite3Error(db, rc);
3479f6b1a8e1Sdrh 
3480633e6d57Sdrh   /* Enable the lookaside-malloc subsystem */
34811b67f3caSdrh   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
34821b67f3caSdrh                         sqlite3GlobalConfig.nLookaside);
3483633e6d57Sdrh 
34845a299f91Sdan   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
3485586b9c8aSdan 
34864ad1713cSdanielk1977 opendb_out:
3487afc91047Sdrh   if( db ){
34883ba689d8Sdrh     assert( db->mutex!=0 || isThreadsafe==0
34893ba689d8Sdrh            || sqlite3GlobalConfig.bFullMutex==0 );
349027641703Sdrh     sqlite3_mutex_leave(db->mutex);
3491f3a65f7eSdrh   }
349259633aeeSdanielk1977   rc = sqlite3_errcode(db);
3493c18e022fSdrh   assert( db!=0 || (rc&0xff)==SQLITE_NOMEM );
349491acf7d3Sdrh   if( (rc&0xff)==SQLITE_NOMEM ){
34957ddad969Sdanielk1977     sqlite3_close(db);
34967ddad969Sdanielk1977     db = 0;
349759633aeeSdanielk1977   }else if( rc!=SQLITE_OK ){
34985f9de6ecSdrh     db->eOpenState = SQLITE_STATE_SICK;
349913073931Sdanielk1977   }
35004ad1713cSdanielk1977   *ppDb = db;
3501ac455939Sdan #ifdef SQLITE_ENABLE_SQLLOG
3502ac455939Sdan   if( sqlite3GlobalConfig.xSqllog ){
350371ba10d3Sdan     /* Opening a db handle. Fourth parameter is passed 0. */
350471ba10d3Sdan     void *pArg = sqlite3GlobalConfig.pSqllogArg;
350571ba10d3Sdan     sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
3506ac455939Sdan   }
3507ac455939Sdan #endif
3508df97d439Sdrh   sqlite3_free_filename(zOpen);
350991acf7d3Sdrh   return rc;
35104ad1713cSdanielk1977 }
35114ad1713cSdanielk1977 
3512e5989723Sdrh 
35134ad1713cSdanielk1977 /*
35144ad1713cSdanielk1977 ** Open a new database handle.
35154ad1713cSdanielk1977 */
sqlite3_open(const char * zFilename,sqlite3 ** ppDb)351680290863Sdanielk1977 int sqlite3_open(
35174ad1713cSdanielk1977   const char *zFilename,
35184f057f90Sdanielk1977   sqlite3 **ppDb
35194ad1713cSdanielk1977 ){
3520605264d2Sdrh   return openDatabase(zFilename, ppDb,
3521605264d2Sdrh                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
3522605264d2Sdrh }
sqlite3_open_v2(const char * filename,sqlite3 ** ppDb,int flags,const char * zVfs)3523605264d2Sdrh int sqlite3_open_v2(
3524428e2826Sdrh   const char *filename,   /* Database filename (UTF-8) */
3525605264d2Sdrh   sqlite3 **ppDb,         /* OUT: SQLite db handle */
3526605264d2Sdrh   int flags,              /* Flags */
3527605264d2Sdrh   const char *zVfs        /* Name of VFS module to use */
3528605264d2Sdrh ){
3529522c26fbSdrh   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
353083ab5a8fSdanielk1977 }
353183ab5a8fSdanielk1977 
35326c62608fSdrh #ifndef SQLITE_OMIT_UTF16
35334ad1713cSdanielk1977 /*
35344ad1713cSdanielk1977 ** Open a new database handle.
35354ad1713cSdanielk1977 */
sqlite3_open16(const void * zFilename,sqlite3 ** ppDb)35364ad1713cSdanielk1977 int sqlite3_open16(
35374ad1713cSdanielk1977   const void *zFilename,
35384f057f90Sdanielk1977   sqlite3 **ppDb
35394ad1713cSdanielk1977 ){
3540bfd6cce5Sdanielk1977   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
3541bfd6cce5Sdanielk1977   sqlite3_value *pVal;
354240257ffdSdrh   int rc;
35434ad1713cSdanielk1977 
35449ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
35459ca95730Sdrh   if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
35469ca95730Sdrh #endif
35474ad1713cSdanielk1977   *ppDb = 0;
354840257ffdSdrh #ifndef SQLITE_OMIT_AUTOINIT
354940257ffdSdrh   rc = sqlite3_initialize();
355040257ffdSdrh   if( rc ) return rc;
355140257ffdSdrh #endif
35529ca95730Sdrh   if( zFilename==0 ) zFilename = "\000\000";
35531e536953Sdanielk1977   pVal = sqlite3ValueNew(0);
3554b21c8cd4Sdrh   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
3555b21c8cd4Sdrh   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
3556bfd6cce5Sdanielk1977   if( zFilename8 ){
3557605264d2Sdrh     rc = openDatabase(zFilename8, ppDb,
3558605264d2Sdrh                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
3559afc91047Sdrh     assert( *ppDb || rc==SQLITE_NOMEM );
3560f51bf48bSdanielk1977     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
35619bd3cc46Sdrh       SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
35624ad1713cSdanielk1977     }
356340257ffdSdrh   }else{
3564fad3039cSmistachkin     rc = SQLITE_NOMEM_BKPT;
3565bfd6cce5Sdanielk1977   }
3566bfd6cce5Sdanielk1977   sqlite3ValueFree(pVal);
35678e227875Sdanielk1977 
3568597d2b64Sdrh   return rc & 0xff;
35694ad1713cSdanielk1977 }
35706c62608fSdrh #endif /* SQLITE_OMIT_UTF16 */
35714ad1713cSdanielk1977 
3572106bb236Sdanielk1977 /*
3573d8123366Sdanielk1977 ** Register a new collation sequence with the database handle db.
3574d8123366Sdanielk1977 */
sqlite3_create_collation(sqlite3 * db,const char * zName,int enc,void * pCtx,int (* xCompare)(void *,int,const void *,int,const void *))35750202b29eSdanielk1977 int sqlite3_create_collation(
35760202b29eSdanielk1977   sqlite3* db,
35770202b29eSdanielk1977   const char *zName,
3578466be56bSdanielk1977   int enc,
35790202b29eSdanielk1977   void* pCtx,
35800202b29eSdanielk1977   int(*xCompare)(void*,int,const void*,int,const void*)
35810202b29eSdanielk1977 ){
35824f81bbb5Sdrh   return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
3583a9808b31Sdanielk1977 }
3584a9808b31Sdanielk1977 
3585a9808b31Sdanielk1977 /*
3586a9808b31Sdanielk1977 ** Register a new collation sequence with the database handle db.
3587a9808b31Sdanielk1977 */
sqlite3_create_collation_v2(sqlite3 * db,const char * zName,int enc,void * pCtx,int (* xCompare)(void *,int,const void *,int,const void *),void (* xDel)(void *))3588a393c036Sdanielk1977 int sqlite3_create_collation_v2(
3589a9808b31Sdanielk1977   sqlite3* db,
3590a9808b31Sdanielk1977   const char *zName,
3591a9808b31Sdanielk1977   int enc,
3592a9808b31Sdanielk1977   void* pCtx,
3593a9808b31Sdanielk1977   int(*xCompare)(void*,int,const void*,int,const void*),
3594a9808b31Sdanielk1977   void(*xDel)(void*)
3595a9808b31Sdanielk1977 ){
3596a9808b31Sdanielk1977   int rc;
35979ca95730Sdrh 
35989ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
35999ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
36009ca95730Sdrh #endif
3601e30f4426Sdrh   sqlite3_mutex_enter(db->mutex);
360217435752Sdrh   assert( !db->mallocFailed );
36034dd65e0fSdrh   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
3604e30f4426Sdrh   rc = sqlite3ApiExit(db, rc);
3605e30f4426Sdrh   sqlite3_mutex_leave(db->mutex);
3606e30f4426Sdrh   return rc;
36070202b29eSdanielk1977 }
36080202b29eSdanielk1977 
36096c62608fSdrh #ifndef SQLITE_OMIT_UTF16
3610d8123366Sdanielk1977 /*
3611d8123366Sdanielk1977 ** Register a new collation sequence with the database handle db.
3612d8123366Sdanielk1977 */
sqlite3_create_collation16(sqlite3 * db,const void * zName,int enc,void * pCtx,int (* xCompare)(void *,int,const void *,int,const void *))36130202b29eSdanielk1977 int sqlite3_create_collation16(
36140202b29eSdanielk1977   sqlite3* db,
3615bda2e62cSmihailim   const void *zName,
3616466be56bSdanielk1977   int enc,
36170202b29eSdanielk1977   void* pCtx,
36180202b29eSdanielk1977   int(*xCompare)(void*,int,const void*,int,const void*)
36190202b29eSdanielk1977 ){
36209a30cf65Sdanielk1977   int rc = SQLITE_OK;
3621af9a7c22Sdrh   char *zName8;
36229ca95730Sdrh 
36239ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
36249ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
36259ca95730Sdrh #endif
3626e30f4426Sdrh   sqlite3_mutex_enter(db->mutex);
362717435752Sdrh   assert( !db->mallocFailed );
3628b7dca7d7Sdan   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
36299a30cf65Sdanielk1977   if( zName8 ){
36304dd65e0fSdrh     rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
3631633e6d57Sdrh     sqlite3DbFree(db, zName8);
36329a30cf65Sdanielk1977   }
3633e30f4426Sdrh   rc = sqlite3ApiExit(db, rc);
3634e30f4426Sdrh   sqlite3_mutex_leave(db->mutex);
3635e30f4426Sdrh   return rc;
36360202b29eSdanielk1977 }
36376c62608fSdrh #endif /* SQLITE_OMIT_UTF16 */
36387cedc8d4Sdanielk1977 
3639d8123366Sdanielk1977 /*
3640d8123366Sdanielk1977 ** Register a collation sequence factory callback with the database handle
3641d8123366Sdanielk1977 ** db. Replace any previously installed collation sequence factory.
3642d8123366Sdanielk1977 */
sqlite3_collation_needed(sqlite3 * db,void * pCollNeededArg,void (* xCollNeeded)(void *,sqlite3 *,int eTextRep,const char *))36437cedc8d4Sdanielk1977 int sqlite3_collation_needed(
36447cedc8d4Sdanielk1977   sqlite3 *db,
36457cedc8d4Sdanielk1977   void *pCollNeededArg,
36467cedc8d4Sdanielk1977   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
36477cedc8d4Sdanielk1977 ){
36489ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
36499ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
36509ca95730Sdrh #endif
3651e30f4426Sdrh   sqlite3_mutex_enter(db->mutex);
36527cedc8d4Sdanielk1977   db->xCollNeeded = xCollNeeded;
36537cedc8d4Sdanielk1977   db->xCollNeeded16 = 0;
36547cedc8d4Sdanielk1977   db->pCollNeededArg = pCollNeededArg;
3655e30f4426Sdrh   sqlite3_mutex_leave(db->mutex);
36567cedc8d4Sdanielk1977   return SQLITE_OK;
36577cedc8d4Sdanielk1977 }
3658d8123366Sdanielk1977 
36596c62608fSdrh #ifndef SQLITE_OMIT_UTF16
3660d8123366Sdanielk1977 /*
3661d8123366Sdanielk1977 ** Register a collation sequence factory callback with the database handle
3662d8123366Sdanielk1977 ** db. Replace any previously installed collation sequence factory.
3663d8123366Sdanielk1977 */
sqlite3_collation_needed16(sqlite3 * db,void * pCollNeededArg,void (* xCollNeeded16)(void *,sqlite3 *,int eTextRep,const void *))36647cedc8d4Sdanielk1977 int sqlite3_collation_needed16(
36657cedc8d4Sdanielk1977   sqlite3 *db,
36667cedc8d4Sdanielk1977   void *pCollNeededArg,
36677cedc8d4Sdanielk1977   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
36687cedc8d4Sdanielk1977 ){
36699ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
36709ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
36719ca95730Sdrh #endif
3672e30f4426Sdrh   sqlite3_mutex_enter(db->mutex);
36737cedc8d4Sdanielk1977   db->xCollNeeded = 0;
36747cedc8d4Sdanielk1977   db->xCollNeeded16 = xCollNeeded16;
36757cedc8d4Sdanielk1977   db->pCollNeededArg = pCollNeededArg;
3676e30f4426Sdrh   sqlite3_mutex_leave(db->mutex);
36777cedc8d4Sdanielk1977   return SQLITE_OK;
36787cedc8d4Sdanielk1977 }
36796c62608fSdrh #endif /* SQLITE_OMIT_UTF16 */
36806b456a2bSdanielk1977 
3681eec556d3Sshane #ifndef SQLITE_OMIT_DEPRECATED
36826b456a2bSdanielk1977 /*
36837ddad969Sdanielk1977 ** This function is now an anachronism. It used to be used to recover from a
36847ddad969Sdanielk1977 ** malloc() failure, but SQLite now does this automatically.
36856b456a2bSdanielk1977 */
sqlite3_global_recover(void)36867d97efbeSdrh int sqlite3_global_recover(void){
3687261919ccSdanielk1977   return SQLITE_OK;
36886b456a2bSdanielk1977 }
36896b456a2bSdanielk1977 #endif
36903e1d8e63Sdrh 
36913e1d8e63Sdrh /*
36923e1d8e63Sdrh ** Test to see whether or not the database connection is in autocommit
36933e1d8e63Sdrh ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
36943e1d8e63Sdrh ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
36953e1d8e63Sdrh ** by the next COMMIT or ROLLBACK.
36963e1d8e63Sdrh */
sqlite3_get_autocommit(sqlite3 * db)36973e1d8e63Sdrh int sqlite3_get_autocommit(sqlite3 *db){
36989ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
36999ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ){
37009ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
37019ca95730Sdrh     return 0;
37029ca95730Sdrh   }
37039ca95730Sdrh #endif
37043e1d8e63Sdrh   return db->autoCommit;
37053e1d8e63Sdrh }
370649285708Sdrh 
370749285708Sdrh /*
370860ec914cSpeter.d.reid ** The following routines are substitutes for constants SQLITE_CORRUPT,
37098fd8413aSmistachkin ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
371060ec914cSpeter.d.reid ** constants.  They serve two purposes:
37119978c97eSdrh **
37129978c97eSdrh **   1.  Serve as a convenient place to set a breakpoint in a debugger
37139978c97eSdrh **       to detect when version error conditions occurs.
37149978c97eSdrh **
37159978c97eSdrh **   2.  Invoke sqlite3_log() to provide the source code location where
37169978c97eSdrh **       a low-level error is first detected.
371749285708Sdrh */
sqlite3ReportError(int iErr,int lineno,const char * zType)3718eebf2f57Sdan int sqlite3ReportError(int iErr, int lineno, const char *zType){
371932c49904Sdrh   sqlite3_log(iErr, "%s at line %d of [%.10s]",
372032c49904Sdrh               zType, lineno, 20+sqlite3_sourceid());
372132c49904Sdrh   return iErr;
372232c49904Sdrh }
sqlite3CorruptError(int lineno)37239978c97eSdrh int sqlite3CorruptError(int lineno){
3724af46dc12Sdrh   testcase( sqlite3GlobalConfig.xLog!=0 );
3725eebf2f57Sdan   return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
372649285708Sdrh }
sqlite3MisuseError(int lineno)37279978c97eSdrh int sqlite3MisuseError(int lineno){
3728af46dc12Sdrh   testcase( sqlite3GlobalConfig.xLog!=0 );
3729eebf2f57Sdan   return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
37309978c97eSdrh }
sqlite3CantopenError(int lineno)37319978c97eSdrh int sqlite3CantopenError(int lineno){
3732af46dc12Sdrh   testcase( sqlite3GlobalConfig.xLog!=0 );
3733eebf2f57Sdan   return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
37349978c97eSdrh }
37353cdc8205Sdan #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
sqlite3CorruptPgnoError(int lineno,Pgno pgno)3736cc97ca4cSdrh int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
3737cc97ca4cSdrh   char zMsg[100];
3738cc97ca4cSdrh   sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
3739cc97ca4cSdrh   testcase( sqlite3GlobalConfig.xLog!=0 );
3740eebf2f57Sdan   return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
3741cc97ca4cSdrh }
37423cdc8205Sdan #endif
37433cdc8205Sdan #ifdef SQLITE_DEBUG
sqlite3NomemError(int lineno)3744fad3039cSmistachkin int sqlite3NomemError(int lineno){
3745fad3039cSmistachkin   testcase( sqlite3GlobalConfig.xLog!=0 );
3746eebf2f57Sdan   return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
3747fad3039cSmistachkin }
sqlite3IoerrnomemError(int lineno)3748fad3039cSmistachkin int sqlite3IoerrnomemError(int lineno){
3749fad3039cSmistachkin   testcase( sqlite3GlobalConfig.xLog!=0 );
3750eebf2f57Sdan   return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
3751fad3039cSmistachkin }
375232c49904Sdrh #endif
37537c1817e2Sdrh 
3754eec556d3Sshane #ifndef SQLITE_OMIT_DEPRECATED
37556f7adc8aSdrh /*
37566f7adc8aSdrh ** This is a convenience routine that makes sure that all thread-specific
37576f7adc8aSdrh ** data for this thread has been deallocated.
3758dce8bdb8Sdrh **
3759dce8bdb8Sdrh ** SQLite no longer uses thread-specific data so this routine is now a
3760dce8bdb8Sdrh ** no-op.  It is retained for historical compatibility.
37616f7adc8aSdrh */
sqlite3_thread_cleanup(void)37626f7adc8aSdrh void sqlite3_thread_cleanup(void){
37636f7adc8aSdrh }
3764eec556d3Sshane #endif
3765deb802cdSdanielk1977 
3766deb802cdSdanielk1977 /*
3767deb802cdSdanielk1977 ** Return meta information about a specific column of a database table.
3768deb802cdSdanielk1977 ** See comment in sqlite3.h (sqlite.h.in) for details.
3769deb802cdSdanielk1977 */
sqlite3_table_column_metadata(sqlite3 * db,const char * zDbName,const char * zTableName,const char * zColumnName,char const ** pzDataType,char const ** pzCollSeq,int * pNotNull,int * pPrimaryKey,int * pAutoinc)3770deb802cdSdanielk1977 int sqlite3_table_column_metadata(
3771deb802cdSdanielk1977   sqlite3 *db,                /* Connection handle */
3772deb802cdSdanielk1977   const char *zDbName,        /* Database name or NULL */
3773deb802cdSdanielk1977   const char *zTableName,     /* Table name */
3774deb802cdSdanielk1977   const char *zColumnName,    /* Column name */
3775deb802cdSdanielk1977   char const **pzDataType,    /* OUTPUT: Declared data type */
3776deb802cdSdanielk1977   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
3777deb802cdSdanielk1977   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
3778deb802cdSdanielk1977   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
37799be07166Sdrh   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
3780deb802cdSdanielk1977 ){
3781deb802cdSdanielk1977   int rc;
3782deb802cdSdanielk1977   char *zErrMsg = 0;
3783deb802cdSdanielk1977   Table *pTab = 0;
3784deb802cdSdanielk1977   Column *pCol = 0;
37851a51ce78Smistachkin   int iCol = 0;
3786deb802cdSdanielk1977   char const *zDataType = 0;
3787deb802cdSdanielk1977   char const *zCollSeq = 0;
3788deb802cdSdanielk1977   int notnull = 0;
3789deb802cdSdanielk1977   int primarykey = 0;
3790deb802cdSdanielk1977   int autoinc = 0;
3791deb802cdSdanielk1977 
379296c707a3Sdrh 
379396c707a3Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
379496c707a3Sdrh   if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
379596c707a3Sdrh     return SQLITE_MISUSE_BKPT;
379696c707a3Sdrh   }
379796c707a3Sdrh #endif
379896c707a3Sdrh 
3799deb802cdSdanielk1977   /* Ensure the database schema has been loaded */
3800e30f4426Sdrh   sqlite3_mutex_enter(db->mutex);
38013cb3edc1Sdrh   sqlite3BtreeEnterAll(db);
3802deb802cdSdanielk1977   rc = sqlite3Init(db, &zErrMsg);
3803deb802cdSdanielk1977   if( SQLITE_OK!=rc ){
3804deb802cdSdanielk1977     goto error_out;
3805deb802cdSdanielk1977   }
3806deb802cdSdanielk1977 
3807deb802cdSdanielk1977   /* Locate the table in question */
3808deb802cdSdanielk1977   pTab = sqlite3FindTable(db, zTableName, zDbName);
3809f38524d2Sdrh   if( !pTab || IsView(pTab) ){
3810deb802cdSdanielk1977     pTab = 0;
3811deb802cdSdanielk1977     goto error_out;
3812deb802cdSdanielk1977   }
3813deb802cdSdanielk1977 
3814deb802cdSdanielk1977   /* Find the column for which info is requested */
381545d1b206Sdrh   if( zColumnName==0 ){
381645d1b206Sdrh     /* Query for existance of table only */
3817deb802cdSdanielk1977   }else{
3818deb802cdSdanielk1977     for(iCol=0; iCol<pTab->nCol; iCol++){
3819deb802cdSdanielk1977       pCol = &pTab->aCol[iCol];
3820cf9d36d1Sdrh       if( 0==sqlite3StrICmp(pCol->zCnName, zColumnName) ){
3821deb802cdSdanielk1977         break;
3822deb802cdSdanielk1977       }
3823deb802cdSdanielk1977     }
3824deb802cdSdanielk1977     if( iCol==pTab->nCol ){
382545d1b206Sdrh       if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
382645d1b206Sdrh         iCol = pTab->iPKey;
382745d1b206Sdrh         pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
382845d1b206Sdrh       }else{
3829deb802cdSdanielk1977         pTab = 0;
3830deb802cdSdanielk1977         goto error_out;
3831deb802cdSdanielk1977       }
3832deb802cdSdanielk1977     }
383345d1b206Sdrh   }
3834deb802cdSdanielk1977 
3835deb802cdSdanielk1977   /* The following block stores the meta information that will be returned
3836deb802cdSdanielk1977   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
3837deb802cdSdanielk1977   ** and autoinc. At this point there are two possibilities:
3838deb802cdSdanielk1977   **
3839deb802cdSdanielk1977   **     1. The specified column name was rowid", "oid" or "_rowid_"
3840deb802cdSdanielk1977   **        and there is no explicitly declared IPK column.
3841deb802cdSdanielk1977   **
3842deb802cdSdanielk1977   **     2. The table is not a view and the column name identified an
3843deb802cdSdanielk1977   **        explicitly declared column. Copy meta information from *pCol.
3844deb802cdSdanielk1977   */
3845deb802cdSdanielk1977   if( pCol ){
3846d7564865Sdrh     zDataType = sqlite3ColumnType(pCol,0);
384765b40093Sdrh     zCollSeq = sqlite3ColumnColl(pCol);
38489be07166Sdrh     notnull = pCol->notNull!=0;
3849a371ace4Sdrh     primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
38507d10d5a6Sdrh     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
3851deb802cdSdanielk1977   }else{
3852deb802cdSdanielk1977     zDataType = "INTEGER";
3853deb802cdSdanielk1977     primarykey = 1;
3854deb802cdSdanielk1977   }
3855deb802cdSdanielk1977   if( !zCollSeq ){
3856f19aa5faSdrh     zCollSeq = sqlite3StrBINARY;
3857deb802cdSdanielk1977   }
3858deb802cdSdanielk1977 
3859deb802cdSdanielk1977 error_out:
386002b4e3b3Sdanielk1977   sqlite3BtreeLeaveAll(db);
3861deb802cdSdanielk1977 
3862deb802cdSdanielk1977   /* Whether the function call succeeded or failed, set the output parameters
3863deb802cdSdanielk1977   ** to whatever their local counterparts contain. If an error did occur,
3864deb802cdSdanielk1977   ** this has the effect of zeroing all output parameters.
3865deb802cdSdanielk1977   */
3866deb802cdSdanielk1977   if( pzDataType ) *pzDataType = zDataType;
3867deb802cdSdanielk1977   if( pzCollSeq ) *pzCollSeq = zCollSeq;
3868deb802cdSdanielk1977   if( pNotNull ) *pNotNull = notnull;
3869deb802cdSdanielk1977   if( pPrimaryKey ) *pPrimaryKey = primarykey;
3870deb802cdSdanielk1977   if( pAutoinc ) *pAutoinc = autoinc;
3871deb802cdSdanielk1977 
3872deb802cdSdanielk1977   if( SQLITE_OK==rc && !pTab ){
3873633e6d57Sdrh     sqlite3DbFree(db, zErrMsg);
3874118640bdSdrh     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
3875f089aa45Sdrh         zColumnName);
3876deb802cdSdanielk1977     rc = SQLITE_ERROR;
3877deb802cdSdanielk1977   }
387813f40da3Sdrh   sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
3879633e6d57Sdrh   sqlite3DbFree(db, zErrMsg);
3880e30f4426Sdrh   rc = sqlite3ApiExit(db, rc);
3881e30f4426Sdrh   sqlite3_mutex_leave(db->mutex);
3882f9cb7f58Sdrh   return rc;
3883f9cb7f58Sdrh }
3884f9cb7f58Sdrh 
3885f9cb7f58Sdrh /*
3886f9cb7f58Sdrh ** Sleep for a little while.  Return the amount of time slept.
3887f9cb7f58Sdrh */
sqlite3_sleep(int ms)3888f9cb7f58Sdrh int sqlite3_sleep(int ms){
3889b4b47411Sdanielk1977   sqlite3_vfs *pVfs;
3890e30f4426Sdrh   int rc;
3891d677b3d6Sdrh   pVfs = sqlite3_vfs_find(0);
389240257ffdSdrh   if( pVfs==0 ) return 0;
3893fee2d25aSdanielk1977 
3894fee2d25aSdanielk1977   /* This function works in milliseconds, but the underlying OsSleep()
3895fee2d25aSdanielk1977   ** API uses microseconds. Hence the 1000's.
3896fee2d25aSdanielk1977   */
3897e30f4426Sdrh   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
3898e30f4426Sdrh   return rc;
3899f9cb7f58Sdrh }
39004ac285a1Sdrh 
39014ac285a1Sdrh /*
39024ac285a1Sdrh ** Enable or disable the extended result codes.
39034ac285a1Sdrh */
sqlite3_extended_result_codes(sqlite3 * db,int onoff)39044ac285a1Sdrh int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
39059ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
39069ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
39079ca95730Sdrh #endif
3908e30f4426Sdrh   sqlite3_mutex_enter(db->mutex);
39094ac285a1Sdrh   db->errMask = onoff ? 0xffffffff : 0xff;
3910e30f4426Sdrh   sqlite3_mutex_leave(db->mutex);
39114ac285a1Sdrh   return SQLITE_OK;
39124ac285a1Sdrh }
3913cc6bb3eaSdrh 
3914cc6bb3eaSdrh /*
3915cc6bb3eaSdrh ** Invoke the xFileControl method on a particular database.
3916cc6bb3eaSdrh */
sqlite3_file_control(sqlite3 * db,const char * zDbName,int op,void * pArg)3917cc6bb3eaSdrh int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
3918cc6bb3eaSdrh   int rc = SQLITE_ERROR;
3919421377e6Sdrh   Btree *pBtree;
3920421377e6Sdrh 
39219ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
39229ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
39239ca95730Sdrh #endif
3924cc6bb3eaSdrh   sqlite3_mutex_enter(db->mutex);
3925421377e6Sdrh   pBtree = sqlite3DbNameToBtree(db, zDbName);
3926cc6bb3eaSdrh   if( pBtree ){
3927cc6bb3eaSdrh     Pager *pPager;
392855176259Sdrh     sqlite3_file *fd;
3929cc6bb3eaSdrh     sqlite3BtreeEnter(pBtree);
3930cc6bb3eaSdrh     pPager = sqlite3BtreePager(pBtree);
393155176259Sdrh     assert( pPager!=0 );
393255176259Sdrh     fd = sqlite3PagerFile(pPager);
393355176259Sdrh     assert( fd!=0 );
39343eb08114Sdrh     if( op==SQLITE_FCNTL_FILE_POINTER ){
39353eb08114Sdrh       *(sqlite3_file**)pArg = fd;
39363eb08114Sdrh       rc = SQLITE_OK;
3937790f287cSdrh     }else if( op==SQLITE_FCNTL_VFS_POINTER ){
3938790f287cSdrh       *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
3939790f287cSdrh       rc = SQLITE_OK;
394021d61853Sdrh     }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
394121d61853Sdrh       *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
394221d61853Sdrh       rc = SQLITE_OK;
3943ea99a31cSdrh     }else if( op==SQLITE_FCNTL_DATA_VERSION ){
3944ea99a31cSdrh       *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager);
3945ea99a31cSdrh       rc = SQLITE_OK;
394645248de3Sdrh     }else if( op==SQLITE_FCNTL_RESERVE_BYTES ){
394745248de3Sdrh       int iNew = *(int*)pArg;
394845248de3Sdrh       *(int*)pArg = sqlite3BtreeGetRequestedReserve(pBtree);
3949e937df81Sdrh       if( iNew>=0 && iNew<=255 ){
395045248de3Sdrh         sqlite3BtreeSetPageSize(pBtree, 0, iNew, 0);
395145248de3Sdrh       }
395245248de3Sdrh       rc = SQLITE_OK;
39530b52b7d0Sdrh     }else{
39542b06b076Sdan       int nSave = db->busyHandler.nBusy;
3955afb39a4cSdrh       rc = sqlite3OsFileControl(fd, op, pArg);
39562b06b076Sdan       db->busyHandler.nBusy = nSave;
3957cc6bb3eaSdrh     }
3958cc6bb3eaSdrh     sqlite3BtreeLeave(pBtree);
3959cc6bb3eaSdrh   }
3960cc6bb3eaSdrh   sqlite3_mutex_leave(db->mutex);
3961cc6bb3eaSdrh   return rc;
3962cc6bb3eaSdrh }
3963ed13d98cSdrh 
3964ed13d98cSdrh /*
3965ed13d98cSdrh ** Interface to the testing logic.
3966ed13d98cSdrh */
sqlite3_test_control(int op,...)3967ed13d98cSdrh int sqlite3_test_control(int op, ...){
3968ed13d98cSdrh   int rc = 0;
3969d12602a9Sdrh #ifdef SQLITE_UNTESTABLE
3970f5ed7ad6Sdrh   UNUSED_PARAMETER(op);
3971f5ed7ad6Sdrh #else
39722fa1868fSdrh   va_list ap;
3973ed13d98cSdrh   va_start(ap, op);
3974ed13d98cSdrh   switch( op ){
3975d09414cdSdanielk1977 
3976d09414cdSdanielk1977     /*
3977984bfaa4Sdrh     ** Save the current state of the PRNG.
3978984bfaa4Sdrh     */
39792fa1868fSdrh     case SQLITE_TESTCTRL_PRNG_SAVE: {
39802fa1868fSdrh       sqlite3PrngSaveState();
39812fa1868fSdrh       break;
39822fa1868fSdrh     }
3983984bfaa4Sdrh 
3984984bfaa4Sdrh     /*
3985984bfaa4Sdrh     ** Restore the state of the PRNG to the last state saved using
3986984bfaa4Sdrh     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
3987984bfaa4Sdrh     ** this verb acts like PRNG_RESET.
3988984bfaa4Sdrh     */
39892fa1868fSdrh     case SQLITE_TESTCTRL_PRNG_RESTORE: {
39902fa1868fSdrh       sqlite3PrngRestoreState();
39912fa1868fSdrh       break;
39922fa1868fSdrh     }
3993984bfaa4Sdrh 
39942e6d83bcSdrh     /*  sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, int x, sqlite3 *db);
3995ade54d68Sdrh     **
39962e6d83bcSdrh     ** Control the seed for the pseudo-random number generator (PRNG) that
39972e6d83bcSdrh     ** is built into SQLite.  Cases:
39982e6d83bcSdrh     **
39992e6d83bcSdrh     **    x!=0 && db!=0       Seed the PRNG to the current value of the
40002e6d83bcSdrh     **                        schema cookie in the main database for db, or
40012e6d83bcSdrh     **                        x if the schema cookie is zero.  This case
40022e6d83bcSdrh     **                        is convenient to use with database fuzzers
40032e6d83bcSdrh     **                        as it allows the fuzzer some control over the
40042e6d83bcSdrh     **                        the PRNG seed.
40052e6d83bcSdrh     **
40062e6d83bcSdrh     **    x!=0 && db==0       Seed the PRNG to the value of x.
40072e6d83bcSdrh     **
40082e6d83bcSdrh     **    x==0 && db==0       Revert to default behavior of using the
40092e6d83bcSdrh     **                        xRandomness method on the primary VFS.
40102e6d83bcSdrh     **
40112e6d83bcSdrh     ** This test-control also resets the PRNG so that the new seed will
40122e6d83bcSdrh     ** be used for the next call to sqlite3_randomness().
4013984bfaa4Sdrh     */
4014ef9f719dSdrh #ifndef SQLITE_OMIT_WSD
4015ade54d68Sdrh     case SQLITE_TESTCTRL_PRNG_SEED: {
40162e6d83bcSdrh       int x = va_arg(ap, int);
40172e6d83bcSdrh       int y;
40182e6d83bcSdrh       sqlite3 *db = va_arg(ap, sqlite3*);
40192e6d83bcSdrh       assert( db==0 || db->aDb[0].pSchema!=0 );
40202e6d83bcSdrh       if( db && (y = db->aDb[0].pSchema->schema_cookie)!=0 ){ x = y; }
40212e6d83bcSdrh       sqlite3Config.iPrngSeed = x;
40222e6d83bcSdrh       sqlite3_randomness(0,0);
40232fa1868fSdrh       break;
40242fa1868fSdrh     }
4025ef9f719dSdrh #endif
40263088d59eSdrh 
40273088d59eSdrh     /*
40283088d59eSdrh     **  sqlite3_test_control(BITVEC_TEST, size, program)
40293088d59eSdrh     **
40303088d59eSdrh     ** Run a test against a Bitvec object of size.  The program argument
40313088d59eSdrh     ** is an array of integers that defines the test.  Return -1 on a
40323088d59eSdrh     ** memory allocation error, 0 on success, or non-zero for an error.
40333088d59eSdrh     ** See the sqlite3BitvecBuiltinTest() for additional information.
40343088d59eSdrh     */
40353088d59eSdrh     case SQLITE_TESTCTRL_BITVEC_TEST: {
40363088d59eSdrh       int sz = va_arg(ap, int);
40373088d59eSdrh       int *aProg = va_arg(ap, int*);
40383088d59eSdrh       rc = sqlite3BitvecBuiltinTest(sz, aProg);
40393088d59eSdrh       break;
40403088d59eSdrh     }
40412d1d86fbSdanielk1977 
40422d1d86fbSdanielk1977     /*
4043c007f61bSdrh     **  sqlite3_test_control(FAULT_INSTALL, xCallback)
4044c007f61bSdrh     **
4045c007f61bSdrh     ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
4046c007f61bSdrh     ** if xCallback is not NULL.
4047c007f61bSdrh     **
4048c007f61bSdrh     ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
4049c007f61bSdrh     ** is called immediately after installing the new callback and the return
4050c007f61bSdrh     ** value from sqlite3FaultSim(0) becomes the return from
4051c007f61bSdrh     ** sqlite3_test_control().
4052c007f61bSdrh     */
4053c007f61bSdrh     case SQLITE_TESTCTRL_FAULT_INSTALL: {
40540d58ae01Sdrh       /* A bug in MSVC prevents it from understanding pointers to functions
40550d58ae01Sdrh       ** types in the second argument to va_arg().  Work around the problem
40560d58ae01Sdrh       ** using a typedef.
40570d58ae01Sdrh       ** http://support.microsoft.com/kb/47961  <-- dead hyperlink
405811fc3c0fSdrh       ** Search at http://web.archive.org/ to find the 2015-03-16 archive
405911fc3c0fSdrh       ** of the link above to see the original text.
4060685ffb13Sdan       ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
406177a90ce8Smistachkin       */
40620d58ae01Sdrh       typedef int(*sqlite3FaultFuncType)(int);
40630d58ae01Sdrh       sqlite3GlobalConfig.xTestCallback = va_arg(ap, sqlite3FaultFuncType);
4064c007f61bSdrh       rc = sqlite3FaultSim(0);
4065c007f61bSdrh       break;
4066c007f61bSdrh     }
4067c007f61bSdrh 
4068c007f61bSdrh     /*
40692d1d86fbSdanielk1977     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
40702d1d86fbSdanielk1977     **
40712d1d86fbSdanielk1977     ** Register hooks to call to indicate which malloc() failures
40722d1d86fbSdanielk1977     ** are benign.
40732d1d86fbSdanielk1977     */
40742d1d86fbSdanielk1977     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
4075ca026796Sdanielk1977       typedef void (*void_function)(void);
4076ca026796Sdanielk1977       void_function xBenignBegin;
4077ca026796Sdanielk1977       void_function xBenignEnd;
4078ca026796Sdanielk1977       xBenignBegin = va_arg(ap, void_function);
4079ca026796Sdanielk1977       xBenignEnd = va_arg(ap, void_function);
40802d1d86fbSdanielk1977       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
40812d1d86fbSdanielk1977       break;
40822d1d86fbSdanielk1977     }
4083c7a3bb94Sdrh 
4084c7a3bb94Sdrh     /*
4085f3af63f9Sdrh     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
4086c7a3bb94Sdrh     **
4087c7a3bb94Sdrh     ** Set the PENDING byte to the value in the argument, if X>0.
4088c7a3bb94Sdrh     ** Make no changes if X==0.  Return the value of the pending byte
4089c7a3bb94Sdrh     ** as it existing before this routine was called.
4090c7a3bb94Sdrh     **
4091c7a3bb94Sdrh     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
4092c7a3bb94Sdrh     ** an incompatible database file format.  Changing the PENDING byte
4093c7a3bb94Sdrh     ** while any database connection is open results in undefined and
409460ec914cSpeter.d.reid     ** deleterious behavior.
4095c7a3bb94Sdrh     */
4096c7a3bb94Sdrh     case SQLITE_TESTCTRL_PENDING_BYTE: {
4097f83dc1efSdrh       rc = PENDING_BYTE;
4098f83dc1efSdrh #ifndef SQLITE_OMIT_WSD
4099f83dc1efSdrh       {
4100c7a3bb94Sdrh         unsigned int newVal = va_arg(ap, unsigned int);
4101c7a3bb94Sdrh         if( newVal ) sqlite3PendingByte = newVal;
4102f83dc1efSdrh       }
4103f83dc1efSdrh #endif
4104c7a3bb94Sdrh       break;
4105c7a3bb94Sdrh     }
4106f3af63f9Sdrh 
4107f3af63f9Sdrh     /*
4108f3af63f9Sdrh     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
4109f3af63f9Sdrh     **
4110f3af63f9Sdrh     ** This action provides a run-time test to see whether or not
4111f3af63f9Sdrh     ** assert() was enabled at compile-time.  If X is true and assert()
4112f3af63f9Sdrh     ** is enabled, then the return value is true.  If X is true and
4113f3af63f9Sdrh     ** assert() is disabled, then the return value is zero.  If X is
4114f3af63f9Sdrh     ** false and assert() is enabled, then the assertion fires and the
4115f3af63f9Sdrh     ** process aborts.  If X is false and assert() is disabled, then the
4116f3af63f9Sdrh     ** return value is zero.
4117f3af63f9Sdrh     */
4118f3af63f9Sdrh     case SQLITE_TESTCTRL_ASSERT: {
4119f3af63f9Sdrh       volatile int x = 0;
4120cc5f8a46Sdrh       assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
4121f3af63f9Sdrh       rc = x;
41224cd8296fSdrh #if defined(SQLITE_DEBUG)
41234cd8296fSdrh       /* Invoke these debugging routines so that the compiler does not
41244cd8296fSdrh       ** issue "defined but not used" warnings. */
41254cd8296fSdrh       if( x==9999 ){
41264cd8296fSdrh         sqlite3ShowExpr(0);
41274cd8296fSdrh         sqlite3ShowExpr(0);
41284cd8296fSdrh         sqlite3ShowExprList(0);
41294cd8296fSdrh         sqlite3ShowIdList(0);
41304cd8296fSdrh         sqlite3ShowSrcList(0);
41314cd8296fSdrh         sqlite3ShowWith(0);
41324cd8296fSdrh         sqlite3ShowUpsert(0);
41334cd8296fSdrh         sqlite3ShowTriggerStep(0);
41344cd8296fSdrh         sqlite3ShowTriggerStepList(0);
41354cd8296fSdrh         sqlite3ShowTrigger(0);
41364cd8296fSdrh         sqlite3ShowTriggerList(0);
4137f53487a4Sdan #ifndef SQLITE_OMIT_WINDOWFUNC
41384cd8296fSdrh         sqlite3ShowWindow(0);
41394cd8296fSdrh         sqlite3ShowWinFunc(0);
4140f53487a4Sdan #endif
4141f1ab642cSdrh         sqlite3ShowSelect(0);
41424cd8296fSdrh       }
41434cd8296fSdrh #endif
4144f3af63f9Sdrh       break;
4145f3af63f9Sdrh     }
4146f3af63f9Sdrh 
4147f3af63f9Sdrh 
4148f3af63f9Sdrh     /*
4149f3af63f9Sdrh     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
4150f3af63f9Sdrh     **
4151f3af63f9Sdrh     ** This action provides a run-time test to see how the ALWAYS and
4152f3af63f9Sdrh     ** NEVER macros were defined at compile-time.
4153f3af63f9Sdrh     **
4154ce2c482eSdrh     ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
4155f3af63f9Sdrh     **
4156f3af63f9Sdrh     ** The recommended test is X==2.  If the return value is 2, that means
4157f3af63f9Sdrh     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
4158f3af63f9Sdrh     ** default setting.  If the return value is 1, then ALWAYS() is either
4159f3af63f9Sdrh     ** hard-coded to true or else it asserts if its argument is false.
4160f3af63f9Sdrh     ** The first behavior (hard-coded to true) is the case if
4161f3af63f9Sdrh     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
4162f3af63f9Sdrh     ** behavior (assert if the argument to ALWAYS() is false) is the case if
4163f3af63f9Sdrh     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
4164f3af63f9Sdrh     **
4165f3af63f9Sdrh     ** The run-time test procedure might look something like this:
4166f3af63f9Sdrh     **
4167f3af63f9Sdrh     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
4168f3af63f9Sdrh     **      // ALWAYS() and NEVER() are no-op pass-through macros
4169f3af63f9Sdrh     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
4170f3af63f9Sdrh     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
4171f3af63f9Sdrh     **    }else{
4172f3af63f9Sdrh     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
4173f3af63f9Sdrh     **    }
4174f3af63f9Sdrh     */
4175f3af63f9Sdrh     case SQLITE_TESTCTRL_ALWAYS: {
4176f3af63f9Sdrh       int x = va_arg(ap,int);
4177ce2c482eSdrh       rc = x ? ALWAYS(x) : 0;
4178f3af63f9Sdrh       break;
4179f3af63f9Sdrh     }
4180c046e3edSdrh 
41812cf4acbdSdrh     /*
41822cf4acbdSdrh     **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
41832cf4acbdSdrh     **
41842cf4acbdSdrh     ** The integer returned reveals the byte-order of the computer on which
41852cf4acbdSdrh     ** SQLite is running:
41862cf4acbdSdrh     **
41872cf4acbdSdrh     **       1     big-endian,    determined at run-time
41882cf4acbdSdrh     **      10     little-endian, determined at run-time
41892cf4acbdSdrh     **  432101     big-endian,    determined at compile-time
41902cf4acbdSdrh     **  123410     little-endian, determined at compile-time
41912cf4acbdSdrh     */
41922cf4acbdSdrh     case SQLITE_TESTCTRL_BYTEORDER: {
41932cf4acbdSdrh       rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
41942cf4acbdSdrh       break;
41952cf4acbdSdrh     }
41962cf4acbdSdrh 
419707096f68Sdrh     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
419807096f68Sdrh     **
419907096f68Sdrh     ** Enable or disable various optimizations for testing purposes.  The
420007096f68Sdrh     ** argument N is a bitmask of optimizations to be disabled.  For normal
420107096f68Sdrh     ** operation N should be 0.  The idea is that a test program (like the
420207096f68Sdrh     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
420307096f68Sdrh     ** with various optimizations disabled to verify that the same answer
420407096f68Sdrh     ** is obtained in every case.
420507096f68Sdrh     */
420607096f68Sdrh     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
420707096f68Sdrh       sqlite3 *db = va_arg(ap, sqlite3*);
4208af7b7653Sdrh       db->dbOptFlags = va_arg(ap, u32);
420907096f68Sdrh       break;
421007096f68Sdrh     }
421107096f68Sdrh 
4212d7e185ceSdrh     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, onoff, xAlt);
4213c17d696cSdan     **
4214d7e185ceSdrh     ** If parameter onoff is 1, subsequent calls to localtime() fail.
4215d7e185ceSdrh     ** If 2, then invoke xAlt() instead of localtime().  If 0, normal
4216d7e185ceSdrh     ** processing.
4217d7e185ceSdrh     **
4218d7e185ceSdrh     ** xAlt arguments are void pointers, but they really want to be:
4219d7e185ceSdrh     **
4220d7e185ceSdrh     **    int xAlt(const time_t*, struct tm*);
4221d7e185ceSdrh     **
4222d7e185ceSdrh     ** xAlt should write results in to struct tm object of its 2nd argument
4223d7e185ceSdrh     ** and return zero on success, or return non-zero on failure.
4224c17d696cSdan     */
4225c17d696cSdan     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
4226c17d696cSdan       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
4227d7e185ceSdrh       if( sqlite3GlobalConfig.bLocaltimeFault==2 ){
42280d58ae01Sdrh         typedef int(*sqlite3LocaltimeType)(const void*,void*);
42290d58ae01Sdrh         sqlite3GlobalConfig.xAltLocaltime = va_arg(ap, sqlite3LocaltimeType);
4230d7e185ceSdrh       }else{
4231d7e185ceSdrh         sqlite3GlobalConfig.xAltLocaltime = 0;
4232d7e185ceSdrh       }
4233c17d696cSdan       break;
4234c17d696cSdan     }
4235c17d696cSdan 
4236171c50ecSdrh     /*   sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, sqlite3*);
4237eea8eb6dSdrh     **
4238171c50ecSdrh     ** Toggle the ability to use internal functions on or off for
4239171c50ecSdrh     ** the database connection given in the argument.
4240eea8eb6dSdrh     */
4241eea8eb6dSdrh     case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: {
4242171c50ecSdrh       sqlite3 *db = va_arg(ap, sqlite3*);
4243171c50ecSdrh       db->mDbFlags ^= DBFLAG_InternalFunc;
4244eea8eb6dSdrh       break;
4245eea8eb6dSdrh     }
4246eea8eb6dSdrh 
424709fe6143Sdrh     /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
424809fe6143Sdrh     **
424909fe6143Sdrh     ** Set or clear a flag that indicates that the database file is always well-
425009fe6143Sdrh     ** formed and never corrupt.  This flag is clear by default, indicating that
425109fe6143Sdrh     ** database files might have arbitrary corruption.  Setting the flag during
425209fe6143Sdrh     ** testing causes certain assert() statements in the code to be activated
425309fe6143Sdrh     ** that demonstrat invariants on well-formed database files.
425409fe6143Sdrh     */
425509fe6143Sdrh     case SQLITE_TESTCTRL_NEVER_CORRUPT: {
42569c2552f2Sdan       sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
425709fe6143Sdrh       break;
425809fe6143Sdrh     }
425909fe6143Sdrh 
426030842990Sdrh     /*   sqlite3_test_control(SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS, int);
426130842990Sdrh     **
426230842990Sdrh     ** Set or clear a flag that causes SQLite to verify that type, name,
42631e32bed3Sdrh     ** and tbl_name fields of the sqlite_schema table.  This is normally
426430842990Sdrh     ** on, but it is sometimes useful to turn it off for testing.
4265ca439a49Sdrh     **
4266ca439a49Sdrh     ** 2020-07-22:  Disabling EXTRA_SCHEMA_CHECKS also disables the
4267ca439a49Sdrh     ** verification of rootpage numbers when parsing the schema.  This
4268ca439a49Sdrh     ** is useful to make it easier to reach strange internal error states
42698c1fbe81Sdrh     ** during testing.  The EXTRA_SCHEMA_CHECKS setting is always enabled
4270ca439a49Sdrh     ** in production.
427130842990Sdrh     */
427230842990Sdrh     case SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS: {
427330842990Sdrh       sqlite3GlobalConfig.bExtraSchemaChecks = va_arg(ap, int);
427430842990Sdrh       break;
427530842990Sdrh     }
427630842990Sdrh 
42779e5eb9c8Sdrh     /* Set the threshold at which OP_Once counters reset back to zero.
4278e0736da1Smistachkin     ** By default this is 0x7ffffffe (over 2 billion), but that value is
42799e5eb9c8Sdrh     ** too big to test in a reasonable amount of time, so this control is
42809e5eb9c8Sdrh     ** provided to set a small and easily reachable reset value.
42819e5eb9c8Sdrh     */
42829e5eb9c8Sdrh     case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
42839e5eb9c8Sdrh       sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
42849e5eb9c8Sdrh       break;
42859e5eb9c8Sdrh     }
4286688852abSdrh 
4287688852abSdrh     /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
4288688852abSdrh     **
4289688852abSdrh     ** Set the VDBE coverage callback function to xCallback with context
4290688852abSdrh     ** pointer ptr.
4291688852abSdrh     */
4292688852abSdrh     case SQLITE_TESTCTRL_VDBE_COVERAGE: {
4293688852abSdrh #ifdef SQLITE_VDBE_COVERAGE
42947083a487Sdrh       typedef void (*branch_callback)(void*,unsigned int,
42957083a487Sdrh                                       unsigned char,unsigned char);
4296688852abSdrh       sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
4297688852abSdrh       sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
4298688852abSdrh #endif
4299688852abSdrh       break;
4300688852abSdrh     }
4301688852abSdrh 
43028930c2abSdan     /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
43038930c2abSdan     case SQLITE_TESTCTRL_SORTER_MMAP: {
43048930c2abSdan       sqlite3 *db = va_arg(ap, sqlite3*);
43058930c2abSdan       db->nMaxSorterMmap = va_arg(ap, int);
43068930c2abSdan       break;
43078930c2abSdan     }
43088930c2abSdan 
430943cfc230Sdrh     /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
431043cfc230Sdrh     **
431143cfc230Sdrh     ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
431243cfc230Sdrh     ** not.
431343cfc230Sdrh     */
431443cfc230Sdrh     case SQLITE_TESTCTRL_ISINIT: {
431543cfc230Sdrh       if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
431643cfc230Sdrh       break;
431743cfc230Sdrh     }
43188964b345Sdrh 
43191ffede8cSdrh     /*  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
43208964b345Sdrh     **
43211ffede8cSdrh     ** This test control is used to create imposter tables.  "db" is a pointer
43221ffede8cSdrh     ** to the database connection.  dbName is the database name (ex: "main" or
43231ffede8cSdrh     ** "temp") which will receive the imposter.  "onOff" turns imposter mode on
43241ffede8cSdrh     ** or off.  "tnum" is the root page of the b-tree to which the imposter
43251ffede8cSdrh     ** table should connect.
43261ffede8cSdrh     **
43271ffede8cSdrh     ** Enable imposter mode only when the schema has already been parsed.  Then
43283ba689d8Sdrh     ** run a single CREATE TABLE statement to construct the imposter table in
43293ba689d8Sdrh     ** the parsed schema.  Then turn imposter mode back off again.
43301ffede8cSdrh     **
43311ffede8cSdrh     ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
43321ffede8cSdrh     ** the schema to be reparsed the next time it is needed.  This has the
43331ffede8cSdrh     ** effect of erasing all imposter tables.
43348964b345Sdrh     */
43351ffede8cSdrh     case SQLITE_TESTCTRL_IMPOSTER: {
43368964b345Sdrh       sqlite3 *db = va_arg(ap, sqlite3*);
433739addd0aSdrh       int iDb;
43388fb15e3bSdrh       sqlite3_mutex_enter(db->mutex);
433939addd0aSdrh       iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
434039addd0aSdrh       if( iDb>=0 ){
434139addd0aSdrh         db->init.iDb = iDb;
43421ffede8cSdrh         db->init.busy = db->init.imposterTable = va_arg(ap,int);
43438964b345Sdrh         db->init.newTnum = va_arg(ap,int);
43441ffede8cSdrh         if( db->init.busy==0 && db->init.newTnum>0 ){
43451ffede8cSdrh           sqlite3ResetAllSchemasOfConnection(db);
43461ffede8cSdrh         }
434739addd0aSdrh       }
43488fb15e3bSdrh       sqlite3_mutex_leave(db->mutex);
43498964b345Sdrh       break;
43508964b345Sdrh     }
43510d9de99cSdrh 
43520d9de99cSdrh #if defined(YYCOVERAGE)
43530d9de99cSdrh     /*  sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
43540d9de99cSdrh     **
43550d9de99cSdrh     ** This test control (only available when SQLite is compiled with
43560d9de99cSdrh     ** -DYYCOVERAGE) writes a report onto "out" that shows all
43570d9de99cSdrh     ** state/lookahead combinations in the parser state machine
43580d9de99cSdrh     ** which are never exercised.  If any state is missed, make the
43590d9de99cSdrh     ** return code SQLITE_ERROR.
43600d9de99cSdrh     */
43610d9de99cSdrh     case SQLITE_TESTCTRL_PARSER_COVERAGE: {
43620d9de99cSdrh       FILE *out = va_arg(ap, FILE*);
43630d9de99cSdrh       if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
43640d9de99cSdrh       break;
43650d9de99cSdrh     }
43660d9de99cSdrh #endif /* defined(YYCOVERAGE) */
43670c8f4038Sdrh 
43680c8f4038Sdrh     /*  sqlite3_test_control(SQLITE_TESTCTRL_RESULT_INTREAL, sqlite3_context*);
43690c8f4038Sdrh     **
43700c8f4038Sdrh     ** This test-control causes the most recent sqlite3_result_int64() value
43710c8f4038Sdrh     ** to be interpreted as a MEM_IntReal instead of as an MEM_Int.  Normally,
43720c8f4038Sdrh     ** MEM_IntReal values only arise during an INSERT operation of integer
43730c8f4038Sdrh     ** values into a REAL column, so they can be challenging to test.  This
43740c8f4038Sdrh     ** test-control enables us to write an intreal() SQL function that can
43750c8f4038Sdrh     ** inject an intreal() value at arbitrary places in an SQL statement,
43760c8f4038Sdrh     ** for testing purposes.
43770c8f4038Sdrh     */
43780c8f4038Sdrh     case SQLITE_TESTCTRL_RESULT_INTREAL: {
43790c8f4038Sdrh       sqlite3_context *pCtx = va_arg(ap, sqlite3_context*);
43800c8f4038Sdrh       sqlite3ResultIntReal(pCtx);
43810c8f4038Sdrh       break;
43820c8f4038Sdrh     }
438337ccfcfeSdrh 
438437ccfcfeSdrh     /*  sqlite3_test_control(SQLITE_TESTCTRL_SEEK_COUNT,
438537ccfcfeSdrh     **    sqlite3 *db,    // Database connection
438637ccfcfeSdrh     **    u64 *pnSeek     // Write seek count here
438737ccfcfeSdrh     **  );
438837ccfcfeSdrh     **
438937ccfcfeSdrh     ** This test-control queries the seek-counter on the "main" database
439037ccfcfeSdrh     ** file.  The seek-counter is written into *pnSeek and is then reset.
439137ccfcfeSdrh     ** The seek-count is only available if compiled with SQLITE_DEBUG.
439237ccfcfeSdrh     */
439337ccfcfeSdrh     case SQLITE_TESTCTRL_SEEK_COUNT: {
439437ccfcfeSdrh       sqlite3 *db = va_arg(ap, sqlite3*);
439537ccfcfeSdrh       u64 *pn = va_arg(ap, sqlite3_uint64*);
439637ccfcfeSdrh       *pn = sqlite3BtreeSeekCount(db->aDb->pBt);
4397d321b6f4Sdrh       (void)db;  /* Silence harmless unused variable warning */
439837ccfcfeSdrh       break;
439937ccfcfeSdrh     }
440037ccfcfeSdrh 
4401c0622a4dSdrh     /*  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, op, ptr)
4402c0622a4dSdrh     **
4403c0622a4dSdrh     **  "ptr" is a pointer to a u32.
4404c0622a4dSdrh     **
44055e431beaSdrh     **   op==0       Store the current sqlite3TreeTrace in *ptr
44065e431beaSdrh     **   op==1       Set sqlite3TreeTrace to the value *ptr
4407c0622a4dSdrh     **   op==3       Store the current sqlite3WhereTrace in *ptr
4408c0622a4dSdrh     **   op==3       Set sqlite3WhereTrace to the value *ptr
4409c0622a4dSdrh     */
4410c0622a4dSdrh     case SQLITE_TESTCTRL_TRACEFLAGS: {
4411fda8e492Sdrh        int opTrace = va_arg(ap, int);
4412c0622a4dSdrh        u32 *ptr = va_arg(ap, u32*);
4413fda8e492Sdrh        switch( opTrace ){
44145e431beaSdrh          case 0:   *ptr = sqlite3TreeTrace;      break;
44155e431beaSdrh          case 1:   sqlite3TreeTrace = *ptr;      break;
4416c0622a4dSdrh          case 2:   *ptr = sqlite3WhereTrace;     break;
4417c0622a4dSdrh          case 3:   sqlite3WhereTrace = *ptr;     break;
4418c0622a4dSdrh        }
4419c0622a4dSdrh        break;
4420c0622a4dSdrh     }
4421f3c1256aSdrh 
44227e910f64Sdrh     /* sqlite3_test_control(SQLITE_TESTCTRL_LOGEST,
44237e910f64Sdrh     **      double fIn,     // Input value
44247e910f64Sdrh     **      int *pLogEst,   // sqlite3LogEstFromDouble(fIn)
44257e910f64Sdrh     **      u64 *pInt,      // sqlite3LogEstToInt(*pLogEst)
44267e910f64Sdrh     **      int *pLogEst2   // sqlite3LogEst(*pInt)
44277e910f64Sdrh     ** );
44287e910f64Sdrh     **
44297e910f64Sdrh     ** Test access for the LogEst conversion routines.
44307e910f64Sdrh     */
44317e910f64Sdrh     case SQLITE_TESTCTRL_LOGEST: {
44327e910f64Sdrh       double rIn = va_arg(ap, double);
44337e910f64Sdrh       LogEst rLogEst = sqlite3LogEstFromDouble(rIn);
4434b528a5a0Sdrh       int *pI1 = va_arg(ap,int*);
4435b528a5a0Sdrh       u64 *pU64 = va_arg(ap,u64*);
4436b528a5a0Sdrh       int *pI2 = va_arg(ap,int*);
4437b528a5a0Sdrh       *pI1 = rLogEst;
4438b528a5a0Sdrh       *pU64 = sqlite3LogEstToInt(rLogEst);
4439b528a5a0Sdrh       *pI2 = sqlite3LogEst(*pU64);
44407e910f64Sdrh       break;
44417e910f64Sdrh     }
44427e910f64Sdrh 
44437e910f64Sdrh 
44449d82a2ccSdrh #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
44452d26cfccSdrh     /* sqlite3_test_control(SQLITE_TESTCTRL_TUNE, id, *piValue)
4446f3c1256aSdrh     **
44472d26cfccSdrh     ** If "id" is an integer between 1 and SQLITE_NTUNE then set the value
44482d26cfccSdrh     ** of the id-th tuning parameter to *piValue.  If "id" is between -1
44492d26cfccSdrh     ** and -SQLITE_NTUNE, then write the current value of the (-id)-th
44502d26cfccSdrh     ** tuning parameter into *piValue.
4451f3c1256aSdrh     **
4452f3c1256aSdrh     ** Tuning parameters are for use during transient development builds,
4453f3c1256aSdrh     ** to help find the best values for constants in the query planner.
4454f3c1256aSdrh     ** Access tuning parameters using the Tuning(ID) macro.  Set the
4455f3c1256aSdrh     ** parameters in the CLI using ".testctrl tune ID VALUE".
4456f3c1256aSdrh     **
4457f3c1256aSdrh     ** Transient use only.  Tuning parameters should not be used in
4458f3c1256aSdrh     ** checked-in code.
4459f3c1256aSdrh     */
4460f3c1256aSdrh     case SQLITE_TESTCTRL_TUNE: {
4461f3c1256aSdrh       int id = va_arg(ap, int);
44622d26cfccSdrh       int *piValue = va_arg(ap, int*);
44632d26cfccSdrh       if( id>0 && id<=SQLITE_NTUNE ){
44642d26cfccSdrh         Tuning(id) = *piValue;
44652d26cfccSdrh       }else if( id<0 && id>=-SQLITE_NTUNE ){
44662d26cfccSdrh         *piValue = Tuning(-id);
44672d26cfccSdrh       }else{
44682d26cfccSdrh         rc = SQLITE_NOTFOUND;
44692d26cfccSdrh       }
4470f3c1256aSdrh       break;
4471f3c1256aSdrh     }
4472f3c1256aSdrh #endif
4473ed13d98cSdrh   }
4474ed13d98cSdrh   va_end(ap);
4475d12602a9Sdrh #endif /* SQLITE_UNTESTABLE */
44767c36d077Sdanielk1977   return rc;
4477ed13d98cSdrh }
4478cc487d13Sdrh 
4479cc487d13Sdrh /*
4480532b0d23Sdrh ** The Pager stores the Database filename, Journal filename, and WAL filename
4481532b0d23Sdrh ** consecutively in memory, in that order.  The database filename is prefixed
4482532b0d23Sdrh ** by four zero bytes.  Locate the start of the database filename by searching
4483532b0d23Sdrh ** backwards for the first byte following four consecutive zero bytes.
4484532b0d23Sdrh **
4485532b0d23Sdrh ** This only works if the filename passed in was obtained from the Pager.
4486532b0d23Sdrh */
databaseName(const char * zName)4487532b0d23Sdrh static const char *databaseName(const char *zName){
4488532b0d23Sdrh   while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
4489532b0d23Sdrh     zName--;
4490532b0d23Sdrh   }
4491532b0d23Sdrh   return zName;
4492532b0d23Sdrh }
4493532b0d23Sdrh 
4494532b0d23Sdrh /*
44954defdddcSdrh ** Append text z[] to the end of p[].  Return a pointer to the first
44964defdddcSdrh ** character after then zero terminator on the new text in p[].
44974defdddcSdrh */
appendText(char * p,const char * z)44984defdddcSdrh static char *appendText(char *p, const char *z){
44994defdddcSdrh   size_t n = strlen(z);
45004defdddcSdrh   memcpy(p, z, n+1);
45014defdddcSdrh   return p+n+1;
45024defdddcSdrh }
45034defdddcSdrh 
45044defdddcSdrh /*
45054defdddcSdrh ** Allocate memory to hold names for a database, journal file, WAL file,
45064defdddcSdrh ** and query parameters.  The pointer returned is valid for use by
45074defdddcSdrh ** sqlite3_filename_database() and sqlite3_uri_parameter() and related
45084defdddcSdrh ** functions.
45094defdddcSdrh **
45104defdddcSdrh ** Memory layout must be compatible with that generated by the pager
45114defdddcSdrh ** and expected by sqlite3_uri_parameter() and databaseName().
45124defdddcSdrh */
sqlite3_create_filename(const char * zDatabase,const char * zJournal,const char * zWal,int nParam,const char ** azParam)4513*52d5d474Sdan const char *sqlite3_create_filename(
45144defdddcSdrh   const char *zDatabase,
45154defdddcSdrh   const char *zJournal,
45164defdddcSdrh   const char *zWal,
45174defdddcSdrh   int nParam,
45184defdddcSdrh   const char **azParam
45194defdddcSdrh ){
45204defdddcSdrh   sqlite3_int64 nByte;
45214defdddcSdrh   int i;
45224defdddcSdrh   char *pResult, *p;
45234defdddcSdrh   nByte = strlen(zDatabase) + strlen(zJournal) + strlen(zWal) + 10;
45244defdddcSdrh   for(i=0; i<nParam*2; i++){
45254defdddcSdrh     nByte += strlen(azParam[i])+1;
45264defdddcSdrh   }
45274defdddcSdrh   pResult = p = sqlite3_malloc64( nByte );
45284defdddcSdrh   if( p==0 ) return 0;
45294defdddcSdrh   memset(p, 0, 4);
45304defdddcSdrh   p += 4;
45314defdddcSdrh   p = appendText(p, zDatabase);
45324defdddcSdrh   for(i=0; i<nParam*2; i++){
45334defdddcSdrh     p = appendText(p, azParam[i]);
45344defdddcSdrh   }
45354defdddcSdrh   *(p++) = 0;
45364defdddcSdrh   p = appendText(p, zJournal);
45374defdddcSdrh   p = appendText(p, zWal);
45384defdddcSdrh   *(p++) = 0;
45394defdddcSdrh   *(p++) = 0;
45404defdddcSdrh   assert( (sqlite3_int64)(p - pResult)==nByte );
45414defdddcSdrh   return pResult + 4;
45424defdddcSdrh }
45434defdddcSdrh 
45444defdddcSdrh /*
45454defdddcSdrh ** Free memory obtained from sqlite3_create_filename().  It is a severe
45464defdddcSdrh ** error to call this routine with any parameter other than a pointer
45474defdddcSdrh ** previously obtained from sqlite3_create_filename() or a NULL pointer.
45484defdddcSdrh */
sqlite3_free_filename(const char * p)4549*52d5d474Sdan void sqlite3_free_filename(const char *p){
45504defdddcSdrh   if( p==0 ) return;
4551*52d5d474Sdan   p = databaseName(p);
4552*52d5d474Sdan   sqlite3_free((char*)p - 4);
45534defdddcSdrh }
45544defdddcSdrh 
45554defdddcSdrh 
45564defdddcSdrh /*
4557cc487d13Sdrh ** This is a utility routine, useful to VFS implementations, that checks
4558cc487d13Sdrh ** to see if a database file was a URI that contained a specific query
4559cc487d13Sdrh ** parameter, and if so obtains the value of the query parameter.
4560cc487d13Sdrh **
4561cc487d13Sdrh ** The zFilename argument is the filename pointer passed into the xOpen()
4562cc487d13Sdrh ** method of a VFS implementation.  The zParam argument is the name of the
4563cc487d13Sdrh ** query parameter we seek.  This routine returns the value of the zParam
4564cc487d13Sdrh ** parameter if it exists.  If the parameter does not exist, this routine
4565cc487d13Sdrh ** returns a NULL pointer.
4566cc487d13Sdrh */
sqlite3_uri_parameter(const char * zFilename,const char * zParam)4567cc487d13Sdrh const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
45689ca95730Sdrh   if( zFilename==0 || zParam==0 ) return 0;
4569532b0d23Sdrh   zFilename = databaseName(zFilename);
45701eac9660Sdrh   return uriParameter(zFilename, zParam);
4571cc487d13Sdrh }
4572283829cbSdrh 
4573283829cbSdrh /*
45748080403eSdrh ** Return a pointer to the name of Nth query parameter of the filename.
45758080403eSdrh */
sqlite3_uri_key(const char * zFilename,int N)45768080403eSdrh const char *sqlite3_uri_key(const char *zFilename, int N){
45778080403eSdrh   if( zFilename==0 || N<0 ) return 0;
4578532b0d23Sdrh   zFilename = databaseName(zFilename);
45798080403eSdrh   zFilename += sqlite3Strlen30(zFilename) + 1;
4580c59ffa8cSdrh   while( ALWAYS(zFilename) && zFilename[0] && (N--)>0 ){
45818080403eSdrh     zFilename += sqlite3Strlen30(zFilename) + 1;
45828080403eSdrh     zFilename += sqlite3Strlen30(zFilename) + 1;
45838080403eSdrh   }
45848080403eSdrh   return zFilename[0] ? zFilename : 0;
45858080403eSdrh }
45868080403eSdrh 
45878080403eSdrh /*
458892913720Sdrh ** Return a boolean value for a query parameter.
458992913720Sdrh */
sqlite3_uri_boolean(const char * zFilename,const char * zParam,int bDflt)459092913720Sdrh int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
459192913720Sdrh   const char *z = sqlite3_uri_parameter(zFilename, zParam);
459238d9c612Sdrh   bDflt = bDflt!=0;
459338d9c612Sdrh   return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
459492913720Sdrh }
459592913720Sdrh 
459692913720Sdrh /*
459792913720Sdrh ** Return a 64-bit integer value for a query parameter.
459892913720Sdrh */
sqlite3_uri_int64(const char * zFilename,const char * zParam,sqlite3_int64 bDflt)459992913720Sdrh sqlite3_int64 sqlite3_uri_int64(
460092913720Sdrh   const char *zFilename,    /* Filename as passed to xOpen */
460192913720Sdrh   const char *zParam,       /* URI parameter sought */
460292913720Sdrh   sqlite3_int64 bDflt       /* return if parameter is missing */
460392913720Sdrh ){
460492913720Sdrh   const char *z = sqlite3_uri_parameter(zFilename, zParam);
460592913720Sdrh   sqlite3_int64 v;
460684d4f1a3Sdrh   if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
460792913720Sdrh     bDflt = v;
460892913720Sdrh   }
460992913720Sdrh   return bDflt;
461092913720Sdrh }
461192913720Sdrh 
461292913720Sdrh /*
46138875b9e7Sdrh ** Translate a filename that was handed to a VFS routine into the corresponding
46148875b9e7Sdrh ** database, journal, or WAL file.
46158875b9e7Sdrh **
46168875b9e7Sdrh ** It is an error to pass this routine a filename string that was not
46178875b9e7Sdrh ** passed into the VFS from the SQLite core.  Doing so is similar to
46188875b9e7Sdrh ** passing free() a pointer that was not obtained from malloc() - it is
46198875b9e7Sdrh ** an error that we cannot easily detect but that will likely cause memory
46208875b9e7Sdrh ** corruption.
46218875b9e7Sdrh */
sqlite3_filename_database(const char * zFilename)46228875b9e7Sdrh const char *sqlite3_filename_database(const char *zFilename){
4623cc9309c7Sdrh   if( zFilename==0 ) return 0;
4624532b0d23Sdrh   return databaseName(zFilename);
46258875b9e7Sdrh }
sqlite3_filename_journal(const char * zFilename)46268875b9e7Sdrh const char *sqlite3_filename_journal(const char *zFilename){
4627cc9309c7Sdrh   if( zFilename==0 ) return 0;
4628532b0d23Sdrh   zFilename = databaseName(zFilename);
4629532b0d23Sdrh   zFilename += sqlite3Strlen30(zFilename) + 1;
4630c59ffa8cSdrh   while( ALWAYS(zFilename) && zFilename[0] ){
4631532b0d23Sdrh     zFilename += sqlite3Strlen30(zFilename) + 1;
4632532b0d23Sdrh     zFilename += sqlite3Strlen30(zFilename) + 1;
4633532b0d23Sdrh   }
4634532b0d23Sdrh   return zFilename + 1;
46358875b9e7Sdrh }
sqlite3_filename_wal(const char * zFilename)46368875b9e7Sdrh const char *sqlite3_filename_wal(const char *zFilename){
4637532b0d23Sdrh #ifdef SQLITE_OMIT_WAL
4638532b0d23Sdrh   return 0;
4639532b0d23Sdrh #else
4640532b0d23Sdrh   zFilename = sqlite3_filename_journal(zFilename);
4641cc9309c7Sdrh   if( zFilename ) zFilename += sqlite3Strlen30(zFilename) + 1;
4642532b0d23Sdrh   return zFilename;
4643532b0d23Sdrh #endif
46448875b9e7Sdrh }
46458875b9e7Sdrh 
46468875b9e7Sdrh /*
4647421377e6Sdrh ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
4648421377e6Sdrh */
sqlite3DbNameToBtree(sqlite3 * db,const char * zDbName)4649421377e6Sdrh Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
46502951809eSdrh   int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
46512951809eSdrh   return iDb<0 ? 0 : db->aDb[iDb].pBt;
4652421377e6Sdrh }
4653421377e6Sdrh 
4654421377e6Sdrh /*
4655ff16267dSdrh ** Return the name of the N-th database schema.  Return NULL if N is out
4656ff16267dSdrh ** of range.
4657ff16267dSdrh */
sqlite3_db_name(sqlite3 * db,int N)4658ff16267dSdrh const char *sqlite3_db_name(sqlite3 *db, int N){
4659ff16267dSdrh #ifdef SQLITE_ENABLE_API_ARMOR
4660ff16267dSdrh   if( !sqlite3SafetyCheckOk(db) ){
4661ff16267dSdrh     (void)SQLITE_MISUSE_BKPT;
4662ff16267dSdrh     return 0;
4663ff16267dSdrh   }
4664ff16267dSdrh #endif
4665ff16267dSdrh   if( N<0 || N>=db->nDb ){
4666ff16267dSdrh     return 0;
4667ff16267dSdrh   }else{
4668ff16267dSdrh     return db->aDb[N].zDbSName;
4669ff16267dSdrh   }
4670ff16267dSdrh }
4671ff16267dSdrh 
4672ff16267dSdrh /*
4673283829cbSdrh ** Return the filename of the database associated with a database
4674283829cbSdrh ** connection.
4675283829cbSdrh */
sqlite3_db_filename(sqlite3 * db,const char * zDbName)4676283829cbSdrh const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
4677cd54bab6Smistachkin   Btree *pBt;
46789ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
46799ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ){
46809ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
46819ca95730Sdrh     return 0;
46829ca95730Sdrh   }
46839ca95730Sdrh #endif
4684cd54bab6Smistachkin   pBt = sqlite3DbNameToBtree(db, zDbName);
4685421377e6Sdrh   return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
4686283829cbSdrh }
4687421377e6Sdrh 
4688421377e6Sdrh /*
4689421377e6Sdrh ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
4690421377e6Sdrh ** no such database exists.
4691421377e6Sdrh */
sqlite3_db_readonly(sqlite3 * db,const char * zDbName)4692421377e6Sdrh int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
4693cd54bab6Smistachkin   Btree *pBt;
46949ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
46959ca95730Sdrh   if( !sqlite3SafetyCheckOk(db) ){
46969ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
46979ca95730Sdrh     return -1;
46989ca95730Sdrh   }
46999ca95730Sdrh #endif
4700cd54bab6Smistachkin   pBt = sqlite3DbNameToBtree(db, zDbName);
4701781597feSdrh   return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
4702283829cbSdrh }
4703fc1acf33Sdan 
4704fc1acf33Sdan #ifdef SQLITE_ENABLE_SNAPSHOT
4705fc1acf33Sdan /*
4706fc1acf33Sdan ** Obtain a snapshot handle for the snapshot of database zDb currently
4707fc1acf33Sdan ** being read by handle db.
4708fc1acf33Sdan */
sqlite3_snapshot_get(sqlite3 * db,const char * zDb,sqlite3_snapshot ** ppSnapshot)4709fc1acf33Sdan int sqlite3_snapshot_get(
4710fc1acf33Sdan   sqlite3 *db,
4711fc1acf33Sdan   const char *zDb,
4712fc1acf33Sdan   sqlite3_snapshot **ppSnapshot
4713fc1acf33Sdan ){
4714fc1acf33Sdan   int rc = SQLITE_ERROR;
4715fc1acf33Sdan #ifndef SQLITE_OMIT_WAL
4716fc1acf33Sdan 
4717fc1acf33Sdan #ifdef SQLITE_ENABLE_API_ARMOR
4718fc1acf33Sdan   if( !sqlite3SafetyCheckOk(db) ){
4719fc1acf33Sdan     return SQLITE_MISUSE_BKPT;
4720fc1acf33Sdan   }
4721fc1acf33Sdan #endif
4722fc1acf33Sdan   sqlite3_mutex_enter(db->mutex);
4723fc1acf33Sdan 
4724edace5d4Sdan   if( db->autoCommit==0 ){
4725edace5d4Sdan     int iDb = sqlite3FindDbName(db, zDb);
4726fc1acf33Sdan     if( iDb==0 || iDb>1 ){
4727fc1acf33Sdan       Btree *pBt = db->aDb[iDb].pBt;
472899744fa4Sdrh       if( SQLITE_TXN_WRITE!=sqlite3BtreeTxnState(pBt) ){
4729685a50adSdrh         rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
47307116dc60Sdan         if( rc==SQLITE_OK ){
4731fc1acf33Sdan           rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
4732fc1acf33Sdan         }
4733fc1acf33Sdan       }
47347116dc60Sdan     }
4735edace5d4Sdan   }
4736fc1acf33Sdan 
4737fc1acf33Sdan   sqlite3_mutex_leave(db->mutex);
4738fc1acf33Sdan #endif   /* SQLITE_OMIT_WAL */
4739fc1acf33Sdan   return rc;
4740fc1acf33Sdan }
4741fc1acf33Sdan 
4742fc1acf33Sdan /*
4743fc1acf33Sdan ** Open a read-transaction on the snapshot idendified by pSnapshot.
4744fc1acf33Sdan */
sqlite3_snapshot_open(sqlite3 * db,const char * zDb,sqlite3_snapshot * pSnapshot)4745fc1acf33Sdan int sqlite3_snapshot_open(
4746fc1acf33Sdan   sqlite3 *db,
4747fc1acf33Sdan   const char *zDb,
4748fc1acf33Sdan   sqlite3_snapshot *pSnapshot
4749fc1acf33Sdan ){
4750fc1acf33Sdan   int rc = SQLITE_ERROR;
4751fc1acf33Sdan #ifndef SQLITE_OMIT_WAL
4752fc1acf33Sdan 
4753fc1acf33Sdan #ifdef SQLITE_ENABLE_API_ARMOR
4754fc1acf33Sdan   if( !sqlite3SafetyCheckOk(db) ){
4755fc1acf33Sdan     return SQLITE_MISUSE_BKPT;
4756fc1acf33Sdan   }
4757fc1acf33Sdan #endif
4758fc1acf33Sdan   sqlite3_mutex_enter(db->mutex);
4759fc1acf33Sdan   if( db->autoCommit==0 ){
4760fc1acf33Sdan     int iDb;
4761fc1acf33Sdan     iDb = sqlite3FindDbName(db, zDb);
4762fc1acf33Sdan     if( iDb==0 || iDb>1 ){
4763fc1acf33Sdan       Btree *pBt = db->aDb[iDb].pBt;
476499744fa4Sdrh       if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE ){
4765fa3d4c19Sdan         Pager *pPager = sqlite3BtreePager(pBt);
4766fa3d4c19Sdan         int bUnlock = 0;
476799744fa4Sdrh         if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_NONE ){
4768fa3d4c19Sdan           if( db->nVdbeActive==0 ){
4769fa3d4c19Sdan             rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot);
4770fa3d4c19Sdan             if( rc==SQLITE_OK ){
4771fa3d4c19Sdan               bUnlock = 1;
4772fa3d4c19Sdan               rc = sqlite3BtreeCommit(pBt);
4773fa3d4c19Sdan             }
4774fa3d4c19Sdan           }
4775fa3d4c19Sdan         }else{
4776fa3d4c19Sdan           rc = SQLITE_OK;
4777fa3d4c19Sdan         }
4778fa3d4c19Sdan         if( rc==SQLITE_OK ){
4779861fb1e9Sdan           rc = sqlite3PagerSnapshotOpen(pPager, pSnapshot);
4780fa3d4c19Sdan         }
4781fc1acf33Sdan         if( rc==SQLITE_OK ){
4782685a50adSdrh           rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
4783861fb1e9Sdan           sqlite3PagerSnapshotOpen(pPager, 0);
4784fa3d4c19Sdan         }
4785fa3d4c19Sdan         if( bUnlock ){
4786fa3d4c19Sdan           sqlite3PagerSnapshotUnlock(pPager);
4787fc1acf33Sdan         }
4788fc1acf33Sdan       }
4789fc1acf33Sdan     }
4790fc1acf33Sdan   }
4791fc1acf33Sdan 
4792fc1acf33Sdan   sqlite3_mutex_leave(db->mutex);
4793fc1acf33Sdan #endif   /* SQLITE_OMIT_WAL */
4794fc1acf33Sdan   return rc;
4795fc1acf33Sdan }
4796fc1acf33Sdan 
4797fc1acf33Sdan /*
47981158498dSdan ** Recover as many snapshots as possible from the wal file associated with
47991158498dSdan ** schema zDb of database db.
48001158498dSdan */
sqlite3_snapshot_recover(sqlite3 * db,const char * zDb)48011158498dSdan int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
48021158498dSdan   int rc = SQLITE_ERROR;
48031158498dSdan #ifndef SQLITE_OMIT_WAL
48047585f49aSdrh   int iDb;
48051158498dSdan 
48061158498dSdan #ifdef SQLITE_ENABLE_API_ARMOR
48071158498dSdan   if( !sqlite3SafetyCheckOk(db) ){
48081158498dSdan     return SQLITE_MISUSE_BKPT;
48091158498dSdan   }
48101158498dSdan #endif
48111158498dSdan 
48121158498dSdan   sqlite3_mutex_enter(db->mutex);
48131158498dSdan   iDb = sqlite3FindDbName(db, zDb);
48141158498dSdan   if( iDb==0 || iDb>1 ){
48151158498dSdan     Btree *pBt = db->aDb[iDb].pBt;
481699744fa4Sdrh     if( SQLITE_TXN_NONE==sqlite3BtreeTxnState(pBt) ){
4817685a50adSdrh       rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
481893f51132Sdan       if( rc==SQLITE_OK ){
48191158498dSdan         rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
482093f51132Sdan         sqlite3BtreeCommit(pBt);
482193f51132Sdan       }
48221158498dSdan     }
48231158498dSdan   }
48241158498dSdan   sqlite3_mutex_leave(db->mutex);
48251158498dSdan #endif   /* SQLITE_OMIT_WAL */
48261158498dSdan   return rc;
48271158498dSdan }
48281158498dSdan 
48291158498dSdan /*
4830fc1acf33Sdan ** Free a snapshot handle obtained from sqlite3_snapshot_get().
4831fc1acf33Sdan */
sqlite3_snapshot_free(sqlite3_snapshot * pSnapshot)4832fc1acf33Sdan void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
4833fc1acf33Sdan   sqlite3_free(pSnapshot);
4834fc1acf33Sdan }
4835fc1acf33Sdan #endif /* SQLITE_ENABLE_SNAPSHOT */
4836da1f49b8Sdan 
4837da1f49b8Sdan #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
4838da1f49b8Sdan /*
4839da1f49b8Sdan ** Given the name of a compile-time option, return true if that option
4840da1f49b8Sdan ** was used and false if not.
4841da1f49b8Sdan **
4842da1f49b8Sdan ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
4843da1f49b8Sdan ** is not required for a match.
4844da1f49b8Sdan */
sqlite3_compileoption_used(const char * zOptName)4845da1f49b8Sdan int sqlite3_compileoption_used(const char *zOptName){
4846da1f49b8Sdan   int i, n;
4847da1f49b8Sdan   int nOpt;
4848da1f49b8Sdan   const char **azCompileOpt;
4849da1f49b8Sdan 
4850da1f49b8Sdan #if SQLITE_ENABLE_API_ARMOR
4851da1f49b8Sdan   if( zOptName==0 ){
4852da1f49b8Sdan     (void)SQLITE_MISUSE_BKPT;
4853da1f49b8Sdan     return 0;
4854da1f49b8Sdan   }
4855da1f49b8Sdan #endif
4856da1f49b8Sdan 
4857da1f49b8Sdan   azCompileOpt = sqlite3CompileOptions(&nOpt);
4858da1f49b8Sdan 
4859da1f49b8Sdan   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
4860da1f49b8Sdan   n = sqlite3Strlen30(zOptName);
4861da1f49b8Sdan 
4862da1f49b8Sdan   /* Since nOpt is normally in single digits, a linear search is
4863da1f49b8Sdan   ** adequate. No need for a binary search. */
4864da1f49b8Sdan   for(i=0; i<nOpt; i++){
4865da1f49b8Sdan     if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
4866da1f49b8Sdan      && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
4867da1f49b8Sdan     ){
4868da1f49b8Sdan       return 1;
4869da1f49b8Sdan     }
4870da1f49b8Sdan   }
4871da1f49b8Sdan   return 0;
4872da1f49b8Sdan }
4873da1f49b8Sdan 
4874da1f49b8Sdan /*
4875da1f49b8Sdan ** Return the N-th compile-time option string.  If N is out of range,
4876da1f49b8Sdan ** return a NULL pointer.
4877da1f49b8Sdan */
sqlite3_compileoption_get(int N)4878da1f49b8Sdan const char *sqlite3_compileoption_get(int N){
4879da1f49b8Sdan   int nOpt;
4880da1f49b8Sdan   const char **azCompileOpt;
4881da1f49b8Sdan   azCompileOpt = sqlite3CompileOptions(&nOpt);
4882da1f49b8Sdan   if( N>=0 && N<nOpt ){
4883da1f49b8Sdan     return azCompileOpt[N];
4884da1f49b8Sdan   }
4885da1f49b8Sdan   return 0;
4886da1f49b8Sdan }
4887da1f49b8Sdan #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
4888