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 sqlite3Config
.bUseLongDouble
= hasHighPrecisionDouble(rc
);
391 ** Undo the effects of sqlite3_initialize(). Must not be called while
392 ** there are outstanding database connections or memory allocations or
393 ** while any part of SQLite is otherwise in use in any thread. This
394 ** routine is not threadsafe. But it is safe to invoke this routine
395 ** on when SQLite is already shut down. If SQLite is already shut down
396 ** when this routine is invoked, then this routine is a harmless no-op.
398 int sqlite3_shutdown(void){
399 #ifdef SQLITE_OMIT_WSD
400 int rc
= sqlite3_wsd_init(4096, 24);
406 if( sqlite3GlobalConfig
.isInit
){
407 #ifdef SQLITE_EXTRA_SHUTDOWN
408 void SQLITE_EXTRA_SHUTDOWN(void);
409 SQLITE_EXTRA_SHUTDOWN();
412 sqlite3_reset_auto_extension();
413 sqlite3GlobalConfig
.isInit
= 0;
415 if( sqlite3GlobalConfig
.isPCacheInit
){
416 sqlite3PcacheShutdown();
417 sqlite3GlobalConfig
.isPCacheInit
= 0;
419 if( sqlite3GlobalConfig
.isMallocInit
){
421 sqlite3GlobalConfig
.isMallocInit
= 0;
423 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
424 /* The heap subsystem has now been shutdown and these values are supposed
425 ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
426 ** which would rely on that heap subsystem; therefore, make sure these
427 ** values cannot refer to heap memory that was just invalidated when the
428 ** heap subsystem was shutdown. This is only done if the current call to
429 ** this function resulted in the heap subsystem actually being shutdown.
431 sqlite3_data_directory
= 0;
432 sqlite3_temp_directory
= 0;
435 if( sqlite3GlobalConfig
.isMutexInit
){
437 sqlite3GlobalConfig
.isMutexInit
= 0;
444 ** This API allows applications to modify the global configuration of
445 ** the SQLite library at run-time.
447 ** This routine should only be called when there are no outstanding
448 ** database connections or memory allocations. This routine is not
449 ** threadsafe. Failure to heed these warnings can lead to unpredictable
452 int sqlite3_config(int op
, ...){
456 /* sqlite3_config() normally returns SQLITE_MISUSE if it is invoked while
457 ** the SQLite library is in use. Except, a few selected opcodes
460 if( sqlite3GlobalConfig
.isInit
){
461 static const u64 mAnytimeConfigOption
= 0
462 | MASKBIT64( SQLITE_CONFIG_LOG
)
463 | MASKBIT64( SQLITE_CONFIG_PCACHE_HDRSZ
)
465 if( op
<0 || op
>63 || (MASKBIT64(op
) & mAnytimeConfigOption
)==0 ){
466 return SQLITE_MISUSE_BKPT
;
468 testcase( op
==SQLITE_CONFIG_LOG
);
469 testcase( op
==SQLITE_CONFIG_PCACHE_HDRSZ
);
475 /* Mutex configuration options are only available in a threadsafe
478 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
479 case SQLITE_CONFIG_SINGLETHREAD
: {
480 /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
482 sqlite3GlobalConfig
.bCoreMutex
= 0; /* Disable mutex on core */
483 sqlite3GlobalConfig
.bFullMutex
= 0; /* Disable mutex on connections */
487 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
488 case SQLITE_CONFIG_MULTITHREAD
: {
489 /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
491 sqlite3GlobalConfig
.bCoreMutex
= 1; /* Enable mutex on core */
492 sqlite3GlobalConfig
.bFullMutex
= 0; /* Disable mutex on connections */
496 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
497 case SQLITE_CONFIG_SERIALIZED
: {
498 /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
500 sqlite3GlobalConfig
.bCoreMutex
= 1; /* Enable mutex on core */
501 sqlite3GlobalConfig
.bFullMutex
= 1; /* Enable mutex on connections */
505 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
506 case SQLITE_CONFIG_MUTEX
: {
507 /* Specify an alternative mutex implementation */
508 sqlite3GlobalConfig
.mutex
= *va_arg(ap
, sqlite3_mutex_methods
*);
512 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
513 case SQLITE_CONFIG_GETMUTEX
: {
514 /* Retrieve the current mutex implementation */
515 *va_arg(ap
, sqlite3_mutex_methods
*) = sqlite3GlobalConfig
.mutex
;
520 case SQLITE_CONFIG_MALLOC
: {
521 /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
522 ** single argument which is a pointer to an instance of the
523 ** sqlite3_mem_methods structure. The argument specifies alternative
524 ** low-level memory allocation routines to be used in place of the memory
525 ** allocation routines built into SQLite. */
526 sqlite3GlobalConfig
.m
= *va_arg(ap
, sqlite3_mem_methods
*);
529 case SQLITE_CONFIG_GETMALLOC
: {
530 /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
531 ** single argument which is a pointer to an instance of the
532 ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
533 ** filled with the currently defined memory allocation routines. */
534 if( sqlite3GlobalConfig
.m
.xMalloc
==0 ) sqlite3MemSetDefault();
535 *va_arg(ap
, sqlite3_mem_methods
*) = sqlite3GlobalConfig
.m
;
538 case SQLITE_CONFIG_MEMSTATUS
: {
539 assert( !sqlite3GlobalConfig
.isInit
); /* Cannot change at runtime */
540 /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
541 ** single argument of type int, interpreted as a boolean, which enables
542 ** or disables the collection of memory allocation statistics. */
543 sqlite3GlobalConfig
.bMemstat
= va_arg(ap
, int);
546 case SQLITE_CONFIG_SMALL_MALLOC
: {
547 sqlite3GlobalConfig
.bSmallMalloc
= va_arg(ap
, int);
550 case SQLITE_CONFIG_PAGECACHE
: {
551 /* EVIDENCE-OF: R-18761-36601 There are three arguments to
552 ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
553 ** the size of each page cache line (sz), and the number of cache lines
555 sqlite3GlobalConfig
.pPage
= va_arg(ap
, void*);
556 sqlite3GlobalConfig
.szPage
= va_arg(ap
, int);
557 sqlite3GlobalConfig
.nPage
= va_arg(ap
, int);
560 case SQLITE_CONFIG_PCACHE_HDRSZ
: {
561 /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
562 ** a single parameter which is a pointer to an integer and writes into
563 ** that integer the number of extra bytes per page required for each page
564 ** in SQLITE_CONFIG_PAGECACHE. */
566 sqlite3HeaderSizeBtree() +
567 sqlite3HeaderSizePcache() +
568 sqlite3HeaderSizePcache1();
572 case SQLITE_CONFIG_PCACHE
: {
576 case SQLITE_CONFIG_GETPCACHE
: {
582 case SQLITE_CONFIG_PCACHE2
: {
583 /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
584 ** single argument which is a pointer to an sqlite3_pcache_methods2
585 ** object. This object specifies the interface to a custom page cache
586 ** implementation. */
587 sqlite3GlobalConfig
.pcache2
= *va_arg(ap
, sqlite3_pcache_methods2
*);
590 case SQLITE_CONFIG_GETPCACHE2
: {
591 /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
592 ** single argument which is a pointer to an sqlite3_pcache_methods2
593 ** object. SQLite copies of the current page cache implementation into
595 if( sqlite3GlobalConfig
.pcache2
.xInit
==0 ){
596 sqlite3PCacheSetDefault();
598 *va_arg(ap
, sqlite3_pcache_methods2
*) = sqlite3GlobalConfig
.pcache2
;
602 /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
603 ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
604 ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
605 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
606 case SQLITE_CONFIG_HEAP
: {
607 /* EVIDENCE-OF: R-19854-42126 There are three arguments to
608 ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
609 ** number of bytes in the memory buffer, and the minimum allocation size.
611 sqlite3GlobalConfig
.pHeap
= va_arg(ap
, void*);
612 sqlite3GlobalConfig
.nHeap
= va_arg(ap
, int);
613 sqlite3GlobalConfig
.mnReq
= va_arg(ap
, int);
615 if( sqlite3GlobalConfig
.mnReq
<1 ){
616 sqlite3GlobalConfig
.mnReq
= 1;
617 }else if( sqlite3GlobalConfig
.mnReq
>(1<<12) ){
618 /* cap min request size at 2^12 */
619 sqlite3GlobalConfig
.mnReq
= (1<<12);
622 if( sqlite3GlobalConfig
.pHeap
==0 ){
623 /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
624 ** is NULL, then SQLite reverts to using its default memory allocator
625 ** (the system malloc() implementation), undoing any prior invocation of
626 ** SQLITE_CONFIG_MALLOC.
628 ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
629 ** revert to its default implementation when sqlite3_initialize() is run
631 memset(&sqlite3GlobalConfig
.m
, 0, sizeof(sqlite3GlobalConfig
.m
));
633 /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
634 ** alternative memory allocator is engaged to handle all of SQLites
635 ** memory allocation needs. */
636 #ifdef SQLITE_ENABLE_MEMSYS3
637 sqlite3GlobalConfig
.m
= *sqlite3MemGetMemsys3();
639 #ifdef SQLITE_ENABLE_MEMSYS5
640 sqlite3GlobalConfig
.m
= *sqlite3MemGetMemsys5();
647 case SQLITE_CONFIG_LOOKASIDE
: {
648 sqlite3GlobalConfig
.szLookaside
= va_arg(ap
, int);
649 sqlite3GlobalConfig
.nLookaside
= va_arg(ap
, int);
653 /* Record a pointer to the logger function and its first argument.
654 ** The default is NULL. Logging is disabled if the function pointer is
657 case SQLITE_CONFIG_LOG
: {
658 /* MSVC is picky about pulling func ptrs from va lists.
659 ** http://support.microsoft.com/kb/47961
660 ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
662 typedef void(*LOGFUNC_t
)(void*,int,const char*);
663 LOGFUNC_t xLog
= va_arg(ap
, LOGFUNC_t
);
664 void *pLogArg
= va_arg(ap
, void*);
665 AtomicStore(&sqlite3GlobalConfig
.xLog
, xLog
);
666 AtomicStore(&sqlite3GlobalConfig
.pLogArg
, pLogArg
);
670 /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
671 ** can be changed at start-time using the
672 ** sqlite3_config(SQLITE_CONFIG_URI,1) or
673 ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
675 case SQLITE_CONFIG_URI
: {
676 /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
677 ** argument of type int. If non-zero, then URI handling is globally
678 ** enabled. If the parameter is zero, then URI handling is globally
680 int bOpenUri
= va_arg(ap
, int);
681 AtomicStore(&sqlite3GlobalConfig
.bOpenUri
, bOpenUri
);
685 case SQLITE_CONFIG_COVERING_INDEX_SCAN
: {
686 /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
687 ** option takes a single integer argument which is interpreted as a
688 ** boolean in order to enable or disable the use of covering indices for
689 ** full table scans in the query optimizer. */
690 sqlite3GlobalConfig
.bUseCis
= va_arg(ap
, int);
694 #ifdef SQLITE_ENABLE_SQLLOG
695 case SQLITE_CONFIG_SQLLOG
: {
696 typedef void(*SQLLOGFUNC_t
)(void*, sqlite3
*, const char*, int);
697 sqlite3GlobalConfig
.xSqllog
= va_arg(ap
, SQLLOGFUNC_t
);
698 sqlite3GlobalConfig
.pSqllogArg
= va_arg(ap
, void *);
703 case SQLITE_CONFIG_MMAP_SIZE
: {
704 /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
705 ** integer (sqlite3_int64) values that are the default mmap size limit
706 ** (the default setting for PRAGMA mmap_size) and the maximum allowed
707 ** mmap size limit. */
708 sqlite3_int64 szMmap
= va_arg(ap
, sqlite3_int64
);
709 sqlite3_int64 mxMmap
= va_arg(ap
, sqlite3_int64
);
710 /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
711 ** negative, then that argument is changed to its compile-time default.
713 ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
714 ** silently truncated if necessary so that it does not exceed the
715 ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
716 ** compile-time option.
718 if( mxMmap
<0 || mxMmap
>SQLITE_MAX_MMAP_SIZE
){
719 mxMmap
= SQLITE_MAX_MMAP_SIZE
;
721 if( szMmap
<0 ) szMmap
= SQLITE_DEFAULT_MMAP_SIZE
;
722 if( szMmap
>mxMmap
) szMmap
= mxMmap
;
723 sqlite3GlobalConfig
.mxMmap
= mxMmap
;
724 sqlite3GlobalConfig
.szMmap
= szMmap
;
728 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
729 case SQLITE_CONFIG_WIN32_HEAPSIZE
: {
730 /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
731 ** unsigned integer value that specifies the maximum size of the created
733 sqlite3GlobalConfig
.nHeap
= va_arg(ap
, int);
738 case SQLITE_CONFIG_PMASZ
: {
739 sqlite3GlobalConfig
.szPma
= va_arg(ap
, unsigned int);
743 case SQLITE_CONFIG_STMTJRNL_SPILL
: {
744 sqlite3GlobalConfig
.nStmtSpill
= va_arg(ap
, int);
748 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
749 case SQLITE_CONFIG_SORTERREF_SIZE
: {
750 int iVal
= va_arg(ap
, int);
752 iVal
= SQLITE_DEFAULT_SORTERREF_SIZE
;
754 sqlite3GlobalConfig
.szSorterRef
= (u32
)iVal
;
757 #endif /* SQLITE_ENABLE_SORTER_REFERENCES */
759 #ifndef SQLITE_OMIT_DESERIALIZE
760 case SQLITE_CONFIG_MEMDB_MAXSIZE
: {
761 sqlite3GlobalConfig
.mxMemdbSize
= va_arg(ap
, sqlite3_int64
);
764 #endif /* SQLITE_OMIT_DESERIALIZE */
776 ** Set up the lookaside buffers for a database connection.
777 ** Return SQLITE_OK on success.
778 ** If lookaside is already active, return SQLITE_BUSY.
780 ** The sz parameter is the number of bytes in each lookaside slot.
781 ** The cnt parameter is the number of slots. If pStart is NULL the
782 ** space for the lookaside memory is obtained from sqlite3_malloc().
783 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
784 ** the lookaside memory.
786 static int setupLookaside(sqlite3
*db
, void *pBuf
, int sz
, int cnt
){
787 #ifndef SQLITE_OMIT_LOOKASIDE
789 sqlite3_int64 szAlloc
= sz
*(sqlite3_int64
)cnt
;
790 int nBig
; /* Number of full-size slots */
791 int nSm
; /* Number smaller LOOKASIDE_SMALL-byte slots */
793 if( sqlite3LookasideUsed(db
,0)>0 ){
796 /* Free any existing lookaside buffer for this handle before
797 ** allocating a new one so we don't have to have space for
798 ** both at the same time.
800 if( db
->lookaside
.bMalloced
){
801 sqlite3_free(db
->lookaside
.pStart
);
803 /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
804 ** than a pointer to be useful.
806 sz
= ROUNDDOWN8(sz
); /* IMP: R-33038-09382 */
807 if( sz
<=(int)sizeof(LookasideSlot
*) ) sz
= 0;
809 if( sz
==0 || cnt
==0 ){
813 sqlite3BeginBenignMalloc();
814 pStart
= sqlite3Malloc( szAlloc
); /* IMP: R-61949-35727 */
815 sqlite3EndBenignMalloc();
816 if( pStart
) szAlloc
= sqlite3MallocSize(pStart
);
820 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
821 if( sz
>=LOOKASIDE_SMALL
*3 ){
822 nBig
= szAlloc
/(3*LOOKASIDE_SMALL
+sz
);
823 nSm
= (szAlloc
- sz
*nBig
)/LOOKASIDE_SMALL
;
824 }else if( sz
>=LOOKASIDE_SMALL
*2 ){
825 nBig
= szAlloc
/(LOOKASIDE_SMALL
+sz
);
826 nSm
= (szAlloc
- sz
*nBig
)/LOOKASIDE_SMALL
;
828 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
835 db
->lookaside
.pStart
= pStart
;
836 db
->lookaside
.pInit
= 0;
837 db
->lookaside
.pFree
= 0;
838 db
->lookaside
.sz
= (u16
)sz
;
839 db
->lookaside
.szTrue
= (u16
)sz
;
843 assert( sz
> (int)sizeof(LookasideSlot
*) );
844 p
= (LookasideSlot
*)pStart
;
845 for(i
=0; i
<nBig
; i
++){
846 p
->pNext
= db
->lookaside
.pInit
;
847 db
->lookaside
.pInit
= p
;
848 p
= (LookasideSlot
*)&((u8
*)p
)[sz
];
850 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
851 db
->lookaside
.pSmallInit
= 0;
852 db
->lookaside
.pSmallFree
= 0;
853 db
->lookaside
.pMiddle
= p
;
854 for(i
=0; i
<nSm
; i
++){
855 p
->pNext
= db
->lookaside
.pSmallInit
;
856 db
->lookaside
.pSmallInit
= p
;
857 p
= (LookasideSlot
*)&((u8
*)p
)[LOOKASIDE_SMALL
];
859 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
860 assert( ((uptr
)p
)<=szAlloc
+ (uptr
)pStart
);
861 db
->lookaside
.pEnd
= p
;
862 db
->lookaside
.bDisable
= 0;
863 db
->lookaside
.bMalloced
= pBuf
==0 ?1:0;
864 db
->lookaside
.nSlot
= nBig
+nSm
;
866 db
->lookaside
.pStart
= 0;
867 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
868 db
->lookaside
.pSmallInit
= 0;
869 db
->lookaside
.pSmallFree
= 0;
870 db
->lookaside
.pMiddle
= 0;
871 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
872 db
->lookaside
.pEnd
= 0;
873 db
->lookaside
.bDisable
= 1;
874 db
->lookaside
.sz
= 0;
875 db
->lookaside
.bMalloced
= 0;
876 db
->lookaside
.nSlot
= 0;
878 db
->lookaside
.pTrueEnd
= db
->lookaside
.pEnd
;
879 assert( sqlite3LookasideUsed(db
,0)==0 );
880 #endif /* SQLITE_OMIT_LOOKASIDE */
885 ** Return the mutex associated with a database connection.
887 sqlite3_mutex
*sqlite3_db_mutex(sqlite3
*db
){
888 #ifdef SQLITE_ENABLE_API_ARMOR
889 if( !sqlite3SafetyCheckOk(db
) ){
890 (void)SQLITE_MISUSE_BKPT
;
898 ** Free up as much memory as we can from the given database
901 int sqlite3_db_release_memory(sqlite3
*db
){
904 #ifdef SQLITE_ENABLE_API_ARMOR
905 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
907 sqlite3_mutex_enter(db
->mutex
);
908 sqlite3BtreeEnterAll(db
);
909 for(i
=0; i
<db
->nDb
; i
++){
910 Btree
*pBt
= db
->aDb
[i
].pBt
;
912 Pager
*pPager
= sqlite3BtreePager(pBt
);
913 sqlite3PagerShrink(pPager
);
916 sqlite3BtreeLeaveAll(db
);
917 sqlite3_mutex_leave(db
->mutex
);
922 ** Flush any dirty pages in the pager-cache for any attached database
925 int sqlite3_db_cacheflush(sqlite3
*db
){
930 #ifdef SQLITE_ENABLE_API_ARMOR
931 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
933 sqlite3_mutex_enter(db
->mutex
);
934 sqlite3BtreeEnterAll(db
);
935 for(i
=0; rc
==SQLITE_OK
&& i
<db
->nDb
; i
++){
936 Btree
*pBt
= db
->aDb
[i
].pBt
;
937 if( pBt
&& sqlite3BtreeTxnState(pBt
)==SQLITE_TXN_WRITE
){
938 Pager
*pPager
= sqlite3BtreePager(pBt
);
939 rc
= sqlite3PagerFlush(pPager
);
940 if( rc
==SQLITE_BUSY
){
946 sqlite3BtreeLeaveAll(db
);
947 sqlite3_mutex_leave(db
->mutex
);
948 return ((rc
==SQLITE_OK
&& bSeenBusy
) ? SQLITE_BUSY
: rc
);
952 ** Configuration settings for an individual database connection
954 int sqlite3_db_config(sqlite3
*db
, int op
, ...){
957 sqlite3_mutex_enter(db
->mutex
);
960 case SQLITE_DBCONFIG_MAINDBNAME
: {
961 /* IMP: R-06824-28531 */
962 /* IMP: R-36257-52125 */
963 db
->aDb
[0].zDbSName
= va_arg(ap
,char*);
967 case SQLITE_DBCONFIG_LOOKASIDE
: {
968 void *pBuf
= va_arg(ap
, void*); /* IMP: R-26835-10964 */
969 int sz
= va_arg(ap
, int); /* IMP: R-47871-25994 */
970 int cnt
= va_arg(ap
, int); /* IMP: R-04460-53386 */
971 rc
= setupLookaside(db
, pBuf
, sz
, cnt
);
975 static const struct {
976 int op
; /* The opcode */
977 u32 mask
; /* Mask of the bit in sqlite3.flags to set/clear */
979 { SQLITE_DBCONFIG_ENABLE_FKEY
, SQLITE_ForeignKeys
},
980 { SQLITE_DBCONFIG_ENABLE_TRIGGER
, SQLITE_EnableTrigger
},
981 { SQLITE_DBCONFIG_ENABLE_VIEW
, SQLITE_EnableView
},
982 { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
, SQLITE_Fts3Tokenizer
},
983 { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
, SQLITE_LoadExtension
},
984 { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE
, SQLITE_NoCkptOnClose
},
985 { SQLITE_DBCONFIG_ENABLE_QPSG
, SQLITE_EnableQPSG
},
986 { SQLITE_DBCONFIG_TRIGGER_EQP
, SQLITE_TriggerEQP
},
987 { SQLITE_DBCONFIG_RESET_DATABASE
, SQLITE_ResetDatabase
},
988 { SQLITE_DBCONFIG_DEFENSIVE
, SQLITE_Defensive
},
989 { SQLITE_DBCONFIG_WRITABLE_SCHEMA
, SQLITE_WriteSchema
|
990 SQLITE_NoSchemaError
},
991 { SQLITE_DBCONFIG_LEGACY_ALTER_TABLE
, SQLITE_LegacyAlter
},
992 { SQLITE_DBCONFIG_DQS_DDL
, SQLITE_DqsDDL
},
993 { SQLITE_DBCONFIG_DQS_DML
, SQLITE_DqsDML
},
994 { SQLITE_DBCONFIG_LEGACY_FILE_FORMAT
, SQLITE_LegacyFileFmt
},
995 { SQLITE_DBCONFIG_TRUSTED_SCHEMA
, SQLITE_TrustedSchema
},
996 { SQLITE_DBCONFIG_STMT_SCANSTATUS
, SQLITE_StmtScanStatus
},
997 { SQLITE_DBCONFIG_REVERSE_SCANORDER
, SQLITE_ReverseOrder
},
1000 rc
= SQLITE_ERROR
; /* IMP: R-42790-23372 */
1001 for(i
=0; i
<ArraySize(aFlagOp
); i
++){
1002 if( aFlagOp
[i
].op
==op
){
1003 int onoff
= va_arg(ap
, int);
1004 int *pRes
= va_arg(ap
, int*);
1005 u64 oldFlags
= db
->flags
;
1007 db
->flags
|= aFlagOp
[i
].mask
;
1008 }else if( onoff
==0 ){
1009 db
->flags
&= ~(u64
)aFlagOp
[i
].mask
;
1011 if( oldFlags
!=db
->flags
){
1012 sqlite3ExpirePreparedStatements(db
, 0);
1015 *pRes
= (db
->flags
& aFlagOp
[i
].mask
)!=0;
1025 sqlite3_mutex_leave(db
->mutex
);
1030 ** This is the default collating function named "BINARY" which is always
1033 static int binCollFunc(
1035 int nKey1
, const void *pKey1
,
1036 int nKey2
, const void *pKey2
1039 UNUSED_PARAMETER(NotUsed
);
1040 n
= nKey1
<nKey2
? nKey1
: nKey2
;
1041 /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
1042 ** strings byte by byte using the memcmp() function from the standard C
1044 assert( pKey1
&& pKey2
);
1045 rc
= memcmp(pKey1
, pKey2
, n
);
1053 ** This is the collating function named "RTRIM" which is always
1054 ** available. Ignore trailing spaces.
1056 static int rtrimCollFunc(
1058 int nKey1
, const void *pKey1
,
1059 int nKey2
, const void *pKey2
1061 const u8
*pK1
= (const u8
*)pKey1
;
1062 const u8
*pK2
= (const u8
*)pKey2
;
1063 while( nKey1
&& pK1
[nKey1
-1]==' ' ) nKey1
--;
1064 while( nKey2
&& pK2
[nKey2
-1]==' ' ) nKey2
--;
1065 return binCollFunc(pUser
, nKey1
, pKey1
, nKey2
, pKey2
);
1069 ** Return true if CollSeq is the default built-in BINARY.
1071 int sqlite3IsBinary(const CollSeq
*p
){
1072 assert( p
==0 || p
->xCmp
!=binCollFunc
|| strcmp(p
->zName
,"BINARY")==0 );
1073 return p
==0 || p
->xCmp
==binCollFunc
;
1077 ** Another built-in collating sequence: NOCASE.
1079 ** This collating sequence is intended to be used for "case independent
1080 ** comparison". SQLite's knowledge of upper and lower case equivalents
1081 ** extends only to the 26 characters used in the English language.
1083 ** At the moment there is only a UTF-8 implementation.
1085 static int nocaseCollatingFunc(
1087 int nKey1
, const void *pKey1
,
1088 int nKey2
, const void *pKey2
1090 int r
= sqlite3StrNICmp(
1091 (const char *)pKey1
, (const char *)pKey2
, (nKey1
<nKey2
)?nKey1
:nKey2
);
1092 UNUSED_PARAMETER(NotUsed
);
1100 ** Return the ROWID of the most recent insert
1102 sqlite_int64
sqlite3_last_insert_rowid(sqlite3
*db
){
1103 #ifdef SQLITE_ENABLE_API_ARMOR
1104 if( !sqlite3SafetyCheckOk(db
) ){
1105 (void)SQLITE_MISUSE_BKPT
;
1109 return db
->lastRowid
;
1113 ** Set the value returned by the sqlite3_last_insert_rowid() API function.
1115 void sqlite3_set_last_insert_rowid(sqlite3
*db
, sqlite3_int64 iRowid
){
1116 #ifdef SQLITE_ENABLE_API_ARMOR
1117 if( !sqlite3SafetyCheckOk(db
) ){
1118 (void)SQLITE_MISUSE_BKPT
;
1122 sqlite3_mutex_enter(db
->mutex
);
1123 db
->lastRowid
= iRowid
;
1124 sqlite3_mutex_leave(db
->mutex
);
1128 ** Return the number of changes in the most recent call to sqlite3_exec().
1130 sqlite3_int64
sqlite3_changes64(sqlite3
*db
){
1131 #ifdef SQLITE_ENABLE_API_ARMOR
1132 if( !sqlite3SafetyCheckOk(db
) ){
1133 (void)SQLITE_MISUSE_BKPT
;
1139 int sqlite3_changes(sqlite3
*db
){
1140 return (int)sqlite3_changes64(db
);
1144 ** Return the number of changes since the database handle was opened.
1146 sqlite3_int64
sqlite3_total_changes64(sqlite3
*db
){
1147 #ifdef SQLITE_ENABLE_API_ARMOR
1148 if( !sqlite3SafetyCheckOk(db
) ){
1149 (void)SQLITE_MISUSE_BKPT
;
1153 return db
->nTotalChange
;
1155 int sqlite3_total_changes(sqlite3
*db
){
1156 return (int)sqlite3_total_changes64(db
);
1160 ** Close all open savepoints. This function only manipulates fields of the
1161 ** database handle object, it does not close any savepoints that may be open
1162 ** at the b-tree/pager level.
1164 void sqlite3CloseSavepoints(sqlite3
*db
){
1165 while( db
->pSavepoint
){
1166 Savepoint
*pTmp
= db
->pSavepoint
;
1167 db
->pSavepoint
= pTmp
->pNext
;
1168 sqlite3DbFree(db
, pTmp
);
1172 db
->isTransactionSavepoint
= 0;
1176 ** Invoke the destructor function associated with FuncDef p, if any. Except,
1177 ** if this is not the last copy of the function, do not invoke it. Multiple
1178 ** copies of a single function are created when create_function() is called
1179 ** with SQLITE_ANY as the encoding.
1181 static void functionDestroy(sqlite3
*db
, FuncDef
*p
){
1182 FuncDestructor
*pDestructor
;
1183 assert( (p
->funcFlags
& SQLITE_FUNC_BUILTIN
)==0 );
1184 pDestructor
= p
->u
.pDestructor
;
1186 pDestructor
->nRef
--;
1187 if( pDestructor
->nRef
==0 ){
1188 pDestructor
->xDestroy(pDestructor
->pUserData
);
1189 sqlite3DbFree(db
, pDestructor
);
1195 ** Disconnect all sqlite3_vtab objects that belong to database connection
1196 ** db. This is called when db is being closed.
1198 static void disconnectAllVtab(sqlite3
*db
){
1199 #ifndef SQLITE_OMIT_VIRTUALTABLE
1202 sqlite3BtreeEnterAll(db
);
1203 for(i
=0; i
<db
->nDb
; i
++){
1204 Schema
*pSchema
= db
->aDb
[i
].pSchema
;
1206 for(p
=sqliteHashFirst(&pSchema
->tblHash
); p
; p
=sqliteHashNext(p
)){
1207 Table
*pTab
= (Table
*)sqliteHashData(p
);
1208 if( IsVirtual(pTab
) ) sqlite3VtabDisconnect(db
, pTab
);
1212 for(p
=sqliteHashFirst(&db
->aModule
); p
; p
=sqliteHashNext(p
)){
1213 Module
*pMod
= (Module
*)sqliteHashData(p
);
1214 if( pMod
->pEpoTab
){
1215 sqlite3VtabDisconnect(db
, pMod
->pEpoTab
);
1218 sqlite3VtabUnlockList(db
);
1219 sqlite3BtreeLeaveAll(db
);
1221 UNUSED_PARAMETER(db
);
1226 ** Return TRUE if database connection db has unfinalized prepared
1227 ** statements or unfinished sqlite3_backup objects.
1229 static int connectionIsBusy(sqlite3
*db
){
1231 assert( sqlite3_mutex_held(db
->mutex
) );
1232 if( db
->pVdbe
) return 1;
1233 for(j
=0; j
<db
->nDb
; j
++){
1234 Btree
*pBt
= db
->aDb
[j
].pBt
;
1235 if( pBt
&& sqlite3BtreeIsInBackup(pBt
) ) return 1;
1241 ** Close an existing SQLite database
1243 static int sqlite3Close(sqlite3
*db
, int forceZombie
){
1245 /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
1246 ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
1249 if( !sqlite3SafetyCheckSickOrOk(db
) ){
1250 return SQLITE_MISUSE_BKPT
;
1252 sqlite3_mutex_enter(db
->mutex
);
1253 if( db
->mTrace
& SQLITE_TRACE_CLOSE
){
1254 db
->trace
.xV2(SQLITE_TRACE_CLOSE
, db
->pTraceArg
, db
, 0);
1257 /* Force xDisconnect calls on all virtual tables */
1258 disconnectAllVtab(db
);
1260 /* If a transaction is open, the disconnectAllVtab() call above
1261 ** will not have called the xDisconnect() method on any virtual
1262 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
1263 ** call will do so. We need to do this before the check for active
1264 ** SQL statements below, as the v-table implementation may be storing
1265 ** some prepared statements internally.
1267 sqlite3VtabRollback(db
);
1269 /* Legacy behavior (sqlite3_close() behavior) is to return
1270 ** SQLITE_BUSY if the connection can not be closed immediately.
1272 if( !forceZombie
&& connectionIsBusy(db
) ){
1273 sqlite3ErrorWithMsg(db
, SQLITE_BUSY
, "unable to close due to unfinalized "
1274 "statements or unfinished backups");
1275 sqlite3_mutex_leave(db
->mutex
);
1279 #ifdef SQLITE_ENABLE_SQLLOG
1280 if( sqlite3GlobalConfig
.xSqllog
){
1281 /* Closing the handle. Fourth parameter is passed the value 2. */
1282 sqlite3GlobalConfig
.xSqllog(sqlite3GlobalConfig
.pSqllogArg
, db
, 0, 2);
1286 while( db
->pDbData
){
1287 DbClientData
*p
= db
->pDbData
;
1288 db
->pDbData
= p
->pNext
;
1289 assert( p
->pData
!=0 );
1290 if( p
->xDestructor
) p
->xDestructor(p
->pData
);
1294 /* Convert the connection into a zombie and then close it.
1296 db
->eOpenState
= SQLITE_STATE_ZOMBIE
;
1297 sqlite3LeaveMutexAndCloseZombie(db
);
1302 ** Return the transaction state for a single databse, or the maximum
1303 ** transaction state over all attached databases if zSchema is null.
1305 int sqlite3_txn_state(sqlite3
*db
, const char *zSchema
){
1308 #ifdef SQLITE_ENABLE_API_ARMOR
1309 if( !sqlite3SafetyCheckOk(db
) ){
1310 (void)SQLITE_MISUSE_BKPT
;
1314 sqlite3_mutex_enter(db
->mutex
);
1316 nDb
= iDb
= sqlite3FindDbName(db
, zSchema
);
1322 for(; iDb
<=nDb
; iDb
++){
1323 Btree
*pBt
= db
->aDb
[iDb
].pBt
;
1324 int x
= pBt
!=0 ? sqlite3BtreeTxnState(pBt
) : SQLITE_TXN_NONE
;
1325 if( x
>iTxn
) iTxn
= x
;
1327 sqlite3_mutex_leave(db
->mutex
);
1332 ** Two variations on the public interface for closing a database
1333 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
1334 ** leaves the connection open if there are unfinalized prepared
1335 ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
1336 ** version forces the connection to become a zombie if there are
1337 ** unclosed resources, and arranges for deallocation when the last
1338 ** prepare statement or sqlite3_backup closes.
1340 int sqlite3_close(sqlite3
*db
){ return sqlite3Close(db
,0); }
1341 int sqlite3_close_v2(sqlite3
*db
){ return sqlite3Close(db
,1); }
1345 ** Close the mutex on database connection db.
1347 ** Furthermore, if database connection db is a zombie (meaning that there
1348 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
1349 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
1350 ** finished, then free all resources.
1352 void sqlite3LeaveMutexAndCloseZombie(sqlite3
*db
){
1353 HashElem
*i
; /* Hash table iterator */
1356 /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
1357 ** or if the connection has not yet been closed by sqlite3_close_v2(),
1358 ** then just leave the mutex and return.
1360 if( db
->eOpenState
!=SQLITE_STATE_ZOMBIE
|| connectionIsBusy(db
) ){
1361 sqlite3_mutex_leave(db
->mutex
);
1365 /* If we reach this point, it means that the database connection has
1366 ** closed all sqlite3_stmt and sqlite3_backup objects and has been
1367 ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
1368 ** go ahead and free all resources.
1371 /* If a transaction is open, roll it back. This also ensures that if
1372 ** any database schemas have been modified by an uncommitted transaction
1373 ** they are reset. And that the required b-tree mutex is held to make
1374 ** the pager rollback and schema reset an atomic operation. */
1375 sqlite3RollbackAll(db
, SQLITE_OK
);
1377 /* Free any outstanding Savepoint structures. */
1378 sqlite3CloseSavepoints(db
);
1380 /* Close all database connections */
1381 for(j
=0; j
<db
->nDb
; j
++){
1382 struct Db
*pDb
= &db
->aDb
[j
];
1384 sqlite3BtreeClose(pDb
->pBt
);
1391 /* Clear the TEMP schema separately and last */
1392 if( db
->aDb
[1].pSchema
){
1393 sqlite3SchemaClear(db
->aDb
[1].pSchema
);
1395 sqlite3VtabUnlockList(db
);
1397 /* Free up the array of auxiliary databases */
1398 sqlite3CollapseDatabaseArray(db
);
1399 assert( db
->nDb
<=2 );
1400 assert( db
->aDb
==db
->aDbStatic
);
1402 /* Tell the code in notify.c that the connection no longer holds any
1403 ** locks and does not require any further unlock-notify callbacks.
1405 sqlite3ConnectionClosed(db
);
1407 for(i
=sqliteHashFirst(&db
->aFunc
); i
; i
=sqliteHashNext(i
)){
1409 p
= sqliteHashData(i
);
1411 functionDestroy(db
, p
);
1413 sqlite3DbFree(db
, p
);
1417 sqlite3HashClear(&db
->aFunc
);
1418 for(i
=sqliteHashFirst(&db
->aCollSeq
); i
; i
=sqliteHashNext(i
)){
1419 CollSeq
*pColl
= (CollSeq
*)sqliteHashData(i
);
1420 /* Invoke any destructors registered for collation sequence user data. */
1422 if( pColl
[j
].xDel
){
1423 pColl
[j
].xDel(pColl
[j
].pUser
);
1426 sqlite3DbFree(db
, pColl
);
1428 sqlite3HashClear(&db
->aCollSeq
);
1429 #ifndef SQLITE_OMIT_VIRTUALTABLE
1430 for(i
=sqliteHashFirst(&db
->aModule
); i
; i
=sqliteHashNext(i
)){
1431 Module
*pMod
= (Module
*)sqliteHashData(i
);
1432 sqlite3VtabEponymousTableClear(db
, pMod
);
1433 sqlite3VtabModuleUnref(db
, pMod
);
1435 sqlite3HashClear(&db
->aModule
);
1438 sqlite3Error(db
, SQLITE_OK
); /* Deallocates any cached error strings. */
1439 sqlite3ValueFree(db
->pErr
);
1440 sqlite3CloseExtensions(db
);
1441 #if SQLITE_USER_AUTHENTICATION
1442 sqlite3_free(db
->auth
.zAuthUser
);
1443 sqlite3_free(db
->auth
.zAuthPW
);
1446 db
->eOpenState
= SQLITE_STATE_ERROR
;
1448 /* The temp-database schema is allocated differently from the other schema
1449 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
1450 ** So it needs to be freed here. Todo: Why not roll the temp schema into
1451 ** the same sqliteMalloc() as the one that allocates the database
1454 sqlite3DbFree(db
, db
->aDb
[1].pSchema
);
1455 if( db
->xAutovacDestr
){
1456 db
->xAutovacDestr(db
->pAutovacPagesArg
);
1458 sqlite3_mutex_leave(db
->mutex
);
1459 db
->eOpenState
= SQLITE_STATE_CLOSED
;
1460 sqlite3_mutex_free(db
->mutex
);
1461 assert( sqlite3LookasideUsed(db
,0)==0 );
1462 if( db
->lookaside
.bMalloced
){
1463 sqlite3_free(db
->lookaside
.pStart
);
1469 ** Rollback all database files. If tripCode is not SQLITE_OK, then
1470 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
1471 ** breaker") and made to return tripCode if there are any further
1472 ** attempts to use that cursor. Read cursors remain open and valid
1473 ** but are "saved" in case the table pages are moved around.
1475 void sqlite3RollbackAll(sqlite3
*db
, int tripCode
){
1479 assert( sqlite3_mutex_held(db
->mutex
) );
1480 sqlite3BeginBenignMalloc();
1482 /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
1483 ** This is important in case the transaction being rolled back has
1484 ** modified the database schema. If the b-tree mutexes are not taken
1485 ** here, then another shared-cache connection might sneak in between
1486 ** the database rollback and schema reset, which can cause false
1487 ** corruption reports in some cases. */
1488 sqlite3BtreeEnterAll(db
);
1489 schemaChange
= (db
->mDbFlags
& DBFLAG_SchemaChange
)!=0 && db
->init
.busy
==0;
1491 for(i
=0; i
<db
->nDb
; i
++){
1492 Btree
*p
= db
->aDb
[i
].pBt
;
1494 if( sqlite3BtreeTxnState(p
)==SQLITE_TXN_WRITE
){
1497 sqlite3BtreeRollback(p
, tripCode
, !schemaChange
);
1500 sqlite3VtabRollback(db
);
1501 sqlite3EndBenignMalloc();
1504 sqlite3ExpirePreparedStatements(db
, 0);
1505 sqlite3ResetAllSchemasOfConnection(db
);
1507 sqlite3BtreeLeaveAll(db
);
1509 /* Any deferred constraint violations have now been resolved. */
1510 db
->nDeferredCons
= 0;
1511 db
->nDeferredImmCons
= 0;
1512 db
->flags
&= ~(u64
)(SQLITE_DeferFKs
|SQLITE_CorruptRdOnly
);
1514 /* If one has been configured, invoke the rollback-hook callback */
1515 if( db
->xRollbackCallback
&& (inTrans
|| !db
->autoCommit
) ){
1516 db
->xRollbackCallback(db
->pRollbackArg
);
1521 ** Return a static string containing the name corresponding to the error code
1522 ** specified in the argument.
1524 #if defined(SQLITE_NEED_ERR_NAME)
1525 const char *sqlite3ErrName(int rc
){
1526 const char *zName
= 0;
1528 for(i
=0; i
<2 && zName
==0; i
++, rc
&= 0xff){
1530 case SQLITE_OK
: zName
= "SQLITE_OK"; break;
1531 case SQLITE_ERROR
: zName
= "SQLITE_ERROR"; break;
1532 case SQLITE_ERROR_SNAPSHOT
: zName
= "SQLITE_ERROR_SNAPSHOT"; break;
1533 case SQLITE_INTERNAL
: zName
= "SQLITE_INTERNAL"; break;
1534 case SQLITE_PERM
: zName
= "SQLITE_PERM"; break;
1535 case SQLITE_ABORT
: zName
= "SQLITE_ABORT"; break;
1536 case SQLITE_ABORT_ROLLBACK
: zName
= "SQLITE_ABORT_ROLLBACK"; break;
1537 case SQLITE_BUSY
: zName
= "SQLITE_BUSY"; break;
1538 case SQLITE_BUSY_RECOVERY
: zName
= "SQLITE_BUSY_RECOVERY"; break;
1539 case SQLITE_BUSY_SNAPSHOT
: zName
= "SQLITE_BUSY_SNAPSHOT"; break;
1540 case SQLITE_LOCKED
: zName
= "SQLITE_LOCKED"; break;
1541 case SQLITE_LOCKED_SHAREDCACHE
: zName
= "SQLITE_LOCKED_SHAREDCACHE";break;
1542 case SQLITE_NOMEM
: zName
= "SQLITE_NOMEM"; break;
1543 case SQLITE_READONLY
: zName
= "SQLITE_READONLY"; break;
1544 case SQLITE_READONLY_RECOVERY
: zName
= "SQLITE_READONLY_RECOVERY"; break;
1545 case SQLITE_READONLY_CANTINIT
: zName
= "SQLITE_READONLY_CANTINIT"; break;
1546 case SQLITE_READONLY_ROLLBACK
: zName
= "SQLITE_READONLY_ROLLBACK"; break;
1547 case SQLITE_READONLY_DBMOVED
: zName
= "SQLITE_READONLY_DBMOVED"; break;
1548 case SQLITE_READONLY_DIRECTORY
: zName
= "SQLITE_READONLY_DIRECTORY";break;
1549 case SQLITE_INTERRUPT
: zName
= "SQLITE_INTERRUPT"; break;
1550 case SQLITE_IOERR
: zName
= "SQLITE_IOERR"; break;
1551 case SQLITE_IOERR_READ
: zName
= "SQLITE_IOERR_READ"; break;
1552 case SQLITE_IOERR_SHORT_READ
: zName
= "SQLITE_IOERR_SHORT_READ"; break;
1553 case SQLITE_IOERR_WRITE
: zName
= "SQLITE_IOERR_WRITE"; break;
1554 case SQLITE_IOERR_FSYNC
: zName
= "SQLITE_IOERR_FSYNC"; break;
1555 case SQLITE_IOERR_DIR_FSYNC
: zName
= "SQLITE_IOERR_DIR_FSYNC"; break;
1556 case SQLITE_IOERR_TRUNCATE
: zName
= "SQLITE_IOERR_TRUNCATE"; break;
1557 case SQLITE_IOERR_FSTAT
: zName
= "SQLITE_IOERR_FSTAT"; break;
1558 case SQLITE_IOERR_UNLOCK
: zName
= "SQLITE_IOERR_UNLOCK"; break;
1559 case SQLITE_IOERR_RDLOCK
: zName
= "SQLITE_IOERR_RDLOCK"; break;
1560 case SQLITE_IOERR_DELETE
: zName
= "SQLITE_IOERR_DELETE"; break;
1561 case SQLITE_IOERR_NOMEM
: zName
= "SQLITE_IOERR_NOMEM"; break;
1562 case SQLITE_IOERR_ACCESS
: zName
= "SQLITE_IOERR_ACCESS"; break;
1563 case SQLITE_IOERR_CHECKRESERVEDLOCK
:
1564 zName
= "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
1565 case SQLITE_IOERR_LOCK
: zName
= "SQLITE_IOERR_LOCK"; break;
1566 case SQLITE_IOERR_CLOSE
: zName
= "SQLITE_IOERR_CLOSE"; break;
1567 case SQLITE_IOERR_DIR_CLOSE
: zName
= "SQLITE_IOERR_DIR_CLOSE"; break;
1568 case SQLITE_IOERR_SHMOPEN
: zName
= "SQLITE_IOERR_SHMOPEN"; break;
1569 case SQLITE_IOERR_SHMSIZE
: zName
= "SQLITE_IOERR_SHMSIZE"; break;
1570 case SQLITE_IOERR_SHMLOCK
: zName
= "SQLITE_IOERR_SHMLOCK"; break;
1571 case SQLITE_IOERR_SHMMAP
: zName
= "SQLITE_IOERR_SHMMAP"; break;
1572 case SQLITE_IOERR_SEEK
: zName
= "SQLITE_IOERR_SEEK"; break;
1573 case SQLITE_IOERR_DELETE_NOENT
: zName
= "SQLITE_IOERR_DELETE_NOENT";break;
1574 case SQLITE_IOERR_MMAP
: zName
= "SQLITE_IOERR_MMAP"; break;
1575 case SQLITE_IOERR_GETTEMPPATH
: zName
= "SQLITE_IOERR_GETTEMPPATH"; break;
1576 case SQLITE_IOERR_CONVPATH
: zName
= "SQLITE_IOERR_CONVPATH"; break;
1577 case SQLITE_CORRUPT
: zName
= "SQLITE_CORRUPT"; break;
1578 case SQLITE_CORRUPT_VTAB
: zName
= "SQLITE_CORRUPT_VTAB"; break;
1579 case SQLITE_NOTFOUND
: zName
= "SQLITE_NOTFOUND"; break;
1580 case SQLITE_FULL
: zName
= "SQLITE_FULL"; break;
1581 case SQLITE_CANTOPEN
: zName
= "SQLITE_CANTOPEN"; break;
1582 case SQLITE_CANTOPEN_NOTEMPDIR
: zName
= "SQLITE_CANTOPEN_NOTEMPDIR";break;
1583 case SQLITE_CANTOPEN_ISDIR
: zName
= "SQLITE_CANTOPEN_ISDIR"; break;
1584 case SQLITE_CANTOPEN_FULLPATH
: zName
= "SQLITE_CANTOPEN_FULLPATH"; break;
1585 case SQLITE_CANTOPEN_CONVPATH
: zName
= "SQLITE_CANTOPEN_CONVPATH"; break;
1586 case SQLITE_CANTOPEN_SYMLINK
: zName
= "SQLITE_CANTOPEN_SYMLINK"; break;
1587 case SQLITE_PROTOCOL
: zName
= "SQLITE_PROTOCOL"; break;
1588 case SQLITE_EMPTY
: zName
= "SQLITE_EMPTY"; break;
1589 case SQLITE_SCHEMA
: zName
= "SQLITE_SCHEMA"; break;
1590 case SQLITE_TOOBIG
: zName
= "SQLITE_TOOBIG"; break;
1591 case SQLITE_CONSTRAINT
: zName
= "SQLITE_CONSTRAINT"; break;
1592 case SQLITE_CONSTRAINT_UNIQUE
: zName
= "SQLITE_CONSTRAINT_UNIQUE"; break;
1593 case SQLITE_CONSTRAINT_TRIGGER
: zName
= "SQLITE_CONSTRAINT_TRIGGER";break;
1594 case SQLITE_CONSTRAINT_FOREIGNKEY
:
1595 zName
= "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
1596 case SQLITE_CONSTRAINT_CHECK
: zName
= "SQLITE_CONSTRAINT_CHECK"; break;
1597 case SQLITE_CONSTRAINT_PRIMARYKEY
:
1598 zName
= "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
1599 case SQLITE_CONSTRAINT_NOTNULL
: zName
= "SQLITE_CONSTRAINT_NOTNULL";break;
1600 case SQLITE_CONSTRAINT_COMMITHOOK
:
1601 zName
= "SQLITE_CONSTRAINT_COMMITHOOK"; break;
1602 case SQLITE_CONSTRAINT_VTAB
: zName
= "SQLITE_CONSTRAINT_VTAB"; break;
1603 case SQLITE_CONSTRAINT_FUNCTION
:
1604 zName
= "SQLITE_CONSTRAINT_FUNCTION"; break;
1605 case SQLITE_CONSTRAINT_ROWID
: zName
= "SQLITE_CONSTRAINT_ROWID"; break;
1606 case SQLITE_MISMATCH
: zName
= "SQLITE_MISMATCH"; break;
1607 case SQLITE_MISUSE
: zName
= "SQLITE_MISUSE"; break;
1608 case SQLITE_NOLFS
: zName
= "SQLITE_NOLFS"; break;
1609 case SQLITE_AUTH
: zName
= "SQLITE_AUTH"; break;
1610 case SQLITE_FORMAT
: zName
= "SQLITE_FORMAT"; break;
1611 case SQLITE_RANGE
: zName
= "SQLITE_RANGE"; break;
1612 case SQLITE_NOTADB
: zName
= "SQLITE_NOTADB"; break;
1613 case SQLITE_ROW
: zName
= "SQLITE_ROW"; break;
1614 case SQLITE_NOTICE
: zName
= "SQLITE_NOTICE"; break;
1615 case SQLITE_NOTICE_RECOVER_WAL
: zName
= "SQLITE_NOTICE_RECOVER_WAL";break;
1616 case SQLITE_NOTICE_RECOVER_ROLLBACK
:
1617 zName
= "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
1618 case SQLITE_NOTICE_RBU
: zName
= "SQLITE_NOTICE_RBU"; break;
1619 case SQLITE_WARNING
: zName
= "SQLITE_WARNING"; break;
1620 case SQLITE_WARNING_AUTOINDEX
: zName
= "SQLITE_WARNING_AUTOINDEX"; break;
1621 case SQLITE_DONE
: zName
= "SQLITE_DONE"; break;
1625 static char zBuf
[50];
1626 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "SQLITE_UNKNOWN(%d)", origRc
);
1634 ** Return a static string that describes the kind of error specified in the
1637 const char *sqlite3ErrStr(int rc
){
1638 static const char* const aMsg
[] = {
1639 /* SQLITE_OK */ "not an error",
1640 /* SQLITE_ERROR */ "SQL logic error",
1641 /* SQLITE_INTERNAL */ 0,
1642 /* SQLITE_PERM */ "access permission denied",
1643 /* SQLITE_ABORT */ "query aborted",
1644 /* SQLITE_BUSY */ "database is locked",
1645 /* SQLITE_LOCKED */ "database table is locked",
1646 /* SQLITE_NOMEM */ "out of memory",
1647 /* SQLITE_READONLY */ "attempt to write a readonly database",
1648 /* SQLITE_INTERRUPT */ "interrupted",
1649 /* SQLITE_IOERR */ "disk I/O error",
1650 /* SQLITE_CORRUPT */ "database disk image is malformed",
1651 /* SQLITE_NOTFOUND */ "unknown operation",
1652 /* SQLITE_FULL */ "database or disk is full",
1653 /* SQLITE_CANTOPEN */ "unable to open database file",
1654 /* SQLITE_PROTOCOL */ "locking protocol",
1655 /* SQLITE_EMPTY */ 0,
1656 /* SQLITE_SCHEMA */ "database schema has changed",
1657 /* SQLITE_TOOBIG */ "string or blob too big",
1658 /* SQLITE_CONSTRAINT */ "constraint failed",
1659 /* SQLITE_MISMATCH */ "datatype mismatch",
1660 /* SQLITE_MISUSE */ "bad parameter or other API misuse",
1661 #ifdef SQLITE_DISABLE_LFS
1662 /* SQLITE_NOLFS */ "large file support is disabled",
1664 /* SQLITE_NOLFS */ 0,
1666 /* SQLITE_AUTH */ "authorization denied",
1667 /* SQLITE_FORMAT */ 0,
1668 /* SQLITE_RANGE */ "column index out of range",
1669 /* SQLITE_NOTADB */ "file is not a database",
1670 /* SQLITE_NOTICE */ "notification message",
1671 /* SQLITE_WARNING */ "warning message",
1673 const char *zErr
= "unknown error";
1675 case SQLITE_ABORT_ROLLBACK
: {
1676 zErr
= "abort due to ROLLBACK";
1680 zErr
= "another row available";
1684 zErr
= "no more rows available";
1689 if( ALWAYS(rc
>=0) && rc
<ArraySize(aMsg
) && aMsg
[rc
]!=0 ){
1699 ** This routine implements a busy callback that sleeps and tries
1700 ** again until a timeout value is reached. The timeout value is
1701 ** an integer number of milliseconds passed in as the first
1704 ** Return non-zero to retry the lock. Return zero to stop trying
1705 ** and cause SQLite to return SQLITE_BUSY.
1707 static int sqliteDefaultBusyCallback(
1708 void *ptr
, /* Database connection */
1709 int count
/* Number of times table has been busy */
1711 #if SQLITE_OS_WIN || !defined(HAVE_NANOSLEEP) || HAVE_NANOSLEEP
1712 /* This case is for systems that have support for sleeping for fractions of
1713 ** a second. Examples: All windows systems, unix systems with nanosleep() */
1714 static const u8 delays
[] =
1715 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
1716 static const u8 totals
[] =
1717 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
1718 # define NDELAY ArraySize(delays)
1719 sqlite3
*db
= (sqlite3
*)ptr
;
1720 int tmout
= db
->busyTimeout
;
1724 if( count
< NDELAY
){
1725 delay
= delays
[count
];
1726 prior
= totals
[count
];
1728 delay
= delays
[NDELAY
-1];
1729 prior
= totals
[NDELAY
-1] + delay
*(count
-(NDELAY
-1));
1731 if( prior
+ delay
> tmout
){
1732 delay
= tmout
- prior
;
1733 if( delay
<=0 ) return 0;
1735 sqlite3OsSleep(db
->pVfs
, delay
*1000);
1738 /* This case for unix systems that lack usleep() support. Sleeping
1739 ** must be done in increments of whole seconds */
1740 sqlite3
*db
= (sqlite3
*)ptr
;
1741 int tmout
= ((sqlite3
*)ptr
)->busyTimeout
;
1742 if( (count
+1)*1000 > tmout
){
1745 sqlite3OsSleep(db
->pVfs
, 1000000);
1751 ** Invoke the given busy handler.
1753 ** This routine is called when an operation failed to acquire a
1754 ** lock on VFS file pFile.
1756 ** If this routine returns non-zero, the lock is retried. If it
1757 ** returns 0, the operation aborts with an SQLITE_BUSY error.
1759 int sqlite3InvokeBusyHandler(BusyHandler
*p
){
1761 if( p
->xBusyHandler
==0 || p
->nBusy
<0 ) return 0;
1762 rc
= p
->xBusyHandler(p
->pBusyArg
, p
->nBusy
);
1772 ** This routine sets the busy callback for an Sqlite database to the
1773 ** given callback function with the given argument.
1775 int sqlite3_busy_handler(
1777 int (*xBusy
)(void*,int),
1780 #ifdef SQLITE_ENABLE_API_ARMOR
1781 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
1783 sqlite3_mutex_enter(db
->mutex
);
1784 db
->busyHandler
.xBusyHandler
= xBusy
;
1785 db
->busyHandler
.pBusyArg
= pArg
;
1786 db
->busyHandler
.nBusy
= 0;
1787 db
->busyTimeout
= 0;
1788 sqlite3_mutex_leave(db
->mutex
);
1792 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1794 ** This routine sets the progress callback for an Sqlite database to the
1795 ** given callback function with the given argument. The progress callback will
1796 ** be invoked every nOps opcodes.
1798 void sqlite3_progress_handler(
1801 int (*xProgress
)(void*),
1804 #ifdef SQLITE_ENABLE_API_ARMOR
1805 if( !sqlite3SafetyCheckOk(db
) ){
1806 (void)SQLITE_MISUSE_BKPT
;
1810 sqlite3_mutex_enter(db
->mutex
);
1812 db
->xProgress
= xProgress
;
1813 db
->nProgressOps
= (unsigned)nOps
;
1814 db
->pProgressArg
= pArg
;
1817 db
->nProgressOps
= 0;
1818 db
->pProgressArg
= 0;
1820 sqlite3_mutex_leave(db
->mutex
);
1826 ** This routine installs a default busy handler that waits for the
1827 ** specified number of milliseconds before returning 0.
1829 int sqlite3_busy_timeout(sqlite3
*db
, int ms
){
1830 #ifdef SQLITE_ENABLE_API_ARMOR
1831 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
1834 sqlite3_busy_handler(db
, (int(*)(void*,int))sqliteDefaultBusyCallback
,
1836 db
->busyTimeout
= ms
;
1838 sqlite3_busy_handler(db
, 0, 0);
1844 ** Cause any pending operation to stop at its earliest opportunity.
1846 void sqlite3_interrupt(sqlite3
*db
){
1847 #ifdef SQLITE_ENABLE_API_ARMOR
1848 if( !sqlite3SafetyCheckOk(db
)
1849 && (db
==0 || db
->eOpenState
!=SQLITE_STATE_ZOMBIE
)
1851 (void)SQLITE_MISUSE_BKPT
;
1855 AtomicStore(&db
->u1
.isInterrupted
, 1);
1859 ** Return true or false depending on whether or not an interrupt is
1860 ** pending on connection db.
1862 int sqlite3_is_interrupted(sqlite3
*db
){
1863 #ifdef SQLITE_ENABLE_API_ARMOR
1864 if( !sqlite3SafetyCheckOk(db
)
1865 && (db
==0 || db
->eOpenState
!=SQLITE_STATE_ZOMBIE
)
1867 (void)SQLITE_MISUSE_BKPT
;
1871 return AtomicLoad(&db
->u1
.isInterrupted
)!=0;
1875 ** This function is exactly the same as sqlite3_create_function(), except
1876 ** that it is designed to be called by internal code. The difference is
1877 ** that if a malloc() fails in sqlite3_create_function(), an error code
1878 ** is returned and the mallocFailed flag cleared.
1880 int sqlite3CreateFunc(
1882 const char *zFunctionName
,
1886 void (*xSFunc
)(sqlite3_context
*,int,sqlite3_value
**),
1887 void (*xStep
)(sqlite3_context
*,int,sqlite3_value
**),
1888 void (*xFinal
)(sqlite3_context
*),
1889 void (*xValue
)(sqlite3_context
*),
1890 void (*xInverse
)(sqlite3_context
*,int,sqlite3_value
**),
1891 FuncDestructor
*pDestructor
1896 assert( sqlite3_mutex_held(db
->mutex
) );
1897 assert( xValue
==0 || xSFunc
==0 );
1898 if( zFunctionName
==0 /* Must have a valid name */
1899 || (xSFunc
!=0 && xFinal
!=0) /* Not both xSFunc and xFinal */
1900 || ((xFinal
==0)!=(xStep
==0)) /* Both or neither of xFinal and xStep */
1901 || ((xValue
==0)!=(xInverse
==0)) /* Both or neither of xValue, xInverse */
1902 || (nArg
<-1 || nArg
>SQLITE_MAX_FUNCTION_ARG
)
1903 || (255<sqlite3Strlen30(zFunctionName
))
1905 return SQLITE_MISUSE_BKPT
;
1908 assert( SQLITE_FUNC_CONSTANT
==SQLITE_DETERMINISTIC
);
1909 assert( SQLITE_FUNC_DIRECT
==SQLITE_DIRECTONLY
);
1910 extraFlags
= enc
& (SQLITE_DETERMINISTIC
|SQLITE_DIRECTONLY
|
1911 SQLITE_SUBTYPE
|SQLITE_INNOCUOUS
);
1912 enc
&= (SQLITE_FUNC_ENCMASK
|SQLITE_ANY
);
1914 /* The SQLITE_INNOCUOUS flag is the same bit as SQLITE_FUNC_UNSAFE. But
1915 ** the meaning is inverted. So flip the bit. */
1916 assert( SQLITE_FUNC_UNSAFE
==SQLITE_INNOCUOUS
);
1917 extraFlags
^= SQLITE_FUNC_UNSAFE
; /* tag-20230109-1 */
1920 #ifndef SQLITE_OMIT_UTF16
1921 /* If SQLITE_UTF16 is specified as the encoding type, transform this
1922 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
1923 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
1925 ** If SQLITE_ANY is specified, add three versions of the function
1926 ** to the hash table.
1930 enc
= SQLITE_UTF16NATIVE
;
1934 rc
= sqlite3CreateFunc(db
, zFunctionName
, nArg
,
1935 (SQLITE_UTF8
|extraFlags
)^SQLITE_FUNC_UNSAFE
, /* tag-20230109-1 */
1936 pUserData
, xSFunc
, xStep
, xFinal
, xValue
, xInverse
, pDestructor
);
1937 if( rc
==SQLITE_OK
){
1938 rc
= sqlite3CreateFunc(db
, zFunctionName
, nArg
,
1939 (SQLITE_UTF16LE
|extraFlags
)^SQLITE_FUNC_UNSAFE
, /* tag-20230109-1*/
1940 pUserData
, xSFunc
, xStep
, xFinal
, xValue
, xInverse
, pDestructor
);
1942 if( rc
!=SQLITE_OK
){
1945 enc
= SQLITE_UTF16BE
;
1949 case SQLITE_UTF16LE
:
1950 case SQLITE_UTF16BE
:
1960 /* Check if an existing function is being overridden or deleted. If so,
1961 ** and there are active VMs, then return SQLITE_BUSY. If a function
1962 ** is being overridden/deleted but there are no active VMs, allow the
1963 ** operation to continue but invalidate all precompiled statements.
1965 p
= sqlite3FindFunction(db
, zFunctionName
, nArg
, (u8
)enc
, 0);
1966 if( p
&& (p
->funcFlags
& SQLITE_FUNC_ENCMASK
)==(u32
)enc
&& p
->nArg
==nArg
){
1967 if( db
->nVdbeActive
){
1968 sqlite3ErrorWithMsg(db
, SQLITE_BUSY
,
1969 "unable to delete/modify user-function due to active statements");
1970 assert( !db
->mallocFailed
);
1973 sqlite3ExpirePreparedStatements(db
, 0);
1975 }else if( xSFunc
==0 && xFinal
==0 ){
1976 /* Trying to delete a function that does not exist. This is a no-op.
1977 ** https://sqlite.org/forum/forumpost/726219164b */
1981 p
= sqlite3FindFunction(db
, zFunctionName
, nArg
, (u8
)enc
, 1);
1982 assert(p
|| db
->mallocFailed
);
1984 return SQLITE_NOMEM_BKPT
;
1987 /* If an older version of the function with a configured destructor is
1988 ** being replaced invoke the destructor function here. */
1989 functionDestroy(db
, p
);
1992 pDestructor
->nRef
++;
1994 p
->u
.pDestructor
= pDestructor
;
1995 p
->funcFlags
= (p
->funcFlags
& SQLITE_FUNC_ENCMASK
) | extraFlags
;
1996 testcase( p
->funcFlags
& SQLITE_DETERMINISTIC
);
1997 testcase( p
->funcFlags
& SQLITE_DIRECTONLY
);
1998 p
->xSFunc
= xSFunc
? xSFunc
: xStep
;
1999 p
->xFinalize
= xFinal
;
2001 p
->xInverse
= xInverse
;
2002 p
->pUserData
= pUserData
;
2003 p
->nArg
= (u16
)nArg
;
2008 ** Worker function used by utf-8 APIs that create new functions:
2010 ** sqlite3_create_function()
2011 ** sqlite3_create_function_v2()
2012 ** sqlite3_create_window_function()
2014 static int createFunctionApi(
2020 void (*xSFunc
)(sqlite3_context
*,int,sqlite3_value
**),
2021 void (*xStep
)(sqlite3_context
*,int,sqlite3_value
**),
2022 void (*xFinal
)(sqlite3_context
*),
2023 void (*xValue
)(sqlite3_context
*),
2024 void (*xInverse
)(sqlite3_context
*,int,sqlite3_value
**),
2025 void(*xDestroy
)(void*)
2027 int rc
= SQLITE_ERROR
;
2028 FuncDestructor
*pArg
= 0;
2030 #ifdef SQLITE_ENABLE_API_ARMOR
2031 if( !sqlite3SafetyCheckOk(db
) ){
2032 return SQLITE_MISUSE_BKPT
;
2035 sqlite3_mutex_enter(db
->mutex
);
2037 pArg
= (FuncDestructor
*)sqlite3Malloc(sizeof(FuncDestructor
));
2039 sqlite3OomFault(db
);
2044 pArg
->xDestroy
= xDestroy
;
2045 pArg
->pUserData
= p
;
2047 rc
= sqlite3CreateFunc(db
, zFunc
, nArg
, enc
, p
,
2048 xSFunc
, xStep
, xFinal
, xValue
, xInverse
, pArg
2050 if( pArg
&& pArg
->nRef
==0 ){
2051 assert( rc
!=SQLITE_OK
|| (xStep
==0 && xFinal
==0) );
2057 rc
= sqlite3ApiExit(db
, rc
);
2058 sqlite3_mutex_leave(db
->mutex
);
2063 ** Create new user functions.
2065 int sqlite3_create_function(
2071 void (*xSFunc
)(sqlite3_context
*,int,sqlite3_value
**),
2072 void (*xStep
)(sqlite3_context
*,int,sqlite3_value
**),
2073 void (*xFinal
)(sqlite3_context
*)
2075 return createFunctionApi(db
, zFunc
, nArg
, enc
, p
, xSFunc
, xStep
,
2078 int sqlite3_create_function_v2(
2084 void (*xSFunc
)(sqlite3_context
*,int,sqlite3_value
**),
2085 void (*xStep
)(sqlite3_context
*,int,sqlite3_value
**),
2086 void (*xFinal
)(sqlite3_context
*),
2087 void (*xDestroy
)(void *)
2089 return createFunctionApi(db
, zFunc
, nArg
, enc
, p
, xSFunc
, xStep
,
2090 xFinal
, 0, 0, xDestroy
);
2092 int sqlite3_create_window_function(
2098 void (*xStep
)(sqlite3_context
*,int,sqlite3_value
**),
2099 void (*xFinal
)(sqlite3_context
*),
2100 void (*xValue
)(sqlite3_context
*),
2101 void (*xInverse
)(sqlite3_context
*,int,sqlite3_value
**),
2102 void (*xDestroy
)(void *)
2104 return createFunctionApi(db
, zFunc
, nArg
, enc
, p
, 0, xStep
,
2105 xFinal
, xValue
, xInverse
, xDestroy
);
2108 #ifndef SQLITE_OMIT_UTF16
2109 int sqlite3_create_function16(
2111 const void *zFunctionName
,
2115 void (*xSFunc
)(sqlite3_context
*,int,sqlite3_value
**),
2116 void (*xStep
)(sqlite3_context
*,int,sqlite3_value
**),
2117 void (*xFinal
)(sqlite3_context
*)
2122 #ifdef SQLITE_ENABLE_API_ARMOR
2123 if( !sqlite3SafetyCheckOk(db
) || zFunctionName
==0 ) return SQLITE_MISUSE_BKPT
;
2125 sqlite3_mutex_enter(db
->mutex
);
2126 assert( !db
->mallocFailed
);
2127 zFunc8
= sqlite3Utf16to8(db
, zFunctionName
, -1, SQLITE_UTF16NATIVE
);
2128 rc
= sqlite3CreateFunc(db
, zFunc8
, nArg
, eTextRep
, p
, xSFunc
,xStep
,xFinal
,0,0,0);
2129 sqlite3DbFree(db
, zFunc8
);
2130 rc
= sqlite3ApiExit(db
, rc
);
2131 sqlite3_mutex_leave(db
->mutex
);
2138 ** The following is the implementation of an SQL function that always
2139 ** fails with an error message stating that the function is used in the
2140 ** wrong context. The sqlite3_overload_function() API might construct
2141 ** SQL function that use this routine so that the functions will exist
2142 ** for name resolution but are actually overloaded by the xFindFunction
2143 ** method of virtual tables.
2145 static void sqlite3InvalidFunction(
2146 sqlite3_context
*context
, /* The function calling context */
2147 int NotUsed
, /* Number of arguments to the function */
2148 sqlite3_value
**NotUsed2
/* Value of each argument */
2150 const char *zName
= (const char*)sqlite3_user_data(context
);
2152 UNUSED_PARAMETER2(NotUsed
, NotUsed2
);
2153 zErr
= sqlite3_mprintf(
2154 "unable to use function %s in the requested context", zName
);
2155 sqlite3_result_error(context
, zErr
, -1);
2160 ** Declare that a function has been overloaded by a virtual table.
2162 ** If the function already exists as a regular global function, then
2163 ** this routine is a no-op. If the function does not exist, then create
2164 ** a new one that always throws a run-time error.
2166 ** When virtual tables intend to provide an overloaded function, they
2167 ** should call this routine to make sure the global function exists.
2168 ** A global function must exist in order for name resolution to work
2171 int sqlite3_overload_function(
2179 #ifdef SQLITE_ENABLE_API_ARMOR
2180 if( !sqlite3SafetyCheckOk(db
) || zName
==0 || nArg
<-2 ){
2181 return SQLITE_MISUSE_BKPT
;
2184 sqlite3_mutex_enter(db
->mutex
);
2185 rc
= sqlite3FindFunction(db
, zName
, nArg
, SQLITE_UTF8
, 0)!=0;
2186 sqlite3_mutex_leave(db
->mutex
);
2187 if( rc
) return SQLITE_OK
;
2188 zCopy
= sqlite3_mprintf("%s", zName
);
2189 if( zCopy
==0 ) return SQLITE_NOMEM
;
2190 return sqlite3_create_function_v2(db
, zName
, nArg
, SQLITE_UTF8
,
2191 zCopy
, sqlite3InvalidFunction
, 0, 0, sqlite3_free
);
2194 #ifndef SQLITE_OMIT_TRACE
2196 ** Register a trace function. The pArg from the previously registered trace
2199 ** A NULL trace function means that no tracing is executes. A non-NULL
2200 ** trace is a pointer to a function that is invoked at the start of each
2203 #ifndef SQLITE_OMIT_DEPRECATED
2204 void *sqlite3_trace(sqlite3
*db
, void(*xTrace
)(void*,const char*), void *pArg
){
2207 #ifdef SQLITE_ENABLE_API_ARMOR
2208 if( !sqlite3SafetyCheckOk(db
) ){
2209 (void)SQLITE_MISUSE_BKPT
;
2213 sqlite3_mutex_enter(db
->mutex
);
2214 pOld
= db
->pTraceArg
;
2215 db
->mTrace
= xTrace
? SQLITE_TRACE_LEGACY
: 0;
2216 db
->trace
.xLegacy
= xTrace
;
2217 db
->pTraceArg
= pArg
;
2218 sqlite3_mutex_leave(db
->mutex
);
2221 #endif /* SQLITE_OMIT_DEPRECATED */
2223 /* Register a trace callback using the version-2 interface.
2225 int sqlite3_trace_v2(
2226 sqlite3
*db
, /* Trace this connection */
2227 unsigned mTrace
, /* Mask of events to be traced */
2228 int(*xTrace
)(unsigned,void*,void*,void*), /* Callback to invoke */
2229 void *pArg
/* Context */
2231 #ifdef SQLITE_ENABLE_API_ARMOR
2232 if( !sqlite3SafetyCheckOk(db
) ){
2233 return SQLITE_MISUSE_BKPT
;
2236 sqlite3_mutex_enter(db
->mutex
);
2237 if( mTrace
==0 ) xTrace
= 0;
2238 if( xTrace
==0 ) mTrace
= 0;
2239 db
->mTrace
= mTrace
;
2240 db
->trace
.xV2
= xTrace
;
2241 db
->pTraceArg
= pArg
;
2242 sqlite3_mutex_leave(db
->mutex
);
2246 #ifndef SQLITE_OMIT_DEPRECATED
2248 ** Register a profile function. The pArg from the previously registered
2249 ** profile function is returned.
2251 ** A NULL profile function means that no profiling is executes. A non-NULL
2252 ** profile is a pointer to a function that is invoked at the conclusion of
2253 ** each SQL statement that is run.
2255 void *sqlite3_profile(
2257 void (*xProfile
)(void*,const char*,sqlite_uint64
),
2262 #ifdef SQLITE_ENABLE_API_ARMOR
2263 if( !sqlite3SafetyCheckOk(db
) ){
2264 (void)SQLITE_MISUSE_BKPT
;
2268 sqlite3_mutex_enter(db
->mutex
);
2269 pOld
= db
->pProfileArg
;
2270 db
->xProfile
= xProfile
;
2271 db
->pProfileArg
= pArg
;
2272 db
->mTrace
&= SQLITE_TRACE_NONLEGACY_MASK
;
2273 if( db
->xProfile
) db
->mTrace
|= SQLITE_TRACE_XPROFILE
;
2274 sqlite3_mutex_leave(db
->mutex
);
2277 #endif /* SQLITE_OMIT_DEPRECATED */
2278 #endif /* SQLITE_OMIT_TRACE */
2281 ** Register a function to be invoked when a transaction commits.
2282 ** If the invoked function returns non-zero, then the commit becomes a
2285 void *sqlite3_commit_hook(
2286 sqlite3
*db
, /* Attach the hook to this database */
2287 int (*xCallback
)(void*), /* Function to invoke on each commit */
2288 void *pArg
/* Argument to the function */
2292 #ifdef SQLITE_ENABLE_API_ARMOR
2293 if( !sqlite3SafetyCheckOk(db
) ){
2294 (void)SQLITE_MISUSE_BKPT
;
2298 sqlite3_mutex_enter(db
->mutex
);
2299 pOld
= db
->pCommitArg
;
2300 db
->xCommitCallback
= xCallback
;
2301 db
->pCommitArg
= pArg
;
2302 sqlite3_mutex_leave(db
->mutex
);
2307 ** Register a callback to be invoked each time a row is updated,
2308 ** inserted or deleted using this database connection.
2310 void *sqlite3_update_hook(
2311 sqlite3
*db
, /* Attach the hook to this database */
2312 void (*xCallback
)(void*,int,char const *,char const *,sqlite_int64
),
2313 void *pArg
/* Argument to the function */
2317 #ifdef SQLITE_ENABLE_API_ARMOR
2318 if( !sqlite3SafetyCheckOk(db
) ){
2319 (void)SQLITE_MISUSE_BKPT
;
2323 sqlite3_mutex_enter(db
->mutex
);
2324 pRet
= db
->pUpdateArg
;
2325 db
->xUpdateCallback
= xCallback
;
2326 db
->pUpdateArg
= pArg
;
2327 sqlite3_mutex_leave(db
->mutex
);
2332 ** Register a callback to be invoked each time a transaction is rolled
2333 ** back by this database connection.
2335 void *sqlite3_rollback_hook(
2336 sqlite3
*db
, /* Attach the hook to this database */
2337 void (*xCallback
)(void*), /* Callback function */
2338 void *pArg
/* Argument to the function */
2342 #ifdef SQLITE_ENABLE_API_ARMOR
2343 if( !sqlite3SafetyCheckOk(db
) ){
2344 (void)SQLITE_MISUSE_BKPT
;
2348 sqlite3_mutex_enter(db
->mutex
);
2349 pRet
= db
->pRollbackArg
;
2350 db
->xRollbackCallback
= xCallback
;
2351 db
->pRollbackArg
= pArg
;
2352 sqlite3_mutex_leave(db
->mutex
);
2356 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2358 ** Register a callback to be invoked each time a row is updated,
2359 ** inserted or deleted using this database connection.
2361 void *sqlite3_preupdate_hook(
2362 sqlite3
*db
, /* Attach the hook to this database */
2363 void(*xCallback
)( /* Callback function */
2364 void*,sqlite3
*,int,char const*,char const*,sqlite3_int64
,sqlite3_int64
),
2365 void *pArg
/* First callback argument */
2368 sqlite3_mutex_enter(db
->mutex
);
2369 pRet
= db
->pPreUpdateArg
;
2370 db
->xPreUpdateCallback
= xCallback
;
2371 db
->pPreUpdateArg
= pArg
;
2372 sqlite3_mutex_leave(db
->mutex
);
2375 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2378 ** Register a function to be invoked prior to each autovacuum that
2379 ** determines the number of pages to vacuum.
2381 int sqlite3_autovacuum_pages(
2382 sqlite3
*db
, /* Attach the hook to this database */
2383 unsigned int (*xCallback
)(void*,const char*,u32
,u32
,u32
),
2384 void *pArg
, /* Argument to the function */
2385 void (*xDestructor
)(void*) /* Destructor for pArg */
2387 #ifdef SQLITE_ENABLE_API_ARMOR
2388 if( !sqlite3SafetyCheckOk(db
) ){
2389 if( xDestructor
) xDestructor(pArg
);
2390 return SQLITE_MISUSE_BKPT
;
2393 sqlite3_mutex_enter(db
->mutex
);
2394 if( db
->xAutovacDestr
){
2395 db
->xAutovacDestr(db
->pAutovacPagesArg
);
2397 db
->xAutovacPages
= xCallback
;
2398 db
->pAutovacPagesArg
= pArg
;
2399 db
->xAutovacDestr
= xDestructor
;
2400 sqlite3_mutex_leave(db
->mutex
);
2405 #ifndef SQLITE_OMIT_WAL
2407 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
2408 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
2409 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
2410 ** wal_autocheckpoint()).
2412 int sqlite3WalDefaultHook(
2413 void *pClientData
, /* Argument */
2414 sqlite3
*db
, /* Connection */
2415 const char *zDb
, /* Database */
2416 int nFrame
/* Size of WAL */
2418 if( nFrame
>=SQLITE_PTR_TO_INT(pClientData
) ){
2419 sqlite3BeginBenignMalloc();
2420 sqlite3_wal_checkpoint(db
, zDb
);
2421 sqlite3EndBenignMalloc();
2425 #endif /* SQLITE_OMIT_WAL */
2428 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
2429 ** a database after committing a transaction if there are nFrame or
2430 ** more frames in the log file. Passing zero or a negative value as the
2431 ** nFrame parameter disables automatic checkpoints entirely.
2433 ** The callback registered by this function replaces any existing callback
2434 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
2435 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
2436 ** configured by this function.
2438 int sqlite3_wal_autocheckpoint(sqlite3
*db
, int nFrame
){
2439 #ifdef SQLITE_OMIT_WAL
2440 UNUSED_PARAMETER(db
);
2441 UNUSED_PARAMETER(nFrame
);
2443 #ifdef SQLITE_ENABLE_API_ARMOR
2444 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
2447 sqlite3_wal_hook(db
, sqlite3WalDefaultHook
, SQLITE_INT_TO_PTR(nFrame
));
2449 sqlite3_wal_hook(db
, 0, 0);
2456 ** Register a callback to be invoked each time a transaction is written
2457 ** into the write-ahead-log by this database connection.
2459 void *sqlite3_wal_hook(
2460 sqlite3
*db
, /* Attach the hook to this db handle */
2461 int(*xCallback
)(void *, sqlite3
*, const char*, int),
2462 void *pArg
/* First argument passed to xCallback() */
2464 #ifndef SQLITE_OMIT_WAL
2466 #ifdef SQLITE_ENABLE_API_ARMOR
2467 if( !sqlite3SafetyCheckOk(db
) ){
2468 (void)SQLITE_MISUSE_BKPT
;
2472 sqlite3_mutex_enter(db
->mutex
);
2474 db
->xWalCallback
= xCallback
;
2476 sqlite3_mutex_leave(db
->mutex
);
2484 ** Checkpoint database zDb.
2486 int sqlite3_wal_checkpoint_v2(
2487 sqlite3
*db
, /* Database handle */
2488 const char *zDb
, /* Name of attached database (or NULL) */
2489 int eMode
, /* SQLITE_CHECKPOINT_* value */
2490 int *pnLog
, /* OUT: Size of WAL log in frames */
2491 int *pnCkpt
/* OUT: Total number of frames checkpointed */
2493 #ifdef SQLITE_OMIT_WAL
2496 int rc
; /* Return code */
2497 int iDb
; /* Schema to checkpoint */
2499 #ifdef SQLITE_ENABLE_API_ARMOR
2500 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
2503 /* Initialize the output variables to -1 in case an error occurs. */
2504 if( pnLog
) *pnLog
= -1;
2505 if( pnCkpt
) *pnCkpt
= -1;
2507 assert( SQLITE_CHECKPOINT_PASSIVE
==0 );
2508 assert( SQLITE_CHECKPOINT_FULL
==1 );
2509 assert( SQLITE_CHECKPOINT_RESTART
==2 );
2510 assert( SQLITE_CHECKPOINT_TRUNCATE
==3 );
2511 if( eMode
<SQLITE_CHECKPOINT_PASSIVE
|| eMode
>SQLITE_CHECKPOINT_TRUNCATE
){
2512 /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
2514 return SQLITE_MISUSE_BKPT
;
2517 sqlite3_mutex_enter(db
->mutex
);
2518 if( zDb
&& zDb
[0] ){
2519 iDb
= sqlite3FindDbName(db
, zDb
);
2521 iDb
= SQLITE_MAX_DB
; /* This means process all schemas */
2525 sqlite3ErrorWithMsg(db
, SQLITE_ERROR
, "unknown database: %s", zDb
);
2527 db
->busyHandler
.nBusy
= 0;
2528 rc
= sqlite3Checkpoint(db
, iDb
, eMode
, pnLog
, pnCkpt
);
2529 sqlite3Error(db
, rc
);
2531 rc
= sqlite3ApiExit(db
, rc
);
2533 /* If there are no active statements, clear the interrupt flag at this
2535 if( db
->nVdbeActive
==0 ){
2536 AtomicStore(&db
->u1
.isInterrupted
, 0);
2539 sqlite3_mutex_leave(db
->mutex
);
2546 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
2547 ** to contains a zero-length string, all attached databases are
2550 int sqlite3_wal_checkpoint(sqlite3
*db
, const char *zDb
){
2551 /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
2552 ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
2553 return sqlite3_wal_checkpoint_v2(db
,zDb
,SQLITE_CHECKPOINT_PASSIVE
,0,0);
2556 #ifndef SQLITE_OMIT_WAL
2558 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
2559 ** not currently open in WAL mode.
2561 ** If a transaction is open on the database being checkpointed, this
2562 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
2563 ** an error occurs while running the checkpoint, an SQLite error code is
2564 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
2566 ** The mutex on database handle db should be held by the caller. The mutex
2567 ** associated with the specific b-tree being checkpointed is taken by
2568 ** this function while the checkpoint is running.
2570 ** If iDb is passed SQLITE_MAX_DB then all attached databases are
2571 ** checkpointed. If an error is encountered it is returned immediately -
2572 ** no attempt is made to checkpoint any remaining databases.
2574 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
2577 int sqlite3Checkpoint(sqlite3
*db
, int iDb
, int eMode
, int *pnLog
, int *pnCkpt
){
2578 int rc
= SQLITE_OK
; /* Return code */
2579 int i
; /* Used to iterate through attached dbs */
2580 int bBusy
= 0; /* True if SQLITE_BUSY has been encountered */
2582 assert( sqlite3_mutex_held(db
->mutex
) );
2583 assert( !pnLog
|| *pnLog
==-1 );
2584 assert( !pnCkpt
|| *pnCkpt
==-1 );
2585 testcase( iDb
==SQLITE_MAX_ATTACHED
); /* See forum post a006d86f72 */
2586 testcase( iDb
==SQLITE_MAX_DB
);
2588 for(i
=0; i
<db
->nDb
&& rc
==SQLITE_OK
; i
++){
2589 if( i
==iDb
|| iDb
==SQLITE_MAX_DB
){
2590 rc
= sqlite3BtreeCheckpoint(db
->aDb
[i
].pBt
, eMode
, pnLog
, pnCkpt
);
2593 if( rc
==SQLITE_BUSY
){
2600 return (rc
==SQLITE_OK
&& bBusy
) ? SQLITE_BUSY
: rc
;
2602 #endif /* SQLITE_OMIT_WAL */
2605 ** This function returns true if main-memory should be used instead of
2606 ** a temporary file for transient pager files and statement journals.
2607 ** The value returned depends on the value of db->temp_store (runtime
2608 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
2609 ** following table describes the relationship between these two values
2610 ** and this functions return value.
2612 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
2613 ** ----------------- -------------- ------------------------------
2614 ** 0 any file (return 0)
2615 ** 1 1 file (return 0)
2616 ** 1 2 memory (return 1)
2617 ** 1 0 file (return 0)
2618 ** 2 1 file (return 0)
2619 ** 2 2 memory (return 1)
2620 ** 2 0 memory (return 1)
2621 ** 3 any memory (return 1)
2623 int sqlite3TempInMemory(const sqlite3
*db
){
2624 #if SQLITE_TEMP_STORE==1
2625 return ( db
->temp_store
==2 );
2627 #if SQLITE_TEMP_STORE==2
2628 return ( db
->temp_store
!=1 );
2630 #if SQLITE_TEMP_STORE==3
2631 UNUSED_PARAMETER(db
);
2634 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
2635 UNUSED_PARAMETER(db
);
2641 ** Return UTF-8 encoded English language explanation of the most recent
2644 const char *sqlite3_errmsg(sqlite3
*db
){
2647 return sqlite3ErrStr(SQLITE_NOMEM_BKPT
);
2649 if( !sqlite3SafetyCheckSickOrOk(db
) ){
2650 return sqlite3ErrStr(SQLITE_MISUSE_BKPT
);
2652 sqlite3_mutex_enter(db
->mutex
);
2653 if( db
->mallocFailed
){
2654 z
= sqlite3ErrStr(SQLITE_NOMEM_BKPT
);
2656 testcase( db
->pErr
==0 );
2657 z
= db
->errCode
? (char*)sqlite3_value_text(db
->pErr
) : 0;
2658 assert( !db
->mallocFailed
);
2660 z
= sqlite3ErrStr(db
->errCode
);
2663 sqlite3_mutex_leave(db
->mutex
);
2668 ** Return the byte offset of the most recent error
2670 int sqlite3_error_offset(sqlite3
*db
){
2672 if( db
&& sqlite3SafetyCheckSickOrOk(db
) && db
->errCode
){
2673 sqlite3_mutex_enter(db
->mutex
);
2674 iOffset
= db
->errByteOffset
;
2675 sqlite3_mutex_leave(db
->mutex
);
2680 #ifndef SQLITE_OMIT_UTF16
2682 ** Return UTF-16 encoded English language explanation of the most recent
2685 const void *sqlite3_errmsg16(sqlite3
*db
){
2686 static const u16 outOfMem
[] = {
2687 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
2689 static const u16 misuse
[] = {
2690 'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
2691 'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
2692 'm', 'i', 's', 'u', 's', 'e', 0
2697 return (void *)outOfMem
;
2699 if( !sqlite3SafetyCheckSickOrOk(db
) ){
2700 return (void *)misuse
;
2702 sqlite3_mutex_enter(db
->mutex
);
2703 if( db
->mallocFailed
){
2704 z
= (void *)outOfMem
;
2706 z
= sqlite3_value_text16(db
->pErr
);
2708 sqlite3ErrorWithMsg(db
, db
->errCode
, sqlite3ErrStr(db
->errCode
));
2709 z
= sqlite3_value_text16(db
->pErr
);
2711 /* A malloc() may have failed within the call to sqlite3_value_text16()
2712 ** above. If this is the case, then the db->mallocFailed flag needs to
2713 ** be cleared before returning. Do this directly, instead of via
2714 ** sqlite3ApiExit(), to avoid setting the database handle error message.
2716 sqlite3OomClear(db
);
2718 sqlite3_mutex_leave(db
->mutex
);
2721 #endif /* SQLITE_OMIT_UTF16 */
2724 ** Return the most recent error code generated by an SQLite routine. If NULL is
2725 ** passed to this function, we assume a malloc() failed during sqlite3_open().
2727 int sqlite3_errcode(sqlite3
*db
){
2728 if( db
&& !sqlite3SafetyCheckSickOrOk(db
) ){
2729 return SQLITE_MISUSE_BKPT
;
2731 if( !db
|| db
->mallocFailed
){
2732 return SQLITE_NOMEM_BKPT
;
2734 return db
->errCode
& db
->errMask
;
2736 int sqlite3_extended_errcode(sqlite3
*db
){
2737 if( db
&& !sqlite3SafetyCheckSickOrOk(db
) ){
2738 return SQLITE_MISUSE_BKPT
;
2740 if( !db
|| db
->mallocFailed
){
2741 return SQLITE_NOMEM_BKPT
;
2745 int sqlite3_system_errno(sqlite3
*db
){
2746 return db
? db
->iSysErrno
: 0;
2750 ** Return a string that describes the kind of error specified in the
2751 ** argument. For now, this simply calls the internal sqlite3ErrStr()
2754 const char *sqlite3_errstr(int rc
){
2755 return sqlite3ErrStr(rc
);
2759 ** Create a new collating function for database "db". The name is zName
2760 ** and the encoding is enc.
2762 static int createCollation(
2767 int(*xCompare
)(void*,int,const void*,int,const void*),
2773 assert( sqlite3_mutex_held(db
->mutex
) );
2775 /* If SQLITE_UTF16 is specified as the encoding type, transform this
2776 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
2777 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
2780 testcase( enc2
==SQLITE_UTF16
);
2781 testcase( enc2
==SQLITE_UTF16_ALIGNED
);
2782 if( enc2
==SQLITE_UTF16
|| enc2
==SQLITE_UTF16_ALIGNED
){
2783 enc2
= SQLITE_UTF16NATIVE
;
2785 if( enc2
<SQLITE_UTF8
|| enc2
>SQLITE_UTF16BE
){
2786 return SQLITE_MISUSE_BKPT
;
2789 /* Check if this call is removing or replacing an existing collation
2790 ** sequence. If so, and there are active VMs, return busy. If there
2791 ** are no active VMs, invalidate any pre-compiled statements.
2793 pColl
= sqlite3FindCollSeq(db
, (u8
)enc2
, zName
, 0);
2794 if( pColl
&& pColl
->xCmp
){
2795 if( db
->nVdbeActive
){
2796 sqlite3ErrorWithMsg(db
, SQLITE_BUSY
,
2797 "unable to delete/modify collation sequence due to active statements");
2800 sqlite3ExpirePreparedStatements(db
, 0);
2802 /* If collation sequence pColl was created directly by a call to
2803 ** sqlite3_create_collation, and not generated by synthCollSeq(),
2804 ** then any copies made by synthCollSeq() need to be invalidated.
2805 ** Also, collation destructor - CollSeq.xDel() - function may need
2808 if( (pColl
->enc
& ~SQLITE_UTF16_ALIGNED
)==enc2
){
2809 CollSeq
*aColl
= sqlite3HashFind(&db
->aCollSeq
, zName
);
2812 CollSeq
*p
= &aColl
[j
];
2813 if( p
->enc
==pColl
->enc
){
2823 pColl
= sqlite3FindCollSeq(db
, (u8
)enc2
, zName
, 1);
2824 if( pColl
==0 ) return SQLITE_NOMEM_BKPT
;
2825 pColl
->xCmp
= xCompare
;
2826 pColl
->pUser
= pCtx
;
2828 pColl
->enc
= (u8
)(enc2
| (enc
& SQLITE_UTF16_ALIGNED
));
2829 sqlite3Error(db
, SQLITE_OK
);
2835 ** This array defines hard upper bounds on limit values. The
2836 ** initializer must be kept in sync with the SQLITE_LIMIT_*
2837 ** #defines in sqlite3.h.
2839 static const int aHardLimit
[] = {
2841 SQLITE_MAX_SQL_LENGTH
,
2843 SQLITE_MAX_EXPR_DEPTH
,
2844 SQLITE_MAX_COMPOUND_SELECT
,
2846 SQLITE_MAX_FUNCTION_ARG
,
2847 SQLITE_MAX_ATTACHED
,
2848 SQLITE_MAX_LIKE_PATTERN_LENGTH
,
2849 SQLITE_MAX_VARIABLE_NUMBER
, /* IMP: R-38091-32352 */
2850 SQLITE_MAX_TRIGGER_DEPTH
,
2851 SQLITE_MAX_WORKER_THREADS
,
2855 ** Make sure the hard limits are set to reasonable values
2857 #if SQLITE_MAX_LENGTH<100
2858 # error SQLITE_MAX_LENGTH must be at least 100
2860 #if SQLITE_MAX_SQL_LENGTH<100
2861 # error SQLITE_MAX_SQL_LENGTH must be at least 100
2863 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
2864 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
2866 #if SQLITE_MAX_COMPOUND_SELECT<2
2867 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
2869 #if SQLITE_MAX_VDBE_OP<40
2870 # error SQLITE_MAX_VDBE_OP must be at least 40
2872 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
2873 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
2875 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
2876 # error SQLITE_MAX_ATTACHED must be between 0 and 125
2878 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
2879 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
2881 #if SQLITE_MAX_COLUMN>32767
2882 # error SQLITE_MAX_COLUMN must not exceed 32767
2884 #if SQLITE_MAX_TRIGGER_DEPTH<1
2885 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
2887 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
2888 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
2893 ** Change the value of a limit. Report the old value.
2894 ** If an invalid limit index is supplied, report -1.
2895 ** Make no changes but still report the old value if the
2896 ** new limit is negative.
2898 ** A new lower limit does not shrink existing constructs.
2899 ** It merely prevents new constructs that exceed the limit
2902 int sqlite3_limit(sqlite3
*db
, int limitId
, int newLimit
){
2905 #ifdef SQLITE_ENABLE_API_ARMOR
2906 if( !sqlite3SafetyCheckOk(db
) ){
2907 (void)SQLITE_MISUSE_BKPT
;
2912 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
2913 ** there is a hard upper bound set at compile-time by a C preprocessor
2914 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
2917 assert( aHardLimit
[SQLITE_LIMIT_LENGTH
]==SQLITE_MAX_LENGTH
);
2918 assert( aHardLimit
[SQLITE_LIMIT_SQL_LENGTH
]==SQLITE_MAX_SQL_LENGTH
);
2919 assert( aHardLimit
[SQLITE_LIMIT_COLUMN
]==SQLITE_MAX_COLUMN
);
2920 assert( aHardLimit
[SQLITE_LIMIT_EXPR_DEPTH
]==SQLITE_MAX_EXPR_DEPTH
);
2921 assert( aHardLimit
[SQLITE_LIMIT_COMPOUND_SELECT
]==SQLITE_MAX_COMPOUND_SELECT
);
2922 assert( aHardLimit
[SQLITE_LIMIT_VDBE_OP
]==SQLITE_MAX_VDBE_OP
);
2923 assert( aHardLimit
[SQLITE_LIMIT_FUNCTION_ARG
]==SQLITE_MAX_FUNCTION_ARG
);
2924 assert( aHardLimit
[SQLITE_LIMIT_ATTACHED
]==SQLITE_MAX_ATTACHED
);
2925 assert( aHardLimit
[SQLITE_LIMIT_LIKE_PATTERN_LENGTH
]==
2926 SQLITE_MAX_LIKE_PATTERN_LENGTH
);
2927 assert( aHardLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
]==SQLITE_MAX_VARIABLE_NUMBER
);
2928 assert( aHardLimit
[SQLITE_LIMIT_TRIGGER_DEPTH
]==SQLITE_MAX_TRIGGER_DEPTH
);
2929 assert( aHardLimit
[SQLITE_LIMIT_WORKER_THREADS
]==SQLITE_MAX_WORKER_THREADS
);
2930 assert( SQLITE_LIMIT_WORKER_THREADS
==(SQLITE_N_LIMIT
-1) );
2933 if( limitId
<0 || limitId
>=SQLITE_N_LIMIT
){
2936 oldLimit
= db
->aLimit
[limitId
];
2937 if( newLimit
>=0 ){ /* IMP: R-52476-28732 */
2938 if( newLimit
>aHardLimit
[limitId
] ){
2939 newLimit
= aHardLimit
[limitId
]; /* IMP: R-51463-25634 */
2940 }else if( newLimit
<1 && limitId
==SQLITE_LIMIT_LENGTH
){
2943 db
->aLimit
[limitId
] = newLimit
;
2945 return oldLimit
; /* IMP: R-53341-35419 */
2949 ** This function is used to parse both URIs and non-URI filenames passed by the
2950 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
2951 ** URIs specified as part of ATTACH statements.
2953 ** The first argument to this function is the name of the VFS to use (or
2954 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
2955 ** query parameter. The second argument contains the URI (or non-URI filename)
2956 ** itself. When this function is called the *pFlags variable should contain
2957 ** the default flags to open the database handle with. The value stored in
2958 ** *pFlags may be updated before returning if the URI filename contains
2959 ** "cache=xxx" or "mode=xxx" query parameters.
2961 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
2962 ** the VFS that should be used to open the database file. *pzFile is set to
2963 ** point to a buffer containing the name of the file to open. The value
2964 ** stored in *pzFile is a database name acceptable to sqlite3_uri_parameter()
2965 ** and is in the same format as names created using sqlite3_create_filename().
2966 ** The caller must invoke sqlite3_free_filename() (not sqlite3_free()!) on
2967 ** the value returned in *pzFile to avoid a memory leak.
2969 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
2970 ** may be set to point to a buffer containing an English language error
2971 ** message. It is the responsibility of the caller to eventually release
2972 ** this buffer by calling sqlite3_free().
2974 int sqlite3ParseUri(
2975 const char *zDefaultVfs
, /* VFS to use if no "vfs=xxx" query option */
2976 const char *zUri
, /* Nul-terminated URI to parse */
2977 unsigned int *pFlags
, /* IN/OUT: SQLITE_OPEN_XXX flags */
2978 sqlite3_vfs
**ppVfs
, /* OUT: VFS to use */
2979 char **pzFile
, /* OUT: Filename component of URI */
2980 char **pzErrMsg
/* OUT: Error message (if rc!=SQLITE_OK) */
2983 unsigned int flags
= *pFlags
;
2984 const char *zVfs
= zDefaultVfs
;
2987 int nUri
= sqlite3Strlen30(zUri
);
2989 assert( *pzErrMsg
==0 );
2991 if( ((flags
& SQLITE_OPEN_URI
) /* IMP: R-48725-32206 */
2992 || AtomicLoad(&sqlite3GlobalConfig
.bOpenUri
)) /* IMP: R-51689-46548 */
2993 && nUri
>=5 && memcmp(zUri
, "file:", 5)==0 /* IMP: R-57884-37496 */
2996 int eState
; /* Parser state when parsing URI */
2997 int iIn
; /* Input character index */
2998 int iOut
= 0; /* Output character index */
2999 u64 nByte
= nUri
+8; /* Bytes of space to allocate */
3001 /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
3002 ** method that there may be extra parameters following the file-name. */
3003 flags
|= SQLITE_OPEN_URI
;
3005 for(iIn
=0; iIn
<nUri
; iIn
++) nByte
+= (zUri
[iIn
]=='&');
3006 zFile
= sqlite3_malloc64(nByte
);
3007 if( !zFile
) return SQLITE_NOMEM_BKPT
;
3009 memset(zFile
, 0, 4); /* 4-byte of 0x00 is the start of DB name marker */
3013 #ifdef SQLITE_ALLOW_URI_AUTHORITY
3014 if( strncmp(zUri
+5, "///", 3)==0 ){
3016 /* The following condition causes URIs with five leading / characters
3017 ** like file://///host/path to be converted into UNCs like //host/path.
3018 ** The correct URI for that UNC has only two or four leading / characters
3019 ** file://host/path or file:////host/path. But 5 leading slashes is a
3020 ** common error, we are told, so we handle it as a special case. */
3021 if( strncmp(zUri
+7, "///", 3)==0 ){ iIn
++; }
3022 }else if( strncmp(zUri
+5, "//localhost/", 12)==0 ){
3026 /* Discard the scheme and authority segments of the URI. */
3027 if( zUri
[5]=='/' && zUri
[6]=='/' ){
3029 while( zUri
[iIn
] && zUri
[iIn
]!='/' ) iIn
++;
3030 if( iIn
!=7 && (iIn
!=16 || memcmp("localhost", &zUri
[7], 9)) ){
3031 *pzErrMsg
= sqlite3_mprintf("invalid uri authority: %.*s",
3039 /* Copy the filename and any query parameters into the zFile buffer.
3040 ** Decode %HH escape codes along the way.
3042 ** Within this loop, variable eState may be set to 0, 1 or 2, depending
3043 ** on the parsing context. As follows:
3045 ** 0: Parsing file-name.
3046 ** 1: Parsing name section of a name=value query parameter.
3047 ** 2: Parsing value section of a name=value query parameter.
3050 while( (c
= zUri
[iIn
])!=0 && c
!='#' ){
3053 && sqlite3Isxdigit(zUri
[iIn
])
3054 && sqlite3Isxdigit(zUri
[iIn
+1])
3056 int octet
= (sqlite3HexToInt(zUri
[iIn
++]) << 4);
3057 octet
+= sqlite3HexToInt(zUri
[iIn
++]);
3059 assert( octet
>=0 && octet
<256 );
3061 #ifndef SQLITE_ENABLE_URI_00_ERROR
3062 /* This branch is taken when "%00" appears within the URI. In this
3063 ** case we ignore all text in the remainder of the path, name or
3064 ** value currently being parsed. So ignore the current character
3065 ** and skip to the next "?", "=" or "&", as appropriate. */
3066 while( (c
= zUri
[iIn
])!=0 && c
!='#'
3067 && (eState
!=0 || c
!='?')
3068 && (eState
!=1 || (c
!='=' && c
!='&'))
3069 && (eState
!=2 || c
!='&')
3075 /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
3076 *pzErrMsg
= sqlite3_mprintf("unexpected %%00 in uri");
3082 }else if( eState
==1 && (c
=='&' || c
=='=') ){
3083 if( zFile
[iOut
-1]==0 ){
3084 /* An empty option name. Ignore this option altogether. */
3085 while( zUri
[iIn
] && zUri
[iIn
]!='#' && zUri
[iIn
-1]!='&' ) iIn
++;
3089 zFile
[iOut
++] = '\0';
3094 }else if( (eState
==0 && c
=='?') || (eState
==2 && c
=='&') ){
3100 if( eState
==1 ) zFile
[iOut
++] = '\0';
3101 memset(zFile
+iOut
, 0, 4); /* end-of-options + empty journal filenames */
3103 /* Check if there were any options specified that should be interpreted
3104 ** here. Options that are interpreted here include "vfs" and those that
3105 ** correspond to flags that may be passed to the sqlite3_open_v2()
3107 zOpt
= &zFile
[sqlite3Strlen30(zFile
)+1];
3109 int nOpt
= sqlite3Strlen30(zOpt
);
3110 char *zVal
= &zOpt
[nOpt
+1];
3111 int nVal
= sqlite3Strlen30(zVal
);
3113 if( nOpt
==3 && memcmp("vfs", zOpt
, 3)==0 ){
3120 char *zModeType
= 0;
3124 if( nOpt
==5 && memcmp("cache", zOpt
, 5)==0 ){
3125 static struct OpenMode aCacheMode
[] = {
3126 { "shared", SQLITE_OPEN_SHAREDCACHE
},
3127 { "private", SQLITE_OPEN_PRIVATECACHE
},
3131 mask
= SQLITE_OPEN_SHAREDCACHE
|SQLITE_OPEN_PRIVATECACHE
;
3134 zModeType
= "cache";
3136 if( nOpt
==4 && memcmp("mode", zOpt
, 4)==0 ){
3137 static struct OpenMode aOpenMode
[] = {
3138 { "ro", SQLITE_OPEN_READONLY
},
3139 { "rw", SQLITE_OPEN_READWRITE
},
3140 { "rwc", SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
},
3141 { "memory", SQLITE_OPEN_MEMORY
},
3145 mask
= SQLITE_OPEN_READONLY
| SQLITE_OPEN_READWRITE
3146 | SQLITE_OPEN_CREATE
| SQLITE_OPEN_MEMORY
;
3148 limit
= mask
& flags
;
3149 zModeType
= "access";
3155 for(i
=0; aMode
[i
].z
; i
++){
3156 const char *z
= aMode
[i
].z
;
3157 if( nVal
==sqlite3Strlen30(z
) && 0==memcmp(zVal
, z
, nVal
) ){
3158 mode
= aMode
[i
].mode
;
3163 *pzErrMsg
= sqlite3_mprintf("no such %s mode: %s", zModeType
, zVal
);
3167 if( (mode
& ~SQLITE_OPEN_MEMORY
)>limit
){
3168 *pzErrMsg
= sqlite3_mprintf("%s mode not allowed: %s",
3173 flags
= (flags
& ~mask
) | mode
;
3177 zOpt
= &zVal
[nVal
+1];
3181 zFile
= sqlite3_malloc64(nUri
+8);
3182 if( !zFile
) return SQLITE_NOMEM_BKPT
;
3183 memset(zFile
, 0, 4);
3186 memcpy(zFile
, zUri
, nUri
);
3188 memset(zFile
+nUri
, 0, 4);
3189 flags
&= ~SQLITE_OPEN_URI
;
3192 *ppVfs
= sqlite3_vfs_find(zVfs
);
3194 *pzErrMsg
= sqlite3_mprintf("no such vfs: %s", zVfs
);
3198 if( rc
!=SQLITE_OK
){
3199 sqlite3_free_filename(zFile
);
3208 ** This routine does the core work of extracting URI parameters from a
3209 ** database filename for the sqlite3_uri_parameter() interface.
3211 static const char *uriParameter(const char *zFilename
, const char *zParam
){
3212 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
3213 while( ALWAYS(zFilename
!=0) && zFilename
[0] ){
3214 int x
= strcmp(zFilename
, zParam
);
3215 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
3216 if( x
==0 ) return zFilename
;
3217 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
3225 ** This routine does the work of opening a database on behalf of
3226 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
3227 ** is UTF-8 encoded.
3229 static int openDatabase(
3230 const char *zFilename
, /* Database filename UTF-8 encoded */
3231 sqlite3
**ppDb
, /* OUT: Returned database handle */
3232 unsigned int flags
, /* Operational flags */
3233 const char *zVfs
/* Name of the VFS to use */
3235 sqlite3
*db
; /* Store allocated handle here */
3236 int rc
; /* Return code */
3237 int isThreadsafe
; /* True for threadsafe connections */
3238 char *zOpen
= 0; /* Filename argument to pass to BtreeOpen() */
3239 char *zErrMsg
= 0; /* Error message from sqlite3ParseUri() */
3240 int i
; /* Loop counter */
3242 #ifdef SQLITE_ENABLE_API_ARMOR
3243 if( ppDb
==0 ) return SQLITE_MISUSE_BKPT
;
3246 #ifndef SQLITE_OMIT_AUTOINIT
3247 rc
= sqlite3_initialize();
3251 if( sqlite3GlobalConfig
.bCoreMutex
==0 ){
3253 }else if( flags
& SQLITE_OPEN_NOMUTEX
){
3255 }else if( flags
& SQLITE_OPEN_FULLMUTEX
){
3258 isThreadsafe
= sqlite3GlobalConfig
.bFullMutex
;
3261 if( flags
& SQLITE_OPEN_PRIVATECACHE
){
3262 flags
&= ~SQLITE_OPEN_SHAREDCACHE
;
3263 }else if( sqlite3GlobalConfig
.sharedCacheEnabled
){
3264 flags
|= SQLITE_OPEN_SHAREDCACHE
;
3267 /* Remove harmful bits from the flags parameter
3269 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
3270 ** dealt with in the previous code block. Besides these, the only
3271 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
3272 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
3273 ** SQLITE_OPEN_PRIVATECACHE, SQLITE_OPEN_EXRESCODE, and some reserved
3274 ** bits. Silently mask off all other flags.
3276 flags
&= ~( SQLITE_OPEN_DELETEONCLOSE
|
3277 SQLITE_OPEN_EXCLUSIVE
|
3278 SQLITE_OPEN_MAIN_DB
|
3279 SQLITE_OPEN_TEMP_DB
|
3280 SQLITE_OPEN_TRANSIENT_DB
|
3281 SQLITE_OPEN_MAIN_JOURNAL
|
3282 SQLITE_OPEN_TEMP_JOURNAL
|
3283 SQLITE_OPEN_SUBJOURNAL
|
3284 SQLITE_OPEN_SUPER_JOURNAL
|
3285 SQLITE_OPEN_NOMUTEX
|
3286 SQLITE_OPEN_FULLMUTEX
|
3290 /* Allocate the sqlite data structure */
3291 db
= sqlite3MallocZero( sizeof(sqlite3
) );
3292 if( db
==0 ) goto opendb_out
;
3294 #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
3295 || sqlite3GlobalConfig
.bCoreMutex
3298 db
->mutex
= sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE
);
3304 if( isThreadsafe
==0 ){
3305 sqlite3MutexWarnOnContention(db
->mutex
);
3308 sqlite3_mutex_enter(db
->mutex
);
3309 db
->errMask
= (flags
& SQLITE_OPEN_EXRESCODE
)!=0 ? 0xffffffff : 0xff;
3311 db
->eOpenState
= SQLITE_STATE_BUSY
;
3312 db
->aDb
= db
->aDbStatic
;
3313 db
->lookaside
.bDisable
= 1;
3314 db
->lookaside
.sz
= 0;
3316 assert( sizeof(db
->aLimit
)==sizeof(aHardLimit
) );
3317 memcpy(db
->aLimit
, aHardLimit
, sizeof(db
->aLimit
));
3318 db
->aLimit
[SQLITE_LIMIT_WORKER_THREADS
] = SQLITE_DEFAULT_WORKER_THREADS
;
3320 db
->nextAutovac
= -1;
3321 db
->szMmap
= sqlite3GlobalConfig
.szMmap
;
3322 db
->nextPagesize
= 0;
3323 db
->init
.azInit
= sqlite3StdType
; /* Any array of string ptrs will do */
3324 #ifdef SQLITE_ENABLE_SORTER_MMAP
3325 /* Beginning with version 3.37.0, using the VFS xFetch() API to memory-map
3326 ** the temporary files used to do external sorts (see code in vdbesort.c)
3327 ** is disabled. It can still be used either by defining
3328 ** SQLITE_ENABLE_SORTER_MMAP at compile time or by using the
3329 ** SQLITE_TESTCTRL_SORTER_MMAP test-control at runtime. */
3330 db
->nMaxSorterMmap
= 0x7FFFFFFF;
3332 db
->flags
|= SQLITE_ShortColNames
3333 | SQLITE_EnableTrigger
3336 #if !defined(SQLITE_TRUSTED_SCHEMA) || SQLITE_TRUSTED_SCHEMA+0!=0
3337 | SQLITE_TrustedSchema
3339 /* The SQLITE_DQS compile-time option determines the default settings
3340 ** for SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML.
3342 ** SQLITE_DQS SQLITE_DBCONFIG_DQS_DDL SQLITE_DBCONFIG_DQS_DML
3343 ** ---------- ----------------------- -----------------------
3350 ** Legacy behavior is 3 (double-quoted string literals are allowed anywhere)
3351 ** and so that is the default. But developers are encouraged to use
3352 ** -DSQLITE_DQS=0 (best) or -DSQLITE_DQS=1 (second choice) if possible.
3354 #if !defined(SQLITE_DQS)
3355 # define SQLITE_DQS 3
3357 #if (SQLITE_DQS&1)==1
3360 #if (SQLITE_DQS&2)==2
3364 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
3367 #if SQLITE_DEFAULT_CKPTFULLFSYNC
3368 | SQLITE_CkptFullFSync
3370 #if SQLITE_DEFAULT_FILE_FORMAT<4
3371 | SQLITE_LegacyFileFmt
3373 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
3374 | SQLITE_LoadExtension
3376 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
3377 | SQLITE_RecTriggers
3379 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
3380 | SQLITE_ForeignKeys
3382 #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
3383 | SQLITE_ReverseOrder
3385 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
3388 #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
3389 | SQLITE_Fts3Tokenizer
3391 #if defined(SQLITE_ENABLE_QPSG)
3394 #if defined(SQLITE_DEFAULT_DEFENSIVE)
3397 #if defined(SQLITE_DEFAULT_LEGACY_ALTER_TABLE)
3398 | SQLITE_LegacyAlter
3400 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
3401 | SQLITE_StmtScanStatus
3404 sqlite3HashInit(&db
->aCollSeq
);
3405 #ifndef SQLITE_OMIT_VIRTUALTABLE
3406 sqlite3HashInit(&db
->aModule
);
3409 /* Add the default collation sequence BINARY. BINARY works for both UTF-8
3410 ** and UTF-16, so add a version for each to avoid any unnecessary
3411 ** conversions. The only error that can occur here is a malloc() failure.
3413 ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
3416 createCollation(db
, sqlite3StrBINARY
, SQLITE_UTF8
, 0, binCollFunc
, 0);
3417 createCollation(db
, sqlite3StrBINARY
, SQLITE_UTF16BE
, 0, binCollFunc
, 0);
3418 createCollation(db
, sqlite3StrBINARY
, SQLITE_UTF16LE
, 0, binCollFunc
, 0);
3419 createCollation(db
, "NOCASE", SQLITE_UTF8
, 0, nocaseCollatingFunc
, 0);
3420 createCollation(db
, "RTRIM", SQLITE_UTF8
, 0, rtrimCollFunc
, 0);
3421 if( db
->mallocFailed
){
3425 #if SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL)
3426 /* Process magic filenames ":localStorage:" and ":sessionStorage:" */
3427 if( zFilename
&& zFilename
[0]==':' ){
3428 if( strcmp(zFilename
, ":localStorage:")==0 ){
3429 zFilename
= "file:local?vfs=kvvfs";
3430 flags
|= SQLITE_OPEN_URI
;
3431 }else if( strcmp(zFilename
, ":sessionStorage:")==0 ){
3432 zFilename
= "file:session?vfs=kvvfs";
3433 flags
|= SQLITE_OPEN_URI
;
3436 #endif /* SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL) */
3438 /* Parse the filename/URI argument
3440 ** Only allow sensible combinations of bits in the flags argument.
3441 ** Throw an error if any non-sense combination is used. If we
3442 ** do not block illegal combinations here, it could trigger
3443 ** assert() statements in deeper layers. Sensible combinations
3446 ** 1: SQLITE_OPEN_READONLY
3447 ** 2: SQLITE_OPEN_READWRITE
3448 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
3450 db
->openFlags
= flags
;
3451 assert( SQLITE_OPEN_READONLY
== 0x01 );
3452 assert( SQLITE_OPEN_READWRITE
== 0x02 );
3453 assert( SQLITE_OPEN_CREATE
== 0x04 );
3454 testcase( (1<<(flags
&7))==0x02 ); /* READONLY */
3455 testcase( (1<<(flags
&7))==0x04 ); /* READWRITE */
3456 testcase( (1<<(flags
&7))==0x40 ); /* READWRITE | CREATE */
3457 if( ((1<<(flags
&7)) & 0x46)==0 ){
3458 rc
= SQLITE_MISUSE_BKPT
; /* IMP: R-18321-05872 */
3460 rc
= sqlite3ParseUri(zVfs
, zFilename
, &flags
, &db
->pVfs
, &zOpen
, &zErrMsg
);
3462 if( rc
!=SQLITE_OK
){
3463 if( rc
==SQLITE_NOMEM
) sqlite3OomFault(db
);
3464 sqlite3ErrorWithMsg(db
, rc
, zErrMsg
? "%s" : 0, zErrMsg
);
3465 sqlite3_free(zErrMsg
);
3468 assert( db
->pVfs
!=0 );
3469 #if SQLITE_OS_KV || defined(SQLITE_OS_KV_OPTIONAL)
3470 if( sqlite3_stricmp(db
->pVfs
->zName
, "kvvfs")==0 ){
3475 /* Open the backend database driver */
3476 rc
= sqlite3BtreeOpen(db
->pVfs
, zOpen
, db
, &db
->aDb
[0].pBt
, 0,
3477 flags
| SQLITE_OPEN_MAIN_DB
);
3478 if( rc
!=SQLITE_OK
){
3479 if( rc
==SQLITE_IOERR_NOMEM
){
3480 rc
= SQLITE_NOMEM_BKPT
;
3482 sqlite3Error(db
, rc
);
3485 sqlite3BtreeEnter(db
->aDb
[0].pBt
);
3486 db
->aDb
[0].pSchema
= sqlite3SchemaGet(db
, db
->aDb
[0].pBt
);
3487 if( !db
->mallocFailed
){
3488 sqlite3SetTextEncoding(db
, SCHEMA_ENC(db
));
3490 sqlite3BtreeLeave(db
->aDb
[0].pBt
);
3491 db
->aDb
[1].pSchema
= sqlite3SchemaGet(db
, 0);
3493 /* The default safety_level for the main database is FULL; for the temp
3494 ** database it is OFF. This matches the pager layer defaults.
3496 db
->aDb
[0].zDbSName
= "main";
3497 db
->aDb
[0].safety_level
= SQLITE_DEFAULT_SYNCHRONOUS
+1;
3498 db
->aDb
[1].zDbSName
= "temp";
3499 db
->aDb
[1].safety_level
= PAGER_SYNCHRONOUS_OFF
;
3501 db
->eOpenState
= SQLITE_STATE_OPEN
;
3502 if( db
->mallocFailed
){
3506 /* Register all built-in functions, but do not attempt to read the
3507 ** database schema yet. This is delayed until the first time the database
3510 sqlite3Error(db
, SQLITE_OK
);
3511 sqlite3RegisterPerConnectionBuiltinFunctions(db
);
3512 rc
= sqlite3_errcode(db
);
3515 /* Load compiled-in extensions */
3516 for(i
=0; rc
==SQLITE_OK
&& i
<ArraySize(sqlite3BuiltinExtensions
); i
++){
3517 rc
= sqlite3BuiltinExtensions
[i
](db
);
3520 /* Load automatic extensions - extensions that have been registered
3521 ** using the sqlite3_automatic_extension() API.
3523 if( rc
==SQLITE_OK
){
3524 sqlite3AutoLoadExtensions(db
);
3525 rc
= sqlite3_errcode(db
);
3526 if( rc
!=SQLITE_OK
){
3531 #ifdef SQLITE_ENABLE_INTERNAL_FUNCTIONS
3532 /* Testing use only!!! The -DSQLITE_ENABLE_INTERNAL_FUNCTIONS=1 compile-time
3533 ** option gives access to internal functions by default.
3534 ** Testing use only!!! */
3535 db
->mDbFlags
|= DBFLAG_InternalFunc
;
3538 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
3539 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
3540 ** mode. Doing nothing at all also makes NORMAL the default.
3542 #ifdef SQLITE_DEFAULT_LOCKING_MODE
3543 db
->dfltLockMode
= SQLITE_DEFAULT_LOCKING_MODE
;
3544 sqlite3PagerLockingMode(sqlite3BtreePager(db
->aDb
[0].pBt
),
3545 SQLITE_DEFAULT_LOCKING_MODE
);
3548 if( rc
) sqlite3Error(db
, rc
);
3550 /* Enable the lookaside-malloc subsystem */
3551 setupLookaside(db
, 0, sqlite3GlobalConfig
.szLookaside
,
3552 sqlite3GlobalConfig
.nLookaside
);
3554 sqlite3_wal_autocheckpoint(db
, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
);
3558 assert( db
->mutex
!=0 || isThreadsafe
==0
3559 || sqlite3GlobalConfig
.bFullMutex
==0 );
3560 sqlite3_mutex_leave(db
->mutex
);
3562 rc
= sqlite3_errcode(db
);
3563 assert( db
!=0 || (rc
&0xff)==SQLITE_NOMEM
);
3564 if( (rc
&0xff)==SQLITE_NOMEM
){
3567 }else if( rc
!=SQLITE_OK
){
3568 db
->eOpenState
= SQLITE_STATE_SICK
;
3571 #ifdef SQLITE_ENABLE_SQLLOG
3572 if( sqlite3GlobalConfig
.xSqllog
){
3573 /* Opening a db handle. Fourth parameter is passed 0. */
3574 void *pArg
= sqlite3GlobalConfig
.pSqllogArg
;
3575 sqlite3GlobalConfig
.xSqllog(pArg
, db
, zFilename
, 0);
3578 sqlite3_free_filename(zOpen
);
3584 ** Open a new database handle.
3587 const char *zFilename
,
3590 return openDatabase(zFilename
, ppDb
,
3591 SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
, 0);
3593 int sqlite3_open_v2(
3594 const char *filename
, /* Database filename (UTF-8) */
3595 sqlite3
**ppDb
, /* OUT: SQLite db handle */
3596 int flags
, /* Flags */
3597 const char *zVfs
/* Name of VFS module to use */
3599 return openDatabase(filename
, ppDb
, (unsigned int)flags
, zVfs
);
3602 #ifndef SQLITE_OMIT_UTF16
3604 ** Open a new database handle.
3607 const void *zFilename
,
3610 char const *zFilename8
; /* zFilename encoded in UTF-8 instead of UTF-16 */
3611 sqlite3_value
*pVal
;
3614 #ifdef SQLITE_ENABLE_API_ARMOR
3615 if( ppDb
==0 ) return SQLITE_MISUSE_BKPT
;
3618 #ifndef SQLITE_OMIT_AUTOINIT
3619 rc
= sqlite3_initialize();
3622 if( zFilename
==0 ) zFilename
= "\000\000";
3623 pVal
= sqlite3ValueNew(0);
3624 sqlite3ValueSetStr(pVal
, -1, zFilename
, SQLITE_UTF16NATIVE
, SQLITE_STATIC
);
3625 zFilename8
= sqlite3ValueText(pVal
, SQLITE_UTF8
);
3627 rc
= openDatabase(zFilename8
, ppDb
,
3628 SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
, 0);
3629 assert( *ppDb
|| rc
==SQLITE_NOMEM
);
3630 if( rc
==SQLITE_OK
&& !DbHasProperty(*ppDb
, 0, DB_SchemaLoaded
) ){
3631 SCHEMA_ENC(*ppDb
) = ENC(*ppDb
) = SQLITE_UTF16NATIVE
;
3634 rc
= SQLITE_NOMEM_BKPT
;
3636 sqlite3ValueFree(pVal
);
3640 #endif /* SQLITE_OMIT_UTF16 */
3643 ** Register a new collation sequence with the database handle db.
3645 int sqlite3_create_collation(
3650 int(*xCompare
)(void*,int,const void*,int,const void*)
3652 return sqlite3_create_collation_v2(db
, zName
, enc
, pCtx
, xCompare
, 0);
3656 ** Register a new collation sequence with the database handle db.
3658 int sqlite3_create_collation_v2(
3663 int(*xCompare
)(void*,int,const void*,int,const void*),
3668 #ifdef SQLITE_ENABLE_API_ARMOR
3669 if( !sqlite3SafetyCheckOk(db
) || zName
==0 ) return SQLITE_MISUSE_BKPT
;
3671 sqlite3_mutex_enter(db
->mutex
);
3672 assert( !db
->mallocFailed
);
3673 rc
= createCollation(db
, zName
, (u8
)enc
, pCtx
, xCompare
, xDel
);
3674 rc
= sqlite3ApiExit(db
, rc
);
3675 sqlite3_mutex_leave(db
->mutex
);
3679 #ifndef SQLITE_OMIT_UTF16
3681 ** Register a new collation sequence with the database handle db.
3683 int sqlite3_create_collation16(
3688 int(*xCompare
)(void*,int,const void*,int,const void*)
3693 #ifdef SQLITE_ENABLE_API_ARMOR
3694 if( !sqlite3SafetyCheckOk(db
) || zName
==0 ) return SQLITE_MISUSE_BKPT
;
3696 sqlite3_mutex_enter(db
->mutex
);
3697 assert( !db
->mallocFailed
);
3698 zName8
= sqlite3Utf16to8(db
, zName
, -1, SQLITE_UTF16NATIVE
);
3700 rc
= createCollation(db
, zName8
, (u8
)enc
, pCtx
, xCompare
, 0);
3701 sqlite3DbFree(db
, zName8
);
3703 rc
= sqlite3ApiExit(db
, rc
);
3704 sqlite3_mutex_leave(db
->mutex
);
3707 #endif /* SQLITE_OMIT_UTF16 */
3710 ** Register a collation sequence factory callback with the database handle
3711 ** db. Replace any previously installed collation sequence factory.
3713 int sqlite3_collation_needed(
3715 void *pCollNeededArg
,
3716 void(*xCollNeeded
)(void*,sqlite3
*,int eTextRep
,const char*)
3718 #ifdef SQLITE_ENABLE_API_ARMOR
3719 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
3721 sqlite3_mutex_enter(db
->mutex
);
3722 db
->xCollNeeded
= xCollNeeded
;
3723 db
->xCollNeeded16
= 0;
3724 db
->pCollNeededArg
= pCollNeededArg
;
3725 sqlite3_mutex_leave(db
->mutex
);
3729 #ifndef SQLITE_OMIT_UTF16
3731 ** Register a collation sequence factory callback with the database handle
3732 ** db. Replace any previously installed collation sequence factory.
3734 int sqlite3_collation_needed16(
3736 void *pCollNeededArg
,
3737 void(*xCollNeeded16
)(void*,sqlite3
*,int eTextRep
,const void*)
3739 #ifdef SQLITE_ENABLE_API_ARMOR
3740 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
3742 sqlite3_mutex_enter(db
->mutex
);
3743 db
->xCollNeeded
= 0;
3744 db
->xCollNeeded16
= xCollNeeded16
;
3745 db
->pCollNeededArg
= pCollNeededArg
;
3746 sqlite3_mutex_leave(db
->mutex
);
3749 #endif /* SQLITE_OMIT_UTF16 */
3752 ** Find existing client data.
3754 void *sqlite3_get_clientdata(sqlite3
*db
, const char *zName
){
3756 sqlite3_mutex_enter(db
->mutex
);
3757 for(p
=db
->pDbData
; p
; p
=p
->pNext
){
3758 if( strcmp(p
->zName
, zName
)==0 ){
3759 void *pResult
= p
->pData
;
3760 sqlite3_mutex_leave(db
->mutex
);
3764 sqlite3_mutex_leave(db
->mutex
);
3769 ** Add new client data to a database connection.
3771 int sqlite3_set_clientdata(
3772 sqlite3
*db
, /* Attach client data to this connection */
3773 const char *zName
, /* Name of the client data */
3774 void *pData
, /* The client data itself */
3775 void (*xDestructor
)(void*) /* Destructor */
3777 DbClientData
*p
, **pp
;
3778 sqlite3_mutex_enter(db
->mutex
);
3780 for(p
=db
->pDbData
; p
&& strcmp(p
->zName
,zName
); p
=p
->pNext
){
3784 assert( p
->pData
!=0 );
3785 if( p
->xDestructor
) p
->xDestructor(p
->pData
);
3789 sqlite3_mutex_leave(db
->mutex
);
3792 }else if( pData
==0 ){
3793 sqlite3_mutex_leave(db
->mutex
);
3796 size_t n
= strlen(zName
);
3797 p
= sqlite3_malloc64( sizeof(DbClientData
)+n
+1 );
3799 if( xDestructor
) xDestructor(pData
);
3800 sqlite3_mutex_leave(db
->mutex
);
3801 return SQLITE_NOMEM
;
3803 memcpy(p
->zName
, zName
, n
+1);
3804 p
->pNext
= db
->pDbData
;
3808 p
->xDestructor
= xDestructor
;
3809 sqlite3_mutex_leave(db
->mutex
);
3814 #ifndef SQLITE_OMIT_DEPRECATED
3816 ** This function is now an anachronism. It used to be used to recover from a
3817 ** malloc() failure, but SQLite now does this automatically.
3819 int sqlite3_global_recover(void){
3825 ** Test to see whether or not the database connection is in autocommit
3826 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
3827 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
3828 ** by the next COMMIT or ROLLBACK.
3830 int sqlite3_get_autocommit(sqlite3
*db
){
3831 #ifdef SQLITE_ENABLE_API_ARMOR
3832 if( !sqlite3SafetyCheckOk(db
) ){
3833 (void)SQLITE_MISUSE_BKPT
;
3837 return db
->autoCommit
;
3841 ** The following routines are substitutes for constants SQLITE_CORRUPT,
3842 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
3843 ** constants. They serve two purposes:
3845 ** 1. Serve as a convenient place to set a breakpoint in a debugger
3846 ** to detect when version error conditions occurs.
3848 ** 2. Invoke sqlite3_log() to provide the source code location where
3849 ** a low-level error is first detected.
3851 int sqlite3ReportError(int iErr
, int lineno
, const char *zType
){
3852 sqlite3_log(iErr
, "%s at line %d of [%.10s]",
3853 zType
, lineno
, 20+sqlite3_sourceid());
3856 int sqlite3CorruptError(int lineno
){
3857 testcase( sqlite3GlobalConfig
.xLog
!=0 );
3858 return sqlite3ReportError(SQLITE_CORRUPT
, lineno
, "database corruption");
3860 int sqlite3MisuseError(int lineno
){
3861 testcase( sqlite3GlobalConfig
.xLog
!=0 );
3862 return sqlite3ReportError(SQLITE_MISUSE
, lineno
, "misuse");
3864 int sqlite3CantopenError(int lineno
){
3865 testcase( sqlite3GlobalConfig
.xLog
!=0 );
3866 return sqlite3ReportError(SQLITE_CANTOPEN
, lineno
, "cannot open file");
3868 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
3869 int sqlite3CorruptPgnoError(int lineno
, Pgno pgno
){
3871 sqlite3_snprintf(sizeof(zMsg
), zMsg
, "database corruption page %d", pgno
);
3872 testcase( sqlite3GlobalConfig
.xLog
!=0 );
3873 return sqlite3ReportError(SQLITE_CORRUPT
, lineno
, zMsg
);
3877 int sqlite3NomemError(int lineno
){
3878 testcase( sqlite3GlobalConfig
.xLog
!=0 );
3879 return sqlite3ReportError(SQLITE_NOMEM
, lineno
, "OOM");
3881 int sqlite3IoerrnomemError(int lineno
){
3882 testcase( sqlite3GlobalConfig
.xLog
!=0 );
3883 return sqlite3ReportError(SQLITE_IOERR_NOMEM
, lineno
, "I/O OOM error");
3887 #ifndef SQLITE_OMIT_DEPRECATED
3889 ** This is a convenience routine that makes sure that all thread-specific
3890 ** data for this thread has been deallocated.
3892 ** SQLite no longer uses thread-specific data so this routine is now a
3893 ** no-op. It is retained for historical compatibility.
3895 void sqlite3_thread_cleanup(void){
3900 ** Return meta information about a specific column of a database table.
3901 ** See comment in sqlite3.h (sqlite.h.in) for details.
3903 int sqlite3_table_column_metadata(
3904 sqlite3
*db
, /* Connection handle */
3905 const char *zDbName
, /* Database name or NULL */
3906 const char *zTableName
, /* Table name */
3907 const char *zColumnName
, /* Column name */
3908 char const **pzDataType
, /* OUTPUT: Declared data type */
3909 char const **pzCollSeq
, /* OUTPUT: Collation sequence name */
3910 int *pNotNull
, /* OUTPUT: True if NOT NULL constraint exists */
3911 int *pPrimaryKey
, /* OUTPUT: True if column part of PK */
3912 int *pAutoinc
/* OUTPUT: True if column is auto-increment */
3919 char const *zDataType
= 0;
3920 char const *zCollSeq
= 0;
3926 #ifdef SQLITE_ENABLE_API_ARMOR
3927 if( !sqlite3SafetyCheckOk(db
) || zTableName
==0 ){
3928 return SQLITE_MISUSE_BKPT
;
3932 /* Ensure the database schema has been loaded */
3933 sqlite3_mutex_enter(db
->mutex
);
3934 sqlite3BtreeEnterAll(db
);
3935 rc
= sqlite3Init(db
, &zErrMsg
);
3936 if( SQLITE_OK
!=rc
){
3940 /* Locate the table in question */
3941 pTab
= sqlite3FindTable(db
, zTableName
, zDbName
);
3942 if( !pTab
|| IsView(pTab
) ){
3947 /* Find the column for which info is requested */
3948 if( zColumnName
==0 ){
3949 /* Query for existence of table only */
3951 for(iCol
=0; iCol
<pTab
->nCol
; iCol
++){
3952 pCol
= &pTab
->aCol
[iCol
];
3953 if( 0==sqlite3StrICmp(pCol
->zCnName
, zColumnName
) ){
3957 if( iCol
==pTab
->nCol
){
3958 if( HasRowid(pTab
) && sqlite3IsRowid(zColumnName
) ){
3960 pCol
= iCol
>=0 ? &pTab
->aCol
[iCol
] : 0;
3968 /* The following block stores the meta information that will be returned
3969 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
3970 ** and autoinc. At this point there are two possibilities:
3972 ** 1. The specified column name was rowid", "oid" or "_rowid_"
3973 ** and there is no explicitly declared IPK column.
3975 ** 2. The table is not a view and the column name identified an
3976 ** explicitly declared column. Copy meta information from *pCol.
3979 zDataType
= sqlite3ColumnType(pCol
,0);
3980 zCollSeq
= sqlite3ColumnColl(pCol
);
3981 notnull
= pCol
->notNull
!=0;
3982 primarykey
= (pCol
->colFlags
& COLFLAG_PRIMKEY
)!=0;
3983 autoinc
= pTab
->iPKey
==iCol
&& (pTab
->tabFlags
& TF_Autoincrement
)!=0;
3985 zDataType
= "INTEGER";
3989 zCollSeq
= sqlite3StrBINARY
;
3993 sqlite3BtreeLeaveAll(db
);
3995 /* Whether the function call succeeded or failed, set the output parameters
3996 ** to whatever their local counterparts contain. If an error did occur,
3997 ** this has the effect of zeroing all output parameters.
3999 if( pzDataType
) *pzDataType
= zDataType
;
4000 if( pzCollSeq
) *pzCollSeq
= zCollSeq
;
4001 if( pNotNull
) *pNotNull
= notnull
;
4002 if( pPrimaryKey
) *pPrimaryKey
= primarykey
;
4003 if( pAutoinc
) *pAutoinc
= autoinc
;
4005 if( SQLITE_OK
==rc
&& !pTab
){
4006 sqlite3DbFree(db
, zErrMsg
);
4007 zErrMsg
= sqlite3MPrintf(db
, "no such table column: %s.%s", zTableName
,
4011 sqlite3ErrorWithMsg(db
, rc
, (zErrMsg
?"%s":0), zErrMsg
);
4012 sqlite3DbFree(db
, zErrMsg
);
4013 rc
= sqlite3ApiExit(db
, rc
);
4014 sqlite3_mutex_leave(db
->mutex
);
4019 ** Sleep for a little while. Return the amount of time slept.
4021 int sqlite3_sleep(int ms
){
4024 pVfs
= sqlite3_vfs_find(0);
4025 if( pVfs
==0 ) return 0;
4027 /* This function works in milliseconds, but the underlying OsSleep()
4028 ** API uses microseconds. Hence the 1000's.
4030 rc
= (sqlite3OsSleep(pVfs
, ms
<0 ? 0 : 1000*ms
)/1000);
4035 ** Enable or disable the extended result codes.
4037 int sqlite3_extended_result_codes(sqlite3
*db
, int onoff
){
4038 #ifdef SQLITE_ENABLE_API_ARMOR
4039 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
4041 sqlite3_mutex_enter(db
->mutex
);
4042 db
->errMask
= onoff
? 0xffffffff : 0xff;
4043 sqlite3_mutex_leave(db
->mutex
);
4048 ** Invoke the xFileControl method on a particular database.
4050 int sqlite3_file_control(sqlite3
*db
, const char *zDbName
, int op
, void *pArg
){
4051 int rc
= SQLITE_ERROR
;
4054 #ifdef SQLITE_ENABLE_API_ARMOR
4055 if( !sqlite3SafetyCheckOk(db
) ) return SQLITE_MISUSE_BKPT
;
4057 sqlite3_mutex_enter(db
->mutex
);
4058 pBtree
= sqlite3DbNameToBtree(db
, zDbName
);
4062 sqlite3BtreeEnter(pBtree
);
4063 pPager
= sqlite3BtreePager(pBtree
);
4064 assert( pPager
!=0 );
4065 fd
= sqlite3PagerFile(pPager
);
4067 if( op
==SQLITE_FCNTL_FILE_POINTER
){
4068 *(sqlite3_file
**)pArg
= fd
;
4070 }else if( op
==SQLITE_FCNTL_VFS_POINTER
){
4071 *(sqlite3_vfs
**)pArg
= sqlite3PagerVfs(pPager
);
4073 }else if( op
==SQLITE_FCNTL_JOURNAL_POINTER
){
4074 *(sqlite3_file
**)pArg
= sqlite3PagerJrnlFile(pPager
);
4076 }else if( op
==SQLITE_FCNTL_DATA_VERSION
){
4077 *(unsigned int*)pArg
= sqlite3PagerDataVersion(pPager
);
4079 }else if( op
==SQLITE_FCNTL_RESERVE_BYTES
){
4080 int iNew
= *(int*)pArg
;
4081 *(int*)pArg
= sqlite3BtreeGetRequestedReserve(pBtree
);
4082 if( iNew
>=0 && iNew
<=255 ){
4083 sqlite3BtreeSetPageSize(pBtree
, 0, iNew
, 0);
4086 }else if( op
==SQLITE_FCNTL_RESET_CACHE
){
4087 sqlite3BtreeClearCache(pBtree
);
4090 int nSave
= db
->busyHandler
.nBusy
;
4091 rc
= sqlite3OsFileControl(fd
, op
, pArg
);
4092 db
->busyHandler
.nBusy
= nSave
;
4094 sqlite3BtreeLeave(pBtree
);
4096 sqlite3_mutex_leave(db
->mutex
);
4101 ** Interface to the testing logic.
4103 int sqlite3_test_control(int op
, ...){
4105 #ifdef SQLITE_UNTESTABLE
4106 UNUSED_PARAMETER(op
);
4113 ** Save the current state of the PRNG.
4115 case SQLITE_TESTCTRL_PRNG_SAVE
: {
4116 sqlite3PrngSaveState();
4121 ** Restore the state of the PRNG to the last state saved using
4122 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
4123 ** this verb acts like PRNG_RESET.
4125 case SQLITE_TESTCTRL_PRNG_RESTORE
: {
4126 sqlite3PrngRestoreState();
4130 /* sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, int x, sqlite3 *db);
4132 ** Control the seed for the pseudo-random number generator (PRNG) that
4133 ** is built into SQLite. Cases:
4135 ** x!=0 && db!=0 Seed the PRNG to the current value of the
4136 ** schema cookie in the main database for db, or
4137 ** x if the schema cookie is zero. This case
4138 ** is convenient to use with database fuzzers
4139 ** as it allows the fuzzer some control over the
4142 ** x!=0 && db==0 Seed the PRNG to the value of x.
4144 ** x==0 && db==0 Revert to default behavior of using the
4145 ** xRandomness method on the primary VFS.
4147 ** This test-control also resets the PRNG so that the new seed will
4148 ** be used for the next call to sqlite3_randomness().
4150 #ifndef SQLITE_OMIT_WSD
4151 case SQLITE_TESTCTRL_PRNG_SEED
: {
4152 int x
= va_arg(ap
, int);
4154 sqlite3
*db
= va_arg(ap
, sqlite3
*);
4155 assert( db
==0 || db
->aDb
[0].pSchema
!=0 );
4156 if( db
&& (y
= db
->aDb
[0].pSchema
->schema_cookie
)!=0 ){ x
= y
; }
4157 sqlite3Config
.iPrngSeed
= x
;
4158 sqlite3_randomness(0,0);
4164 ** sqlite3_test_control(BITVEC_TEST, size, program)
4166 ** Run a test against a Bitvec object of size. The program argument
4167 ** is an array of integers that defines the test. Return -1 on a
4168 ** memory allocation error, 0 on success, or non-zero for an error.
4169 ** See the sqlite3BitvecBuiltinTest() for additional information.
4171 case SQLITE_TESTCTRL_BITVEC_TEST
: {
4172 int sz
= va_arg(ap
, int);
4173 int *aProg
= va_arg(ap
, int*);
4174 rc
= sqlite3BitvecBuiltinTest(sz
, aProg
);
4179 ** sqlite3_test_control(FAULT_INSTALL, xCallback)
4181 ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
4182 ** if xCallback is not NULL.
4184 ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
4185 ** is called immediately after installing the new callback and the return
4186 ** value from sqlite3FaultSim(0) becomes the return from
4187 ** sqlite3_test_control().
4189 case SQLITE_TESTCTRL_FAULT_INSTALL
: {
4190 /* A bug in MSVC prevents it from understanding pointers to functions
4191 ** types in the second argument to va_arg(). Work around the problem
4193 ** http://support.microsoft.com/kb/47961 <-- dead hyperlink
4194 ** Search at http://web.archive.org/ to find the 2015-03-16 archive
4195 ** of the link above to see the original text.
4196 ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
4198 typedef int(*sqlite3FaultFuncType
)(int);
4199 sqlite3GlobalConfig
.xTestCallback
= va_arg(ap
, sqlite3FaultFuncType
);
4200 rc
= sqlite3FaultSim(0);
4205 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
4207 ** Register hooks to call to indicate which malloc() failures
4210 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS
: {
4211 typedef void (*void_function
)(void);
4212 void_function xBenignBegin
;
4213 void_function xBenignEnd
;
4214 xBenignBegin
= va_arg(ap
, void_function
);
4215 xBenignEnd
= va_arg(ap
, void_function
);
4216 sqlite3BenignMallocHooks(xBenignBegin
, xBenignEnd
);
4221 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
4223 ** Set the PENDING byte to the value in the argument, if X>0.
4224 ** Make no changes if X==0. Return the value of the pending byte
4225 ** as it existing before this routine was called.
4227 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
4228 ** an incompatible database file format. Changing the PENDING byte
4229 ** while any database connection is open results in undefined and
4230 ** deleterious behavior.
4232 case SQLITE_TESTCTRL_PENDING_BYTE
: {
4234 #ifndef SQLITE_OMIT_WSD
4236 unsigned int newVal
= va_arg(ap
, unsigned int);
4237 if( newVal
) sqlite3PendingByte
= newVal
;
4244 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
4246 ** This action provides a run-time test to see whether or not
4247 ** assert() was enabled at compile-time. If X is true and assert()
4248 ** is enabled, then the return value is true. If X is true and
4249 ** assert() is disabled, then the return value is zero. If X is
4250 ** false and assert() is enabled, then the assertion fires and the
4251 ** process aborts. If X is false and assert() is disabled, then the
4252 ** return value is zero.
4254 case SQLITE_TESTCTRL_ASSERT
: {
4256 assert( /*side-effects-ok*/ (x
= va_arg(ap
,int))!=0 );
4258 #if defined(SQLITE_DEBUG)
4259 /* Invoke these debugging routines so that the compiler does not
4260 ** issue "defined but not used" warnings. */
4264 sqlite3ShowExprList(0);
4265 sqlite3ShowIdList(0);
4266 sqlite3ShowSrcList(0);
4268 sqlite3ShowUpsert(0);
4269 #ifndef SQLITE_OMIT_TRIGGER
4270 sqlite3ShowTriggerStep(0);
4271 sqlite3ShowTriggerStepList(0);
4272 sqlite3ShowTrigger(0);
4273 sqlite3ShowTriggerList(0);
4275 #ifndef SQLITE_OMIT_WINDOWFUNC
4276 sqlite3ShowWindow(0);
4277 sqlite3ShowWinFunc(0);
4279 sqlite3ShowSelect(0);
4287 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
4289 ** This action provides a run-time test to see how the ALWAYS and
4290 ** NEVER macros were defined at compile-time.
4292 ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
4294 ** The recommended test is X==2. If the return value is 2, that means
4295 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
4296 ** default setting. If the return value is 1, then ALWAYS() is either
4297 ** hard-coded to true or else it asserts if its argument is false.
4298 ** The first behavior (hard-coded to true) is the case if
4299 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
4300 ** behavior (assert if the argument to ALWAYS() is false) is the case if
4301 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
4303 ** The run-time test procedure might look something like this:
4305 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
4306 ** // ALWAYS() and NEVER() are no-op pass-through macros
4307 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
4308 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
4310 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
4313 case SQLITE_TESTCTRL_ALWAYS
: {
4314 int x
= va_arg(ap
,int);
4315 rc
= x
? ALWAYS(x
) : 0;
4320 ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
4322 ** The integer returned reveals the byte-order of the computer on which
4323 ** SQLite is running:
4325 ** 1 big-endian, determined at run-time
4326 ** 10 little-endian, determined at run-time
4327 ** 432101 big-endian, determined at compile-time
4328 ** 123410 little-endian, determined at compile-time
4330 case SQLITE_TESTCTRL_BYTEORDER
: {
4331 rc
= SQLITE_BYTEORDER
*100 + SQLITE_LITTLEENDIAN
*10 + SQLITE_BIGENDIAN
;
4335 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
4337 ** Enable or disable various optimizations for testing purposes. The
4338 ** argument N is a bitmask of optimizations to be disabled. For normal
4339 ** operation N should be 0. The idea is that a test program (like the
4340 ** SQL Logic Test or SLT test module) can run the same SQL multiple times
4341 ** with various optimizations disabled to verify that the same answer
4342 ** is obtained in every case.
4344 case SQLITE_TESTCTRL_OPTIMIZATIONS
: {
4345 sqlite3
*db
= va_arg(ap
, sqlite3
*);
4346 db
->dbOptFlags
= va_arg(ap
, u32
);
4350 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, onoff, xAlt);
4352 ** If parameter onoff is 1, subsequent calls to localtime() fail.
4353 ** If 2, then invoke xAlt() instead of localtime(). If 0, normal
4356 ** xAlt arguments are void pointers, but they really want to be:
4358 ** int xAlt(const time_t*, struct tm*);
4360 ** xAlt should write results in to struct tm object of its 2nd argument
4361 ** and return zero on success, or return non-zero on failure.
4363 case SQLITE_TESTCTRL_LOCALTIME_FAULT
: {
4364 sqlite3GlobalConfig
.bLocaltimeFault
= va_arg(ap
, int);
4365 if( sqlite3GlobalConfig
.bLocaltimeFault
==2 ){
4366 typedef int(*sqlite3LocaltimeType
)(const void*,void*);
4367 sqlite3GlobalConfig
.xAltLocaltime
= va_arg(ap
, sqlite3LocaltimeType
);
4369 sqlite3GlobalConfig
.xAltLocaltime
= 0;
4374 /* sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, sqlite3*);
4376 ** Toggle the ability to use internal functions on or off for
4377 ** the database connection given in the argument.
4379 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
: {
4380 sqlite3
*db
= va_arg(ap
, sqlite3
*);
4381 db
->mDbFlags
^= DBFLAG_InternalFunc
;
4385 /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
4387 ** Set or clear a flag that indicates that the database file is always well-
4388 ** formed and never corrupt. This flag is clear by default, indicating that
4389 ** database files might have arbitrary corruption. Setting the flag during
4390 ** testing causes certain assert() statements in the code to be activated
4391 ** that demonstrate invariants on well-formed database files.
4393 case SQLITE_TESTCTRL_NEVER_CORRUPT
: {
4394 sqlite3GlobalConfig
.neverCorrupt
= va_arg(ap
, int);
4398 /* sqlite3_test_control(SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS, int);
4400 ** Set or clear a flag that causes SQLite to verify that type, name,
4401 ** and tbl_name fields of the sqlite_schema table. This is normally
4402 ** on, but it is sometimes useful to turn it off for testing.
4404 ** 2020-07-22: Disabling EXTRA_SCHEMA_CHECKS also disables the
4405 ** verification of rootpage numbers when parsing the schema. This
4406 ** is useful to make it easier to reach strange internal error states
4407 ** during testing. The EXTRA_SCHEMA_CHECKS setting is always enabled
4410 case SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS
: {
4411 sqlite3GlobalConfig
.bExtraSchemaChecks
= va_arg(ap
, int);
4415 /* Set the threshold at which OP_Once counters reset back to zero.
4416 ** By default this is 0x7ffffffe (over 2 billion), but that value is
4417 ** too big to test in a reasonable amount of time, so this control is
4418 ** provided to set a small and easily reachable reset value.
4420 case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD
: {
4421 sqlite3GlobalConfig
.iOnceResetThreshold
= va_arg(ap
, int);
4425 /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
4427 ** Set the VDBE coverage callback function to xCallback with context
4430 case SQLITE_TESTCTRL_VDBE_COVERAGE
: {
4431 #ifdef SQLITE_VDBE_COVERAGE
4432 typedef void (*branch_callback
)(void*,unsigned int,
4433 unsigned char,unsigned char);
4434 sqlite3GlobalConfig
.xVdbeBranch
= va_arg(ap
,branch_callback
);
4435 sqlite3GlobalConfig
.pVdbeBranchArg
= va_arg(ap
,void*);
4440 /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
4441 case SQLITE_TESTCTRL_SORTER_MMAP
: {
4442 sqlite3
*db
= va_arg(ap
, sqlite3
*);
4443 db
->nMaxSorterMmap
= va_arg(ap
, int);
4447 /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
4449 ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
4452 case SQLITE_TESTCTRL_ISINIT
: {
4453 if( sqlite3GlobalConfig
.isInit
==0 ) rc
= SQLITE_ERROR
;
4457 /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
4459 ** This test control is used to create imposter tables. "db" is a pointer
4460 ** to the database connection. dbName is the database name (ex: "main" or
4461 ** "temp") which will receive the imposter. "onOff" turns imposter mode on
4462 ** or off. "tnum" is the root page of the b-tree to which the imposter
4463 ** table should connect.
4465 ** Enable imposter mode only when the schema has already been parsed. Then
4466 ** run a single CREATE TABLE statement to construct the imposter table in
4467 ** the parsed schema. Then turn imposter mode back off again.
4469 ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
4470 ** the schema to be reparsed the next time it is needed. This has the
4471 ** effect of erasing all imposter tables.
4473 case SQLITE_TESTCTRL_IMPOSTER
: {
4474 sqlite3
*db
= va_arg(ap
, sqlite3
*);
4476 sqlite3_mutex_enter(db
->mutex
);
4477 iDb
= sqlite3FindDbName(db
, va_arg(ap
,const char*));
4480 db
->init
.busy
= db
->init
.imposterTable
= va_arg(ap
,int);
4481 db
->init
.newTnum
= va_arg(ap
,int);
4482 if( db
->init
.busy
==0 && db
->init
.newTnum
>0 ){
4483 sqlite3ResetAllSchemasOfConnection(db
);
4486 sqlite3_mutex_leave(db
->mutex
);
4490 #if defined(YYCOVERAGE)
4491 /* sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
4493 ** This test control (only available when SQLite is compiled with
4494 ** -DYYCOVERAGE) writes a report onto "out" that shows all
4495 ** state/lookahead combinations in the parser state machine
4496 ** which are never exercised. If any state is missed, make the
4497 ** return code SQLITE_ERROR.
4499 case SQLITE_TESTCTRL_PARSER_COVERAGE
: {
4500 FILE *out
= va_arg(ap
, FILE*);
4501 if( sqlite3ParserCoverage(out
) ) rc
= SQLITE_ERROR
;
4504 #endif /* defined(YYCOVERAGE) */
4506 /* sqlite3_test_control(SQLITE_TESTCTRL_RESULT_INTREAL, sqlite3_context*);
4508 ** This test-control causes the most recent sqlite3_result_int64() value
4509 ** to be interpreted as a MEM_IntReal instead of as an MEM_Int. Normally,
4510 ** MEM_IntReal values only arise during an INSERT operation of integer
4511 ** values into a REAL column, so they can be challenging to test. This
4512 ** test-control enables us to write an intreal() SQL function that can
4513 ** inject an intreal() value at arbitrary places in an SQL statement,
4514 ** for testing purposes.
4516 case SQLITE_TESTCTRL_RESULT_INTREAL
: {
4517 sqlite3_context
*pCtx
= va_arg(ap
, sqlite3_context
*);
4518 sqlite3ResultIntReal(pCtx
);
4522 /* sqlite3_test_control(SQLITE_TESTCTRL_SEEK_COUNT,
4523 ** sqlite3 *db, // Database connection
4524 ** u64 *pnSeek // Write seek count here
4527 ** This test-control queries the seek-counter on the "main" database
4528 ** file. The seek-counter is written into *pnSeek and is then reset.
4529 ** The seek-count is only available if compiled with SQLITE_DEBUG.
4531 case SQLITE_TESTCTRL_SEEK_COUNT
: {
4532 sqlite3
*db
= va_arg(ap
, sqlite3
*);
4533 u64
*pn
= va_arg(ap
, sqlite3_uint64
*);
4534 *pn
= sqlite3BtreeSeekCount(db
->aDb
->pBt
);
4535 (void)db
; /* Silence harmless unused variable warning */
4539 /* sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, op, ptr)
4541 ** "ptr" is a pointer to a u32.
4543 ** op==0 Store the current sqlite3TreeTrace in *ptr
4544 ** op==1 Set sqlite3TreeTrace to the value *ptr
4545 ** op==2 Store the current sqlite3WhereTrace in *ptr
4546 ** op==3 Set sqlite3WhereTrace to the value *ptr
4548 case SQLITE_TESTCTRL_TRACEFLAGS
: {
4549 int opTrace
= va_arg(ap
, int);
4550 u32
*ptr
= va_arg(ap
, u32
*);
4552 case 0: *ptr
= sqlite3TreeTrace
; break;
4553 case 1: sqlite3TreeTrace
= *ptr
; break;
4554 case 2: *ptr
= sqlite3WhereTrace
; break;
4555 case 3: sqlite3WhereTrace
= *ptr
; break;
4560 /* sqlite3_test_control(SQLITE_TESTCTRL_LOGEST,
4561 ** double fIn, // Input value
4562 ** int *pLogEst, // sqlite3LogEstFromDouble(fIn)
4563 ** u64 *pInt, // sqlite3LogEstToInt(*pLogEst)
4564 ** int *pLogEst2 // sqlite3LogEst(*pInt)
4567 ** Test access for the LogEst conversion routines.
4569 case SQLITE_TESTCTRL_LOGEST
: {
4570 double rIn
= va_arg(ap
, double);
4571 LogEst rLogEst
= sqlite3LogEstFromDouble(rIn
);
4572 int *pI1
= va_arg(ap
,int*);
4573 u64
*pU64
= va_arg(ap
,u64
*);
4574 int *pI2
= va_arg(ap
,int*);
4576 *pU64
= sqlite3LogEstToInt(rLogEst
);
4577 *pI2
= sqlite3LogEst(*pU64
);
4581 #if !defined(SQLITE_OMIT_WSD)
4582 /* sqlite3_test_control(SQLITE_TESTCTRL_USELONGDOUBLE, int X);
4584 ** X<0 Make no changes to the bUseLongDouble. Just report value.
4585 ** X==0 Disable bUseLongDouble
4586 ** X==1 Enable bUseLongDouble
4587 ** X>=2 Set bUseLongDouble to its default value for this platform
4589 case SQLITE_TESTCTRL_USELONGDOUBLE
: {
4590 int b
= va_arg(ap
, int);
4591 if( b
>=2 ) b
= hasHighPrecisionDouble(b
);
4592 if( b
>=0 ) sqlite3Config
.bUseLongDouble
= b
>0;
4593 rc
= sqlite3Config
.bUseLongDouble
!=0;
4599 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
4600 /* sqlite3_test_control(SQLITE_TESTCTRL_TUNE, id, *piValue)
4602 ** If "id" is an integer between 1 and SQLITE_NTUNE then set the value
4603 ** of the id-th tuning parameter to *piValue. If "id" is between -1
4604 ** and -SQLITE_NTUNE, then write the current value of the (-id)-th
4605 ** tuning parameter into *piValue.
4607 ** Tuning parameters are for use during transient development builds,
4608 ** to help find the best values for constants in the query planner.
4609 ** Access tuning parameters using the Tuning(ID) macro. Set the
4610 ** parameters in the CLI using ".testctrl tune ID VALUE".
4612 ** Transient use only. Tuning parameters should not be used in
4615 case SQLITE_TESTCTRL_TUNE
: {
4616 int id
= va_arg(ap
, int);
4617 int *piValue
= va_arg(ap
, int*);
4618 if( id
>0 && id
<=SQLITE_NTUNE
){
4619 Tuning(id
) = *piValue
;
4620 }else if( id
<0 && id
>=-SQLITE_NTUNE
){
4621 *piValue
= Tuning(-id
);
4623 rc
= SQLITE_NOTFOUND
;
4630 #endif /* SQLITE_UNTESTABLE */
4635 ** The Pager stores the Database filename, Journal filename, and WAL filename
4636 ** consecutively in memory, in that order. The database filename is prefixed
4637 ** by four zero bytes. Locate the start of the database filename by searching
4638 ** backwards for the first byte following four consecutive zero bytes.
4640 ** This only works if the filename passed in was obtained from the Pager.
4642 static const char *databaseName(const char *zName
){
4643 while( zName
[-1]!=0 || zName
[-2]!=0 || zName
[-3]!=0 || zName
[-4]!=0 ){
4650 ** Append text z[] to the end of p[]. Return a pointer to the first
4651 ** character after then zero terminator on the new text in p[].
4653 static char *appendText(char *p
, const char *z
){
4654 size_t n
= strlen(z
);
4660 ** Allocate memory to hold names for a database, journal file, WAL file,
4661 ** and query parameters. The pointer returned is valid for use by
4662 ** sqlite3_filename_database() and sqlite3_uri_parameter() and related
4665 ** Memory layout must be compatible with that generated by the pager
4666 ** and expected by sqlite3_uri_parameter() and databaseName().
4668 const char *sqlite3_create_filename(
4669 const char *zDatabase
,
4670 const char *zJournal
,
4673 const char **azParam
4675 sqlite3_int64 nByte
;
4678 nByte
= strlen(zDatabase
) + strlen(zJournal
) + strlen(zWal
) + 10;
4679 for(i
=0; i
<nParam
*2; i
++){
4680 nByte
+= strlen(azParam
[i
])+1;
4682 pResult
= p
= sqlite3_malloc64( nByte
);
4683 if( p
==0 ) return 0;
4686 p
= appendText(p
, zDatabase
);
4687 for(i
=0; i
<nParam
*2; i
++){
4688 p
= appendText(p
, azParam
[i
]);
4691 p
= appendText(p
, zJournal
);
4692 p
= appendText(p
, zWal
);
4695 assert( (sqlite3_int64
)(p
- pResult
)==nByte
);
4700 ** Free memory obtained from sqlite3_create_filename(). It is a severe
4701 ** error to call this routine with any parameter other than a pointer
4702 ** previously obtained from sqlite3_create_filename() or a NULL pointer.
4704 void sqlite3_free_filename(const char *p
){
4706 p
= databaseName(p
);
4707 sqlite3_free((char*)p
- 4);
4712 ** This is a utility routine, useful to VFS implementations, that checks
4713 ** to see if a database file was a URI that contained a specific query
4714 ** parameter, and if so obtains the value of the query parameter.
4716 ** The zFilename argument is the filename pointer passed into the xOpen()
4717 ** method of a VFS implementation. The zParam argument is the name of the
4718 ** query parameter we seek. This routine returns the value of the zParam
4719 ** parameter if it exists. If the parameter does not exist, this routine
4720 ** returns a NULL pointer.
4722 const char *sqlite3_uri_parameter(const char *zFilename
, const char *zParam
){
4723 if( zFilename
==0 || zParam
==0 ) return 0;
4724 zFilename
= databaseName(zFilename
);
4725 return uriParameter(zFilename
, zParam
);
4729 ** Return a pointer to the name of Nth query parameter of the filename.
4731 const char *sqlite3_uri_key(const char *zFilename
, int N
){
4732 if( zFilename
==0 || N
<0 ) return 0;
4733 zFilename
= databaseName(zFilename
);
4734 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
4735 while( ALWAYS(zFilename
) && zFilename
[0] && (N
--)>0 ){
4736 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
4737 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
4739 return zFilename
[0] ? zFilename
: 0;
4743 ** Return a boolean value for a query parameter.
4745 int sqlite3_uri_boolean(const char *zFilename
, const char *zParam
, int bDflt
){
4746 const char *z
= sqlite3_uri_parameter(zFilename
, zParam
);
4748 return z
? sqlite3GetBoolean(z
, bDflt
) : bDflt
;
4752 ** Return a 64-bit integer value for a query parameter.
4754 sqlite3_int64
sqlite3_uri_int64(
4755 const char *zFilename
, /* Filename as passed to xOpen */
4756 const char *zParam
, /* URI parameter sought */
4757 sqlite3_int64 bDflt
/* return if parameter is missing */
4759 const char *z
= sqlite3_uri_parameter(zFilename
, zParam
);
4761 if( z
&& sqlite3DecOrHexToI64(z
, &v
)==0 ){
4768 ** Translate a filename that was handed to a VFS routine into the corresponding
4769 ** database, journal, or WAL file.
4771 ** It is an error to pass this routine a filename string that was not
4772 ** passed into the VFS from the SQLite core. Doing so is similar to
4773 ** passing free() a pointer that was not obtained from malloc() - it is
4774 ** an error that we cannot easily detect but that will likely cause memory
4777 const char *sqlite3_filename_database(const char *zFilename
){
4778 if( zFilename
==0 ) return 0;
4779 return databaseName(zFilename
);
4781 const char *sqlite3_filename_journal(const char *zFilename
){
4782 if( zFilename
==0 ) return 0;
4783 zFilename
= databaseName(zFilename
);
4784 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
4785 while( ALWAYS(zFilename
) && zFilename
[0] ){
4786 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
4787 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
4789 return zFilename
+ 1;
4791 const char *sqlite3_filename_wal(const char *zFilename
){
4792 #ifdef SQLITE_OMIT_WAL
4795 zFilename
= sqlite3_filename_journal(zFilename
);
4796 if( zFilename
) zFilename
+= sqlite3Strlen30(zFilename
) + 1;
4802 ** Return the Btree pointer identified by zDbName. Return NULL if not found.
4804 Btree
*sqlite3DbNameToBtree(sqlite3
*db
, const char *zDbName
){
4805 int iDb
= zDbName
? sqlite3FindDbName(db
, zDbName
) : 0;
4806 return iDb
<0 ? 0 : db
->aDb
[iDb
].pBt
;
4810 ** Return the name of the N-th database schema. Return NULL if N is out
4813 const char *sqlite3_db_name(sqlite3
*db
, int N
){
4814 #ifdef SQLITE_ENABLE_API_ARMOR
4815 if( !sqlite3SafetyCheckOk(db
) ){
4816 (void)SQLITE_MISUSE_BKPT
;
4820 if( N
<0 || N
>=db
->nDb
){
4823 return db
->aDb
[N
].zDbSName
;
4828 ** Return the filename of the database associated with a database
4831 const char *sqlite3_db_filename(sqlite3
*db
, const char *zDbName
){
4833 #ifdef SQLITE_ENABLE_API_ARMOR
4834 if( !sqlite3SafetyCheckOk(db
) ){
4835 (void)SQLITE_MISUSE_BKPT
;
4839 pBt
= sqlite3DbNameToBtree(db
, zDbName
);
4840 return pBt
? sqlite3BtreeGetFilename(pBt
) : 0;
4844 ** Return 1 if database is read-only or 0 if read/write. Return -1 if
4845 ** no such database exists.
4847 int sqlite3_db_readonly(sqlite3
*db
, const char *zDbName
){
4849 #ifdef SQLITE_ENABLE_API_ARMOR
4850 if( !sqlite3SafetyCheckOk(db
) ){
4851 (void)SQLITE_MISUSE_BKPT
;
4855 pBt
= sqlite3DbNameToBtree(db
, zDbName
);
4856 return pBt
? sqlite3BtreeIsReadonly(pBt
) : -1;
4859 #ifdef SQLITE_ENABLE_SNAPSHOT
4861 ** Obtain a snapshot handle for the snapshot of database zDb currently
4862 ** being read by handle db.
4864 int sqlite3_snapshot_get(
4867 sqlite3_snapshot
**ppSnapshot
4869 int rc
= SQLITE_ERROR
;
4870 #ifndef SQLITE_OMIT_WAL
4872 #ifdef SQLITE_ENABLE_API_ARMOR
4873 if( !sqlite3SafetyCheckOk(db
) ){
4874 return SQLITE_MISUSE_BKPT
;
4877 sqlite3_mutex_enter(db
->mutex
);
4879 if( db
->autoCommit
==0 ){
4880 int iDb
= sqlite3FindDbName(db
, zDb
);
4881 if( iDb
==0 || iDb
>1 ){
4882 Btree
*pBt
= db
->aDb
[iDb
].pBt
;
4883 if( SQLITE_TXN_WRITE
!=sqlite3BtreeTxnState(pBt
) ){
4884 rc
= sqlite3BtreeBeginTrans(pBt
, 0, 0);
4885 if( rc
==SQLITE_OK
){
4886 rc
= sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt
), ppSnapshot
);
4892 sqlite3_mutex_leave(db
->mutex
);
4893 #endif /* SQLITE_OMIT_WAL */
4898 ** Open a read-transaction on the snapshot identified by pSnapshot.
4900 int sqlite3_snapshot_open(
4903 sqlite3_snapshot
*pSnapshot
4905 int rc
= SQLITE_ERROR
;
4906 #ifndef SQLITE_OMIT_WAL
4908 #ifdef SQLITE_ENABLE_API_ARMOR
4909 if( !sqlite3SafetyCheckOk(db
) ){
4910 return SQLITE_MISUSE_BKPT
;
4913 sqlite3_mutex_enter(db
->mutex
);
4914 if( db
->autoCommit
==0 ){
4916 iDb
= sqlite3FindDbName(db
, zDb
);
4917 if( iDb
==0 || iDb
>1 ){
4918 Btree
*pBt
= db
->aDb
[iDb
].pBt
;
4919 if( sqlite3BtreeTxnState(pBt
)!=SQLITE_TXN_WRITE
){
4920 Pager
*pPager
= sqlite3BtreePager(pBt
);
4922 if( sqlite3BtreeTxnState(pBt
)!=SQLITE_TXN_NONE
){
4923 if( db
->nVdbeActive
==0 ){
4924 rc
= sqlite3PagerSnapshotCheck(pPager
, pSnapshot
);
4925 if( rc
==SQLITE_OK
){
4927 rc
= sqlite3BtreeCommit(pBt
);
4933 if( rc
==SQLITE_OK
){
4934 rc
= sqlite3PagerSnapshotOpen(pPager
, pSnapshot
);
4936 if( rc
==SQLITE_OK
){
4937 rc
= sqlite3BtreeBeginTrans(pBt
, 0, 0);
4938 sqlite3PagerSnapshotOpen(pPager
, 0);
4941 sqlite3PagerSnapshotUnlock(pPager
);
4947 sqlite3_mutex_leave(db
->mutex
);
4948 #endif /* SQLITE_OMIT_WAL */
4953 ** Recover as many snapshots as possible from the wal file associated with
4954 ** schema zDb of database db.
4956 int sqlite3_snapshot_recover(sqlite3
*db
, const char *zDb
){
4957 int rc
= SQLITE_ERROR
;
4958 #ifndef SQLITE_OMIT_WAL
4961 #ifdef SQLITE_ENABLE_API_ARMOR
4962 if( !sqlite3SafetyCheckOk(db
) ){
4963 return SQLITE_MISUSE_BKPT
;
4967 sqlite3_mutex_enter(db
->mutex
);
4968 iDb
= sqlite3FindDbName(db
, zDb
);
4969 if( iDb
==0 || iDb
>1 ){
4970 Btree
*pBt
= db
->aDb
[iDb
].pBt
;
4971 if( SQLITE_TXN_NONE
==sqlite3BtreeTxnState(pBt
) ){
4972 rc
= sqlite3BtreeBeginTrans(pBt
, 0, 0);
4973 if( rc
==SQLITE_OK
){
4974 rc
= sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt
));
4975 sqlite3BtreeCommit(pBt
);
4979 sqlite3_mutex_leave(db
->mutex
);
4980 #endif /* SQLITE_OMIT_WAL */
4985 ** Free a snapshot handle obtained from sqlite3_snapshot_get().
4987 void sqlite3_snapshot_free(sqlite3_snapshot
*pSnapshot
){
4988 sqlite3_free(pSnapshot
);
4990 #endif /* SQLITE_ENABLE_SNAPSHOT */
4992 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
4994 ** Given the name of a compile-time option, return true if that option
4995 ** was used and false if not.
4997 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
4998 ** is not required for a match.
5000 int sqlite3_compileoption_used(const char *zOptName
){
5003 const char **azCompileOpt
;
5005 #if SQLITE_ENABLE_API_ARMOR
5007 (void)SQLITE_MISUSE_BKPT
;
5012 azCompileOpt
= sqlite3CompileOptions(&nOpt
);
5014 if( sqlite3StrNICmp(zOptName
, "SQLITE_", 7)==0 ) zOptName
+= 7;
5015 n
= sqlite3Strlen30(zOptName
);
5017 /* Since nOpt is normally in single digits, a linear search is
5018 ** adequate. No need for a binary search. */
5019 for(i
=0; i
<nOpt
; i
++){
5020 if( sqlite3StrNICmp(zOptName
, azCompileOpt
[i
], n
)==0
5021 && sqlite3IsIdChar((unsigned char)azCompileOpt
[i
][n
])==0
5030 ** Return the N-th compile-time option string. If N is out of range,
5031 ** return a NULL pointer.
5033 const char *sqlite3_compileoption_get(int N
){
5035 const char **azCompileOpt
;
5036 azCompileOpt
= sqlite3CompileOptions(&nOpt
);
5037 if( N
>=0 && N
<nOpt
){
5038 return azCompileOpt
[N
];
5042 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */