4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** Main file for the SQLite library. The routines in this file
13 ** implement the programmer interface to the library. Routines in
14 ** other files are for internal use by SQLite and should not be
15 ** accessed by users of the library.
17 #include "sqliteInt.h"
19 #ifdef SQLITE_ENABLE_FTS3
22 #ifdef SQLITE_ENABLE_RTREE
25 #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
26 # include "sqliteicu.h"
30 ** This is an extension initializer that is a no-op and always
31 ** succeeds, except that it fails if the fault-simulation is set
34 static int sqlite3TestExtInit(sqlite3
*db
){
36 return sqlite3FaultSim(500);
41 ** Forward declarations of external module initializer functions
42 ** for modules that need them.
44 #ifdef SQLITE_ENABLE_FTS5
45 int sqlite3Fts5Init(sqlite3
*);
47 #ifdef SQLITE_ENABLE_STMTVTAB
48 int sqlite3StmtVtabInit(sqlite3
*);
50 #ifdef SQLITE_EXTRA_AUTOEXT
51 int SQLITE_EXTRA_AUTOEXT(sqlite3
*);
54 ** An array of pointers to extension initializer functions for
55 ** built-in extensions.
57 static int (*const sqlite3BuiltinExtensions
[])(sqlite3
*) = {
58 #ifdef SQLITE_ENABLE_FTS3
61 #ifdef SQLITE_ENABLE_FTS5
64 #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
67 #ifdef SQLITE_ENABLE_RTREE
70 #ifdef SQLITE_ENABLE_DBPAGE_VTAB
71 sqlite3DbpageRegister
,
73 #ifdef SQLITE_ENABLE_DBSTAT_VTAB
74 sqlite3DbstatRegister
,
77 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
78 sqlite3JsonTableFunctions
,
80 #ifdef SQLITE_ENABLE_STMTVTAB
83 #ifdef SQLITE_ENABLE_BYTECODE_VTAB
84 sqlite3VdbeBytecodeVtabInit
,
86 #ifdef SQLITE_EXTRA_AUTOEXT
91 #ifndef SQLITE_AMALGAMATION
92 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
93 ** contains the text of SQLITE_VERSION macro.
95 const char sqlite3_version
[] = SQLITE_VERSION
;
98 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
99 ** a pointer to the to the sqlite3_version[] string constant.
101 const char *sqlite3_libversion(void){ return sqlite3_version
; }
103 /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
104 ** pointer to a string constant whose value is the same as the
105 ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
106 ** an edited copy of the amalgamation, then the last four characters of
107 ** the hash might be different from SQLITE_SOURCE_ID.
109 const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID
; }
111 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
112 ** returns an integer equal to SQLITE_VERSION_NUMBER.
114 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER
; }
116 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
117 ** zero if and only if SQLite was compiled with mutexing code omitted due to
118 ** the SQLITE_THREADSAFE compile-time option being set to 0.
120 int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE
; }
123 ** When compiling the test fixture or with debugging enabled (on Win32),
124 ** this variable being set to non-zero will cause OSTRACE macros to emit
125 ** extra diagnostic information.
127 #ifdef SQLITE_HAVE_OS_TRACE
128 # ifndef SQLITE_DEBUG_OS_TRACE
129 # define SQLITE_DEBUG_OS_TRACE 0
131 int sqlite3OSTrace
= SQLITE_DEBUG_OS_TRACE
;
134 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
136 ** If the following function pointer is not NULL and if
137 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
138 ** I/O active are written using this function. These messages
139 ** are intended for debugging activity only.
141 SQLITE_API
void (SQLITE_CDECL
*sqlite3IoTrace
)(const char*, ...) = 0;
145 ** If the following global variable points to a string which is the
146 ** name of a directory, then that directory will be used to store
149 ** See also the "PRAGMA temp_store_directory" SQL command.
151 char *sqlite3_temp_directory
= 0;
154 ** If the following global variable points to a string which is the
155 ** name of a directory, then that directory will be used to store
156 ** all database files specified with a relative pathname.
158 ** See also the "PRAGMA data_store_directory" SQL command.
160 char *sqlite3_data_directory
= 0;
163 ** Determine whether or not high-precision (long double) floating point
164 ** math works correctly on CPU currently running.
166 static SQLITE_NOINLINE
int hasHighPrecisionDouble(int rc
){
167 if( sizeof(LONGDOUBLE_TYPE
)<=8 ){
168 /* If the size of "long double" is not more than 8, then
169 ** high-precision math is not possible. */
172 /* Just because sizeof(long double)>8 does not mean that the underlying
173 ** hardware actually supports high-precision floating point. For example,
174 ** clearing the 0x100 bit in the floating-point control word on Intel
175 ** processors will make long double work like double, even though long
176 ** double takes up more space. The only way to determine if long double
177 ** actually works is to run an experiment. */
178 LONGDOUBLE_TYPE a
, b
, c
;
189 ** Initialize SQLite.
191 ** This routine must be called to initialize the memory allocation,
192 ** VFS, and mutex subsystems prior to doing any serious work with
193 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
194 ** this routine will be called automatically by key routines such as
197 ** This routine is a no-op except on its very first call for the process,
198 ** or for the first call after a call to sqlite3_shutdown.
200 ** The first thread to call this routine runs the initialization to
201 ** completion. If subsequent threads call this routine before the first
202 ** thread has finished the initialization process, then the subsequent
203 ** threads must block until the first thread finishes with the initialization.
205 ** The first thread might call this routine recursively. Recursive
206 ** calls to this routine should not block, of course. Otherwise the
207 ** initialization process would never complete.
209 ** Let X be the first thread to enter this routine. Let Y be some other
210 ** thread. Then while the initial invocation of this routine by X is
211 ** incomplete, it is required that:
213 ** * Calls to this routine from Y must block until the outer-most
214 ** call by X completes.
216 ** * Recursive calls to this routine from thread X return immediately
219 int sqlite3_initialize(void){
220 MUTEX_LOGIC( sqlite3_mutex
*pMainMtx
; ) /* The main static mutex */
221 int rc
; /* Result code */
222 #ifdef SQLITE_EXTRA_INIT
223 int bRunExtraInit
= 0; /* Extra initialization needed */
226 #ifdef SQLITE_OMIT_WSD
227 rc
= sqlite3_wsd_init(4096, 24);
233 /* If the following assert() fails on some obscure processor/compiler
234 ** combination, the work-around is to set the correct pointer
235 ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
236 assert( SQLITE_PTRSIZE
==sizeof(char*) );
238 /* If SQLite is already completely initialized, then this call
239 ** to sqlite3_initialize() should be a no-op. But the initialization
240 ** must be complete. So isInit must not be set until the very end
243 if( sqlite3GlobalConfig
.isInit
){
244 sqlite3MemoryBarrier();
248 /* Make sure the mutex subsystem is initialized. If unable to
249 ** initialize the mutex subsystem, return early with the error.
250 ** If the system is so sick that we are unable to allocate a mutex,
251 ** there is not much SQLite is going to be able to do.
253 ** The mutex subsystem must take care of serializing its own
256 rc
= sqlite3MutexInit();
259 /* Initialize the malloc() system and the recursive pInitMutex mutex.
260 ** This operation is protected by the STATIC_MAIN mutex. Note that
261 ** MutexAlloc() is called for a static mutex prior to initializing the
262 ** malloc subsystem - this implies that the allocation of a static
263 ** mutex must not require support from the malloc subsystem.
265 MUTEX_LOGIC( pMainMtx
= sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN
); )
266 sqlite3_mutex_enter(pMainMtx
);
267 sqlite3GlobalConfig
.isMutexInit
= 1;
268 if( !sqlite3GlobalConfig
.isMallocInit
){
269 rc
= sqlite3MallocInit();
272 sqlite3GlobalConfig
.isMallocInit
= 1;
273 if( !sqlite3GlobalConfig
.pInitMutex
){
274 sqlite3GlobalConfig
.pInitMutex
=
275 sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE
);
276 if( sqlite3GlobalConfig
.bCoreMutex
&& !sqlite3GlobalConfig
.pInitMutex
){
277 rc
= SQLITE_NOMEM_BKPT
;
282 sqlite3GlobalConfig
.nRefInitMutex
++;
284 sqlite3_mutex_leave(pMainMtx
);
286 /* If rc is not SQLITE_OK at this point, then either the malloc
287 ** subsystem could not be initialized or the system failed to allocate
288 ** the pInitMutex mutex. Return an error in either case. */
293 /* Do the rest of the initialization under the recursive mutex so
294 ** that we will be able to handle recursive calls into
295 ** sqlite3_initialize(). The recursive calls normally come through
296 ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
297 ** recursive calls might also be possible.
299 ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
300 ** to the xInit method, so the xInit method need not be threadsafe.
302 ** The following mutex is what serializes access to the appdef pcache xInit
303 ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
304 ** call to sqlite3PcacheInitialize().
306 sqlite3_mutex_enter(sqlite3GlobalConfig
.pInitMutex
);
307 if( sqlite3GlobalConfig
.isInit
==0 && sqlite3GlobalConfig
.inProgress
==0 ){
308 sqlite3GlobalConfig
.inProgress
= 1;
309 #ifdef SQLITE_ENABLE_SQLLOG
311 extern void sqlite3_init_sqllog(void);
312 sqlite3_init_sqllog();
315 memset(&sqlite3BuiltinFunctions
, 0, sizeof(sqlite3BuiltinFunctions
));
316 sqlite3RegisterBuiltinFunctions();
317 if( sqlite3GlobalConfig
.isPCacheInit
==0 ){
318 rc
= sqlite3PcacheInitialize();
321 sqlite3GlobalConfig
.isPCacheInit
= 1;
322 rc
= sqlite3OsInit();
324 #ifndef SQLITE_OMIT_DESERIALIZE
326 rc
= sqlite3MemdbInit();
330 sqlite3PCacheBufferSetup( sqlite3GlobalConfig
.pPage
,
331 sqlite3GlobalConfig
.szPage
, sqlite3GlobalConfig
.nPage
);
332 sqlite3MemoryBarrier();
333 sqlite3GlobalConfig
.isInit
= 1;
334 #ifdef SQLITE_EXTRA_INIT
338 sqlite3GlobalConfig
.inProgress
= 0;
340 sqlite3_mutex_leave(sqlite3GlobalConfig
.pInitMutex
);
342 /* Go back under the static mutex and clean up the recursive
343 ** mutex to prevent a resource leak.
345 sqlite3_mutex_enter(pMainMtx
);
346 sqlite3GlobalConfig
.nRefInitMutex
--;
347 if( sqlite3GlobalConfig
.nRefInitMutex
<=0 ){
348 assert( sqlite3GlobalConfig
.nRefInitMutex
==0 );
349 sqlite3_mutex_free(sqlite3GlobalConfig
.pInitMutex
);
350 sqlite3GlobalConfig
.pInitMutex
= 0;
352 sqlite3_mutex_leave(pMainMtx
);
354 /* The following is just a sanity check to make sure SQLite has
355 ** been compiled correctly. It is important to run this code, but
356 ** we don't want to run it too often and soak up CPU cycles for no
357 ** reason. So we run it once during initialization.
360 #ifndef SQLITE_OMIT_FLOATING_POINT
361 /* This section of code's only "output" is via assert() statements. */
363 u64 x
= (((u64
)1)<<63)-1;
365 assert(sizeof(x
)==8);
366 assert(sizeof(x
)==sizeof(y
));
368 assert( sqlite3IsNaN(y
) );
373 /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
374 ** compile-time option.
376 #ifdef SQLITE_EXTRA_INIT
378 int SQLITE_EXTRA_INIT(const char*);
379 rc
= SQLITE_EXTRA_INIT(0);
383 /* Experimentally determine if high-precision floating point is
385 #ifndef SQLITE_OMIT_WSD
386 sqlite3Config
.bUseLongDouble
= hasHighPrecisionDouble(rc
);
393 ** Undo the effects of sqlite3_initialize(). Must not be called while
394 ** there are outstanding database connections or memory allocations or
395 ** while any part of SQLite is otherwise in use in any thread. This
396 ** routine is not threadsafe. But it is safe to invoke this routine
397 ** on when SQLite is already shut down. If SQLite is already shut down
398 ** when this routine is invoked, then this routine is a harmless no-op.
400 int sqlite3_shutdown(void){
401 #ifdef SQLITE_OMIT_WSD
402 int rc
= sqlite3_wsd_init(4096, 24);
408 if( sqlite3GlobalConfig
.isInit
){
409 #ifdef SQLITE_EXTRA_SHUTDOWN
410 void SQLITE_EXTRA_SHUTDOWN(void);
411 SQLITE_EXTRA_SHUTDOWN();
414 sqlite3_reset_auto_extension();
415 sqlite3GlobalConfig
.isInit
= 0;
417 if( sqlite3GlobalConfig
.isPCacheInit
){
418 sqlite3PcacheShutdown();
419 sqlite3GlobalConfig
.isPCacheInit
= 0;
421 if( sqlite3GlobalConfig
.isMallocInit
){
423 sqlite3GlobalConfig
.isMallocInit
= 0;
425 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
426 /* The heap subsystem has now been shutdown and these values are supposed
427 ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
428 ** which would rely on that heap subsystem; therefore, make sure these
429 ** values cannot refer to heap memory that was just invalidated when the
430 ** heap subsystem was shutdown. This is only done if the current call to
431 ** this function resulted in the heap subsystem actually being shutdown.
433 sqlite3_data_directory
= 0;
434 sqlite3_temp_directory
= 0;
437 if( sqlite3GlobalConfig
.isMutexInit
){
439 sqlite3GlobalConfig
.isMutexInit
= 0;
446 ** This API allows applications to modify the global configuration of
447 ** the SQLite library at run-time.
449 ** This routine should only be called when there are no outstanding
450 ** database connections or memory allocations. This routine is not
451 ** threadsafe. Failure to heed these warnings can lead to unpredictable
454 int sqlite3_config(int op
, ...){
458 /* sqlite3_config() normally returns SQLITE_MISUSE if it is invoked while
459 ** the SQLite library is in use. Except, a few selected opcodes
462 if( sqlite3GlobalConfig
.isInit
){
463 static const u64 mAnytimeConfigOption
= 0
464 | MASKBIT64( SQLITE_CONFIG_LOG
)
465 | MASKBIT64( SQLITE_CONFIG_PCACHE_HDRSZ
)
467 if( op
<0 || op
>63 || (MASKBIT64(op
) & mAnytimeConfigOption
)==0 ){
468 return SQLITE_MISUSE_BKPT
;
470 testcase( op
==SQLITE_CONFIG_LOG
);
471 testcase( op
==SQLITE_CONFIG_PCACHE_HDRSZ
);
477 /* Mutex configuration options are only available in a threadsafe
480 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
481 case SQLITE_CONFIG_SINGLETHREAD
: {
482 /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
484 sqlite3GlobalConfig
.bCoreMutex
= 0; /* Disable mutex on core */
485 sqlite3GlobalConfig
.bFullMutex
= 0; /* Disable mutex on connections */
489 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
490 case SQLITE_CONFIG_MULTITHREAD
: {
491 /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
493 sqlite3GlobalConfig
.bCoreMutex
= 1; /* Enable mutex on core */
494 sqlite3GlobalConfig
.bFullMutex
= 0; /* Disable mutex on connections */
498 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
499 case SQLITE_CONFIG_SERIALIZED
: {
500 /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
502 sqlite3GlobalConfig
.bCoreMutex
= 1; /* Enable mutex on core */
503 sqlite3GlobalConfig
.bFullMutex
= 1; /* Enable mutex on connections */
507 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
508 case SQLITE_CONFIG_MUTEX
: {
509 /* Specify an alternative mutex implementation */
510 sqlite3GlobalConfig
.mutex
= *va_arg(ap
, sqlite3_mutex_methods
*);
514 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
515 case SQLITE_CONFIG_GETMUTEX
: {
516 /* Retrieve the current mutex implementation */
517 *va_arg(ap
, sqlite3_mutex_methods
*) = sqlite3GlobalConfig
.mutex
;
522 case SQLITE_CONFIG_MALLOC
: {
523 /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
524 ** single argument which is a pointer to an instance of the
525 ** sqlite3_mem_methods structure. The argument specifies alternative
526 ** low-level memory allocation routines to be used in place of the memory
527 ** allocation routines built into SQLite. */
528 sqlite3GlobalConfig
.m
= *va_arg(ap
, sqlite3_mem_methods
*);
531 case SQLITE_CONFIG_GETMALLOC
: {
532 /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
533 ** single argument which is a pointer to an instance of the
534 ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
535 ** filled with the currently defined memory allocation routines. */
536 if( sqlite3GlobalConfig
.m
.xMalloc
==0 ) sqlite3MemSetDefault();
537 *va_arg(ap
, sqlite3_mem_methods
*) = sqlite3GlobalConfig
.m
;
540 case SQLITE_CONFIG_MEMSTATUS
: {
541 assert( !sqlite3GlobalConfig
.isInit
); /* Cannot change at runtime */
542 /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
543 ** single argument of type int, interpreted as a boolean, which enables
544 ** or disables the collection of memory allocation statistics. */
545 sqlite3GlobalConfig
.bMemstat
= va_arg(ap
, int);
548 case SQLITE_CONFIG_SMALL_MALLOC
: {
549 sqlite3GlobalConfig
.bSmallMalloc
= va_arg(ap
, int);
552 case SQLITE_CONFIG_PAGECACHE
: {
553 /* EVIDENCE-OF: R-18761-36601 There are three arguments to
554 ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
555 ** the size of each page cache line (sz), and the number of cache lines
557 sqlite3GlobalConfig
.pPage
= va_arg(ap
, void*);
558 sqlite3GlobalConfig
.szPage
= va_arg(ap
, int);
559 sqlite3GlobalConfig
.nPage
= va_arg(ap
, int);
562 case SQLITE_CONFIG_PCACHE_HDRSZ
: {
563 /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
564 ** a single parameter which is a pointer to an integer and writes into
565 ** that integer the number of extra bytes per page required for each page
566 ** in SQLITE_CONFIG_PAGECACHE. */
568 sqlite3HeaderSizeBtree() +
569 sqlite3HeaderSizePcache() +
570 sqlite3HeaderSizePcache1();
574 case SQLITE_CONFIG_PCACHE
: {
578 case SQLITE_CONFIG_GETPCACHE
: {
584 case SQLITE_CONFIG_PCACHE2
: {
585 /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
586 ** single argument which is a pointer to an sqlite3_pcache_methods2
587 ** object. This object specifies the interface to a custom page cache
588 ** implementation. */
589 sqlite3GlobalConfig
.pcache2
= *va_arg(ap
, sqlite3_pcache_methods2
*);
592 case SQLITE_CONFIG_GETPCACHE2
: {
593 /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
594 ** single argument which is a pointer to an sqlite3_pcache_methods2
595 ** object. SQLite copies of the current page cache implementation into
597 if( sqlite3GlobalConfig
.pcache2
.xInit
==0 ){
598 sqlite3PCacheSetDefault();
600 *va_arg(ap
, sqlite3_pcache_methods2
*) = sqlite3GlobalConfig
.pcache2
;
604 /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
605 ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
606 ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
607 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
608 case SQLITE_CONFIG_HEAP
: {
609 /* EVIDENCE-OF: R-19854-42126 There are three arguments to
610 ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
611 ** number of bytes in the memory buffer, and the minimum allocation size.
613 sqlite3GlobalConfig
.pHeap
= va_arg(ap
, void*);
614 sqlite3GlobalConfig
.nHeap
= va_arg(ap
, int);
615 sqlite3GlobalConfig
.mnReq
= va_arg(ap
, int);
617 if( sqlite3GlobalConfig
.mnReq
<1 ){
618 sqlite3GlobalConfig
.mnReq
= 1;
619 }else if( sqlite3GlobalConfig
.mnReq
>(1<<12) ){
620 /* cap min request size at 2^12 */
621 sqlite3GlobalConfig
.mnReq
= (1<<12);
624 if( sqlite3GlobalConfig
.pHeap
==0 ){
625 /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
626 ** is NULL, then SQLite reverts to using its default memory allocator
627 ** (the system malloc() implementation), undoing any prior invocation of
628 ** SQLITE_CONFIG_MALLOC.
630 ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
631 ** revert to its default implementation when sqlite3_initialize() is run
633 memset(&sqlite3GlobalConfig
.m
, 0, sizeof(sqlite3GlobalConfig
.m
));
635 /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
636 ** alternative memory allocator is engaged to handle all of SQLites
637 ** memory allocation needs. */
638 #ifdef SQLITE_ENABLE_MEMSYS3
639 sqlite3GlobalConfig
.m
= *sqlite3MemGetMemsys3();
641 #ifdef SQLITE_ENABLE_MEMSYS5
642 sqlite3GlobalConfig
.m
= *sqlite3MemGetMemsys5();
649 case SQLITE_CONFIG_LOOKASIDE
: {
650 sqlite3GlobalConfig
.szLookaside
= va_arg(ap
, int);
651 sqlite3GlobalConfig
.nLookaside
= va_arg(ap
, int);
655 /* Record a pointer to the logger function and its first argument.
656 ** The default is NULL. Logging is disabled if the function pointer is
659 case SQLITE_CONFIG_LOG
: {
660 /* MSVC is picky about pulling func ptrs from va lists.
661 ** http://support.microsoft.com/kb/47961
662 ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
664 typedef void(*LOGFUNC_t
)(void*,int,const char*);
665 LOGFUNC_t xLog
= va_arg(ap
, LOGFUNC_t
);
666 void *pLogArg
= va_arg(ap
, void*);
667 AtomicStore(&sqlite3GlobalConfig
.xLog
, xLog
);
668 AtomicStore(&sqlite3GlobalConfig
.pLogArg
, pLogArg
);
672 /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
673 ** can be changed at start-time using the
674 ** sqlite3_config(SQLITE_CONFIG_URI,1) or
675 ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
677 case SQLITE_CONFIG_URI
: {
678 /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
679 ** argument of type int. If non-zero, then URI handling is globally
680 ** enabled. If the parameter is zero, then URI handling is globally
682 int bOpenUri
= va_arg(ap
, int);
683 AtomicStore(&sqlite3GlobalConfig
.bOpenUri
, bOpenUri
);
687 case SQLITE_CONFIG_COVERING_INDEX_SCAN
: {
688 /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
689 ** option takes a single integer argument which is interpreted as a
690 ** boolean in order to enable or disable the use of covering indices for
691 ** full table scans in the query optimizer. */
692 sqlite3GlobalConfig
.bUseCis
= va_arg(ap
, int);
696 #ifdef SQLITE_ENABLE_SQLLOG
697 case SQLITE_CONFIG_SQLLOG
: {
698 typedef void(*SQLLOGFUNC_t
)(void*, sqlite3
*, const char*, int);
699 sqlite3GlobalConfig
.xSqllog
= va_arg(ap
, SQLLOGFUNC_t
);
700 sqlite3GlobalConfig
.pSqllogArg
= va_arg(ap
, void *);
705 case SQLITE_CONFIG_MMAP_SIZE
: {
706 /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
707 ** integer (sqlite3_int64) values that are the default mmap size limit
708 ** (the default setting for PRAGMA mmap_size) and the maximum allowed
709 ** mmap size limit. */
710 sqlite3_int64 szMmap
= va_arg(ap
, sqlite3_int64
);
711 sqlite3_int64 mxMmap
= va_arg(ap
, sqlite3_int64
);
712 /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
713 ** negative, then that argument is changed to its compile-time default.
715 ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
716 ** silently truncated if necessary so that it does not exceed the
717 ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
718 ** compile-time option.
720 if( mxMmap
<0 || mxMmap
>SQLITE_MAX_MMAP_SIZE
){
721 mxMmap
= SQLITE_MAX_MMAP_SIZE
;
723 if( szMmap
<0 ) szMmap
= SQLITE_DEFAULT_MMAP_SIZE
;
724 if( szMmap
>mxMmap
) szMmap
= mxMmap
;
725 sqlite3GlobalConfig
.mxMmap
= mxMmap
;
726 sqlite3GlobalConfig
.szMmap
= szMmap
;
730 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
731 case SQLITE_CONFIG_WIN32_HEAPSIZE
: {
732 /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
733 ** unsigned integer value that specifies the maximum size of the created
735 sqlite3GlobalConfig
.nHeap
= va_arg(ap
, int);
740 case SQLITE_CONFIG_PMASZ
: {
741 sqlite3GlobalConfig
.szPma
= va_arg(ap
, unsigned int);
745 case SQLITE_CONFIG_STMTJRNL_SPILL
: {
746 sqlite3GlobalConfig
.nStmtSpill
= va_arg(ap
, int);
750 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
751 case SQLITE_CONFIG_SORTERREF_SIZE
: {
752 int iVal
= va_arg(ap
, int);
754 iVal
= SQLITE_DEFAULT_SORTERREF_SIZE
;
756 sqlite3GlobalConfig
.szSorterRef
= (u32
)iVal
;
759 #endif /* SQLITE_ENABLE_SORTER_REFERENCES */
761 #ifndef SQLITE_OMIT_DESERIALIZE
762 case SQLITE_CONFIG_MEMDB_MAXSIZE
: {
763 sqlite3GlobalConfig
.mxMemdbSize
= va_arg(ap
, sqlite3_int64
);
766 #endif /* SQLITE_OMIT_DESERIALIZE */
768 case SQLITE_CONFIG_ROWID_IN_VIEW
: {
769 int *pVal
= va_arg(ap
,int*);
770 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
771 if( 0==*pVal
) sqlite3GlobalConfig
.mNoVisibleRowid
= TF_NoVisibleRowid
;
772 if( 1==*pVal
) sqlite3GlobalConfig
.mNoVisibleRowid
= 0;
773 *pVal
= (sqlite3GlobalConfig
.mNoVisibleRowid
==0);
790 ** Set up the lookaside buffers for a database connection.
791 ** Return SQLITE_OK on success.
792 ** If lookaside is already active, return SQLITE_BUSY.
794 ** The sz parameter is the number of bytes in each lookaside slot.
795 ** The cnt parameter is the number of slots. If pStart is NULL the
796 ** space for the lookaside memory is obtained from sqlite3_malloc().
797 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
798 ** the lookaside memory.
800 static int setupLookaside(sqlite3
*db
, void *pBuf
, int sz
, int cnt
){
801 #ifndef SQLITE_OMIT_LOOKASIDE
803 sqlite3_int64 szAlloc
= sz
*(sqlite3_int64
)cnt
;
804 int nBig
; /* Number of full-size slots */
805 int nSm
; /* Number smaller LOOKASIDE_SMALL-byte slots */
807 if( sqlite3LookasideUsed(db
,0)>0 ){
810 /* Free any existing lookaside buffer for this handle before
811 ** allocating a new one so we don't have to have space for
812 ** both at the same time.
814 if( db
->lookaside
.bMalloced
){
815 sqlite3_free(db
->lookaside
.pStart
);
817 /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
818 ** than a pointer to be useful.
820 sz
= ROUNDDOWN8(sz
); /* IMP: R-33038-09382 */
821 if( sz
<=(int)sizeof(LookasideSlot
*) ) sz
= 0;
823 if( sz
==0 || cnt
==0 ){
827 sqlite3BeginBenignMalloc();
828 pStart
= sqlite3Malloc( szAlloc
); /* IMP: R-61949-35727 */
829 sqlite3EndBenignMalloc();
830 if( pStart
) szAlloc
= sqlite3MallocSize(pStart
);
834 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
835 if( sz
>=LOOKASIDE_SMALL
*3 ){
836 nBig
= szAlloc
/(3*LOOKASIDE_SMALL
+sz
);
837 nSm
= (szAlloc
- sz
*nBig
)/LOOKASIDE_SMALL
;
838 }else if( sz
>=LOOKASIDE_SMALL
*2 ){
839 nBig
= szAlloc
/(LOOKASIDE_SMALL
+sz
);
840 nSm
= (szAlloc
- sz
*nBig
)/LOOKASIDE_SMALL
;
842 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
849 db
->lookaside
.pStart
= pStart
;
850 db
->lookaside
.pInit
= 0;
851 db
->lookaside
.pFree
= 0;
852 db
->lookaside
.sz
= (u16
)sz
;
853 db
->lookaside
.szTrue
= (u16
)sz
;
857 assert( sz
> (int)sizeof(LookasideSlot
*) );
858 p
= (LookasideSlot
*)pStart
;
859 for(i
=0; i
<nBig
; i
++){
860 p
->pNext
= db
->lookaside
.pInit
;
861 db
->lookaside
.pInit
= p
;
862 p
= (LookasideSlot
*)&((u8
*)p
)[sz
];
864 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
865 db
->lookaside
.pSmallInit
= 0;
866 db
->lookaside
.pSmallFree
= 0;
867 db
->lookaside
.pMiddle
= p
;
868 for(i
=0; i
<nSm
; i
++){
869 p
->pNext
= db
->lookaside
.pSmallInit
;
870 db
->lookaside
.pSmallInit
= p
;
871 p
= (LookasideSlot
*)&((u8
*)p
)[LOOKASIDE_SMALL
];
873 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
874 assert( ((uptr
)p
)<=szAlloc
+ (uptr
)pStart
);
875 db
->lookaside
.pEnd
= p
;
876 db
->lookaside
.bDisable
= 0;
877 db
->lookaside
.bMalloced
= pBuf
==0 ?1:0;
878 db
->lookaside
.nSlot
= nBig
+nSm
;
880 db
->lookaside
.pStart
= 0;
881 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
882 db
->lookaside
.pSmallInit
= 0;
883 db
->lookaside
.pSmallFree
= 0;
884 db
->lookaside
.pMiddle
= 0;
885 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
886 db
->lookaside
.pEnd
= 0;
887 db
->lookaside
.bDisable
= 1;
888 db
->lookaside
.sz
= 0;
889 db
->lookaside
.bMalloced
= 0;
890 db
->lookaside
.nSlot
= 0;
892 db
->lookaside
.pTrueEnd
= db
->lookaside
.pEnd
;
893 assert( sqlite3LookasideUsed(db
,0)==0 );
894 #endif /* SQLITE_OMIT_LOOKASIDE */
899 ** Return the mutex associated with a database connection.
901 sqlite3_mutex
*sqlite3_db_mutex(sqlite3
*db
){
902 #ifdef SQLITE_ENABLE_API_ARMOR
903 if( !sqlite3SafetyCheckOk(db
) ){
904 (void)SQLITE_MISUSE_BKPT
;
912 ** Free up as much memory as we can from the given database
915 int sqlite3_db_release_memory(sqlite3
*db
){
918 #ifdef SQLITE_ENABLE_API_ARMOR
919 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
921 sqlite3_mutex_enter(db
->mutex
);
922 sqlite3BtreeEnterAll(db
);
923 for(i
=0; i
<db
->nDb
; i
++){
924 Btree
*pBt
= db
->aDb
[i
].pBt
;
926 Pager
*pPager
= sqlite3BtreePager(pBt
);
927 sqlite3PagerShrink(pPager
);
930 sqlite3BtreeLeaveAll(db
);
931 sqlite3_mutex_leave(db
->mutex
);
936 ** Flush any dirty pages in the pager-cache for any attached database
939 int sqlite3_db_cacheflush(sqlite3
*db
){
944 #ifdef SQLITE_ENABLE_API_ARMOR
945 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
947 sqlite3_mutex_enter(db
->mutex
);
948 sqlite3BtreeEnterAll(db
);
949 for(i
=0; rc
==SQLITE_OK
&& i
<db
->nDb
; i
++){
950 Btree
*pBt
= db
->aDb
[i
].pBt
;
951 if( pBt
&& sqlite3BtreeTxnState(pBt
)==SQLITE_TXN_WRITE
){
952 Pager
*pPager
= sqlite3BtreePager(pBt
);
953 rc
= sqlite3PagerFlush(pPager
);
954 if( rc
==SQLITE_BUSY
){
960 sqlite3BtreeLeaveAll(db
);
961 sqlite3_mutex_leave(db
->mutex
);
962 return ((rc
==SQLITE_OK
&& bSeenBusy
) ? SQLITE_BUSY
: rc
);
966 ** Configuration settings for an individual database connection
968 int sqlite3_db_config(sqlite3
*db
, int op
, ...){
972 #ifdef SQLITE_ENABLE_API_ARMOR
973 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
975 sqlite3_mutex_enter(db
->mutex
);
978 case SQLITE_DBCONFIG_MAINDBNAME
: {
979 /* IMP: R-06824-28531 */
980 /* IMP: R-36257-52125 */
981 db
->aDb
[0].zDbSName
= va_arg(ap
,char*);
985 case SQLITE_DBCONFIG_LOOKASIDE
: {
986 void *pBuf
= va_arg(ap
, void*); /* IMP: R-26835-10964 */
987 int sz
= va_arg(ap
, int); /* IMP: R-47871-25994 */
988 int cnt
= va_arg(ap
, int); /* IMP: R-04460-53386 */
989 rc
= setupLookaside(db
, pBuf
, sz
, cnt
);
993 static const struct {
994 int op
; /* The opcode */
995 u32 mask
; /* Mask of the bit in sqlite3.flags to set/clear */
997 { SQLITE_DBCONFIG_ENABLE_FKEY
, SQLITE_ForeignKeys
},
998 { SQLITE_DBCONFIG_ENABLE_TRIGGER
, SQLITE_EnableTrigger
},
999 { SQLITE_DBCONFIG_ENABLE_VIEW
, SQLITE_EnableView
},
1000 { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
, SQLITE_Fts3Tokenizer
},
1001 { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
, SQLITE_LoadExtension
},
1002 { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE
, SQLITE_NoCkptOnClose
},
1003 { SQLITE_DBCONFIG_ENABLE_QPSG
, SQLITE_EnableQPSG
},
1004 { SQLITE_DBCONFIG_TRIGGER_EQP
, SQLITE_TriggerEQP
},
1005 { SQLITE_DBCONFIG_RESET_DATABASE
, SQLITE_ResetDatabase
},
1006 { SQLITE_DBCONFIG_DEFENSIVE
, SQLITE_Defensive
},
1007 { SQLITE_DBCONFIG_WRITABLE_SCHEMA
, SQLITE_WriteSchema
|
1008 SQLITE_NoSchemaError
},
1009 { SQLITE_DBCONFIG_LEGACY_ALTER_TABLE
, SQLITE_LegacyAlter
},
1010 { SQLITE_DBCONFIG_DQS_DDL
, SQLITE_DqsDDL
},
1011 { SQLITE_DBCONFIG_DQS_DML
, SQLITE_DqsDML
},
1012 { SQLITE_DBCONFIG_LEGACY_FILE_FORMAT
, SQLITE_LegacyFileFmt
},
1013 { SQLITE_DBCONFIG_TRUSTED_SCHEMA
, SQLITE_TrustedSchema
},
1014 { SQLITE_DBCONFIG_STMT_SCANSTATUS
, SQLITE_StmtScanStatus
},
1015 { SQLITE_DBCONFIG_REVERSE_SCANORDER
, SQLITE_ReverseOrder
},
1018 rc
= SQLITE_ERROR
; /* IMP: R-42790-23372 */
1019 for(i
=0; i
<ArraySize(aFlagOp
); i
++){
1020 if( aFlagOp
[i
].op
==op
){
1021 int onoff
= va_arg(ap
, int);
1022 int *pRes
= va_arg(ap
, int*);
1023 u64 oldFlags
= db
->flags
;
1025 db
->flags
|= aFlagOp
[i
].mask
;
1026 }else if( onoff
==0 ){
1027 db
->flags
&= ~(u64
)aFlagOp
[i
].mask
;
1029 if( oldFlags
!=db
->flags
){
1030 sqlite3ExpirePreparedStatements(db
, 0);
1033 *pRes
= (db
->flags
& aFlagOp
[i
].mask
)!=0;
1043 sqlite3_mutex_leave(db
->mutex
);
1048 ** This is the default collating function named "BINARY" which is always
1051 static int binCollFunc(
1053 int nKey1
, const void *pKey1
,
1054 int nKey2
, const void *pKey2
1057 UNUSED_PARAMETER(NotUsed
);
1058 n
= nKey1
<nKey2
? nKey1
: nKey2
;
1059 /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
1060 ** strings byte by byte using the memcmp() function from the standard C
1062 assert( pKey1
&& pKey2
);
1063 rc
= memcmp(pKey1
, pKey2
, n
);
1071 ** This is the collating function named "RTRIM" which is always
1072 ** available. Ignore trailing spaces.
1074 static int rtrimCollFunc(
1076 int nKey1
, const void *pKey1
,
1077 int nKey2
, const void *pKey2
1079 const u8
*pK1
= (const u8
*)pKey1
;
1080 const u8
*pK2
= (const u8
*)pKey2
;
1081 while( nKey1
&& pK1
[nKey1
-1]==' ' ) nKey1
--;
1082 while( nKey2
&& pK2
[nKey2
-1]==' ' ) nKey2
--;
1083 return binCollFunc(pUser
, nKey1
, pKey1
, nKey2
, pKey2
);
1087 ** Return true if CollSeq is the default built-in BINARY.
1089 int sqlite3IsBinary(const CollSeq
*p
){
1090 assert( p
==0 || p
->xCmp
!=binCollFunc
|| strcmp(p
->zName
,"BINARY")==0 );
1091 return p
==0 || p
->xCmp
==binCollFunc
;
1095 ** Another built-in collating sequence: NOCASE.
1097 ** This collating sequence is intended to be used for "case independent
1098 ** comparison". SQLite's knowledge of upper and lower case equivalents
1099 ** extends only to the 26 characters used in the English language.
1101 ** At the moment there is only a UTF-8 implementation.
1103 static int nocaseCollatingFunc(
1105 int nKey1
, const void *pKey1
,
1106 int nKey2
, const void *pKey2
1108 int r
= sqlite3StrNICmp(
1109 (const char *)pKey1
, (const char *)pKey2
, (nKey1
<nKey2
)?nKey1
:nKey2
);
1110 UNUSED_PARAMETER(NotUsed
);
1118 ** Return the ROWID of the most recent insert
1120 sqlite_int64
sqlite3_last_insert_rowid(sqlite3
*db
){
1121 #ifdef SQLITE_ENABLE_API_ARMOR
1122 if( !sqlite3SafetyCheckOk(db
) ){
1123 (void)SQLITE_MISUSE_BKPT
;
1127 return db
->lastRowid
;
1131 ** Set the value returned by the sqlite3_last_insert_rowid() API function.
1133 void sqlite3_set_last_insert_rowid(sqlite3
*db
, sqlite3_int64 iRowid
){
1134 #ifdef SQLITE_ENABLE_API_ARMOR
1135 if( !sqlite3SafetyCheckOk(db
) ){
1136 (void)SQLITE_MISUSE_BKPT
;
1140 sqlite3_mutex_enter(db
->mutex
);
1141 db
->lastRowid
= iRowid
;
1142 sqlite3_mutex_leave(db
->mutex
);
1146 ** Return the number of changes in the most recent call to sqlite3_exec().
1148 sqlite3_int64
sqlite3_changes64(sqlite3
*db
){
1149 #ifdef SQLITE_ENABLE_API_ARMOR
1150 if( !sqlite3SafetyCheckOk(db
) ){
1151 (void)SQLITE_MISUSE_BKPT
;
1157 int sqlite3_changes(sqlite3
*db
){
1158 return (int)sqlite3_changes64(db
);
1162 ** Return the number of changes since the database handle was opened.
1164 sqlite3_int64
sqlite3_total_changes64(sqlite3
*db
){
1165 #ifdef SQLITE_ENABLE_API_ARMOR
1166 if( !sqlite3SafetyCheckOk(db
) ){
1167 (void)SQLITE_MISUSE_BKPT
;
1171 return db
->nTotalChange
;
1173 int sqlite3_total_changes(sqlite3
*db
){
1174 return (int)sqlite3_total_changes64(db
);
1178 ** Close all open savepoints. This function only manipulates fields of the
1179 ** database handle object, it does not close any savepoints that may be open
1180 ** at the b-tree/pager level.
1182 void sqlite3CloseSavepoints(sqlite3
*db
){
1183 while( db
->pSavepoint
){
1184 Savepoint
*pTmp
= db
->pSavepoint
;
1185 db
->pSavepoint
= pTmp
->pNext
;
1186 sqlite3DbFree(db
, pTmp
);
1190 db
->isTransactionSavepoint
= 0;
1194 ** Invoke the destructor function associated with FuncDef p, if any. Except,
1195 ** if this is not the last copy of the function, do not invoke it. Multiple
1196 ** copies of a single function are created when create_function() is called
1197 ** with SQLITE_ANY as the encoding.
1199 static void functionDestroy(sqlite3
*db
, FuncDef
*p
){
1200 FuncDestructor
*pDestructor
;
1201 assert( (p
->funcFlags
& SQLITE_FUNC_BUILTIN
)==0 );
1202 pDestructor
= p
->u
.pDestructor
;
1204 pDestructor
->nRef
--;
1205 if( pDestructor
->nRef
==0 ){
1206 pDestructor
->xDestroy(pDestructor
->pUserData
);
1207 sqlite3DbFree(db
, pDestructor
);
1213 ** Disconnect all sqlite3_vtab objects that belong to database connection
1214 ** db. This is called when db is being closed.
1216 static void disconnectAllVtab(sqlite3
*db
){
1217 #ifndef SQLITE_OMIT_VIRTUALTABLE
1220 sqlite3BtreeEnterAll(db
);
1221 for(i
=0; i
<db
->nDb
; i
++){
1222 Schema
*pSchema
= db
->aDb
[i
].pSchema
;
1224 for(p
=sqliteHashFirst(&pSchema
->tblHash
); p
; p
=sqliteHashNext(p
)){
1225 Table
*pTab
= (Table
*)sqliteHashData(p
);
1226 if( IsVirtual(pTab
) ) sqlite3VtabDisconnect(db
, pTab
);
1230 for(p
=sqliteHashFirst(&db
->aModule
); p
; p
=sqliteHashNext(p
)){
1231 Module
*pMod
= (Module
*)sqliteHashData(p
);
1232 if( pMod
->pEpoTab
){
1233 sqlite3VtabDisconnect(db
, pMod
->pEpoTab
);
1236 sqlite3VtabUnlockList(db
);
1237 sqlite3BtreeLeaveAll(db
);
1239 UNUSED_PARAMETER(db
);
1244 ** Return TRUE if database connection db has unfinalized prepared
1245 ** statements or unfinished sqlite3_backup objects.
1247 static int connectionIsBusy(sqlite3
*db
){
1249 assert( sqlite3_mutex_held(db
->mutex
) );
1250 if( db
->pVdbe
) return 1;
1251 for(j
=0; j
<db
->nDb
; j
++){
1252 Btree
*pBt
= db
->aDb
[j
].pBt
;
1253 if( pBt
&& sqlite3BtreeIsInBackup(pBt
) ) return 1;
1259 ** Close an existing SQLite database
1261 static int sqlite3Close(sqlite3
*db
, int forceZombie
){
1263 /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
1264 ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
1267 if( !sqlite3SafetyCheckSickOrOk(db
) ){
1268 return SQLITE_MISUSE_BKPT
;
1270 sqlite3_mutex_enter(db
->mutex
);
1271 if( db
->mTrace
& SQLITE_TRACE_CLOSE
){
1272 db
->trace
.xV2(SQLITE_TRACE_CLOSE
, db
->pTraceArg
, db
, 0);
1275 /* Force xDisconnect calls on all virtual tables */
1276 disconnectAllVtab(db
);
1278 /* If a transaction is open, the disconnectAllVtab() call above
1279 ** will not have called the xDisconnect() method on any virtual
1280 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
1281 ** call will do so. We need to do this before the check for active
1282 ** SQL statements below, as the v-table implementation may be storing
1283 ** some prepared statements internally.
1285 sqlite3VtabRollback(db
);
1287 /* Legacy behavior (sqlite3_close() behavior) is to return
1288 ** SQLITE_BUSY if the connection can not be closed immediately.
1290 if( !forceZombie
&& connectionIsBusy(db
) ){
1291 sqlite3ErrorWithMsg(db
, SQLITE_BUSY
, "unable to close due to unfinalized "
1292 "statements or unfinished backups");
1293 sqlite3_mutex_leave(db
->mutex
);
1297 #ifdef SQLITE_ENABLE_SQLLOG
1298 if( sqlite3GlobalConfig
.xSqllog
){
1299 /* Closing the handle. Fourth parameter is passed the value 2. */
1300 sqlite3GlobalConfig
.xSqllog(sqlite3GlobalConfig
.pSqllogArg
, db
, 0, 2);
1304 while( db
->pDbData
){
1305 DbClientData
*p
= db
->pDbData
;
1306 db
->pDbData
= p
->pNext
;
1307 assert( p
->pData
!=0 );
1308 if( p
->xDestructor
) p
->xDestructor(p
->pData
);
1312 /* Convert the connection into a zombie and then close it.
1314 db
->eOpenState
= SQLITE_STATE_ZOMBIE
;
1315 sqlite3LeaveMutexAndCloseZombie(db
);
1320 ** Return the transaction state for a single databse, or the maximum
1321 ** transaction state over all attached databases if zSchema is null.
1323 int sqlite3_txn_state(sqlite3
*db
, const char *zSchema
){
1326 #ifdef SQLITE_ENABLE_API_ARMOR
1327 if( !sqlite3SafetyCheckOk(db
) ){
1328 (void)SQLITE_MISUSE_BKPT
;
1332 sqlite3_mutex_enter(db
->mutex
);
1334 nDb
= iDb
= sqlite3FindDbName(db
, zSchema
);
1340 for(; iDb
<=nDb
; iDb
++){
1341 Btree
*pBt
= db
->aDb
[iDb
].pBt
;
1342 int x
= pBt
!=0 ? sqlite3BtreeTxnState(pBt
) : SQLITE_TXN_NONE
;
1343 if( x
>iTxn
) iTxn
= x
;
1345 sqlite3_mutex_leave(db
->mutex
);
1350 ** Two variations on the public interface for closing a database
1351 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
1352 ** leaves the connection open if there are unfinalized prepared
1353 ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
1354 ** version forces the connection to become a zombie if there are
1355 ** unclosed resources, and arranges for deallocation when the last
1356 ** prepare statement or sqlite3_backup closes.
1358 int sqlite3_close(sqlite3
*db
){ return sqlite3Close(db
,0); }
1359 int sqlite3_close_v2(sqlite3
*db
){ return sqlite3Close(db
,1); }
1363 ** Close the mutex on database connection db.
1365 ** Furthermore, if database connection db is a zombie (meaning that there
1366 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
1367 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
1368 ** finished, then free all resources.
1370 void sqlite3LeaveMutexAndCloseZombie(sqlite3
*db
){
1371 HashElem
*i
; /* Hash table iterator */
1374 /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
1375 ** or if the connection has not yet been closed by sqlite3_close_v2(),
1376 ** then just leave the mutex and return.
1378 if( db
->eOpenState
!=SQLITE_STATE_ZOMBIE
|| connectionIsBusy(db
) ){
1379 sqlite3_mutex_leave(db
->mutex
);
1383 /* If we reach this point, it means that the database connection has
1384 ** closed all sqlite3_stmt and sqlite3_backup objects and has been
1385 ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
1386 ** go ahead and free all resources.
1389 /* If a transaction is open, roll it back. This also ensures that if
1390 ** any database schemas have been modified by an uncommitted transaction
1391 ** they are reset. And that the required b-tree mutex is held to make
1392 ** the pager rollback and schema reset an atomic operation. */
1393 sqlite3RollbackAll(db
, SQLITE_OK
);
1395 /* Free any outstanding Savepoint structures. */
1396 sqlite3CloseSavepoints(db
);
1398 /* Close all database connections */
1399 for(j
=0; j
<db
->nDb
; j
++){
1400 struct Db
*pDb
= &db
->aDb
[j
];
1402 sqlite3BtreeClose(pDb
->pBt
);
1409 /* Clear the TEMP schema separately and last */
1410 if( db
->aDb
[1].pSchema
){
1411 sqlite3SchemaClear(db
->aDb
[1].pSchema
);
1413 sqlite3VtabUnlockList(db
);
1415 /* Free up the array of auxiliary databases */
1416 sqlite3CollapseDatabaseArray(db
);
1417 assert( db
->nDb
<=2 );
1418 assert( db
->aDb
==db
->aDbStatic
);
1420 /* Tell the code in notify.c that the connection no longer holds any
1421 ** locks and does not require any further unlock-notify callbacks.
1423 sqlite3ConnectionClosed(db
);
1425 for(i
=sqliteHashFirst(&db
->aFunc
); i
; i
=sqliteHashNext(i
)){
1427 p
= sqliteHashData(i
);
1429 functionDestroy(db
, p
);
1431 sqlite3DbFree(db
, p
);
1435 sqlite3HashClear(&db
->aFunc
);
1436 for(i
=sqliteHashFirst(&db
->aCollSeq
); i
; i
=sqliteHashNext(i
)){
1437 CollSeq
*pColl
= (CollSeq
*)sqliteHashData(i
);
1438 /* Invoke any destructors registered for collation sequence user data. */
1440 if( pColl
[j
].xDel
){
1441 pColl
[j
].xDel(pColl
[j
].pUser
);
1444 sqlite3DbFree(db
, pColl
);
1446 sqlite3HashClear(&db
->aCollSeq
);
1447 #ifndef SQLITE_OMIT_VIRTUALTABLE
1448 for(i
=sqliteHashFirst(&db
->aModule
); i
; i
=sqliteHashNext(i
)){
1449 Module
*pMod
= (Module
*)sqliteHashData(i
);
1450 sqlite3VtabEponymousTableClear(db
, pMod
);
1451 sqlite3VtabModuleUnref(db
, pMod
);
1453 sqlite3HashClear(&db
->aModule
);
1456 sqlite3Error(db
, SQLITE_OK
); /* Deallocates any cached error strings. */
1457 sqlite3ValueFree(db
->pErr
);
1458 sqlite3CloseExtensions(db
);
1459 #if SQLITE_USER_AUTHENTICATION
1460 sqlite3_free(db
->auth
.zAuthUser
);
1461 sqlite3_free(db
->auth
.zAuthPW
);
1464 db
->eOpenState
= SQLITE_STATE_ERROR
;
1466 /* The temp-database schema is allocated differently from the other schema
1467 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
1468 ** So it needs to be freed here. Todo: Why not roll the temp schema into
1469 ** the same sqliteMalloc() as the one that allocates the database
1472 sqlite3DbFree(db
, db
->aDb
[1].pSchema
);
1473 if( db
->xAutovacDestr
){
1474 db
->xAutovacDestr(db
->pAutovacPagesArg
);
1476 sqlite3_mutex_leave(db
->mutex
);
1477 db
->eOpenState
= SQLITE_STATE_CLOSED
;
1478 sqlite3_mutex_free(db
->mutex
);
1479 assert( sqlite3LookasideUsed(db
,0)==0 );
1480 if( db
->lookaside
.bMalloced
){
1481 sqlite3_free(db
->lookaside
.pStart
);
1487 ** Rollback all database files. If tripCode is not SQLITE_OK, then
1488 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
1489 ** breaker") and made to return tripCode if there are any further
1490 ** attempts to use that cursor. Read cursors remain open and valid
1491 ** but are "saved" in case the table pages are moved around.
1493 void sqlite3RollbackAll(sqlite3
*db
, int tripCode
){
1497 assert( sqlite3_mutex_held(db
->mutex
) );
1498 sqlite3BeginBenignMalloc();
1500 /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
1501 ** This is important in case the transaction being rolled back has
1502 ** modified the database schema. If the b-tree mutexes are not taken
1503 ** here, then another shared-cache connection might sneak in between
1504 ** the database rollback and schema reset, which can cause false
1505 ** corruption reports in some cases. */
1506 sqlite3BtreeEnterAll(db
);
1507 schemaChange
= (db
->mDbFlags
& DBFLAG_SchemaChange
)!=0 && db
->init
.busy
==0;
1509 for(i
=0; i
<db
->nDb
; i
++){
1510 Btree
*p
= db
->aDb
[i
].pBt
;
1512 if( sqlite3BtreeTxnState(p
)==SQLITE_TXN_WRITE
){
1515 sqlite3BtreeRollback(p
, tripCode
, !schemaChange
);
1518 sqlite3VtabRollback(db
);
1519 sqlite3EndBenignMalloc();
1522 sqlite3ExpirePreparedStatements(db
, 0);
1523 sqlite3ResetAllSchemasOfConnection(db
);
1525 sqlite3BtreeLeaveAll(db
);
1527 /* Any deferred constraint violations have now been resolved. */
1528 db
->nDeferredCons
= 0;
1529 db
->nDeferredImmCons
= 0;
1530 db
->flags
&= ~(u64
)(SQLITE_DeferFKs
|SQLITE_CorruptRdOnly
);
1532 /* If one has been configured, invoke the rollback-hook callback */
1533 if( db
->xRollbackCallback
&& (inTrans
|| !db
->autoCommit
) ){
1534 db
->xRollbackCallback(db
->pRollbackArg
);
1539 ** Return a static string containing the name corresponding to the error code
1540 ** specified in the argument.
1542 #if defined(SQLITE_NEED_ERR_NAME)
1543 const char *sqlite3ErrName(int rc
){
1544 const char *zName
= 0;
1546 for(i
=0; i
<2 && zName
==0; i
++, rc
&= 0xff){
1548 case SQLITE_OK
: zName
= "SQLITE_OK"; break;
1549 case SQLITE_ERROR
: zName
= "SQLITE_ERROR"; break;
1550 case SQLITE_ERROR_SNAPSHOT
: zName
= "SQLITE_ERROR_SNAPSHOT"; break;
1551 case SQLITE_INTERNAL
: zName
= "SQLITE_INTERNAL"; break;
1552 case SQLITE_PERM
: zName
= "SQLITE_PERM"; break;
1553 case SQLITE_ABORT
: zName
= "SQLITE_ABORT"; break;
1554 case SQLITE_ABORT_ROLLBACK
: zName
= "SQLITE_ABORT_ROLLBACK"; break;
1555 case SQLITE_BUSY
: zName
= "SQLITE_BUSY"; break;
1556 case SQLITE_BUSY_RECOVERY
: zName
= "SQLITE_BUSY_RECOVERY"; break;
1557 case SQLITE_BUSY_SNAPSHOT
: zName
= "SQLITE_BUSY_SNAPSHOT"; break;
1558 case SQLITE_LOCKED
: zName
= "SQLITE_LOCKED"; break;
1559 case SQLITE_LOCKED_SHAREDCACHE
: zName
= "SQLITE_LOCKED_SHAREDCACHE";break;
1560 case SQLITE_NOMEM
: zName
= "SQLITE_NOMEM"; break;
1561 case SQLITE_READONLY
: zName
= "SQLITE_READONLY"; break;
1562 case SQLITE_READONLY_RECOVERY
: zName
= "SQLITE_READONLY_RECOVERY"; break;
1563 case SQLITE_READONLY_CANTINIT
: zName
= "SQLITE_READONLY_CANTINIT"; break;
1564 case SQLITE_READONLY_ROLLBACK
: zName
= "SQLITE_READONLY_ROLLBACK"; break;
1565 case SQLITE_READONLY_DBMOVED
: zName
= "SQLITE_READONLY_DBMOVED"; break;
1566 case SQLITE_READONLY_DIRECTORY
: zName
= "SQLITE_READONLY_DIRECTORY";break;
1567 case SQLITE_INTERRUPT
: zName
= "SQLITE_INTERRUPT"; break;
1568 case SQLITE_IOERR
: zName
= "SQLITE_IOERR"; break;
1569 case SQLITE_IOERR_READ
: zName
= "SQLITE_IOERR_READ"; break;
1570 case SQLITE_IOERR_SHORT_READ
: zName
= "SQLITE_IOERR_SHORT_READ"; break;
1571 case SQLITE_IOERR_WRITE
: zName
= "SQLITE_IOERR_WRITE"; break;
1572 case SQLITE_IOERR_FSYNC
: zName
= "SQLITE_IOERR_FSYNC"; break;
1573 case SQLITE_IOERR_DIR_FSYNC
: zName
= "SQLITE_IOERR_DIR_FSYNC"; break;
1574 case SQLITE_IOERR_TRUNCATE
: zName
= "SQLITE_IOERR_TRUNCATE"; break;
1575 case SQLITE_IOERR_FSTAT
: zName
= "SQLITE_IOERR_FSTAT"; break;
1576 case SQLITE_IOERR_UNLOCK
: zName
= "SQLITE_IOERR_UNLOCK"; break;
1577 case SQLITE_IOERR_RDLOCK
: zName
= "SQLITE_IOERR_RDLOCK"; break;
1578 case SQLITE_IOERR_DELETE
: zName
= "SQLITE_IOERR_DELETE"; break;
1579 case SQLITE_IOERR_NOMEM
: zName
= "SQLITE_IOERR_NOMEM"; break;
1580 case SQLITE_IOERR_ACCESS
: zName
= "SQLITE_IOERR_ACCESS"; break;
1581 case SQLITE_IOERR_CHECKRESERVEDLOCK
:
1582 zName
= "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
1583 case SQLITE_IOERR_LOCK
: zName
= "SQLITE_IOERR_LOCK"; break;
1584 case SQLITE_IOERR_CLOSE
: zName
= "SQLITE_IOERR_CLOSE"; break;
1585 case SQLITE_IOERR_DIR_CLOSE
: zName
= "SQLITE_IOERR_DIR_CLOSE"; break;
1586 case SQLITE_IOERR_SHMOPEN
: zName
= "SQLITE_IOERR_SHMOPEN"; break;
1587 case SQLITE_IOERR_SHMSIZE
: zName
= "SQLITE_IOERR_SHMSIZE"; break;
1588 case SQLITE_IOERR_SHMLOCK
: zName
= "SQLITE_IOERR_SHMLOCK"; break;
1589 case SQLITE_IOERR_SHMMAP
: zName
= "SQLITE_IOERR_SHMMAP"; break;
1590 case SQLITE_IOERR_SEEK
: zName
= "SQLITE_IOERR_SEEK"; break;
1591 case SQLITE_IOERR_DELETE_NOENT
: zName
= "SQLITE_IOERR_DELETE_NOENT";break;
1592 case SQLITE_IOERR_MMAP
: zName
= "SQLITE_IOERR_MMAP"; break;
1593 case SQLITE_IOERR_GETTEMPPATH
: zName
= "SQLITE_IOERR_GETTEMPPATH"; break;
1594 case SQLITE_IOERR_CONVPATH
: zName
= "SQLITE_IOERR_CONVPATH"; break;
1595 case SQLITE_CORRUPT
: zName
= "SQLITE_CORRUPT"; break;
1596 case SQLITE_CORRUPT_VTAB
: zName
= "SQLITE_CORRUPT_VTAB"; break;
1597 case SQLITE_NOTFOUND
: zName
= "SQLITE_NOTFOUND"; break;
1598 case SQLITE_FULL
: zName
= "SQLITE_FULL"; break;
1599 case SQLITE_CANTOPEN
: zName
= "SQLITE_CANTOPEN"; break;
1600 case SQLITE_CANTOPEN_NOTEMPDIR
: zName
= "SQLITE_CANTOPEN_NOTEMPDIR";break;
1601 case SQLITE_CANTOPEN_ISDIR
: zName
= "SQLITE_CANTOPEN_ISDIR"; break;
1602 case SQLITE_CANTOPEN_FULLPATH
: zName
= "SQLITE_CANTOPEN_FULLPATH"; break;
1603 case SQLITE_CANTOPEN_CONVPATH
: zName
= "SQLITE_CANTOPEN_CONVPATH"; break;
1604 case SQLITE_CANTOPEN_SYMLINK
: zName
= "SQLITE_CANTOPEN_SYMLINK"; break;
1605 case SQLITE_PROTOCOL
: zName
= "SQLITE_PROTOCOL"; break;
1606 case SQLITE_EMPTY
: zName
= "SQLITE_EMPTY"; break;
1607 case SQLITE_SCHEMA
: zName
= "SQLITE_SCHEMA"; break;
1608 case SQLITE_TOOBIG
: zName
= "SQLITE_TOOBIG"; break;
1609 case SQLITE_CONSTRAINT
: zName
= "SQLITE_CONSTRAINT"; break;
1610 case SQLITE_CONSTRAINT_UNIQUE
: zName
= "SQLITE_CONSTRAINT_UNIQUE"; break;
1611 case SQLITE_CONSTRAINT_TRIGGER
: zName
= "SQLITE_CONSTRAINT_TRIGGER";break;
1612 case SQLITE_CONSTRAINT_FOREIGNKEY
:
1613 zName
= "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
1614 case SQLITE_CONSTRAINT_CHECK
: zName
= "SQLITE_CONSTRAINT_CHECK"; break;
1615 case SQLITE_CONSTRAINT_PRIMARYKEY
:
1616 zName
= "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
1617 case SQLITE_CONSTRAINT_NOTNULL
: zName
= "SQLITE_CONSTRAINT_NOTNULL";break;
1618 case SQLITE_CONSTRAINT_COMMITHOOK
:
1619 zName
= "SQLITE_CONSTRAINT_COMMITHOOK"; break;
1620 case SQLITE_CONSTRAINT_VTAB
: zName
= "SQLITE_CONSTRAINT_VTAB"; break;
1621 case SQLITE_CONSTRAINT_FUNCTION
:
1622 zName
= "SQLITE_CONSTRAINT_FUNCTION"; break;
1623 case SQLITE_CONSTRAINT_ROWID
: zName
= "SQLITE_CONSTRAINT_ROWID"; break;
1624 case SQLITE_MISMATCH
: zName
= "SQLITE_MISMATCH"; break;
1625 case SQLITE_MISUSE
: zName
= "SQLITE_MISUSE"; break;
1626 case SQLITE_NOLFS
: zName
= "SQLITE_NOLFS"; break;
1627 case SQLITE_AUTH
: zName
= "SQLITE_AUTH"; break;
1628 case SQLITE_FORMAT
: zName
= "SQLITE_FORMAT"; break;
1629 case SQLITE_RANGE
: zName
= "SQLITE_RANGE"; break;
1630 case SQLITE_NOTADB
: zName
= "SQLITE_NOTADB"; break;
1631 case SQLITE_ROW
: zName
= "SQLITE_ROW"; break;
1632 case SQLITE_NOTICE
: zName
= "SQLITE_NOTICE"; break;
1633 case SQLITE_NOTICE_RECOVER_WAL
: zName
= "SQLITE_NOTICE_RECOVER_WAL";break;
1634 case SQLITE_NOTICE_RECOVER_ROLLBACK
:
1635 zName
= "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
1636 case SQLITE_NOTICE_RBU
: zName
= "SQLITE_NOTICE_RBU"; break;
1637 case SQLITE_WARNING
: zName
= "SQLITE_WARNING"; break;
1638 case SQLITE_WARNING_AUTOINDEX
: zName
= "SQLITE_WARNING_AUTOINDEX"; break;
1639 case SQLITE_DONE
: zName
= "SQLITE_DONE"; break;
1643 static char zBuf
[50];
1644 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "SQLITE_UNKNOWN(%d)", origRc
);
1652 ** Return a static string that describes the kind of error specified in the
1655 const char *sqlite3ErrStr(int rc
){
1656 static const char* const aMsg
[] = {
1657 /* SQLITE_OK */ "not an error",
1658 /* SQLITE_ERROR */ "SQL logic error",
1659 /* SQLITE_INTERNAL */ 0,
1660 /* SQLITE_PERM */ "access permission denied",
1661 /* SQLITE_ABORT */ "query aborted",
1662 /* SQLITE_BUSY */ "database is locked",
1663 /* SQLITE_LOCKED */ "database table is locked",
1664 /* SQLITE_NOMEM */ "out of memory",
1665 /* SQLITE_READONLY */ "attempt to write a readonly database",
1666 /* SQLITE_INTERRUPT */ "interrupted",
1667 /* SQLITE_IOERR */ "disk I/O error",
1668 /* SQLITE_CORRUPT */ "database disk image is malformed",
1669 /* SQLITE_NOTFOUND */ "unknown operation",
1670 /* SQLITE_FULL */ "database or disk is full",
1671 /* SQLITE_CANTOPEN */ "unable to open database file",
1672 /* SQLITE_PROTOCOL */ "locking protocol",
1673 /* SQLITE_EMPTY */ 0,
1674 /* SQLITE_SCHEMA */ "database schema has changed",
1675 /* SQLITE_TOOBIG */ "string or blob too big",
1676 /* SQLITE_CONSTRAINT */ "constraint failed",
1677 /* SQLITE_MISMATCH */ "datatype mismatch",
1678 /* SQLITE_MISUSE */ "bad parameter or other API misuse",
1679 #ifdef SQLITE_DISABLE_LFS
1680 /* SQLITE_NOLFS */ "large file support is disabled",
1682 /* SQLITE_NOLFS */ 0,
1684 /* SQLITE_AUTH */ "authorization denied",
1685 /* SQLITE_FORMAT */ 0,
1686 /* SQLITE_RANGE */ "column index out of range",
1687 /* SQLITE_NOTADB */ "file is not a database",
1688 /* SQLITE_NOTICE */ "notification message",
1689 /* SQLITE_WARNING */ "warning message",
1691 const char *zErr
= "unknown error";
1693 case SQLITE_ABORT_ROLLBACK
: {
1694 zErr
= "abort due to ROLLBACK";
1698 zErr
= "another row available";
1702 zErr
= "no more rows available";
1707 if( ALWAYS(rc
>=0) && rc
<ArraySize(aMsg
) && aMsg
[rc
]!=0 ){
1717 ** This routine implements a busy callback that sleeps and tries
1718 ** again until a timeout value is reached. The timeout value is
1719 ** an integer number of milliseconds passed in as the first
1722 ** Return non-zero to retry the lock. Return zero to stop trying
1723 ** and cause SQLite to return SQLITE_BUSY.
1725 static int sqliteDefaultBusyCallback(
1726 void *ptr
, /* Database connection */
1727 int count
/* Number of times table has been busy */
1729 #if SQLITE_OS_WIN || !defined(HAVE_NANOSLEEP) || HAVE_NANOSLEEP
1730 /* This case is for systems that have support for sleeping for fractions of
1731 ** a second. Examples: All windows systems, unix systems with nanosleep() */
1732 static const u8 delays
[] =
1733 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
1734 static const u8 totals
[] =
1735 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
1736 # define NDELAY ArraySize(delays)
1737 sqlite3
*db
= (sqlite3
*)ptr
;
1738 int tmout
= db
->busyTimeout
;
1742 if( count
< NDELAY
){
1743 delay
= delays
[count
];
1744 prior
= totals
[count
];
1746 delay
= delays
[NDELAY
-1];
1747 prior
= totals
[NDELAY
-1] + delay
*(count
-(NDELAY
-1));
1749 if( prior
+ delay
> tmout
){
1750 delay
= tmout
- prior
;
1751 if( delay
<=0 ) return 0;
1753 sqlite3OsSleep(db
->pVfs
, delay
*1000);
1756 /* This case for unix systems that lack usleep() support. Sleeping
1757 ** must be done in increments of whole seconds */
1758 sqlite3
*db
= (sqlite3
*)ptr
;
1759 int tmout
= ((sqlite3
*)ptr
)->busyTimeout
;
1760 if( (count
+1)*1000 > tmout
){
1763 sqlite3OsSleep(db
->pVfs
, 1000000);
1769 ** Invoke the given busy handler.
1771 ** This routine is called when an operation failed to acquire a
1772 ** lock on VFS file pFile.
1774 ** If this routine returns non-zero, the lock is retried. If it
1775 ** returns 0, the operation aborts with an SQLITE_BUSY error.
1777 int sqlite3InvokeBusyHandler(BusyHandler
*p
){
1779 if( p
->xBusyHandler
==0 || p
->nBusy
<0 ) return 0;
1780 rc
= p
->xBusyHandler(p
->pBusyArg
, p
->nBusy
);
1790 ** This routine sets the busy callback for an Sqlite database to the
1791 ** given callback function with the given argument.
1793 int sqlite3_busy_handler(
1795 int (*xBusy
)(void*,int),
1798 #ifdef SQLITE_ENABLE_API_ARMOR
1799 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
1801 sqlite3_mutex_enter(db
->mutex
);
1802 db
->busyHandler
.xBusyHandler
= xBusy
;
1803 db
->busyHandler
.pBusyArg
= pArg
;
1804 db
->busyHandler
.nBusy
= 0;
1805 db
->busyTimeout
= 0;
1806 sqlite3_mutex_leave(db
->mutex
);
1810 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1812 ** This routine sets the progress callback for an Sqlite database to the
1813 ** given callback function with the given argument. The progress callback will
1814 ** be invoked every nOps opcodes.
1816 void sqlite3_progress_handler(
1819 int (*xProgress
)(void*),
1822 #ifdef SQLITE_ENABLE_API_ARMOR
1823 if( !sqlite3SafetyCheckOk(db
) ){
1824 (void)SQLITE_MISUSE_BKPT
;
1828 sqlite3_mutex_enter(db
->mutex
);
1830 db
->xProgress
= xProgress
;
1831 db
->nProgressOps
= (unsigned)nOps
;
1832 db
->pProgressArg
= pArg
;
1835 db
->nProgressOps
= 0;
1836 db
->pProgressArg
= 0;
1838 sqlite3_mutex_leave(db
->mutex
);
1844 ** This routine installs a default busy handler that waits for the
1845 ** specified number of milliseconds before returning 0.
1847 int sqlite3_busy_timeout(sqlite3
*db
, int ms
){
1848 #ifdef SQLITE_ENABLE_API_ARMOR
1849 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
1852 sqlite3_busy_handler(db
, (int(*)(void*,int))sqliteDefaultBusyCallback
,
1854 db
->busyTimeout
= ms
;
1856 sqlite3_busy_handler(db
, 0, 0);
1862 ** Cause any pending operation to stop at its earliest opportunity.
1864 void sqlite3_interrupt(sqlite3
*db
){
1865 #ifdef SQLITE_ENABLE_API_ARMOR
1866 if( !sqlite3SafetyCheckOk(db
)
1867 && (db
==0 || db
->eOpenState
!=SQLITE_STATE_ZOMBIE
)
1869 (void)SQLITE_MISUSE_BKPT
;
1873 AtomicStore(&db
->u1
.isInterrupted
, 1);
1877 ** Return true or false depending on whether or not an interrupt is
1878 ** pending on connection db.
1880 int sqlite3_is_interrupted(sqlite3
*db
){
1881 #ifdef SQLITE_ENABLE_API_ARMOR
1882 if( !sqlite3SafetyCheckOk(db
)
1883 && (db
==0 || db
->eOpenState
!=SQLITE_STATE_ZOMBIE
)
1885 (void)SQLITE_MISUSE_BKPT
;
1889 return AtomicLoad(&db
->u1
.isInterrupted
)!=0;
1893 ** This function is exactly the same as sqlite3_create_function(), except
1894 ** that it is designed to be called by internal code. The difference is
1895 ** that if a malloc() fails in sqlite3_create_function(), an error code
1896 ** is returned and the mallocFailed flag cleared.
1898 int sqlite3CreateFunc(
1900 const char *zFunctionName
,
1904 void (*xSFunc
)(sqlite3_context
*,int,sqlite3_value
**),
1905 void (*xStep
)(sqlite3_context
*,int,sqlite3_value
**),
1906 void (*xFinal
)(sqlite3_context
*),
1907 void (*xValue
)(sqlite3_context
*),
1908 void (*xInverse
)(sqlite3_context
*,int,sqlite3_value
**),
1909 FuncDestructor
*pDestructor
1914 assert( sqlite3_mutex_held(db
->mutex
) );
1915 assert( xValue
==0 || xSFunc
==0 );
1916 if( zFunctionName
==0 /* Must have a valid name */
1917 || (xSFunc
!=0 && xFinal
!=0) /* Not both xSFunc and xFinal */
1918 || ((xFinal
==0)!=(xStep
==0)) /* Both or neither of xFinal and xStep */
1919 || ((xValue
==0)!=(xInverse
==0)) /* Both or neither of xValue, xInverse */
1920 || (nArg
<-1 || nArg
>SQLITE_MAX_FUNCTION_ARG
)
1921 || (255<sqlite3Strlen30(zFunctionName
))
1923 return SQLITE_MISUSE_BKPT
;
1926 assert( SQLITE_FUNC_CONSTANT
==SQLITE_DETERMINISTIC
);
1927 assert( SQLITE_FUNC_DIRECT
==SQLITE_DIRECTONLY
);
1928 extraFlags
= enc
& (SQLITE_DETERMINISTIC
|SQLITE_DIRECTONLY
|
1929 SQLITE_SUBTYPE
|SQLITE_INNOCUOUS
|SQLITE_RESULT_SUBTYPE
);
1930 enc
&= (SQLITE_FUNC_ENCMASK
|SQLITE_ANY
);
1932 /* The SQLITE_INNOCUOUS flag is the same bit as SQLITE_FUNC_UNSAFE. But
1933 ** the meaning is inverted. So flip the bit. */
1934 assert( SQLITE_FUNC_UNSAFE
==SQLITE_INNOCUOUS
);
1935 extraFlags
^= SQLITE_FUNC_UNSAFE
; /* tag-20230109-1 */
1938 #ifndef SQLITE_OMIT_UTF16
1939 /* If SQLITE_UTF16 is specified as the encoding type, transform this
1940 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
1941 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
1943 ** If SQLITE_ANY is specified, add three versions of the function
1944 ** to the hash table.
1948 enc
= SQLITE_UTF16NATIVE
;
1952 rc
= sqlite3CreateFunc(db
, zFunctionName
, nArg
,
1953 (SQLITE_UTF8
|extraFlags
)^SQLITE_FUNC_UNSAFE
, /* tag-20230109-1 */
1954 pUserData
, xSFunc
, xStep
, xFinal
, xValue
, xInverse
, pDestructor
);
1955 if( rc
==SQLITE_OK
){
1956 rc
= sqlite3CreateFunc(db
, zFunctionName
, nArg
,
1957 (SQLITE_UTF16LE
|extraFlags
)^SQLITE_FUNC_UNSAFE
, /* tag-20230109-1*/
1958 pUserData
, xSFunc
, xStep
, xFinal
, xValue
, xInverse
, pDestructor
);
1960 if( rc
!=SQLITE_OK
){
1963 enc
= SQLITE_UTF16BE
;
1967 case SQLITE_UTF16LE
:
1968 case SQLITE_UTF16BE
:
1978 /* Check if an existing function is being overridden or deleted. If so,
1979 ** and there are active VMs, then return SQLITE_BUSY. If a function
1980 ** is being overridden/deleted but there are no active VMs, allow the
1981 ** operation to continue but invalidate all precompiled statements.
1983 p
= sqlite3FindFunction(db
, zFunctionName
, nArg
, (u8
)enc
, 0);
1984 if( p
&& (p
->funcFlags
& SQLITE_FUNC_ENCMASK
)==(u32
)enc
&& p
->nArg
==nArg
){
1985 if( db
->nVdbeActive
){
1986 sqlite3ErrorWithMsg(db
, SQLITE_BUSY
,
1987 "unable to delete/modify user-function due to active statements");
1988 assert( !db
->mallocFailed
);
1991 sqlite3ExpirePreparedStatements(db
, 0);
1993 }else if( xSFunc
==0 && xFinal
==0 ){
1994 /* Trying to delete a function that does not exist. This is a no-op.
1995 ** https://sqlite.org/forum/forumpost/726219164b */
1999 p
= sqlite3FindFunction(db
, zFunctionName
, nArg
, (u8
)enc
, 1);
2000 assert(p
|| db
->mallocFailed
);
2002 return SQLITE_NOMEM_BKPT
;
2005 /* If an older version of the function with a configured destructor is
2006 ** being replaced invoke the destructor function here. */
2007 functionDestroy(db
, p
);
2010 pDestructor
->nRef
++;
2012 p
->u
.pDestructor
= pDestructor
;
2013 p
->funcFlags
= (p
->funcFlags
& SQLITE_FUNC_ENCMASK
) | extraFlags
;
2014 testcase( p
->funcFlags
& SQLITE_DETERMINISTIC
);
2015 testcase( p
->funcFlags
& SQLITE_DIRECTONLY
);
2016 p
->xSFunc
= xSFunc
? xSFunc
: xStep
;
2017 p
->xFinalize
= xFinal
;
2019 p
->xInverse
= xInverse
;
2020 p
->pUserData
= pUserData
;
2021 p
->nArg
= (u16
)nArg
;
2026 ** Worker function used by utf-8 APIs that create new functions:
2028 ** sqlite3_create_function()
2029 ** sqlite3_create_function_v2()
2030 ** sqlite3_create_window_function()
2032 static int createFunctionApi(
2038 void (*xSFunc
)(sqlite3_context
*,int,sqlite3_value
**),
2039 void (*xStep
)(sqlite3_context
*,int,sqlite3_value
**),
2040 void (*xFinal
)(sqlite3_context
*),
2041 void (*xValue
)(sqlite3_context
*),
2042 void (*xInverse
)(sqlite3_context
*,int,sqlite3_value
**),
2043 void(*xDestroy
)(void*)
2045 int rc
= SQLITE_ERROR
;
2046 FuncDestructor
*pArg
= 0;
2048 #ifdef SQLITE_ENABLE_API_ARMOR
2049 if( !sqlite3SafetyCheckOk(db
) ){
2050 return SQLITE_MISUSE_BKPT
;
2053 sqlite3_mutex_enter(db
->mutex
);
2055 pArg
= (FuncDestructor
*)sqlite3Malloc(sizeof(FuncDestructor
));
2057 sqlite3OomFault(db
);
2062 pArg
->xDestroy
= xDestroy
;
2063 pArg
->pUserData
= p
;
2065 rc
= sqlite3CreateFunc(db
, zFunc
, nArg
, enc
, p
,
2066 xSFunc
, xStep
, xFinal
, xValue
, xInverse
, pArg
2068 if( pArg
&& pArg
->nRef
==0 ){
2069 assert( rc
!=SQLITE_OK
|| (xStep
==0 && xFinal
==0) );
2075 rc
= sqlite3ApiExit(db
, rc
);
2076 sqlite3_mutex_leave(db
->mutex
);
2081 ** Create new user functions.
2083 int sqlite3_create_function(
2089 void (*xSFunc
)(sqlite3_context
*,int,sqlite3_value
**),
2090 void (*xStep
)(sqlite3_context
*,int,sqlite3_value
**),
2091 void (*xFinal
)(sqlite3_context
*)
2093 return createFunctionApi(db
, zFunc
, nArg
, enc
, p
, xSFunc
, xStep
,
2096 int sqlite3_create_function_v2(
2102 void (*xSFunc
)(sqlite3_context
*,int,sqlite3_value
**),
2103 void (*xStep
)(sqlite3_context
*,int,sqlite3_value
**),
2104 void (*xFinal
)(sqlite3_context
*),
2105 void (*xDestroy
)(void *)
2107 return createFunctionApi(db
, zFunc
, nArg
, enc
, p
, xSFunc
, xStep
,
2108 xFinal
, 0, 0, xDestroy
);
2110 int sqlite3_create_window_function(
2116 void (*xStep
)(sqlite3_context
*,int,sqlite3_value
**),
2117 void (*xFinal
)(sqlite3_context
*),
2118 void (*xValue
)(sqlite3_context
*),
2119 void (*xInverse
)(sqlite3_context
*,int,sqlite3_value
**),
2120 void (*xDestroy
)(void *)
2122 return createFunctionApi(db
, zFunc
, nArg
, enc
, p
, 0, xStep
,
2123 xFinal
, xValue
, xInverse
, xDestroy
);
2126 #ifndef SQLITE_OMIT_UTF16
2127 int sqlite3_create_function16(
2129 const void *zFunctionName
,
2133 void (*xSFunc
)(sqlite3_context
*,int,sqlite3_value
**),
2134 void (*xStep
)(sqlite3_context
*,int,sqlite3_value
**),
2135 void (*xFinal
)(sqlite3_context
*)
2140 #ifdef SQLITE_ENABLE_API_ARMOR
2141 if( !sqlite3SafetyCheckOk(db
) || zFunctionName
==0 ) return SQLITE_MISUSE_BKPT
;
2143 sqlite3_mutex_enter(db
->mutex
);
2144 assert( !db
->mallocFailed
);
2145 zFunc8
= sqlite3Utf16to8(db
, zFunctionName
, -1, SQLITE_UTF16NATIVE
);
2146 rc
= sqlite3CreateFunc(db
, zFunc8
, nArg
, eTextRep
, p
, xSFunc
,xStep
,xFinal
,0,0,0);
2147 sqlite3DbFree(db
, zFunc8
);
2148 rc
= sqlite3ApiExit(db
, rc
);
2149 sqlite3_mutex_leave(db
->mutex
);
2156 ** The following is the implementation of an SQL function that always
2157 ** fails with an error message stating that the function is used in the
2158 ** wrong context. The sqlite3_overload_function() API might construct
2159 ** SQL function that use this routine so that the functions will exist
2160 ** for name resolution but are actually overloaded by the xFindFunction
2161 ** method of virtual tables.
2163 static void sqlite3InvalidFunction(
2164 sqlite3_context
*context
, /* The function calling context */
2165 int NotUsed
, /* Number of arguments to the function */
2166 sqlite3_value
**NotUsed2
/* Value of each argument */
2168 const char *zName
= (const char*)sqlite3_user_data(context
);
2170 UNUSED_PARAMETER2(NotUsed
, NotUsed2
);
2171 zErr
= sqlite3_mprintf(
2172 "unable to use function %s in the requested context", zName
);
2173 sqlite3_result_error(context
, zErr
, -1);
2178 ** Declare that a function has been overloaded by a virtual table.
2180 ** If the function already exists as a regular global function, then
2181 ** this routine is a no-op. If the function does not exist, then create
2182 ** a new one that always throws a run-time error.
2184 ** When virtual tables intend to provide an overloaded function, they
2185 ** should call this routine to make sure the global function exists.
2186 ** A global function must exist in order for name resolution to work
2189 int sqlite3_overload_function(
2197 #ifdef SQLITE_ENABLE_API_ARMOR
2198 if( !sqlite3SafetyCheckOk(db
) || zName
==0 || nArg
<-2 ){
2199 return SQLITE_MISUSE_BKPT
;
2202 sqlite3_mutex_enter(db
->mutex
);
2203 rc
= sqlite3FindFunction(db
, zName
, nArg
, SQLITE_UTF8
, 0)!=0;
2204 sqlite3_mutex_leave(db
->mutex
);
2205 if( rc
) return SQLITE_OK
;
2206 zCopy
= sqlite3_mprintf("%s", zName
);
2207 if( zCopy
==0 ) return SQLITE_NOMEM
;
2208 return sqlite3_create_function_v2(db
, zName
, nArg
, SQLITE_UTF8
,
2209 zCopy
, sqlite3InvalidFunction
, 0, 0, sqlite3_free
);
2212 #ifndef SQLITE_OMIT_TRACE
2214 ** Register a trace function. The pArg from the previously registered trace
2217 ** A NULL trace function means that no tracing is executes. A non-NULL
2218 ** trace is a pointer to a function that is invoked at the start of each
2221 #ifndef SQLITE_OMIT_DEPRECATED
2222 void *sqlite3_trace(sqlite3
*db
, void(*xTrace
)(void*,const char*), void *pArg
){
2225 #ifdef SQLITE_ENABLE_API_ARMOR
2226 if( !sqlite3SafetyCheckOk(db
) ){
2227 (void)SQLITE_MISUSE_BKPT
;
2231 sqlite3_mutex_enter(db
->mutex
);
2232 pOld
= db
->pTraceArg
;
2233 db
->mTrace
= xTrace
? SQLITE_TRACE_LEGACY
: 0;
2234 db
->trace
.xLegacy
= xTrace
;
2235 db
->pTraceArg
= pArg
;
2236 sqlite3_mutex_leave(db
->mutex
);
2239 #endif /* SQLITE_OMIT_DEPRECATED */
2241 /* Register a trace callback using the version-2 interface.
2243 int sqlite3_trace_v2(
2244 sqlite3
*db
, /* Trace this connection */
2245 unsigned mTrace
, /* Mask of events to be traced */
2246 int(*xTrace
)(unsigned,void*,void*,void*), /* Callback to invoke */
2247 void *pArg
/* Context */
2249 #ifdef SQLITE_ENABLE_API_ARMOR
2250 if( !sqlite3SafetyCheckOk(db
) ){
2251 return SQLITE_MISUSE_BKPT
;
2254 sqlite3_mutex_enter(db
->mutex
);
2255 if( mTrace
==0 ) xTrace
= 0;
2256 if( xTrace
==0 ) mTrace
= 0;
2257 db
->mTrace
= mTrace
;
2258 db
->trace
.xV2
= xTrace
;
2259 db
->pTraceArg
= pArg
;
2260 sqlite3_mutex_leave(db
->mutex
);
2264 #ifndef SQLITE_OMIT_DEPRECATED
2266 ** Register a profile function. The pArg from the previously registered
2267 ** profile function is returned.
2269 ** A NULL profile function means that no profiling is executes. A non-NULL
2270 ** profile is a pointer to a function that is invoked at the conclusion of
2271 ** each SQL statement that is run.
2273 void *sqlite3_profile(
2275 void (*xProfile
)(void*,const char*,sqlite_uint64
),
2280 #ifdef SQLITE_ENABLE_API_ARMOR
2281 if( !sqlite3SafetyCheckOk(db
) ){
2282 (void)SQLITE_MISUSE_BKPT
;
2286 sqlite3_mutex_enter(db
->mutex
);
2287 pOld
= db
->pProfileArg
;
2288 db
->xProfile
= xProfile
;
2289 db
->pProfileArg
= pArg
;
2290 db
->mTrace
&= SQLITE_TRACE_NONLEGACY_MASK
;
2291 if( db
->xProfile
) db
->mTrace
|= SQLITE_TRACE_XPROFILE
;
2292 sqlite3_mutex_leave(db
->mutex
);
2295 #endif /* SQLITE_OMIT_DEPRECATED */
2296 #endif /* SQLITE_OMIT_TRACE */
2299 ** Register a function to be invoked when a transaction commits.
2300 ** If the invoked function returns non-zero, then the commit becomes a
2303 void *sqlite3_commit_hook(
2304 sqlite3
*db
, /* Attach the hook to this database */
2305 int (*xCallback
)(void*), /* Function to invoke on each commit */
2306 void *pArg
/* Argument to the function */
2310 #ifdef SQLITE_ENABLE_API_ARMOR
2311 if( !sqlite3SafetyCheckOk(db
) ){
2312 (void)SQLITE_MISUSE_BKPT
;
2316 sqlite3_mutex_enter(db
->mutex
);
2317 pOld
= db
->pCommitArg
;
2318 db
->xCommitCallback
= xCallback
;
2319 db
->pCommitArg
= pArg
;
2320 sqlite3_mutex_leave(db
->mutex
);
2325 ** Register a callback to be invoked each time a row is updated,
2326 ** inserted or deleted using this database connection.
2328 void *sqlite3_update_hook(
2329 sqlite3
*db
, /* Attach the hook to this database */
2330 void (*xCallback
)(void*,int,char const *,char const *,sqlite_int64
),
2331 void *pArg
/* Argument to the function */
2335 #ifdef SQLITE_ENABLE_API_ARMOR
2336 if( !sqlite3SafetyCheckOk(db
) ){
2337 (void)SQLITE_MISUSE_BKPT
;
2341 sqlite3_mutex_enter(db
->mutex
);
2342 pRet
= db
->pUpdateArg
;
2343 db
->xUpdateCallback
= xCallback
;
2344 db
->pUpdateArg
= pArg
;
2345 sqlite3_mutex_leave(db
->mutex
);
2350 ** Register a callback to be invoked each time a transaction is rolled
2351 ** back by this database connection.
2353 void *sqlite3_rollback_hook(
2354 sqlite3
*db
, /* Attach the hook to this database */
2355 void (*xCallback
)(void*), /* Callback function */
2356 void *pArg
/* Argument to the function */
2360 #ifdef SQLITE_ENABLE_API_ARMOR
2361 if( !sqlite3SafetyCheckOk(db
) ){
2362 (void)SQLITE_MISUSE_BKPT
;
2366 sqlite3_mutex_enter(db
->mutex
);
2367 pRet
= db
->pRollbackArg
;
2368 db
->xRollbackCallback
= xCallback
;
2369 db
->pRollbackArg
= pArg
;
2370 sqlite3_mutex_leave(db
->mutex
);
2374 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2376 ** Register a callback to be invoked each time a row is updated,
2377 ** inserted or deleted using this database connection.
2379 void *sqlite3_preupdate_hook(
2380 sqlite3
*db
, /* Attach the hook to this database */
2381 void(*xCallback
)( /* Callback function */
2382 void*,sqlite3
*,int,char const*,char const*,sqlite3_int64
,sqlite3_int64
),
2383 void *pArg
/* First callback argument */
2387 #ifdef SQLITE_ENABLE_API_ARMOR
2392 sqlite3_mutex_enter(db
->mutex
);
2393 pRet
= db
->pPreUpdateArg
;
2394 db
->xPreUpdateCallback
= xCallback
;
2395 db
->pPreUpdateArg
= pArg
;
2396 sqlite3_mutex_leave(db
->mutex
);
2399 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2402 ** Register a function to be invoked prior to each autovacuum that
2403 ** determines the number of pages to vacuum.
2405 int sqlite3_autovacuum_pages(
2406 sqlite3
*db
, /* Attach the hook to this database */
2407 unsigned int (*xCallback
)(void*,const char*,u32
,u32
,u32
),
2408 void *pArg
, /* Argument to the function */
2409 void (*xDestructor
)(void*) /* Destructor for pArg */
2411 #ifdef SQLITE_ENABLE_API_ARMOR
2412 if( !sqlite3SafetyCheckOk(db
) ){
2413 if( xDestructor
) xDestructor(pArg
);
2414 return SQLITE_MISUSE_BKPT
;
2417 sqlite3_mutex_enter(db
->mutex
);
2418 if( db
->xAutovacDestr
){
2419 db
->xAutovacDestr(db
->pAutovacPagesArg
);
2421 db
->xAutovacPages
= xCallback
;
2422 db
->pAutovacPagesArg
= pArg
;
2423 db
->xAutovacDestr
= xDestructor
;
2424 sqlite3_mutex_leave(db
->mutex
);
2429 #ifndef SQLITE_OMIT_WAL
2431 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
2432 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
2433 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
2434 ** wal_autocheckpoint()).
2436 int sqlite3WalDefaultHook(
2437 void *pClientData
, /* Argument */
2438 sqlite3
*db
, /* Connection */
2439 const char *zDb
, /* Database */
2440 int nFrame
/* Size of WAL */
2442 if( nFrame
>=SQLITE_PTR_TO_INT(pClientData
) ){
2443 sqlite3BeginBenignMalloc();
2444 sqlite3_wal_checkpoint(db
, zDb
);
2445 sqlite3EndBenignMalloc();
2449 #endif /* SQLITE_OMIT_WAL */
2452 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
2453 ** a database after committing a transaction if there are nFrame or
2454 ** more frames in the log file. Passing zero or a negative value as the
2455 ** nFrame parameter disables automatic checkpoints entirely.
2457 ** The callback registered by this function replaces any existing callback
2458 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
2459 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
2460 ** configured by this function.
2462 int sqlite3_wal_autocheckpoint(sqlite3
*db
, int nFrame
){
2463 #ifdef SQLITE_OMIT_WAL
2464 UNUSED_PARAMETER(db
);
2465 UNUSED_PARAMETER(nFrame
);
2467 #ifdef SQLITE_ENABLE_API_ARMOR
2468 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
2471 sqlite3_wal_hook(db
, sqlite3WalDefaultHook
, SQLITE_INT_TO_PTR(nFrame
));
2473 sqlite3_wal_hook(db
, 0, 0);
2480 ** Register a callback to be invoked each time a transaction is written
2481 ** into the write-ahead-log by this database connection.
2483 void *sqlite3_wal_hook(
2484 sqlite3
*db
, /* Attach the hook to this db handle */
2485 int(*xCallback
)(void *, sqlite3
*, const char*, int),
2486 void *pArg
/* First argument passed to xCallback() */
2488 #ifndef SQLITE_OMIT_WAL
2490 #ifdef SQLITE_ENABLE_API_ARMOR
2491 if( !sqlite3SafetyCheckOk(db
) ){
2492 (void)SQLITE_MISUSE_BKPT
;
2496 sqlite3_mutex_enter(db
->mutex
);
2498 db
->xWalCallback
= xCallback
;
2500 sqlite3_mutex_leave(db
->mutex
);
2508 ** Checkpoint database zDb.
2510 int sqlite3_wal_checkpoint_v2(
2511 sqlite3
*db
, /* Database handle */
2512 const char *zDb
, /* Name of attached database (or NULL) */
2513 int eMode
, /* SQLITE_CHECKPOINT_* value */
2514 int *pnLog
, /* OUT: Size of WAL log in frames */
2515 int *pnCkpt
/* OUT: Total number of frames checkpointed */
2517 #ifdef SQLITE_OMIT_WAL
2520 int rc
; /* Return code */
2521 int iDb
; /* Schema to checkpoint */
2523 #ifdef SQLITE_ENABLE_API_ARMOR
2524 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
2527 /* Initialize the output variables to -1 in case an error occurs. */
2528 if( pnLog
) *pnLog
= -1;
2529 if( pnCkpt
) *pnCkpt
= -1;
2531 assert( SQLITE_CHECKPOINT_PASSIVE
==0 );
2532 assert( SQLITE_CHECKPOINT_FULL
==1 );
2533 assert( SQLITE_CHECKPOINT_RESTART
==2 );
2534 assert( SQLITE_CHECKPOINT_TRUNCATE
==3 );
2535 if( eMode
<SQLITE_CHECKPOINT_PASSIVE
|| eMode
>SQLITE_CHECKPOINT_TRUNCATE
){
2536 /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
2538 return SQLITE_MISUSE_BKPT
;
2541 sqlite3_mutex_enter(db
->mutex
);
2542 if( zDb
&& zDb
[0] ){
2543 iDb
= sqlite3FindDbName(db
, zDb
);
2545 iDb
= SQLITE_MAX_DB
; /* This means process all schemas */
2549 sqlite3ErrorWithMsg(db
, SQLITE_ERROR
, "unknown database: %s", zDb
);
2551 db
->busyHandler
.nBusy
= 0;
2552 rc
= sqlite3Checkpoint(db
, iDb
, eMode
, pnLog
, pnCkpt
);
2553 sqlite3Error(db
, rc
);
2555 rc
= sqlite3ApiExit(db
, rc
);
2557 /* If there are no active statements, clear the interrupt flag at this
2559 if( db
->nVdbeActive
==0 ){
2560 AtomicStore(&db
->u1
.isInterrupted
, 0);
2563 sqlite3_mutex_leave(db
->mutex
);
2570 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
2571 ** to contains a zero-length string, all attached databases are
2574 int sqlite3_wal_checkpoint(sqlite3
*db
, const char *zDb
){
2575 /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
2576 ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
2577 return sqlite3_wal_checkpoint_v2(db
,zDb
,SQLITE_CHECKPOINT_PASSIVE
,0,0);
2580 #ifndef SQLITE_OMIT_WAL
2582 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
2583 ** not currently open in WAL mode.
2585 ** If a transaction is open on the database being checkpointed, this
2586 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
2587 ** an error occurs while running the checkpoint, an SQLite error code is
2588 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
2590 ** The mutex on database handle db should be held by the caller. The mutex
2591 ** associated with the specific b-tree being checkpointed is taken by
2592 ** this function while the checkpoint is running.
2594 ** If iDb is passed SQLITE_MAX_DB then all attached databases are
2595 ** checkpointed. If an error is encountered it is returned immediately -
2596 ** no attempt is made to checkpoint any remaining databases.
2598 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
2601 int sqlite3Checkpoint(sqlite3
*db
, int iDb
, int eMode
, int *pnLog
, int *pnCkpt
){
2602 int rc
= SQLITE_OK
; /* Return code */
2603 int i
; /* Used to iterate through attached dbs */
2604 int bBusy
= 0; /* True if SQLITE_BUSY has been encountered */
2606 assert( sqlite3_mutex_held(db
->mutex
) );
2607 assert( !pnLog
|| *pnLog
==-1 );
2608 assert( !pnCkpt
|| *pnCkpt
==-1 );
2609 testcase( iDb
==SQLITE_MAX_ATTACHED
); /* See forum post a006d86f72 */
2610 testcase( iDb
==SQLITE_MAX_DB
);
2612 for(i
=0; i
<db
->nDb
&& rc
==SQLITE_OK
; i
++){
2613 if( i
==iDb
|| iDb
==SQLITE_MAX_DB
){
2614 rc
= sqlite3BtreeCheckpoint(db
->aDb
[i
].pBt
, eMode
, pnLog
, pnCkpt
);
2617 if( rc
==SQLITE_BUSY
){
2624 return (rc
==SQLITE_OK
&& bBusy
) ? SQLITE_BUSY
: rc
;
2626 #endif /* SQLITE_OMIT_WAL */
2629 ** This function returns true if main-memory should be used instead of
2630 ** a temporary file for transient pager files and statement journals.
2631 ** The value returned depends on the value of db->temp_store (runtime
2632 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
2633 ** following table describes the relationship between these two values
2634 ** and this functions return value.
2636 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
2637 ** ----------------- -------------- ------------------------------
2638 ** 0 any file (return 0)
2639 ** 1 1 file (return 0)
2640 ** 1 2 memory (return 1)
2641 ** 1 0 file (return 0)
2642 ** 2 1 file (return 0)
2643 ** 2 2 memory (return 1)
2644 ** 2 0 memory (return 1)
2645 ** 3 any memory (return 1)
2647 int sqlite3TempInMemory(const sqlite3
*db
){
2648 #if SQLITE_TEMP_STORE==1
2649 return ( db
->temp_store
==2 );
2651 #if SQLITE_TEMP_STORE==2
2652 return ( db
->temp_store
!=1 );
2654 #if SQLITE_TEMP_STORE==3
2655 UNUSED_PARAMETER(db
);
2658 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
2659 UNUSED_PARAMETER(db
);
2665 ** Return UTF-8 encoded English language explanation of the most recent
2668 const char *sqlite3_errmsg(sqlite3
*db
){
2671 return sqlite3ErrStr(SQLITE_NOMEM_BKPT
);
2673 if( !sqlite3SafetyCheckSickOrOk(db
) ){
2674 return sqlite3ErrStr(SQLITE_MISUSE_BKPT
);
2676 sqlite3_mutex_enter(db
->mutex
);
2677 if( db
->mallocFailed
){
2678 z
= sqlite3ErrStr(SQLITE_NOMEM_BKPT
);
2680 testcase( db
->pErr
==0 );
2681 z
= db
->errCode
? (char*)sqlite3_value_text(db
->pErr
) : 0;
2682 assert( !db
->mallocFailed
);
2684 z
= sqlite3ErrStr(db
->errCode
);
2687 sqlite3_mutex_leave(db
->mutex
);
2692 ** Return the byte offset of the most recent error
2694 int sqlite3_error_offset(sqlite3
*db
){
2696 if( db
&& sqlite3SafetyCheckSickOrOk(db
) && db
->errCode
){
2697 sqlite3_mutex_enter(db
->mutex
);
2698 iOffset
= db
->errByteOffset
;
2699 sqlite3_mutex_leave(db
->mutex
);
2704 #ifndef SQLITE_OMIT_UTF16
2706 ** Return UTF-16 encoded English language explanation of the most recent
2709 const void *sqlite3_errmsg16(sqlite3
*db
){
2710 static const u16 outOfMem
[] = {
2711 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
2713 static const u16 misuse
[] = {
2714 'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
2715 'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
2716 'm', 'i', 's', 'u', 's', 'e', 0
2721 return (void *)outOfMem
;
2723 if( !sqlite3SafetyCheckSickOrOk(db
) ){
2724 return (void *)misuse
;
2726 sqlite3_mutex_enter(db
->mutex
);
2727 if( db
->mallocFailed
){
2728 z
= (void *)outOfMem
;
2730 z
= sqlite3_value_text16(db
->pErr
);
2732 sqlite3ErrorWithMsg(db
, db
->errCode
, sqlite3ErrStr(db
->errCode
));
2733 z
= sqlite3_value_text16(db
->pErr
);
2735 /* A malloc() may have failed within the call to sqlite3_value_text16()
2736 ** above. If this is the case, then the db->mallocFailed flag needs to
2737 ** be cleared before returning. Do this directly, instead of via
2738 ** sqlite3ApiExit(), to avoid setting the database handle error message.
2740 sqlite3OomClear(db
);
2742 sqlite3_mutex_leave(db
->mutex
);
2745 #endif /* SQLITE_OMIT_UTF16 */
2748 ** Return the most recent error code generated by an SQLite routine. If NULL is
2749 ** passed to this function, we assume a malloc() failed during sqlite3_open().
2751 int sqlite3_errcode(sqlite3
*db
){
2752 if( db
&& !sqlite3SafetyCheckSickOrOk(db
) ){
2753 return SQLITE_MISUSE_BKPT
;
2755 if( !db
|| db
->mallocFailed
){
2756 return SQLITE_NOMEM_BKPT
;
2758 return db
->errCode
& db
->errMask
;
2760 int sqlite3_extended_errcode(sqlite3
*db
){
2761 if( db
&& !sqlite3SafetyCheckSickOrOk(db
) ){
2762 return SQLITE_MISUSE_BKPT
;
2764 if( !db
|| db
->mallocFailed
){
2765 return SQLITE_NOMEM_BKPT
;
2769 int sqlite3_system_errno(sqlite3
*db
){
2770 return db
? db
->iSysErrno
: 0;
2774 ** Return a string that describes the kind of error specified in the
2775 ** argument. For now, this simply calls the internal sqlite3ErrStr()
2778 const char *sqlite3_errstr(int rc
){
2779 return sqlite3ErrStr(rc
);
2783 ** Create a new collating function for database "db". The name is zName
2784 ** and the encoding is enc.
2786 static int createCollation(
2791 int(*xCompare
)(void*,int,const void*,int,const void*),
2797 assert( sqlite3_mutex_held(db
->mutex
) );
2799 /* If SQLITE_UTF16 is specified as the encoding type, transform this
2800 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
2801 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
2804 testcase( enc2
==SQLITE_UTF16
);
2805 testcase( enc2
==SQLITE_UTF16_ALIGNED
);
2806 if( enc2
==SQLITE_UTF16
|| enc2
==SQLITE_UTF16_ALIGNED
){
2807 enc2
= SQLITE_UTF16NATIVE
;
2809 if( enc2
<SQLITE_UTF8
|| enc2
>SQLITE_UTF16BE
){
2810 return SQLITE_MISUSE_BKPT
;
2813 /* Check if this call is removing or replacing an existing collation
2814 ** sequence. If so, and there are active VMs, return busy. If there
2815 ** are no active VMs, invalidate any pre-compiled statements.
2817 pColl
= sqlite3FindCollSeq(db
, (u8
)enc2
, zName
, 0);
2818 if( pColl
&& pColl
->xCmp
){
2819 if( db
->nVdbeActive
){
2820 sqlite3ErrorWithMsg(db
, SQLITE_BUSY
,
2821 "unable to delete/modify collation sequence due to active statements");
2824 sqlite3ExpirePreparedStatements(db
, 0);
2826 /* If collation sequence pColl was created directly by a call to
2827 ** sqlite3_create_collation, and not generated by synthCollSeq(),
2828 ** then any copies made by synthCollSeq() need to be invalidated.
2829 ** Also, collation destructor - CollSeq.xDel() - function may need
2832 if( (pColl
->enc
& ~SQLITE_UTF16_ALIGNED
)==enc2
){
2833 CollSeq
*aColl
= sqlite3HashFind(&db
->aCollSeq
, zName
);
2836 CollSeq
*p
= &aColl
[j
];
2837 if( p
->enc
==pColl
->enc
){
2847 pColl
= sqlite3FindCollSeq(db
, (u8
)enc2
, zName
, 1);
2848 if( pColl
==0 ) return SQLITE_NOMEM_BKPT
;
2849 pColl
->xCmp
= xCompare
;
2850 pColl
->pUser
= pCtx
;
2852 pColl
->enc
= (u8
)(enc2
| (enc
& SQLITE_UTF16_ALIGNED
));
2853 sqlite3Error(db
, SQLITE_OK
);
2859 ** This array defines hard upper bounds on limit values. The
2860 ** initializer must be kept in sync with the SQLITE_LIMIT_*
2861 ** #defines in sqlite3.h.
2863 static const int aHardLimit
[] = {
2865 SQLITE_MAX_SQL_LENGTH
,
2867 SQLITE_MAX_EXPR_DEPTH
,
2868 SQLITE_MAX_COMPOUND_SELECT
,
2870 SQLITE_MAX_FUNCTION_ARG
,
2871 SQLITE_MAX_ATTACHED
,
2872 SQLITE_MAX_LIKE_PATTERN_LENGTH
,
2873 SQLITE_MAX_VARIABLE_NUMBER
, /* IMP: R-38091-32352 */
2874 SQLITE_MAX_TRIGGER_DEPTH
,
2875 SQLITE_MAX_WORKER_THREADS
,
2879 ** Make sure the hard limits are set to reasonable values
2881 #if SQLITE_MAX_LENGTH<100
2882 # error SQLITE_MAX_LENGTH must be at least 100
2884 #if SQLITE_MAX_SQL_LENGTH<100
2885 # error SQLITE_MAX_SQL_LENGTH must be at least 100
2887 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
2888 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
2890 #if SQLITE_MAX_COMPOUND_SELECT<2
2891 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
2893 #if SQLITE_MAX_VDBE_OP<40
2894 # error SQLITE_MAX_VDBE_OP must be at least 40
2896 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
2897 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
2899 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
2900 # error SQLITE_MAX_ATTACHED must be between 0 and 125
2902 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
2903 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
2905 #if SQLITE_MAX_COLUMN>32767
2906 # error SQLITE_MAX_COLUMN must not exceed 32767
2908 #if SQLITE_MAX_TRIGGER_DEPTH<1
2909 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
2911 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
2912 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
2917 ** Change the value of a limit. Report the old value.
2918 ** If an invalid limit index is supplied, report -1.
2919 ** Make no changes but still report the old value if the
2920 ** new limit is negative.
2922 ** A new lower limit does not shrink existing constructs.
2923 ** It merely prevents new constructs that exceed the limit
2926 int sqlite3_limit(sqlite3
*db
, int limitId
, int newLimit
){
2929 #ifdef SQLITE_ENABLE_API_ARMOR
2930 if( !sqlite3SafetyCheckOk(db
) ){
2931 (void)SQLITE_MISUSE_BKPT
;
2936 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
2937 ** there is a hard upper bound set at compile-time by a C preprocessor
2938 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
2941 assert( aHardLimit
[SQLITE_LIMIT_LENGTH
]==SQLITE_MAX_LENGTH
);
2942 assert( aHardLimit
[SQLITE_LIMIT_SQL_LENGTH
]==SQLITE_MAX_SQL_LENGTH
);
2943 assert( aHardLimit
[SQLITE_LIMIT_COLUMN
]==SQLITE_MAX_COLUMN
);
2944 assert( aHardLimit
[SQLITE_LIMIT_EXPR_DEPTH
]==SQLITE_MAX_EXPR_DEPTH
);
2945 assert( aHardLimit
[SQLITE_LIMIT_COMPOUND_SELECT
]==SQLITE_MAX_COMPOUND_SELECT
);
2946 assert( aHardLimit
[SQLITE_LIMIT_VDBE_OP
]==SQLITE_MAX_VDBE_OP
);
2947 assert( aHardLimit
[SQLITE_LIMIT_FUNCTION_ARG
]==SQLITE_MAX_FUNCTION_ARG
);
2948 assert( aHardLimit
[SQLITE_LIMIT_ATTACHED
]==SQLITE_MAX_ATTACHED
);
2949 assert( aHardLimit
[SQLITE_LIMIT_LIKE_PATTERN_LENGTH
]==
2950 SQLITE_MAX_LIKE_PATTERN_LENGTH
);
2951 assert( aHardLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
]==SQLITE_MAX_VARIABLE_NUMBER
);
2952 assert( aHardLimit
[SQLITE_LIMIT_TRIGGER_DEPTH
]==SQLITE_MAX_TRIGGER_DEPTH
);
2953 assert( aHardLimit
[SQLITE_LIMIT_WORKER_THREADS
]==SQLITE_MAX_WORKER_THREADS
);
2954 assert( SQLITE_LIMIT_WORKER_THREADS
==(SQLITE_N_LIMIT
-1) );
2957 if( limitId
<0 || limitId
>=SQLITE_N_LIMIT
){
2960 oldLimit
= db
->aLimit
[limitId
];
2961 if( newLimit
>=0 ){ /* IMP: R-52476-28732 */
2962 if( newLimit
>aHardLimit
[limitId
] ){
2963 newLimit
= aHardLimit
[limitId
]; /* IMP: R-51463-25634 */
2964 }else if( newLimit
<1 && limitId
==SQLITE_LIMIT_LENGTH
){
2967 db
->aLimit
[limitId
] = newLimit
;
2969 return oldLimit
; /* IMP: R-53341-35419 */
2973 ** This function is used to parse both URIs and non-URI filenames passed by the
2974 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
2975 ** URIs specified as part of ATTACH statements.
2977 ** The first argument to this function is the name of the VFS to use (or
2978 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
2979 ** query parameter. The second argument contains the URI (or non-URI filename)
2980 ** itself. When this function is called the *pFlags variable should contain
2981 ** the default flags to open the database handle with. The value stored in
2982 ** *pFlags may be updated before returning if the URI filename contains
2983 ** "cache=xxx" or "mode=xxx" query parameters.
2985 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
2986 ** the VFS that should be used to open the database file. *pzFile is set to
2987 ** point to a buffer containing the name of the file to open. The value
2988 ** stored in *pzFile is a database name acceptable to sqlite3_uri_parameter()
2989 ** and is in the same format as names created using sqlite3_create_filename().
2990 ** The caller must invoke sqlite3_free_filename() (not sqlite3_free()!) on
2991 ** the value returned in *pzFile to avoid a memory leak.
2993 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
2994 ** may be set to point to a buffer containing an English language error
2995 ** message. It is the responsibility of the caller to eventually release
2996 ** this buffer by calling sqlite3_free().
2998 int sqlite3ParseUri(
2999 const char *zDefaultVfs
, /* VFS to use if no "vfs=xxx" query option */
3000 const char *zUri
, /* Nul-terminated URI to parse */
3001 unsigned int *pFlags
, /* IN/OUT: SQLITE_OPEN_XXX flags */
3002 sqlite3_vfs
**ppVfs
, /* OUT: VFS to use */
3003 char **pzFile
, /* OUT: Filename component of URI */
3004 char **pzErrMsg
/* OUT: Error message (if rc!=SQLITE_OK) */
3007 unsigned int flags
= *pFlags
;
3008 const char *zVfs
= zDefaultVfs
;
3011 int nUri
= sqlite3Strlen30(zUri
);
3013 assert( *pzErrMsg
==0 );
3015 if( ((flags
& SQLITE_OPEN_URI
) /* IMP: R-48725-32206 */
3016 || AtomicLoad(&sqlite3GlobalConfig
.bOpenUri
)) /* IMP: R-51689-46548 */
3017 && nUri
>=5 && memcmp(zUri
, "file:", 5)==0 /* IMP: R-57884-37496 */
3020 int eState
; /* Parser state when parsing URI */
3021 int iIn
; /* Input character index */
3022 int iOut
= 0; /* Output character index */
3023 u64 nByte
= nUri
+8; /* Bytes of space to allocate */
3025 /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
3026 ** method that there may be extra parameters following the file-name. */
3027 flags
|= SQLITE_OPEN_URI
;
3029 for(iIn
=0; iIn
<nUri
; iIn
++) nByte
+= (zUri
[iIn
]=='&');
3030 zFile
= sqlite3_malloc64(nByte
);
3031 if( !zFile
) return SQLITE_NOMEM_BKPT
;
3033 memset(zFile
, 0, 4); /* 4-byte of 0x00 is the start of DB name marker */
3037 #ifdef SQLITE_ALLOW_URI_AUTHORITY
3038 if( strncmp(zUri
+5, "///", 3)==0 ){
3040 /* The following condition causes URIs with five leading / characters
3041 ** like file://///host/path to be converted into UNCs like //host/path.
3042 ** The correct URI for that UNC has only two or four leading / characters
3043 ** file://host/path or file:////host/path. But 5 leading slashes is a
3044 ** common error, we are told, so we handle it as a special case. */
3045 if( strncmp(zUri
+7, "///", 3)==0 ){ iIn
++; }
3046 }else if( strncmp(zUri
+5, "//localhost/", 12)==0 ){
3050 /* Discard the scheme and authority segments of the URI. */
3051 if( zUri
[5]=='/' && zUri
[6]=='/' ){
3053 while( zUri
[iIn
] && zUri
[iIn
]!='/' ) iIn
++;
3054 if( iIn
!=7 && (iIn
!=16 || memcmp("localhost", &zUri
[7], 9)) ){
3055 *pzErrMsg
= sqlite3_mprintf("invalid uri authority: %.*s",
3063 /* Copy the filename and any query parameters into the zFile buffer.
3064 ** Decode %HH escape codes along the way.
3066 ** Within this loop, variable eState may be set to 0, 1 or 2, depending
3067 ** on the parsing context. As follows:
3069 ** 0: Parsing file-name.
3070 ** 1: Parsing name section of a name=value query parameter.
3071 ** 2: Parsing value section of a name=value query parameter.
3074 while( (c
= zUri
[iIn
])!=0 && c
!='#' ){
3077 && sqlite3Isxdigit(zUri
[iIn
])
3078 && sqlite3Isxdigit(zUri
[iIn
+1])
3080 int octet
= (sqlite3HexToInt(zUri
[iIn
++]) << 4);
3081 octet
+= sqlite3HexToInt(zUri
[iIn
++]);
3083 assert( octet
>=0 && octet
<256 );
3085 #ifndef SQLITE_ENABLE_URI_00_ERROR
3086 /* This branch is taken when "%00" appears within the URI. In this
3087 ** case we ignore all text in the remainder of the path, name or
3088 ** value currently being parsed. So ignore the current character
3089 ** and skip to the next "?", "=" or "&", as appropriate. */
3090 while( (c
= zUri
[iIn
])!=0 && c
!='#'
3091 && (eState
!=0 || c
!='?')
3092 && (eState
!=1 || (c
!='=' && c
!='&'))
3093 && (eState
!=2 || c
!='&')
3099 /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
3100 *pzErrMsg
= sqlite3_mprintf("unexpected %%00 in uri");
3106 }else if( eState
==1 && (c
=='&' || c
=='=') ){
3107 if( zFile
[iOut
-1]==0 ){
3108 /* An empty option name. Ignore this option altogether. */
3109 while( zUri
[iIn
] && zUri
[iIn
]!='#' && zUri
[iIn
-1]!='&' ) iIn
++;
3113 zFile
[iOut
++] = '\0';
3118 }else if( (eState
==0 && c
=='?') || (eState
==2 && c
=='&') ){
3124 if( eState
==1 ) zFile
[iOut
++] = '\0';
3125 memset(zFile
+iOut
, 0, 4); /* end-of-options + empty journal filenames */
3127 /* Check if there were any options specified that should be interpreted
3128 ** here. Options that are interpreted here include "vfs" and those that
3129 ** correspond to flags that may be passed to the sqlite3_open_v2()
3131 zOpt
= &zFile
[sqlite3Strlen30(zFile
)+1];
3133 int nOpt
= sqlite3Strlen30(zOpt
);
3134 char *zVal
= &zOpt
[nOpt
+1];
3135 int nVal
= sqlite3Strlen30(zVal
);
3137 if( nOpt
==3 && memcmp("vfs", zOpt
, 3)==0 ){
3144 char *zModeType
= 0;
3148 if( nOpt
==5 && memcmp("cache", zOpt
, 5)==0 ){
3149 static struct OpenMode aCacheMode
[] = {
3150 { "shared", SQLITE_OPEN_SHAREDCACHE
},
3151 { "private", SQLITE_OPEN_PRIVATECACHE
},
3155 mask
= SQLITE_OPEN_SHAREDCACHE
|SQLITE_OPEN_PRIVATECACHE
;
3158 zModeType
= "cache";
3160 if( nOpt
==4 && memcmp("mode", zOpt
, 4)==0 ){
3161 static struct OpenMode aOpenMode
[] = {
3162 { "ro", SQLITE_OPEN_READONLY
},
3163 { "rw", SQLITE_OPEN_READWRITE
},
3164 { "rwc", SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
},
3165 { "memory", SQLITE_OPEN_MEMORY
},
3169 mask
= SQLITE_OPEN_READONLY
| SQLITE_OPEN_READWRITE
3170 | SQLITE_OPEN_CREATE
| SQLITE_OPEN_MEMORY
;
3172 limit
= mask
& flags
;
3173 zModeType
= "access";
3179 for(i
=0; aMode
[i
].z
; i
++){
3180 const char *z
= aMode
[i
].z
;
3181 if( nVal
==sqlite3Strlen30(z
) && 0==memcmp(zVal
, z
, nVal
) ){
3182 mode
= aMode
[i
].mode
;
3187 *pzErrMsg
= sqlite3_mprintf("no such %s mode: %s", zModeType
, zVal
);
3191 if( (mode
& ~SQLITE_OPEN_MEMORY
)>limit
){
3192 *pzErrMsg
= sqlite3_mprintf("%s mode not allowed: %s",
3197 flags
= (flags
& ~mask
) | mode
;
3201 zOpt
= &zVal
[nVal
+1];
3205 zFile
= sqlite3_malloc64(nUri
+8);
3206 if( !zFile
) return SQLITE_NOMEM_BKPT
;
3207 memset(zFile
, 0, 4);
3210 memcpy(zFile
, zUri
, nUri
);
3212 memset(zFile
+nUri
, 0, 4);
3213 flags
&= ~SQLITE_OPEN_URI
;
3216 *ppVfs
= sqlite3_vfs_find(zVfs
);
3218 *pzErrMsg
= sqlite3_mprintf("no such vfs: %s", zVfs
);
3222 if( rc
!=SQLITE_OK
){
3223 sqlite3_free_filename(zFile
);
3232 ** This routine does the core work of extracting URI parameters from a
3233 ** database filename for the sqlite3_uri_parameter() interface.
3235 static const char *uriParameter(const char *zFilename
, const char *zParam
){
3236 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
3237 while( ALWAYS(zFilename
!=0) && zFilename
[0] ){
3238 int x
= strcmp(zFilename
, zParam
);
3239 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
3240 if( x
==0 ) return zFilename
;
3241 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
3246 /* BEGIN SQLCIPHER */
3247 #if defined(SQLITE_HAS_CODEC)
3249 ** Process URI filename query parameters relevant to the SQLite Encryption
3250 ** Extension. Return true if any of the relevant query parameters are
3251 ** seen and return false if not.
3253 int sqlite3CodecQueryParameters(
3254 sqlite3
*db
, /* Database connection */
3255 const char *zDb
, /* Which schema is being created/attached */
3256 const char *zUri
/* URI filename */
3261 }else if( (zKey
= uriParameter(zUri
, "hexkey"))!=0 && zKey
[0] ){
3265 for(i
=0, iByte
=0; i
<sizeof(zDecoded
)*2 && sqlite3Isxdigit(zKey
[i
]); i
++){
3266 iByte
= (iByte
<<4) + sqlite3HexToInt(zKey
[i
]);
3267 if( (i
&1)!=0 ) zDecoded
[i
/2] = iByte
;
3269 sqlite3_key_v2(db
, zDb
, zDecoded
, i
/2);
3271 }else if( (zKey
= uriParameter(zUri
, "key"))!=0 ){
3272 sqlite3_key_v2(db
, zDb
, zKey
, sqlite3Strlen30(zKey
));
3274 }else if( (zKey
= uriParameter(zUri
, "textkey"))!=0 ){
3275 sqlite3_key_v2(db
, zDb
, zKey
, -1);
3286 ** This routine does the work of opening a database on behalf of
3287 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
3288 ** is UTF-8 encoded.
3290 static int openDatabase(
3291 const char *zFilename
, /* Database filename UTF-8 encoded */
3292 sqlite3
**ppDb
, /* OUT: Returned database handle */
3293 unsigned int flags
, /* Operational flags */
3294 const char *zVfs
/* Name of the VFS to use */
3296 sqlite3
*db
; /* Store allocated handle here */
3297 int rc
; /* Return code */
3298 int isThreadsafe
; /* True for threadsafe connections */
3299 char *zOpen
= 0; /* Filename argument to pass to BtreeOpen() */
3300 char *zErrMsg
= 0; /* Error message from sqlite3ParseUri() */
3301 int i
; /* Loop counter */
3303 #ifdef SQLITE_ENABLE_API_ARMOR
3304 if( ppDb
==0 ) return SQLITE_MISUSE_BKPT
;
3307 #ifndef SQLITE_OMIT_AUTOINIT
3308 rc
= sqlite3_initialize();
3312 if( sqlite3GlobalConfig
.bCoreMutex
==0 ){
3314 }else if( flags
& SQLITE_OPEN_NOMUTEX
){
3316 }else if( flags
& SQLITE_OPEN_FULLMUTEX
){
3319 isThreadsafe
= sqlite3GlobalConfig
.bFullMutex
;
3322 if( flags
& SQLITE_OPEN_PRIVATECACHE
){
3323 flags
&= ~SQLITE_OPEN_SHAREDCACHE
;
3324 }else if( sqlite3GlobalConfig
.sharedCacheEnabled
){
3325 flags
|= SQLITE_OPEN_SHAREDCACHE
;
3328 /* Remove harmful bits from the flags parameter
3330 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
3331 ** dealt with in the previous code block. Besides these, the only
3332 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
3333 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
3334 ** SQLITE_OPEN_PRIVATECACHE, SQLITE_OPEN_EXRESCODE, and some reserved
3335 ** bits. Silently mask off all other flags.
3337 flags
&= ~( SQLITE_OPEN_DELETEONCLOSE
|
3338 SQLITE_OPEN_EXCLUSIVE
|
3339 SQLITE_OPEN_MAIN_DB
|
3340 SQLITE_OPEN_TEMP_DB
|
3341 SQLITE_OPEN_TRANSIENT_DB
|
3342 SQLITE_OPEN_MAIN_JOURNAL
|
3343 SQLITE_OPEN_TEMP_JOURNAL
|
3344 SQLITE_OPEN_SUBJOURNAL
|
3345 SQLITE_OPEN_SUPER_JOURNAL
|
3346 SQLITE_OPEN_NOMUTEX
|
3347 SQLITE_OPEN_FULLMUTEX
|
3351 /* Allocate the sqlite data structure */
3352 db
= sqlite3MallocZero( sizeof(sqlite3
) );
3353 if( db
==0 ) goto opendb_out
;
3355 #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
3356 || sqlite3GlobalConfig
.bCoreMutex
3359 db
->mutex
= sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE
);
3365 if( isThreadsafe
==0 ){
3366 sqlite3MutexWarnOnContention(db
->mutex
);
3369 sqlite3_mutex_enter(db
->mutex
);
3370 db
->errMask
= (flags
& SQLITE_OPEN_EXRESCODE
)!=0 ? 0xffffffff : 0xff;
3372 db
->eOpenState
= SQLITE_STATE_BUSY
;
3373 db
->aDb
= db
->aDbStatic
;
3374 db
->lookaside
.bDisable
= 1;
3375 db
->lookaside
.sz
= 0;
3377 assert( sizeof(db
->aLimit
)==sizeof(aHardLimit
) );
3378 memcpy(db
->aLimit
, aHardLimit
, sizeof(db
->aLimit
));
3379 db
->aLimit
[SQLITE_LIMIT_WORKER_THREADS
] = SQLITE_DEFAULT_WORKER_THREADS
;
3381 db
->nextAutovac
= -1;
3382 db
->szMmap
= sqlite3GlobalConfig
.szMmap
;
3383 db
->nextPagesize
= 0;
3384 db
->init
.azInit
= sqlite3StdType
; /* Any array of string ptrs will do */
3385 #ifdef SQLITE_ENABLE_SORTER_MMAP
3386 /* Beginning with version 3.37.0, using the VFS xFetch() API to memory-map
3387 ** the temporary files used to do external sorts (see code in vdbesort.c)
3388 ** is disabled. It can still be used either by defining
3389 ** SQLITE_ENABLE_SORTER_MMAP at compile time or by using the
3390 ** SQLITE_TESTCTRL_SORTER_MMAP test-control at runtime. */
3391 db
->nMaxSorterMmap
= 0x7FFFFFFF;
3393 db
->flags
|= SQLITE_ShortColNames
3394 | SQLITE_EnableTrigger
3397 #if !defined(SQLITE_TRUSTED_SCHEMA) || SQLITE_TRUSTED_SCHEMA+0!=0
3398 | SQLITE_TrustedSchema
3400 /* The SQLITE_DQS compile-time option determines the default settings
3401 ** for SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML.
3403 ** SQLITE_DQS SQLITE_DBCONFIG_DQS_DDL SQLITE_DBCONFIG_DQS_DML
3404 ** ---------- ----------------------- -----------------------
3411 ** Legacy behavior is 3 (double-quoted string literals are allowed anywhere)
3412 ** and so that is the default. But developers are encouraged to use
3413 ** -DSQLITE_DQS=0 (best) or -DSQLITE_DQS=1 (second choice) if possible.
3415 #if !defined(SQLITE_DQS)
3416 # define SQLITE_DQS 3
3418 #if (SQLITE_DQS&1)==1
3421 #if (SQLITE_DQS&2)==2
3425 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
3428 #if SQLITE_DEFAULT_CKPTFULLFSYNC
3429 | SQLITE_CkptFullFSync
3431 #if SQLITE_DEFAULT_FILE_FORMAT<4
3432 | SQLITE_LegacyFileFmt
3434 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
3435 | SQLITE_LoadExtension
3437 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
3438 | SQLITE_RecTriggers
3440 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
3441 | SQLITE_ForeignKeys
3443 #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
3444 | SQLITE_ReverseOrder
3446 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
3449 #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
3450 | SQLITE_Fts3Tokenizer
3452 #if defined(SQLITE_ENABLE_QPSG)
3455 #if defined(SQLITE_DEFAULT_DEFENSIVE)
3458 #if defined(SQLITE_DEFAULT_LEGACY_ALTER_TABLE)
3459 | SQLITE_LegacyAlter
3461 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
3462 | SQLITE_StmtScanStatus
3465 sqlite3HashInit(&db
->aCollSeq
);
3466 #ifndef SQLITE_OMIT_VIRTUALTABLE
3467 sqlite3HashInit(&db
->aModule
);
3470 /* Add the default collation sequence BINARY. BINARY works for both UTF-8
3471 ** and UTF-16, so add a version for each to avoid any unnecessary
3472 ** conversions. The only error that can occur here is a malloc() failure.
3474 ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
3477 createCollation(db
, sqlite3StrBINARY
, SQLITE_UTF8
, 0, binCollFunc
, 0);
3478 createCollation(db
, sqlite3StrBINARY
, SQLITE_UTF16BE
, 0, binCollFunc
, 0);
3479 createCollation(db
, sqlite3StrBINARY
, SQLITE_UTF16LE
, 0, binCollFunc
, 0);
3480 createCollation(db
, "NOCASE", SQLITE_UTF8
, 0, nocaseCollatingFunc
, 0);
3481 createCollation(db
, "RTRIM", SQLITE_UTF8
, 0, rtrimCollFunc
, 0);
3482 if( db
->mallocFailed
){
3486 #if SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL)
3487 /* Process magic filenames ":localStorage:" and ":sessionStorage:" */
3488 if( zFilename
&& zFilename
[0]==':' ){
3489 if( strcmp(zFilename
, ":localStorage:")==0 ){
3490 zFilename
= "file:local?vfs=kvvfs";
3491 flags
|= SQLITE_OPEN_URI
;
3492 }else if( strcmp(zFilename
, ":sessionStorage:")==0 ){
3493 zFilename
= "file:session?vfs=kvvfs";
3494 flags
|= SQLITE_OPEN_URI
;
3497 #endif /* SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL) */
3499 /* Parse the filename/URI argument
3501 ** Only allow sensible combinations of bits in the flags argument.
3502 ** Throw an error if any non-sense combination is used. If we
3503 ** do not block illegal combinations here, it could trigger
3504 ** assert() statements in deeper layers. Sensible combinations
3507 ** 1: SQLITE_OPEN_READONLY
3508 ** 2: SQLITE_OPEN_READWRITE
3509 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
3511 db
->openFlags
= flags
;
3512 assert( SQLITE_OPEN_READONLY
== 0x01 );
3513 assert( SQLITE_OPEN_READWRITE
== 0x02 );
3514 assert( SQLITE_OPEN_CREATE
== 0x04 );
3515 testcase( (1<<(flags
&7))==0x02 ); /* READONLY */
3516 testcase( (1<<(flags
&7))==0x04 ); /* READWRITE */
3517 testcase( (1<<(flags
&7))==0x40 ); /* READWRITE | CREATE */
3518 if( ((1<<(flags
&7)) & 0x46)==0 ){
3519 rc
= SQLITE_MISUSE_BKPT
; /* IMP: R-18321-05872 */
3521 rc
= sqlite3ParseUri(zVfs
, zFilename
, &flags
, &db
->pVfs
, &zOpen
, &zErrMsg
);
3523 if( rc
!=SQLITE_OK
){
3524 if( rc
==SQLITE_NOMEM
) sqlite3OomFault(db
);
3525 sqlite3ErrorWithMsg(db
, rc
, zErrMsg
? "%s" : 0, zErrMsg
);
3526 sqlite3_free(zErrMsg
);
3529 assert( db
->pVfs
!=0 );
3530 #if SQLITE_OS_KV || defined(SQLITE_OS_KV_OPTIONAL)
3531 if( sqlite3_stricmp(db
->pVfs
->zName
, "kvvfs")==0 ){
3536 /* Open the backend database driver */
3537 rc
= sqlite3BtreeOpen(db
->pVfs
, zOpen
, db
, &db
->aDb
[0].pBt
, 0,
3538 flags
| SQLITE_OPEN_MAIN_DB
);
3539 if( rc
!=SQLITE_OK
){
3540 if( rc
==SQLITE_IOERR_NOMEM
){
3541 rc
= SQLITE_NOMEM_BKPT
;
3543 sqlite3Error(db
, rc
);
3546 sqlite3BtreeEnter(db
->aDb
[0].pBt
);
3547 db
->aDb
[0].pSchema
= sqlite3SchemaGet(db
, db
->aDb
[0].pBt
);
3548 if( !db
->mallocFailed
){
3549 sqlite3SetTextEncoding(db
, SCHEMA_ENC(db
));
3551 sqlite3BtreeLeave(db
->aDb
[0].pBt
);
3552 db
->aDb
[1].pSchema
= sqlite3SchemaGet(db
, 0);
3554 /* The default safety_level for the main database is FULL; for the temp
3555 ** database it is OFF. This matches the pager layer defaults.
3557 db
->aDb
[0].zDbSName
= "main";
3558 db
->aDb
[0].safety_level
= SQLITE_DEFAULT_SYNCHRONOUS
+1;
3559 db
->aDb
[1].zDbSName
= "temp";
3560 db
->aDb
[1].safety_level
= PAGER_SYNCHRONOUS_OFF
;
3562 db
->eOpenState
= SQLITE_STATE_OPEN
;
3563 if( db
->mallocFailed
){
3567 /* Register all built-in functions, but do not attempt to read the
3568 ** database schema yet. This is delayed until the first time the database
3571 sqlite3Error(db
, SQLITE_OK
);
3572 sqlite3RegisterPerConnectionBuiltinFunctions(db
);
3573 rc
= sqlite3_errcode(db
);
3576 /* Load compiled-in extensions */
3577 for(i
=0; rc
==SQLITE_OK
&& i
<ArraySize(sqlite3BuiltinExtensions
); i
++){
3578 rc
= sqlite3BuiltinExtensions
[i
](db
);
3581 /* Load automatic extensions - extensions that have been registered
3582 ** using the sqlite3_automatic_extension() API.
3584 if( rc
==SQLITE_OK
){
3585 sqlite3AutoLoadExtensions(db
);
3586 rc
= sqlite3_errcode(db
);
3587 if( rc
!=SQLITE_OK
){
3592 #ifdef SQLCIPHER_EXT
3593 if( !db
->mallocFailed
&& rc
==SQLITE_OK
){
3594 extern int sqlcipherVtabInit(sqlite3
*);
3595 rc
= sqlcipherVtabInit(db
);
3599 #ifdef SQLITE_ENABLE_INTERNAL_FUNCTIONS
3600 /* Testing use only!!! The -DSQLITE_ENABLE_INTERNAL_FUNCTIONS=1 compile-time
3601 ** option gives access to internal functions by default.
3602 ** Testing use only!!! */
3603 db
->mDbFlags
|= DBFLAG_InternalFunc
;
3606 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
3607 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
3608 ** mode. Doing nothing at all also makes NORMAL the default.
3610 #ifdef SQLITE_DEFAULT_LOCKING_MODE
3611 db
->dfltLockMode
= SQLITE_DEFAULT_LOCKING_MODE
;
3612 sqlite3PagerLockingMode(sqlite3BtreePager(db
->aDb
[0].pBt
),
3613 SQLITE_DEFAULT_LOCKING_MODE
);
3616 if( rc
) sqlite3Error(db
, rc
);
3618 /* Enable the lookaside-malloc subsystem */
3619 setupLookaside(db
, 0, sqlite3GlobalConfig
.szLookaside
,
3620 sqlite3GlobalConfig
.nLookaside
);
3622 sqlite3_wal_autocheckpoint(db
, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
);
3626 assert( db
->mutex
!=0 || isThreadsafe
==0
3627 || sqlite3GlobalConfig
.bFullMutex
==0 );
3628 sqlite3_mutex_leave(db
->mutex
);
3630 rc
= sqlite3_errcode(db
);
3631 assert( db
!=0 || (rc
&0xff)==SQLITE_NOMEM
);
3632 if( (rc
&0xff)==SQLITE_NOMEM
){
3635 }else if( rc
!=SQLITE_OK
){
3636 db
->eOpenState
= SQLITE_STATE_SICK
;
3639 #ifdef SQLITE_ENABLE_SQLLOG
3640 if( sqlite3GlobalConfig
.xSqllog
){
3641 /* Opening a db handle. Fourth parameter is passed 0. */
3642 void *pArg
= sqlite3GlobalConfig
.pSqllogArg
;
3643 sqlite3GlobalConfig
.xSqllog(pArg
, db
, zFilename
, 0);
3646 /* BEGIN SQLCIPHER */
3647 #if defined(SQLITE_HAS_CODEC)
3648 if( rc
==SQLITE_OK
) sqlite3CodecQueryParameters(db
, 0, zOpen
);
3651 sqlite3_free_filename(zOpen
);
3657 ** Open a new database handle.
3660 const char *zFilename
,
3663 return openDatabase(zFilename
, ppDb
,
3664 SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
, 0);
3666 int sqlite3_open_v2(
3667 const char *filename
, /* Database filename (UTF-8) */
3668 sqlite3
**ppDb
, /* OUT: SQLite db handle */
3669 int flags
, /* Flags */
3670 const char *zVfs
/* Name of VFS module to use */
3672 return openDatabase(filename
, ppDb
, (unsigned int)flags
, zVfs
);
3675 #ifndef SQLITE_OMIT_UTF16
3677 ** Open a new database handle.
3680 const void *zFilename
,
3683 char const *zFilename8
; /* zFilename encoded in UTF-8 instead of UTF-16 */
3684 sqlite3_value
*pVal
;
3687 #ifdef SQLITE_ENABLE_API_ARMOR
3688 if( ppDb
==0 ) return SQLITE_MISUSE_BKPT
;
3691 #ifndef SQLITE_OMIT_AUTOINIT
3692 rc
= sqlite3_initialize();
3695 if( zFilename
==0 ) zFilename
= "\000\000";
3696 pVal
= sqlite3ValueNew(0);
3697 sqlite3ValueSetStr(pVal
, -1, zFilename
, SQLITE_UTF16NATIVE
, SQLITE_STATIC
);
3698 zFilename8
= sqlite3ValueText(pVal
, SQLITE_UTF8
);
3700 rc
= openDatabase(zFilename8
, ppDb
,
3701 SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
, 0);
3702 assert( *ppDb
|| rc
==SQLITE_NOMEM
);
3703 if( rc
==SQLITE_OK
&& !DbHasProperty(*ppDb
, 0, DB_SchemaLoaded
) ){
3704 SCHEMA_ENC(*ppDb
) = ENC(*ppDb
) = SQLITE_UTF16NATIVE
;
3707 rc
= SQLITE_NOMEM_BKPT
;
3709 sqlite3ValueFree(pVal
);
3713 #endif /* SQLITE_OMIT_UTF16 */
3716 ** Register a new collation sequence with the database handle db.
3718 int sqlite3_create_collation(
3723 int(*xCompare
)(void*,int,const void*,int,const void*)
3725 return sqlite3_create_collation_v2(db
, zName
, enc
, pCtx
, xCompare
, 0);
3729 ** Register a new collation sequence with the database handle db.
3731 int sqlite3_create_collation_v2(
3736 int(*xCompare
)(void*,int,const void*,int,const void*),
3741 #ifdef SQLITE_ENABLE_API_ARMOR
3742 if( !sqlite3SafetyCheckOk(db
) || zName
==0 ) return SQLITE_MISUSE_BKPT
;
3744 sqlite3_mutex_enter(db
->mutex
);
3745 assert( !db
->mallocFailed
);
3746 rc
= createCollation(db
, zName
, (u8
)enc
, pCtx
, xCompare
, xDel
);
3747 rc
= sqlite3ApiExit(db
, rc
);
3748 sqlite3_mutex_leave(db
->mutex
);
3752 #ifndef SQLITE_OMIT_UTF16
3754 ** Register a new collation sequence with the database handle db.
3756 int sqlite3_create_collation16(
3761 int(*xCompare
)(void*,int,const void*,int,const void*)
3766 #ifdef SQLITE_ENABLE_API_ARMOR
3767 if( !sqlite3SafetyCheckOk(db
) || zName
==0 ) return SQLITE_MISUSE_BKPT
;
3769 sqlite3_mutex_enter(db
->mutex
);
3770 assert( !db
->mallocFailed
);
3771 zName8
= sqlite3Utf16to8(db
, zName
, -1, SQLITE_UTF16NATIVE
);
3773 rc
= createCollation(db
, zName8
, (u8
)enc
, pCtx
, xCompare
, 0);
3774 sqlite3DbFree(db
, zName8
);
3776 rc
= sqlite3ApiExit(db
, rc
);
3777 sqlite3_mutex_leave(db
->mutex
);
3780 #endif /* SQLITE_OMIT_UTF16 */
3783 ** Register a collation sequence factory callback with the database handle
3784 ** db. Replace any previously installed collation sequence factory.
3786 int sqlite3_collation_needed(
3788 void *pCollNeededArg
,
3789 void(*xCollNeeded
)(void*,sqlite3
*,int eTextRep
,const char*)
3791 #ifdef SQLITE_ENABLE_API_ARMOR
3792 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
3794 sqlite3_mutex_enter(db
->mutex
);
3795 db
->xCollNeeded
= xCollNeeded
;
3796 db
->xCollNeeded16
= 0;
3797 db
->pCollNeededArg
= pCollNeededArg
;
3798 sqlite3_mutex_leave(db
->mutex
);
3802 #ifndef SQLITE_OMIT_UTF16
3804 ** Register a collation sequence factory callback with the database handle
3805 ** db. Replace any previously installed collation sequence factory.
3807 int sqlite3_collation_needed16(
3809 void *pCollNeededArg
,
3810 void(*xCollNeeded16
)(void*,sqlite3
*,int eTextRep
,const void*)
3812 #ifdef SQLITE_ENABLE_API_ARMOR
3813 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
3815 sqlite3_mutex_enter(db
->mutex
);
3816 db
->xCollNeeded
= 0;
3817 db
->xCollNeeded16
= xCollNeeded16
;
3818 db
->pCollNeededArg
= pCollNeededArg
;
3819 sqlite3_mutex_leave(db
->mutex
);
3822 #endif /* SQLITE_OMIT_UTF16 */
3825 ** Find existing client data.
3827 void *sqlite3_get_clientdata(sqlite3
*db
, const char *zName
){
3829 sqlite3_mutex_enter(db
->mutex
);
3830 for(p
=db
->pDbData
; p
; p
=p
->pNext
){
3831 if( strcmp(p
->zName
, zName
)==0 ){
3832 void *pResult
= p
->pData
;
3833 sqlite3_mutex_leave(db
->mutex
);
3837 sqlite3_mutex_leave(db
->mutex
);
3842 ** Add new client data to a database connection.
3844 int sqlite3_set_clientdata(
3845 sqlite3
*db
, /* Attach client data to this connection */
3846 const char *zName
, /* Name of the client data */
3847 void *pData
, /* The client data itself */
3848 void (*xDestructor
)(void*) /* Destructor */
3850 DbClientData
*p
, **pp
;
3851 sqlite3_mutex_enter(db
->mutex
);
3853 for(p
=db
->pDbData
; p
&& strcmp(p
->zName
,zName
); p
=p
->pNext
){
3857 assert( p
->pData
!=0 );
3858 if( p
->xDestructor
) p
->xDestructor(p
->pData
);
3862 sqlite3_mutex_leave(db
->mutex
);
3865 }else if( pData
==0 ){
3866 sqlite3_mutex_leave(db
->mutex
);
3869 size_t n
= strlen(zName
);
3870 p
= sqlite3_malloc64( sizeof(DbClientData
)+n
+1 );
3872 if( xDestructor
) xDestructor(pData
);
3873 sqlite3_mutex_leave(db
->mutex
);
3874 return SQLITE_NOMEM
;
3876 memcpy(p
->zName
, zName
, n
+1);
3877 p
->pNext
= db
->pDbData
;
3881 p
->xDestructor
= xDestructor
;
3882 sqlite3_mutex_leave(db
->mutex
);
3887 #ifndef SQLITE_OMIT_DEPRECATED
3889 ** This function is now an anachronism. It used to be used to recover from a
3890 ** malloc() failure, but SQLite now does this automatically.
3892 int sqlite3_global_recover(void){
3898 ** Test to see whether or not the database connection is in autocommit
3899 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
3900 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
3901 ** by the next COMMIT or ROLLBACK.
3903 int sqlite3_get_autocommit(sqlite3
*db
){
3904 #ifdef SQLITE_ENABLE_API_ARMOR
3905 if( !sqlite3SafetyCheckOk(db
) ){
3906 (void)SQLITE_MISUSE_BKPT
;
3910 return db
->autoCommit
;
3914 ** The following routines are substitutes for constants SQLITE_CORRUPT,
3915 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
3916 ** constants. They serve two purposes:
3918 ** 1. Serve as a convenient place to set a breakpoint in a debugger
3919 ** to detect when version error conditions occurs.
3921 ** 2. Invoke sqlite3_log() to provide the source code location where
3922 ** a low-level error is first detected.
3924 int sqlite3ReportError(int iErr
, int lineno
, const char *zType
){
3925 sqlite3_log(iErr
, "%s at line %d of [%.10s]",
3926 zType
, lineno
, 20+sqlite3_sourceid());
3929 int sqlite3CorruptError(int lineno
){
3930 testcase( sqlite3GlobalConfig
.xLog
!=0 );
3931 return sqlite3ReportError(SQLITE_CORRUPT
, lineno
, "database corruption");
3933 int sqlite3MisuseError(int lineno
){
3934 testcase( sqlite3GlobalConfig
.xLog
!=0 );
3935 return sqlite3ReportError(SQLITE_MISUSE
, lineno
, "misuse");
3937 int sqlite3CantopenError(int lineno
){
3938 testcase( sqlite3GlobalConfig
.xLog
!=0 );
3939 return sqlite3ReportError(SQLITE_CANTOPEN
, lineno
, "cannot open file");
3941 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
3942 int sqlite3CorruptPgnoError(int lineno
, Pgno pgno
){
3944 sqlite3_snprintf(sizeof(zMsg
), zMsg
, "database corruption page %d", pgno
);
3945 testcase( sqlite3GlobalConfig
.xLog
!=0 );
3946 return sqlite3ReportError(SQLITE_CORRUPT
, lineno
, zMsg
);
3950 int sqlite3NomemError(int lineno
){
3951 testcase( sqlite3GlobalConfig
.xLog
!=0 );
3952 return sqlite3ReportError(SQLITE_NOMEM
, lineno
, "OOM");
3954 int sqlite3IoerrnomemError(int lineno
){
3955 testcase( sqlite3GlobalConfig
.xLog
!=0 );
3956 return sqlite3ReportError(SQLITE_IOERR_NOMEM
, lineno
, "I/O OOM error");
3960 #ifndef SQLITE_OMIT_DEPRECATED
3962 ** This is a convenience routine that makes sure that all thread-specific
3963 ** data for this thread has been deallocated.
3965 ** SQLite no longer uses thread-specific data so this routine is now a
3966 ** no-op. It is retained for historical compatibility.
3968 void sqlite3_thread_cleanup(void){
3973 ** Return meta information about a specific column of a database table.
3974 ** See comment in sqlite3.h (sqlite.h.in) for details.
3976 int sqlite3_table_column_metadata(
3977 sqlite3
*db
, /* Connection handle */
3978 const char *zDbName
, /* Database name or NULL */
3979 const char *zTableName
, /* Table name */
3980 const char *zColumnName
, /* Column name */
3981 char const **pzDataType
, /* OUTPUT: Declared data type */
3982 char const **pzCollSeq
, /* OUTPUT: Collation sequence name */
3983 int *pNotNull
, /* OUTPUT: True if NOT NULL constraint exists */
3984 int *pPrimaryKey
, /* OUTPUT: True if column part of PK */
3985 int *pAutoinc
/* OUTPUT: True if column is auto-increment */
3992 char const *zDataType
= 0;
3993 char const *zCollSeq
= 0;
3999 #ifdef SQLITE_ENABLE_API_ARMOR
4000 if( !sqlite3SafetyCheckOk(db
) || zTableName
==0 ){
4001 return SQLITE_MISUSE_BKPT
;
4005 /* Ensure the database schema has been loaded */
4006 sqlite3_mutex_enter(db
->mutex
);
4007 sqlite3BtreeEnterAll(db
);
4008 rc
= sqlite3Init(db
, &zErrMsg
);
4009 if( SQLITE_OK
!=rc
){
4013 /* Locate the table in question */
4014 pTab
= sqlite3FindTable(db
, zTableName
, zDbName
);
4015 if( !pTab
|| IsView(pTab
) ){
4020 /* Find the column for which info is requested */
4021 if( zColumnName
==0 ){
4022 /* Query for existence of table only */
4024 for(iCol
=0; iCol
<pTab
->nCol
; iCol
++){
4025 pCol
= &pTab
->aCol
[iCol
];
4026 if( 0==sqlite3StrICmp(pCol
->zCnName
, zColumnName
) ){
4030 if( iCol
==pTab
->nCol
){
4031 if( HasRowid(pTab
) && sqlite3IsRowid(zColumnName
) ){
4033 pCol
= iCol
>=0 ? &pTab
->aCol
[iCol
] : 0;
4041 /* The following block stores the meta information that will be returned
4042 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
4043 ** and autoinc. At this point there are two possibilities:
4045 ** 1. The specified column name was rowid", "oid" or "_rowid_"
4046 ** and there is no explicitly declared IPK column.
4048 ** 2. The table is not a view and the column name identified an
4049 ** explicitly declared column. Copy meta information from *pCol.
4052 zDataType
= sqlite3ColumnType(pCol
,0);
4053 zCollSeq
= sqlite3ColumnColl(pCol
);
4054 notnull
= pCol
->notNull
!=0;
4055 primarykey
= (pCol
->colFlags
& COLFLAG_PRIMKEY
)!=0;
4056 autoinc
= pTab
->iPKey
==iCol
&& (pTab
->tabFlags
& TF_Autoincrement
)!=0;
4058 zDataType
= "INTEGER";
4062 zCollSeq
= sqlite3StrBINARY
;
4066 sqlite3BtreeLeaveAll(db
);
4068 /* Whether the function call succeeded or failed, set the output parameters
4069 ** to whatever their local counterparts contain. If an error did occur,
4070 ** this has the effect of zeroing all output parameters.
4072 if( pzDataType
) *pzDataType
= zDataType
;
4073 if( pzCollSeq
) *pzCollSeq
= zCollSeq
;
4074 if( pNotNull
) *pNotNull
= notnull
;
4075 if( pPrimaryKey
) *pPrimaryKey
= primarykey
;
4076 if( pAutoinc
) *pAutoinc
= autoinc
;
4078 if( SQLITE_OK
==rc
&& !pTab
){
4079 sqlite3DbFree(db
, zErrMsg
);
4080 zErrMsg
= sqlite3MPrintf(db
, "no such table column: %s.%s", zTableName
,
4084 sqlite3ErrorWithMsg(db
, rc
, (zErrMsg
?"%s":0), zErrMsg
);
4085 sqlite3DbFree(db
, zErrMsg
);
4086 rc
= sqlite3ApiExit(db
, rc
);
4087 sqlite3_mutex_leave(db
->mutex
);
4092 ** Sleep for a little while. Return the amount of time slept.
4094 int sqlite3_sleep(int ms
){
4097 pVfs
= sqlite3_vfs_find(0);
4098 if( pVfs
==0 ) return 0;
4100 /* This function works in milliseconds, but the underlying OsSleep()
4101 ** API uses microseconds. Hence the 1000's.
4103 rc
= (sqlite3OsSleep(pVfs
, ms
<0 ? 0 : 1000*ms
)/1000);
4108 ** Enable or disable the extended result codes.
4110 int sqlite3_extended_result_codes(sqlite3
*db
, int onoff
){
4111 #ifdef SQLITE_ENABLE_API_ARMOR
4112 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
4114 sqlite3_mutex_enter(db
->mutex
);
4115 db
->errMask
= onoff
? 0xffffffff : 0xff;
4116 sqlite3_mutex_leave(db
->mutex
);
4121 ** Invoke the xFileControl method on a particular database.
4123 int sqlite3_file_control(sqlite3
*db
, const char *zDbName
, int op
, void *pArg
){
4124 int rc
= SQLITE_ERROR
;
4127 #ifdef SQLITE_ENABLE_API_ARMOR
4128 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
4130 sqlite3_mutex_enter(db
->mutex
);
4131 pBtree
= sqlite3DbNameToBtree(db
, zDbName
);
4135 sqlite3BtreeEnter(pBtree
);
4136 pPager
= sqlite3BtreePager(pBtree
);
4137 assert( pPager
!=0 );
4138 fd
= sqlite3PagerFile(pPager
);
4140 if( op
==SQLITE_FCNTL_FILE_POINTER
){
4141 *(sqlite3_file
**)pArg
= fd
;
4143 }else if( op
==SQLITE_FCNTL_VFS_POINTER
){
4144 *(sqlite3_vfs
**)pArg
= sqlite3PagerVfs(pPager
);
4146 }else if( op
==SQLITE_FCNTL_JOURNAL_POINTER
){
4147 *(sqlite3_file
**)pArg
= sqlite3PagerJrnlFile(pPager
);
4149 }else if( op
==SQLITE_FCNTL_DATA_VERSION
){
4150 *(unsigned int*)pArg
= sqlite3PagerDataVersion(pPager
);
4152 }else if( op
==SQLITE_FCNTL_RESERVE_BYTES
){
4153 int iNew
= *(int*)pArg
;
4154 *(int*)pArg
= sqlite3BtreeGetRequestedReserve(pBtree
);
4155 if( iNew
>=0 && iNew
<=255 ){
4156 sqlite3BtreeSetPageSize(pBtree
, 0, iNew
, 0);
4159 }else if( op
==SQLITE_FCNTL_RESET_CACHE
){
4160 sqlite3BtreeClearCache(pBtree
);
4163 int nSave
= db
->busyHandler
.nBusy
;
4164 rc
= sqlite3OsFileControl(fd
, op
, pArg
);
4165 db
->busyHandler
.nBusy
= nSave
;
4167 sqlite3BtreeLeave(pBtree
);
4169 sqlite3_mutex_leave(db
->mutex
);
4174 ** Interface to the testing logic.
4176 int sqlite3_test_control(int op
, ...){
4178 #ifdef SQLITE_UNTESTABLE
4179 UNUSED_PARAMETER(op
);
4186 ** Save the current state of the PRNG.
4188 case SQLITE_TESTCTRL_PRNG_SAVE
: {
4189 sqlite3PrngSaveState();
4194 ** Restore the state of the PRNG to the last state saved using
4195 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
4196 ** this verb acts like PRNG_RESET.
4198 case SQLITE_TESTCTRL_PRNG_RESTORE
: {
4199 sqlite3PrngRestoreState();
4203 /* sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, int x, sqlite3 *db);
4205 ** Control the seed for the pseudo-random number generator (PRNG) that
4206 ** is built into SQLite. Cases:
4208 ** x!=0 && db!=0 Seed the PRNG to the current value of the
4209 ** schema cookie in the main database for db, or
4210 ** x if the schema cookie is zero. This case
4211 ** is convenient to use with database fuzzers
4212 ** as it allows the fuzzer some control over the
4215 ** x!=0 && db==0 Seed the PRNG to the value of x.
4217 ** x==0 && db==0 Revert to default behavior of using the
4218 ** xRandomness method on the primary VFS.
4220 ** This test-control also resets the PRNG so that the new seed will
4221 ** be used for the next call to sqlite3_randomness().
4223 #ifndef SQLITE_OMIT_WSD
4224 case SQLITE_TESTCTRL_PRNG_SEED
: {
4225 int x
= va_arg(ap
, int);
4227 sqlite3
*db
= va_arg(ap
, sqlite3
*);
4228 assert( db
==0 || db
->aDb
[0].pSchema
!=0 );
4229 if( db
&& (y
= db
->aDb
[0].pSchema
->schema_cookie
)!=0 ){ x
= y
; }
4230 sqlite3Config
.iPrngSeed
= x
;
4231 sqlite3_randomness(0,0);
4236 /* sqlite3_test_control(SQLITE_TESTCTRL_FK_NO_ACTION, sqlite3 *db, int b);
4238 ** If b is true, then activate the SQLITE_FkNoAction setting. If b is
4239 ** false then clearn that setting. If the SQLITE_FkNoAction setting is
4240 ** abled, all foreign key ON DELETE and ON UPDATE actions behave as if
4241 ** they were NO ACTION, regardless of how they are defined.
4243 ** NB: One must usually run "PRAGMA writable_schema=RESET" after
4244 ** using this test-control, before it will take full effect. failing
4245 ** to reset the schema can result in some unexpected behavior.
4247 case SQLITE_TESTCTRL_FK_NO_ACTION
: {
4248 sqlite3
*db
= va_arg(ap
, sqlite3
*);
4249 int b
= va_arg(ap
, int);
4251 db
->flags
|= SQLITE_FkNoAction
;
4253 db
->flags
&= ~SQLITE_FkNoAction
;
4259 ** sqlite3_test_control(BITVEC_TEST, size, program)
4261 ** Run a test against a Bitvec object of size. The program argument
4262 ** is an array of integers that defines the test. Return -1 on a
4263 ** memory allocation error, 0 on success, or non-zero for an error.
4264 ** See the sqlite3BitvecBuiltinTest() for additional information.
4266 case SQLITE_TESTCTRL_BITVEC_TEST
: {
4267 int sz
= va_arg(ap
, int);
4268 int *aProg
= va_arg(ap
, int*);
4269 rc
= sqlite3BitvecBuiltinTest(sz
, aProg
);
4274 ** sqlite3_test_control(FAULT_INSTALL, xCallback)
4276 ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
4277 ** if xCallback is not NULL.
4279 ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
4280 ** is called immediately after installing the new callback and the return
4281 ** value from sqlite3FaultSim(0) becomes the return from
4282 ** sqlite3_test_control().
4284 case SQLITE_TESTCTRL_FAULT_INSTALL
: {
4285 /* A bug in MSVC prevents it from understanding pointers to functions
4286 ** types in the second argument to va_arg(). Work around the problem
4288 ** http://support.microsoft.com/kb/47961 <-- dead hyperlink
4289 ** Search at http://web.archive.org/ to find the 2015-03-16 archive
4290 ** of the link above to see the original text.
4291 ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
4293 typedef int(*sqlite3FaultFuncType
)(int);
4294 sqlite3GlobalConfig
.xTestCallback
= va_arg(ap
, sqlite3FaultFuncType
);
4295 rc
= sqlite3FaultSim(0);
4300 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
4302 ** Register hooks to call to indicate which malloc() failures
4305 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS
: {
4306 typedef void (*void_function
)(void);
4307 void_function xBenignBegin
;
4308 void_function xBenignEnd
;
4309 xBenignBegin
= va_arg(ap
, void_function
);
4310 xBenignEnd
= va_arg(ap
, void_function
);
4311 sqlite3BenignMallocHooks(xBenignBegin
, xBenignEnd
);
4316 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
4318 ** Set the PENDING byte to the value in the argument, if X>0.
4319 ** Make no changes if X==0. Return the value of the pending byte
4320 ** as it existing before this routine was called.
4322 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
4323 ** an incompatible database file format. Changing the PENDING byte
4324 ** while any database connection is open results in undefined and
4325 ** deleterious behavior.
4327 case SQLITE_TESTCTRL_PENDING_BYTE
: {
4329 #ifndef SQLITE_OMIT_WSD
4331 unsigned int newVal
= va_arg(ap
, unsigned int);
4332 if( newVal
) sqlite3PendingByte
= newVal
;
4339 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
4341 ** This action provides a run-time test to see whether or not
4342 ** assert() was enabled at compile-time. If X is true and assert()
4343 ** is enabled, then the return value is true. If X is true and
4344 ** assert() is disabled, then the return value is zero. If X is
4345 ** false and assert() is enabled, then the assertion fires and the
4346 ** process aborts. If X is false and assert() is disabled, then the
4347 ** return value is zero.
4349 case SQLITE_TESTCTRL_ASSERT
: {
4351 assert( /*side-effects-ok*/ (x
= va_arg(ap
,int))!=0 );
4353 #if defined(SQLITE_DEBUG)
4354 /* Invoke these debugging routines so that the compiler does not
4355 ** issue "defined but not used" warnings. */
4359 sqlite3ShowExprList(0);
4360 sqlite3ShowIdList(0);
4361 sqlite3ShowSrcList(0);
4363 sqlite3ShowUpsert(0);
4364 #ifndef SQLITE_OMIT_TRIGGER
4365 sqlite3ShowTriggerStep(0);
4366 sqlite3ShowTriggerStepList(0);
4367 sqlite3ShowTrigger(0);
4368 sqlite3ShowTriggerList(0);
4370 #ifndef SQLITE_OMIT_WINDOWFUNC
4371 sqlite3ShowWindow(0);
4372 sqlite3ShowWinFunc(0);
4374 sqlite3ShowSelect(0);
4382 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
4384 ** This action provides a run-time test to see how the ALWAYS and
4385 ** NEVER macros were defined at compile-time.
4387 ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
4389 ** The recommended test is X==2. If the return value is 2, that means
4390 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
4391 ** default setting. If the return value is 1, then ALWAYS() is either
4392 ** hard-coded to true or else it asserts if its argument is false.
4393 ** The first behavior (hard-coded to true) is the case if
4394 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
4395 ** behavior (assert if the argument to ALWAYS() is false) is the case if
4396 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
4398 ** The run-time test procedure might look something like this:
4400 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
4401 ** // ALWAYS() and NEVER() are no-op pass-through macros
4402 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
4403 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
4405 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
4408 case SQLITE_TESTCTRL_ALWAYS
: {
4409 int x
= va_arg(ap
,int);
4410 rc
= x
? ALWAYS(x
) : 0;
4415 ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
4417 ** The integer returned reveals the byte-order of the computer on which
4418 ** SQLite is running:
4420 ** 1 big-endian, determined at run-time
4421 ** 10 little-endian, determined at run-time
4422 ** 432101 big-endian, determined at compile-time
4423 ** 123410 little-endian, determined at compile-time
4425 case SQLITE_TESTCTRL_BYTEORDER
: {
4426 rc
= SQLITE_BYTEORDER
*100 + SQLITE_LITTLEENDIAN
*10 + SQLITE_BIGENDIAN
;
4430 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
4432 ** Enable or disable various optimizations for testing purposes. The
4433 ** argument N is a bitmask of optimizations to be disabled. For normal
4434 ** operation N should be 0. The idea is that a test program (like the
4435 ** SQL Logic Test or SLT test module) can run the same SQL multiple times
4436 ** with various optimizations disabled to verify that the same answer
4437 ** is obtained in every case.
4439 case SQLITE_TESTCTRL_OPTIMIZATIONS
: {
4440 sqlite3
*db
= va_arg(ap
, sqlite3
*);
4441 db
->dbOptFlags
= va_arg(ap
, u32
);
4445 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, onoff, xAlt);
4447 ** If parameter onoff is 1, subsequent calls to localtime() fail.
4448 ** If 2, then invoke xAlt() instead of localtime(). If 0, normal
4451 ** xAlt arguments are void pointers, but they really want to be:
4453 ** int xAlt(const time_t*, struct tm*);
4455 ** xAlt should write results in to struct tm object of its 2nd argument
4456 ** and return zero on success, or return non-zero on failure.
4458 case SQLITE_TESTCTRL_LOCALTIME_FAULT
: {
4459 sqlite3GlobalConfig
.bLocaltimeFault
= va_arg(ap
, int);
4460 if( sqlite3GlobalConfig
.bLocaltimeFault
==2 ){
4461 typedef int(*sqlite3LocaltimeType
)(const void*,void*);
4462 sqlite3GlobalConfig
.xAltLocaltime
= va_arg(ap
, sqlite3LocaltimeType
);
4464 sqlite3GlobalConfig
.xAltLocaltime
= 0;
4469 /* sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, sqlite3*);
4471 ** Toggle the ability to use internal functions on or off for
4472 ** the database connection given in the argument.
4474 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
: {
4475 sqlite3
*db
= va_arg(ap
, sqlite3
*);
4476 db
->mDbFlags
^= DBFLAG_InternalFunc
;
4480 /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
4482 ** Set or clear a flag that indicates that the database file is always well-
4483 ** formed and never corrupt. This flag is clear by default, indicating that
4484 ** database files might have arbitrary corruption. Setting the flag during
4485 ** testing causes certain assert() statements in the code to be activated
4486 ** that demonstrate invariants on well-formed database files.
4488 case SQLITE_TESTCTRL_NEVER_CORRUPT
: {
4489 sqlite3GlobalConfig
.neverCorrupt
= va_arg(ap
, int);
4493 /* sqlite3_test_control(SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS, int);
4495 ** Set or clear a flag that causes SQLite to verify that type, name,
4496 ** and tbl_name fields of the sqlite_schema table. This is normally
4497 ** on, but it is sometimes useful to turn it off for testing.
4499 ** 2020-07-22: Disabling EXTRA_SCHEMA_CHECKS also disables the
4500 ** verification of rootpage numbers when parsing the schema. This
4501 ** is useful to make it easier to reach strange internal error states
4502 ** during testing. The EXTRA_SCHEMA_CHECKS setting is always enabled
4505 case SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS
: {
4506 sqlite3GlobalConfig
.bExtraSchemaChecks
= va_arg(ap
, int);
4510 /* Set the threshold at which OP_Once counters reset back to zero.
4511 ** By default this is 0x7ffffffe (over 2 billion), but that value is
4512 ** too big to test in a reasonable amount of time, so this control is
4513 ** provided to set a small and easily reachable reset value.
4515 case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD
: {
4516 sqlite3GlobalConfig
.iOnceResetThreshold
= va_arg(ap
, int);
4520 /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
4522 ** Set the VDBE coverage callback function to xCallback with context
4525 case SQLITE_TESTCTRL_VDBE_COVERAGE
: {
4526 #ifdef SQLITE_VDBE_COVERAGE
4527 typedef void (*branch_callback
)(void*,unsigned int,
4528 unsigned char,unsigned char);
4529 sqlite3GlobalConfig
.xVdbeBranch
= va_arg(ap
,branch_callback
);
4530 sqlite3GlobalConfig
.pVdbeBranchArg
= va_arg(ap
,void*);
4535 /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
4536 case SQLITE_TESTCTRL_SORTER_MMAP
: {
4537 sqlite3
*db
= va_arg(ap
, sqlite3
*);
4538 db
->nMaxSorterMmap
= va_arg(ap
, int);
4542 /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
4544 ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
4547 case SQLITE_TESTCTRL_ISINIT
: {
4548 if( sqlite3GlobalConfig
.isInit
==0 ) rc
= SQLITE_ERROR
;
4552 /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
4554 ** This test control is used to create imposter tables. "db" is a pointer
4555 ** to the database connection. dbName is the database name (ex: "main" or
4556 ** "temp") which will receive the imposter. "onOff" turns imposter mode on
4557 ** or off. "tnum" is the root page of the b-tree to which the imposter
4558 ** table should connect.
4560 ** Enable imposter mode only when the schema has already been parsed. Then
4561 ** run a single CREATE TABLE statement to construct the imposter table in
4562 ** the parsed schema. Then turn imposter mode back off again.
4564 ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
4565 ** the schema to be reparsed the next time it is needed. This has the
4566 ** effect of erasing all imposter tables.
4568 case SQLITE_TESTCTRL_IMPOSTER
: {
4569 sqlite3
*db
= va_arg(ap
, sqlite3
*);
4571 sqlite3_mutex_enter(db
->mutex
);
4572 iDb
= sqlite3FindDbName(db
, va_arg(ap
,const char*));
4575 db
->init
.busy
= db
->init
.imposterTable
= va_arg(ap
,int);
4576 db
->init
.newTnum
= va_arg(ap
,int);
4577 if( db
->init
.busy
==0 && db
->init
.newTnum
>0 ){
4578 sqlite3ResetAllSchemasOfConnection(db
);
4581 sqlite3_mutex_leave(db
->mutex
);
4585 #if defined(YYCOVERAGE)
4586 /* sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
4588 ** This test control (only available when SQLite is compiled with
4589 ** -DYYCOVERAGE) writes a report onto "out" that shows all
4590 ** state/lookahead combinations in the parser state machine
4591 ** which are never exercised. If any state is missed, make the
4592 ** return code SQLITE_ERROR.
4594 case SQLITE_TESTCTRL_PARSER_COVERAGE
: {
4595 FILE *out
= va_arg(ap
, FILE*);
4596 if( sqlite3ParserCoverage(out
) ) rc
= SQLITE_ERROR
;
4599 #endif /* defined(YYCOVERAGE) */
4601 /* sqlite3_test_control(SQLITE_TESTCTRL_RESULT_INTREAL, sqlite3_context*);
4603 ** This test-control causes the most recent sqlite3_result_int64() value
4604 ** to be interpreted as a MEM_IntReal instead of as an MEM_Int. Normally,
4605 ** MEM_IntReal values only arise during an INSERT operation of integer
4606 ** values into a REAL column, so they can be challenging to test. This
4607 ** test-control enables us to write an intreal() SQL function that can
4608 ** inject an intreal() value at arbitrary places in an SQL statement,
4609 ** for testing purposes.
4611 case SQLITE_TESTCTRL_RESULT_INTREAL
: {
4612 sqlite3_context
*pCtx
= va_arg(ap
, sqlite3_context
*);
4613 sqlite3ResultIntReal(pCtx
);
4617 /* sqlite3_test_control(SQLITE_TESTCTRL_SEEK_COUNT,
4618 ** sqlite3 *db, // Database connection
4619 ** u64 *pnSeek // Write seek count here
4622 ** This test-control queries the seek-counter on the "main" database
4623 ** file. The seek-counter is written into *pnSeek and is then reset.
4624 ** The seek-count is only available if compiled with SQLITE_DEBUG.
4626 case SQLITE_TESTCTRL_SEEK_COUNT
: {
4627 sqlite3
*db
= va_arg(ap
, sqlite3
*);
4628 u64
*pn
= va_arg(ap
, sqlite3_uint64
*);
4629 *pn
= sqlite3BtreeSeekCount(db
->aDb
->pBt
);
4630 (void)db
; /* Silence harmless unused variable warning */
4634 /* sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, op, ptr)
4636 ** "ptr" is a pointer to a u32.
4638 ** op==0 Store the current sqlite3TreeTrace in *ptr
4639 ** op==1 Set sqlite3TreeTrace to the value *ptr
4640 ** op==2 Store the current sqlite3WhereTrace in *ptr
4641 ** op==3 Set sqlite3WhereTrace to the value *ptr
4643 case SQLITE_TESTCTRL_TRACEFLAGS
: {
4644 int opTrace
= va_arg(ap
, int);
4645 u32
*ptr
= va_arg(ap
, u32
*);
4647 case 0: *ptr
= sqlite3TreeTrace
; break;
4648 case 1: sqlite3TreeTrace
= *ptr
; break;
4649 case 2: *ptr
= sqlite3WhereTrace
; break;
4650 case 3: sqlite3WhereTrace
= *ptr
; break;
4655 /* sqlite3_test_control(SQLITE_TESTCTRL_LOGEST,
4656 ** double fIn, // Input value
4657 ** int *pLogEst, // sqlite3LogEstFromDouble(fIn)
4658 ** u64 *pInt, // sqlite3LogEstToInt(*pLogEst)
4659 ** int *pLogEst2 // sqlite3LogEst(*pInt)
4662 ** Test access for the LogEst conversion routines.
4664 case SQLITE_TESTCTRL_LOGEST
: {
4665 double rIn
= va_arg(ap
, double);
4666 LogEst rLogEst
= sqlite3LogEstFromDouble(rIn
);
4667 int *pI1
= va_arg(ap
,int*);
4668 u64
*pU64
= va_arg(ap
,u64
*);
4669 int *pI2
= va_arg(ap
,int*);
4671 *pU64
= sqlite3LogEstToInt(rLogEst
);
4672 *pI2
= sqlite3LogEst(*pU64
);
4676 #if !defined(SQLITE_OMIT_WSD)
4677 /* sqlite3_test_control(SQLITE_TESTCTRL_USELONGDOUBLE, int X);
4679 ** X<0 Make no changes to the bUseLongDouble. Just report value.
4680 ** X==0 Disable bUseLongDouble
4681 ** X==1 Enable bUseLongDouble
4682 ** X>=2 Set bUseLongDouble to its default value for this platform
4684 case SQLITE_TESTCTRL_USELONGDOUBLE
: {
4685 int b
= va_arg(ap
, int);
4686 if( b
>=2 ) b
= hasHighPrecisionDouble(b
);
4687 if( b
>=0 ) sqlite3Config
.bUseLongDouble
= b
>0;
4688 rc
= sqlite3Config
.bUseLongDouble
!=0;
4694 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
4695 /* sqlite3_test_control(SQLITE_TESTCTRL_TUNE, id, *piValue)
4697 ** If "id" is an integer between 1 and SQLITE_NTUNE then set the value
4698 ** of the id-th tuning parameter to *piValue. If "id" is between -1
4699 ** and -SQLITE_NTUNE, then write the current value of the (-id)-th
4700 ** tuning parameter into *piValue.
4702 ** Tuning parameters are for use during transient development builds,
4703 ** to help find the best values for constants in the query planner.
4704 ** Access tuning parameters using the Tuning(ID) macro. Set the
4705 ** parameters in the CLI using ".testctrl tune ID VALUE".
4707 ** Transient use only. Tuning parameters should not be used in
4710 case SQLITE_TESTCTRL_TUNE
: {
4711 int id
= va_arg(ap
, int);
4712 int *piValue
= va_arg(ap
, int*);
4713 if( id
>0 && id
<=SQLITE_NTUNE
){
4714 Tuning(id
) = *piValue
;
4715 }else if( id
<0 && id
>=-SQLITE_NTUNE
){
4716 *piValue
= Tuning(-id
);
4718 rc
= SQLITE_NOTFOUND
;
4724 /* sqlite3_test_control(SQLITE_TESTCTRL_JSON_SELFCHECK, &onOff);
4726 ** Activate or deactivate validation of JSONB that is generated from
4727 ** text. Off by default, as the validation is slow. Validation is
4728 ** only available if compiled using SQLITE_DEBUG.
4730 ** If onOff is initially 1, then turn it on. If onOff is initially
4731 ** off, turn it off. If onOff is initially -1, then change onOff
4732 ** to be the current setting.
4734 case SQLITE_TESTCTRL_JSON_SELFCHECK
: {
4735 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
4736 int *pOnOff
= va_arg(ap
, int*);
4738 *pOnOff
= sqlite3Config
.bJsonSelfcheck
;
4740 sqlite3Config
.bJsonSelfcheck
= (u8
)((*pOnOff
)&0xff);
4747 #endif /* SQLITE_UNTESTABLE */
4752 ** The Pager stores the Database filename, Journal filename, and WAL filename
4753 ** consecutively in memory, in that order. The database filename is prefixed
4754 ** by four zero bytes. Locate the start of the database filename by searching
4755 ** backwards for the first byte following four consecutive zero bytes.
4757 ** This only works if the filename passed in was obtained from the Pager.
4759 static const char *databaseName(const char *zName
){
4760 while( zName
[-1]!=0 || zName
[-2]!=0 || zName
[-3]!=0 || zName
[-4]!=0 ){
4767 ** Append text z[] to the end of p[]. Return a pointer to the first
4768 ** character after then zero terminator on the new text in p[].
4770 static char *appendText(char *p
, const char *z
){
4771 size_t n
= strlen(z
);
4777 ** Allocate memory to hold names for a database, journal file, WAL file,
4778 ** and query parameters. The pointer returned is valid for use by
4779 ** sqlite3_filename_database() and sqlite3_uri_parameter() and related
4782 ** Memory layout must be compatible with that generated by the pager
4783 ** and expected by sqlite3_uri_parameter() and databaseName().
4785 const char *sqlite3_create_filename(
4786 const char *zDatabase
,
4787 const char *zJournal
,
4790 const char **azParam
4792 sqlite3_int64 nByte
;
4795 nByte
= strlen(zDatabase
) + strlen(zJournal
) + strlen(zWal
) + 10;
4796 for(i
=0; i
<nParam
*2; i
++){
4797 nByte
+= strlen(azParam
[i
])+1;
4799 pResult
= p
= sqlite3_malloc64( nByte
);
4800 if( p
==0 ) return 0;
4803 p
= appendText(p
, zDatabase
);
4804 for(i
=0; i
<nParam
*2; i
++){
4805 p
= appendText(p
, azParam
[i
]);
4808 p
= appendText(p
, zJournal
);
4809 p
= appendText(p
, zWal
);
4812 assert( (sqlite3_int64
)(p
- pResult
)==nByte
);
4817 ** Free memory obtained from sqlite3_create_filename(). It is a severe
4818 ** error to call this routine with any parameter other than a pointer
4819 ** previously obtained from sqlite3_create_filename() or a NULL pointer.
4821 void sqlite3_free_filename(const char *p
){
4823 p
= databaseName(p
);
4824 sqlite3_free((char*)p
- 4);
4829 ** This is a utility routine, useful to VFS implementations, that checks
4830 ** to see if a database file was a URI that contained a specific query
4831 ** parameter, and if so obtains the value of the query parameter.
4833 ** The zFilename argument is the filename pointer passed into the xOpen()
4834 ** method of a VFS implementation. The zParam argument is the name of the
4835 ** query parameter we seek. This routine returns the value of the zParam
4836 ** parameter if it exists. If the parameter does not exist, this routine
4837 ** returns a NULL pointer.
4839 const char *sqlite3_uri_parameter(const char *zFilename
, const char *zParam
){
4840 if( zFilename
==0 || zParam
==0 ) return 0;
4841 zFilename
= databaseName(zFilename
);
4842 return uriParameter(zFilename
, zParam
);
4846 ** Return a pointer to the name of Nth query parameter of the filename.
4848 const char *sqlite3_uri_key(const char *zFilename
, int N
){
4849 if( zFilename
==0 || N
<0 ) return 0;
4850 zFilename
= databaseName(zFilename
);
4851 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
4852 while( ALWAYS(zFilename
) && zFilename
[0] && (N
--)>0 ){
4853 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
4854 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
4856 return zFilename
[0] ? zFilename
: 0;
4860 ** Return a boolean value for a query parameter.
4862 int sqlite3_uri_boolean(const char *zFilename
, const char *zParam
, int bDflt
){
4863 const char *z
= sqlite3_uri_parameter(zFilename
, zParam
);
4865 return z
? sqlite3GetBoolean(z
, bDflt
) : bDflt
;
4869 ** Return a 64-bit integer value for a query parameter.
4871 sqlite3_int64
sqlite3_uri_int64(
4872 const char *zFilename
, /* Filename as passed to xOpen */
4873 const char *zParam
, /* URI parameter sought */
4874 sqlite3_int64 bDflt
/* return if parameter is missing */
4876 const char *z
= sqlite3_uri_parameter(zFilename
, zParam
);
4878 if( z
&& sqlite3DecOrHexToI64(z
, &v
)==0 ){
4885 ** Translate a filename that was handed to a VFS routine into the corresponding
4886 ** database, journal, or WAL file.
4888 ** It is an error to pass this routine a filename string that was not
4889 ** passed into the VFS from the SQLite core. Doing so is similar to
4890 ** passing free() a pointer that was not obtained from malloc() - it is
4891 ** an error that we cannot easily detect but that will likely cause memory
4894 const char *sqlite3_filename_database(const char *zFilename
){
4895 if( zFilename
==0 ) return 0;
4896 return databaseName(zFilename
);
4898 const char *sqlite3_filename_journal(const char *zFilename
){
4899 if( zFilename
==0 ) return 0;
4900 zFilename
= databaseName(zFilename
);
4901 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
4902 while( ALWAYS(zFilename
) && zFilename
[0] ){
4903 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
4904 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
4906 return zFilename
+ 1;
4908 const char *sqlite3_filename_wal(const char *zFilename
){
4909 #ifdef SQLITE_OMIT_WAL
4912 zFilename
= sqlite3_filename_journal(zFilename
);
4913 if( zFilename
) zFilename
+= sqlite3Strlen30(zFilename
) + 1;
4919 ** Return the Btree pointer identified by zDbName. Return NULL if not found.
4921 Btree
*sqlite3DbNameToBtree(sqlite3
*db
, const char *zDbName
){
4922 int iDb
= zDbName
? sqlite3FindDbName(db
, zDbName
) : 0;
4923 return iDb
<0 ? 0 : db
->aDb
[iDb
].pBt
;
4927 ** Return the name of the N-th database schema. Return NULL if N is out
4930 const char *sqlite3_db_name(sqlite3
*db
, int N
){
4931 #ifdef SQLITE_ENABLE_API_ARMOR
4932 if( !sqlite3SafetyCheckOk(db
) ){
4933 (void)SQLITE_MISUSE_BKPT
;
4937 if( N
<0 || N
>=db
->nDb
){
4940 return db
->aDb
[N
].zDbSName
;
4945 ** Return the filename of the database associated with a database
4948 const char *sqlite3_db_filename(sqlite3
*db
, const char *zDbName
){
4950 #ifdef SQLITE_ENABLE_API_ARMOR
4951 if( !sqlite3SafetyCheckOk(db
) ){
4952 (void)SQLITE_MISUSE_BKPT
;
4956 pBt
= sqlite3DbNameToBtree(db
, zDbName
);
4957 return pBt
? sqlite3BtreeGetFilename(pBt
) : 0;
4961 ** Return 1 if database is read-only or 0 if read/write. Return -1 if
4962 ** no such database exists.
4964 int sqlite3_db_readonly(sqlite3
*db
, const char *zDbName
){
4966 #ifdef SQLITE_ENABLE_API_ARMOR
4967 if( !sqlite3SafetyCheckOk(db
) ){
4968 (void)SQLITE_MISUSE_BKPT
;
4972 pBt
= sqlite3DbNameToBtree(db
, zDbName
);
4973 return pBt
? sqlite3BtreeIsReadonly(pBt
) : -1;
4976 #ifdef SQLITE_ENABLE_SNAPSHOT
4978 ** Obtain a snapshot handle for the snapshot of database zDb currently
4979 ** being read by handle db.
4981 int sqlite3_snapshot_get(
4984 sqlite3_snapshot
**ppSnapshot
4986 int rc
= SQLITE_ERROR
;
4987 #ifndef SQLITE_OMIT_WAL
4989 #ifdef SQLITE_ENABLE_API_ARMOR
4990 if( !sqlite3SafetyCheckOk(db
) ){
4991 return SQLITE_MISUSE_BKPT
;
4994 sqlite3_mutex_enter(db
->mutex
);
4996 if( db
->autoCommit
==0 ){
4997 int iDb
= sqlite3FindDbName(db
, zDb
);
4998 if( iDb
==0 || iDb
>1 ){
4999 Btree
*pBt
= db
->aDb
[iDb
].pBt
;
5000 if( SQLITE_TXN_WRITE
!=sqlite3BtreeTxnState(pBt
) ){
5001 rc
= sqlite3BtreeBeginTrans(pBt
, 0, 0);
5002 if( rc
==SQLITE_OK
){
5003 rc
= sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt
), ppSnapshot
);
5009 sqlite3_mutex_leave(db
->mutex
);
5010 #endif /* SQLITE_OMIT_WAL */
5015 ** Open a read-transaction on the snapshot identified by pSnapshot.
5017 int sqlite3_snapshot_open(
5020 sqlite3_snapshot
*pSnapshot
5022 int rc
= SQLITE_ERROR
;
5023 #ifndef SQLITE_OMIT_WAL
5025 #ifdef SQLITE_ENABLE_API_ARMOR
5026 if( !sqlite3SafetyCheckOk(db
) ){
5027 return SQLITE_MISUSE_BKPT
;
5030 sqlite3_mutex_enter(db
->mutex
);
5031 if( db
->autoCommit
==0 ){
5033 iDb
= sqlite3FindDbName(db
, zDb
);
5034 if( iDb
==0 || iDb
>1 ){
5035 Btree
*pBt
= db
->aDb
[iDb
].pBt
;
5036 if( sqlite3BtreeTxnState(pBt
)!=SQLITE_TXN_WRITE
){
5037 Pager
*pPager
= sqlite3BtreePager(pBt
);
5039 if( sqlite3BtreeTxnState(pBt
)!=SQLITE_TXN_NONE
){
5040 if( db
->nVdbeActive
==0 ){
5041 rc
= sqlite3PagerSnapshotCheck(pPager
, pSnapshot
);
5042 if( rc
==SQLITE_OK
){
5044 rc
= sqlite3BtreeCommit(pBt
);
5050 if( rc
==SQLITE_OK
){
5051 rc
= sqlite3PagerSnapshotOpen(pPager
, pSnapshot
);
5053 if( rc
==SQLITE_OK
){
5054 rc
= sqlite3BtreeBeginTrans(pBt
, 0, 0);
5055 sqlite3PagerSnapshotOpen(pPager
, 0);
5058 sqlite3PagerSnapshotUnlock(pPager
);
5064 sqlite3_mutex_leave(db
->mutex
);
5065 #endif /* SQLITE_OMIT_WAL */
5070 ** Recover as many snapshots as possible from the wal file associated with
5071 ** schema zDb of database db.
5073 int sqlite3_snapshot_recover(sqlite3
*db
, const char *zDb
){
5074 int rc
= SQLITE_ERROR
;
5075 #ifndef SQLITE_OMIT_WAL
5078 #ifdef SQLITE_ENABLE_API_ARMOR
5079 if( !sqlite3SafetyCheckOk(db
) ){
5080 return SQLITE_MISUSE_BKPT
;
5084 sqlite3_mutex_enter(db
->mutex
);
5085 iDb
= sqlite3FindDbName(db
, zDb
);
5086 if( iDb
==0 || iDb
>1 ){
5087 Btree
*pBt
= db
->aDb
[iDb
].pBt
;
5088 if( SQLITE_TXN_NONE
==sqlite3BtreeTxnState(pBt
) ){
5089 rc
= sqlite3BtreeBeginTrans(pBt
, 0, 0);
5090 if( rc
==SQLITE_OK
){
5091 rc
= sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt
));
5092 sqlite3BtreeCommit(pBt
);
5096 sqlite3_mutex_leave(db
->mutex
);
5097 #endif /* SQLITE_OMIT_WAL */
5102 ** Free a snapshot handle obtained from sqlite3_snapshot_get().
5104 void sqlite3_snapshot_free(sqlite3_snapshot
*pSnapshot
){
5105 sqlite3_free(pSnapshot
);
5107 #endif /* SQLITE_ENABLE_SNAPSHOT */
5109 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
5111 ** Given the name of a compile-time option, return true if that option
5112 ** was used and false if not.
5114 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
5115 ** is not required for a match.
5117 int sqlite3_compileoption_used(const char *zOptName
){
5120 const char **azCompileOpt
;
5122 #ifdef SQLITE_ENABLE_API_ARMOR
5124 (void)SQLITE_MISUSE_BKPT
;
5129 azCompileOpt
= sqlite3CompileOptions(&nOpt
);
5131 if( sqlite3StrNICmp(zOptName
, "SQLITE_", 7)==0 ) zOptName
+= 7;
5132 n
= sqlite3Strlen30(zOptName
);
5134 /* Since nOpt is normally in single digits, a linear search is
5135 ** adequate. No need for a binary search. */
5136 for(i
=0; i
<nOpt
; i
++){
5137 if( sqlite3StrNICmp(zOptName
, azCompileOpt
[i
], n
)==0
5138 && sqlite3IsIdChar((unsigned char)azCompileOpt
[i
][n
])==0
5147 ** Return the N-th compile-time option string. If N is out of range,
5148 ** return a NULL pointer.
5150 const char *sqlite3_compileoption_get(int N
){
5152 const char **azCompileOpt
;
5153 azCompileOpt
= sqlite3CompileOptions(&nOpt
);
5154 if( N
>=0 && N
<nOpt
){
5155 return azCompileOpt
[N
];
5159 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */