Snapshot of upstream SQLite 3.42.0
[sqlcipher.git] / src / main.c
blobd7f366b5ebf64f7d339da731c8ab5e02b31a7a9a
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
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
20 # include "fts3.h"
21 #endif
22 #ifdef SQLITE_ENABLE_RTREE
23 # include "rtree.h"
24 #endif
25 #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
26 # include "sqliteicu.h"
27 #endif
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
32 ** to 500.
34 static int sqlite3TestExtInit(sqlite3 *db){
35 (void)db;
36 return sqlite3FaultSim(500);
41 ** Forward declarations of external module initializer functions
42 ** for modules that need them.
44 #ifdef SQLITE_ENABLE_FTS1
45 int sqlite3Fts1Init(sqlite3*);
46 #endif
47 #ifdef SQLITE_ENABLE_FTS2
48 int sqlite3Fts2Init(sqlite3*);
49 #endif
50 #ifdef SQLITE_ENABLE_FTS5
51 int sqlite3Fts5Init(sqlite3*);
52 #endif
53 #ifdef SQLITE_ENABLE_STMTVTAB
54 int sqlite3StmtVtabInit(sqlite3*);
55 #endif
58 ** An array of pointers to extension initializer functions for
59 ** built-in extensions.
61 static int (*const sqlite3BuiltinExtensions[])(sqlite3*) = {
62 #ifdef SQLITE_ENABLE_FTS1
63 sqlite3Fts1Init,
64 #endif
65 #ifdef SQLITE_ENABLE_FTS2
66 sqlite3Fts2Init,
67 #endif
68 #ifdef SQLITE_ENABLE_FTS3
69 sqlite3Fts3Init,
70 #endif
71 #ifdef SQLITE_ENABLE_FTS5
72 sqlite3Fts5Init,
73 #endif
74 #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
75 sqlite3IcuInit,
76 #endif
77 #ifdef SQLITE_ENABLE_RTREE
78 sqlite3RtreeInit,
79 #endif
80 #ifdef SQLITE_ENABLE_DBPAGE_VTAB
81 sqlite3DbpageRegister,
82 #endif
83 #ifdef SQLITE_ENABLE_DBSTAT_VTAB
84 sqlite3DbstatRegister,
85 #endif
86 sqlite3TestExtInit,
87 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
88 sqlite3JsonTableFunctions,
89 #endif
90 #ifdef SQLITE_ENABLE_STMTVTAB
91 sqlite3StmtVtabInit,
92 #endif
93 #ifdef SQLITE_ENABLE_BYTECODE_VTAB
94 sqlite3VdbeBytecodeVtabInit,
95 #endif
98 #ifndef SQLITE_AMALGAMATION
99 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
100 ** contains the text of SQLITE_VERSION macro.
102 const char sqlite3_version[] = SQLITE_VERSION;
103 #endif
105 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
106 ** a pointer to the to the sqlite3_version[] string constant.
108 const char *sqlite3_libversion(void){ return sqlite3_version; }
110 /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
111 ** pointer to a string constant whose value is the same as the
112 ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
113 ** an edited copy of the amalgamation, then the last four characters of
114 ** the hash might be different from SQLITE_SOURCE_ID.
116 const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
118 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
119 ** returns an integer equal to SQLITE_VERSION_NUMBER.
121 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
123 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
124 ** zero if and only if SQLite was compiled with mutexing code omitted due to
125 ** the SQLITE_THREADSAFE compile-time option being set to 0.
127 int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
130 ** When compiling the test fixture or with debugging enabled (on Win32),
131 ** this variable being set to non-zero will cause OSTRACE macros to emit
132 ** extra diagnostic information.
134 #ifdef SQLITE_HAVE_OS_TRACE
135 # ifndef SQLITE_DEBUG_OS_TRACE
136 # define SQLITE_DEBUG_OS_TRACE 0
137 # endif
138 int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
139 #endif
141 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
143 ** If the following function pointer is not NULL and if
144 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
145 ** I/O active are written using this function. These messages
146 ** are intended for debugging activity only.
148 SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
149 #endif
152 ** If the following global variable points to a string which is the
153 ** name of a directory, then that directory will be used to store
154 ** temporary files.
156 ** See also the "PRAGMA temp_store_directory" SQL command.
158 char *sqlite3_temp_directory = 0;
161 ** If the following global variable points to a string which is the
162 ** name of a directory, then that directory will be used to store
163 ** all database files specified with a relative pathname.
165 ** See also the "PRAGMA data_store_directory" SQL command.
167 char *sqlite3_data_directory = 0;
170 ** Initialize SQLite.
172 ** This routine must be called to initialize the memory allocation,
173 ** VFS, and mutex subsystems prior to doing any serious work with
174 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
175 ** this routine will be called automatically by key routines such as
176 ** sqlite3_open().
178 ** This routine is a no-op except on its very first call for the process,
179 ** or for the first call after a call to sqlite3_shutdown.
181 ** The first thread to call this routine runs the initialization to
182 ** completion. If subsequent threads call this routine before the first
183 ** thread has finished the initialization process, then the subsequent
184 ** threads must block until the first thread finishes with the initialization.
186 ** The first thread might call this routine recursively. Recursive
187 ** calls to this routine should not block, of course. Otherwise the
188 ** initialization process would never complete.
190 ** Let X be the first thread to enter this routine. Let Y be some other
191 ** thread. Then while the initial invocation of this routine by X is
192 ** incomplete, it is required that:
194 ** * Calls to this routine from Y must block until the outer-most
195 ** call by X completes.
197 ** * Recursive calls to this routine from thread X return immediately
198 ** without blocking.
200 int sqlite3_initialize(void){
201 MUTEX_LOGIC( sqlite3_mutex *pMainMtx; ) /* The main static mutex */
202 int rc; /* Result code */
203 #ifdef SQLITE_EXTRA_INIT
204 int bRunExtraInit = 0; /* Extra initialization needed */
205 #endif
207 #ifdef SQLITE_OMIT_WSD
208 rc = sqlite3_wsd_init(4096, 24);
209 if( rc!=SQLITE_OK ){
210 return rc;
212 #endif
214 /* If the following assert() fails on some obscure processor/compiler
215 ** combination, the work-around is to set the correct pointer
216 ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
217 assert( SQLITE_PTRSIZE==sizeof(char*) );
219 /* If SQLite is already completely initialized, then this call
220 ** to sqlite3_initialize() should be a no-op. But the initialization
221 ** must be complete. So isInit must not be set until the very end
222 ** of this routine.
224 if( sqlite3GlobalConfig.isInit ){
225 sqlite3MemoryBarrier();
226 return SQLITE_OK;
229 /* Make sure the mutex subsystem is initialized. If unable to
230 ** initialize the mutex subsystem, return early with the error.
231 ** If the system is so sick that we are unable to allocate a mutex,
232 ** there is not much SQLite is going to be able to do.
234 ** The mutex subsystem must take care of serializing its own
235 ** initialization.
237 rc = sqlite3MutexInit();
238 if( rc ) return rc;
240 /* Initialize the malloc() system and the recursive pInitMutex mutex.
241 ** This operation is protected by the STATIC_MAIN mutex. Note that
242 ** MutexAlloc() is called for a static mutex prior to initializing the
243 ** malloc subsystem - this implies that the allocation of a static
244 ** mutex must not require support from the malloc subsystem.
246 MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
247 sqlite3_mutex_enter(pMainMtx);
248 sqlite3GlobalConfig.isMutexInit = 1;
249 if( !sqlite3GlobalConfig.isMallocInit ){
250 rc = sqlite3MallocInit();
252 if( rc==SQLITE_OK ){
253 sqlite3GlobalConfig.isMallocInit = 1;
254 if( !sqlite3GlobalConfig.pInitMutex ){
255 sqlite3GlobalConfig.pInitMutex =
256 sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
257 if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
258 rc = SQLITE_NOMEM_BKPT;
262 if( rc==SQLITE_OK ){
263 sqlite3GlobalConfig.nRefInitMutex++;
265 sqlite3_mutex_leave(pMainMtx);
267 /* If rc is not SQLITE_OK at this point, then either the malloc
268 ** subsystem could not be initialized or the system failed to allocate
269 ** the pInitMutex mutex. Return an error in either case. */
270 if( rc!=SQLITE_OK ){
271 return rc;
274 /* Do the rest of the initialization under the recursive mutex so
275 ** that we will be able to handle recursive calls into
276 ** sqlite3_initialize(). The recursive calls normally come through
277 ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
278 ** recursive calls might also be possible.
280 ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
281 ** to the xInit method, so the xInit method need not be threadsafe.
283 ** The following mutex is what serializes access to the appdef pcache xInit
284 ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
285 ** call to sqlite3PcacheInitialize().
287 sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
288 if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
289 sqlite3GlobalConfig.inProgress = 1;
290 #ifdef SQLITE_ENABLE_SQLLOG
292 extern void sqlite3_init_sqllog(void);
293 sqlite3_init_sqllog();
295 #endif
296 memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
297 sqlite3RegisterBuiltinFunctions();
298 if( sqlite3GlobalConfig.isPCacheInit==0 ){
299 rc = sqlite3PcacheInitialize();
301 if( rc==SQLITE_OK ){
302 sqlite3GlobalConfig.isPCacheInit = 1;
303 rc = sqlite3OsInit();
305 #ifndef SQLITE_OMIT_DESERIALIZE
306 if( rc==SQLITE_OK ){
307 rc = sqlite3MemdbInit();
309 #endif
310 if( rc==SQLITE_OK ){
311 sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
312 sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
313 sqlite3MemoryBarrier();
314 sqlite3GlobalConfig.isInit = 1;
315 #ifdef SQLITE_EXTRA_INIT
316 bRunExtraInit = 1;
317 #endif
319 sqlite3GlobalConfig.inProgress = 0;
321 sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
323 /* Go back under the static mutex and clean up the recursive
324 ** mutex to prevent a resource leak.
326 sqlite3_mutex_enter(pMainMtx);
327 sqlite3GlobalConfig.nRefInitMutex--;
328 if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
329 assert( sqlite3GlobalConfig.nRefInitMutex==0 );
330 sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
331 sqlite3GlobalConfig.pInitMutex = 0;
333 sqlite3_mutex_leave(pMainMtx);
335 /* The following is just a sanity check to make sure SQLite has
336 ** been compiled correctly. It is important to run this code, but
337 ** we don't want to run it too often and soak up CPU cycles for no
338 ** reason. So we run it once during initialization.
340 #ifndef NDEBUG
341 #ifndef SQLITE_OMIT_FLOATING_POINT
342 /* This section of code's only "output" is via assert() statements. */
343 if( rc==SQLITE_OK ){
344 u64 x = (((u64)1)<<63)-1;
345 double y;
346 assert(sizeof(x)==8);
347 assert(sizeof(x)==sizeof(y));
348 memcpy(&y, &x, 8);
349 assert( sqlite3IsNaN(y) );
351 #endif
352 #endif
354 /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
355 ** compile-time option.
357 #ifdef SQLITE_EXTRA_INIT
358 if( bRunExtraInit ){
359 int SQLITE_EXTRA_INIT(const char*);
360 rc = SQLITE_EXTRA_INIT(0);
362 #endif
364 return rc;
368 ** Undo the effects of sqlite3_initialize(). Must not be called while
369 ** there are outstanding database connections or memory allocations or
370 ** while any part of SQLite is otherwise in use in any thread. This
371 ** routine is not threadsafe. But it is safe to invoke this routine
372 ** on when SQLite is already shut down. If SQLite is already shut down
373 ** when this routine is invoked, then this routine is a harmless no-op.
375 int sqlite3_shutdown(void){
376 #ifdef SQLITE_OMIT_WSD
377 int rc = sqlite3_wsd_init(4096, 24);
378 if( rc!=SQLITE_OK ){
379 return rc;
381 #endif
383 if( sqlite3GlobalConfig.isInit ){
384 #ifdef SQLITE_EXTRA_SHUTDOWN
385 void SQLITE_EXTRA_SHUTDOWN(void);
386 SQLITE_EXTRA_SHUTDOWN();
387 #endif
388 sqlite3_os_end();
389 sqlite3_reset_auto_extension();
390 sqlite3GlobalConfig.isInit = 0;
392 if( sqlite3GlobalConfig.isPCacheInit ){
393 sqlite3PcacheShutdown();
394 sqlite3GlobalConfig.isPCacheInit = 0;
396 if( sqlite3GlobalConfig.isMallocInit ){
397 sqlite3MallocEnd();
398 sqlite3GlobalConfig.isMallocInit = 0;
400 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
401 /* The heap subsystem has now been shutdown and these values are supposed
402 ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
403 ** which would rely on that heap subsystem; therefore, make sure these
404 ** values cannot refer to heap memory that was just invalidated when the
405 ** heap subsystem was shutdown. This is only done if the current call to
406 ** this function resulted in the heap subsystem actually being shutdown.
408 sqlite3_data_directory = 0;
409 sqlite3_temp_directory = 0;
410 #endif
412 if( sqlite3GlobalConfig.isMutexInit ){
413 sqlite3MutexEnd();
414 sqlite3GlobalConfig.isMutexInit = 0;
417 return SQLITE_OK;
421 ** This API allows applications to modify the global configuration of
422 ** the SQLite library at run-time.
424 ** This routine should only be called when there are no outstanding
425 ** database connections or memory allocations. This routine is not
426 ** threadsafe. Failure to heed these warnings can lead to unpredictable
427 ** behavior.
429 int sqlite3_config(int op, ...){
430 va_list ap;
431 int rc = SQLITE_OK;
433 /* sqlite3_config() normally returns SQLITE_MISUSE if it is invoked while
434 ** the SQLite library is in use. Except, a few selected opcodes
435 ** are allowed.
437 if( sqlite3GlobalConfig.isInit ){
438 static const u64 mAnytimeConfigOption = 0
439 | MASKBIT64( SQLITE_CONFIG_LOG )
440 | MASKBIT64( SQLITE_CONFIG_PCACHE_HDRSZ )
442 if( op<0 || op>63 || (MASKBIT64(op) & mAnytimeConfigOption)==0 ){
443 return SQLITE_MISUSE_BKPT;
445 testcase( op==SQLITE_CONFIG_LOG );
446 testcase( op==SQLITE_CONFIG_PCACHE_HDRSZ );
449 va_start(ap, op);
450 switch( op ){
452 /* Mutex configuration options are only available in a threadsafe
453 ** compile.
455 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
456 case SQLITE_CONFIG_SINGLETHREAD: {
457 /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
458 ** Single-thread. */
459 sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
460 sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
461 break;
463 #endif
464 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
465 case SQLITE_CONFIG_MULTITHREAD: {
466 /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
467 ** Multi-thread. */
468 sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
469 sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
470 break;
472 #endif
473 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
474 case SQLITE_CONFIG_SERIALIZED: {
475 /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
476 ** Serialized. */
477 sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
478 sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
479 break;
481 #endif
482 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
483 case SQLITE_CONFIG_MUTEX: {
484 /* Specify an alternative mutex implementation */
485 sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
486 break;
488 #endif
489 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
490 case SQLITE_CONFIG_GETMUTEX: {
491 /* Retrieve the current mutex implementation */
492 *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
493 break;
495 #endif
497 case SQLITE_CONFIG_MALLOC: {
498 /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
499 ** single argument which is a pointer to an instance of the
500 ** sqlite3_mem_methods structure. The argument specifies alternative
501 ** low-level memory allocation routines to be used in place of the memory
502 ** allocation routines built into SQLite. */
503 sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
504 break;
506 case SQLITE_CONFIG_GETMALLOC: {
507 /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
508 ** single argument which is a pointer to an instance of the
509 ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
510 ** filled with the currently defined memory allocation routines. */
511 if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
512 *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
513 break;
515 case SQLITE_CONFIG_MEMSTATUS: {
516 assert( !sqlite3GlobalConfig.isInit ); /* Cannot change at runtime */
517 /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
518 ** single argument of type int, interpreted as a boolean, which enables
519 ** or disables the collection of memory allocation statistics. */
520 sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
521 break;
523 case SQLITE_CONFIG_SMALL_MALLOC: {
524 sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
525 break;
527 case SQLITE_CONFIG_PAGECACHE: {
528 /* EVIDENCE-OF: R-18761-36601 There are three arguments to
529 ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
530 ** the size of each page cache line (sz), and the number of cache lines
531 ** (N). */
532 sqlite3GlobalConfig.pPage = va_arg(ap, void*);
533 sqlite3GlobalConfig.szPage = va_arg(ap, int);
534 sqlite3GlobalConfig.nPage = va_arg(ap, int);
535 break;
537 case SQLITE_CONFIG_PCACHE_HDRSZ: {
538 /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
539 ** a single parameter which is a pointer to an integer and writes into
540 ** that integer the number of extra bytes per page required for each page
541 ** in SQLITE_CONFIG_PAGECACHE. */
542 *va_arg(ap, int*) =
543 sqlite3HeaderSizeBtree() +
544 sqlite3HeaderSizePcache() +
545 sqlite3HeaderSizePcache1();
546 break;
549 case SQLITE_CONFIG_PCACHE: {
550 /* no-op */
551 break;
553 case SQLITE_CONFIG_GETPCACHE: {
554 /* now an error */
555 rc = SQLITE_ERROR;
556 break;
559 case SQLITE_CONFIG_PCACHE2: {
560 /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
561 ** single argument which is a pointer to an sqlite3_pcache_methods2
562 ** object. This object specifies the interface to a custom page cache
563 ** implementation. */
564 sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
565 break;
567 case SQLITE_CONFIG_GETPCACHE2: {
568 /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
569 ** single argument which is a pointer to an sqlite3_pcache_methods2
570 ** object. SQLite copies of the current page cache implementation into
571 ** that object. */
572 if( sqlite3GlobalConfig.pcache2.xInit==0 ){
573 sqlite3PCacheSetDefault();
575 *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
576 break;
579 /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
580 ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
581 ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
582 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
583 case SQLITE_CONFIG_HEAP: {
584 /* EVIDENCE-OF: R-19854-42126 There are three arguments to
585 ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
586 ** number of bytes in the memory buffer, and the minimum allocation size.
588 sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
589 sqlite3GlobalConfig.nHeap = va_arg(ap, int);
590 sqlite3GlobalConfig.mnReq = va_arg(ap, int);
592 if( sqlite3GlobalConfig.mnReq<1 ){
593 sqlite3GlobalConfig.mnReq = 1;
594 }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
595 /* cap min request size at 2^12 */
596 sqlite3GlobalConfig.mnReq = (1<<12);
599 if( sqlite3GlobalConfig.pHeap==0 ){
600 /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
601 ** is NULL, then SQLite reverts to using its default memory allocator
602 ** (the system malloc() implementation), undoing any prior invocation of
603 ** SQLITE_CONFIG_MALLOC.
605 ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
606 ** revert to its default implementation when sqlite3_initialize() is run
608 memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
609 }else{
610 /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
611 ** alternative memory allocator is engaged to handle all of SQLites
612 ** memory allocation needs. */
613 #ifdef SQLITE_ENABLE_MEMSYS3
614 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
615 #endif
616 #ifdef SQLITE_ENABLE_MEMSYS5
617 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
618 #endif
620 break;
622 #endif
624 case SQLITE_CONFIG_LOOKASIDE: {
625 sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
626 sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
627 break;
630 /* Record a pointer to the logger function and its first argument.
631 ** The default is NULL. Logging is disabled if the function pointer is
632 ** NULL.
634 case SQLITE_CONFIG_LOG: {
635 /* MSVC is picky about pulling func ptrs from va lists.
636 ** http://support.microsoft.com/kb/47961
637 ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
639 typedef void(*LOGFUNC_t)(void*,int,const char*);
640 LOGFUNC_t xLog = va_arg(ap, LOGFUNC_t);
641 void *pLogArg = va_arg(ap, void*);
642 AtomicStore(&sqlite3GlobalConfig.xLog, xLog);
643 AtomicStore(&sqlite3GlobalConfig.pLogArg, pLogArg);
644 break;
647 /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
648 ** can be changed at start-time using the
649 ** sqlite3_config(SQLITE_CONFIG_URI,1) or
650 ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
652 case SQLITE_CONFIG_URI: {
653 /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
654 ** argument of type int. If non-zero, then URI handling is globally
655 ** enabled. If the parameter is zero, then URI handling is globally
656 ** disabled. */
657 int bOpenUri = va_arg(ap, int);
658 AtomicStore(&sqlite3GlobalConfig.bOpenUri, bOpenUri);
659 break;
662 case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
663 /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
664 ** option takes a single integer argument which is interpreted as a
665 ** boolean in order to enable or disable the use of covering indices for
666 ** full table scans in the query optimizer. */
667 sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
668 break;
671 #ifdef SQLITE_ENABLE_SQLLOG
672 case SQLITE_CONFIG_SQLLOG: {
673 typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
674 sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
675 sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
676 break;
678 #endif
680 case SQLITE_CONFIG_MMAP_SIZE: {
681 /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
682 ** integer (sqlite3_int64) values that are the default mmap size limit
683 ** (the default setting for PRAGMA mmap_size) and the maximum allowed
684 ** mmap size limit. */
685 sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
686 sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
687 /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
688 ** negative, then that argument is changed to its compile-time default.
690 ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
691 ** silently truncated if necessary so that it does not exceed the
692 ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
693 ** compile-time option.
695 if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
696 mxMmap = SQLITE_MAX_MMAP_SIZE;
698 if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
699 if( szMmap>mxMmap) szMmap = mxMmap;
700 sqlite3GlobalConfig.mxMmap = mxMmap;
701 sqlite3GlobalConfig.szMmap = szMmap;
702 break;
705 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
706 case SQLITE_CONFIG_WIN32_HEAPSIZE: {
707 /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
708 ** unsigned integer value that specifies the maximum size of the created
709 ** heap. */
710 sqlite3GlobalConfig.nHeap = va_arg(ap, int);
711 break;
713 #endif
715 case SQLITE_CONFIG_PMASZ: {
716 sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
717 break;
720 case SQLITE_CONFIG_STMTJRNL_SPILL: {
721 sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
722 break;
725 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
726 case SQLITE_CONFIG_SORTERREF_SIZE: {
727 int iVal = va_arg(ap, int);
728 if( iVal<0 ){
729 iVal = SQLITE_DEFAULT_SORTERREF_SIZE;
731 sqlite3GlobalConfig.szSorterRef = (u32)iVal;
732 break;
734 #endif /* SQLITE_ENABLE_SORTER_REFERENCES */
736 #ifndef SQLITE_OMIT_DESERIALIZE
737 case SQLITE_CONFIG_MEMDB_MAXSIZE: {
738 sqlite3GlobalConfig.mxMemdbSize = va_arg(ap, sqlite3_int64);
739 break;
741 #endif /* SQLITE_OMIT_DESERIALIZE */
743 default: {
744 rc = SQLITE_ERROR;
745 break;
748 va_end(ap);
749 return rc;
753 ** Set up the lookaside buffers for a database connection.
754 ** Return SQLITE_OK on success.
755 ** If lookaside is already active, return SQLITE_BUSY.
757 ** The sz parameter is the number of bytes in each lookaside slot.
758 ** The cnt parameter is the number of slots. If pStart is NULL the
759 ** space for the lookaside memory is obtained from sqlite3_malloc().
760 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
761 ** the lookaside memory.
763 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
764 #ifndef SQLITE_OMIT_LOOKASIDE
765 void *pStart;
766 sqlite3_int64 szAlloc = sz*(sqlite3_int64)cnt;
767 int nBig; /* Number of full-size slots */
768 int nSm; /* Number smaller LOOKASIDE_SMALL-byte slots */
770 if( sqlite3LookasideUsed(db,0)>0 ){
771 return SQLITE_BUSY;
773 /* Free any existing lookaside buffer for this handle before
774 ** allocating a new one so we don't have to have space for
775 ** both at the same time.
777 if( db->lookaside.bMalloced ){
778 sqlite3_free(db->lookaside.pStart);
780 /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
781 ** than a pointer to be useful.
783 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
784 if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
785 if( cnt<0 ) cnt = 0;
786 if( sz==0 || cnt==0 ){
787 sz = 0;
788 pStart = 0;
789 }else if( pBuf==0 ){
790 sqlite3BeginBenignMalloc();
791 pStart = sqlite3Malloc( szAlloc ); /* IMP: R-61949-35727 */
792 sqlite3EndBenignMalloc();
793 if( pStart ) szAlloc = sqlite3MallocSize(pStart);
794 }else{
795 pStart = pBuf;
797 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
798 if( sz>=LOOKASIDE_SMALL*3 ){
799 nBig = szAlloc/(3*LOOKASIDE_SMALL+sz);
800 nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
801 }else if( sz>=LOOKASIDE_SMALL*2 ){
802 nBig = szAlloc/(LOOKASIDE_SMALL+sz);
803 nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
804 }else
805 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
806 if( sz>0 ){
807 nBig = szAlloc/sz;
808 nSm = 0;
809 }else{
810 nBig = nSm = 0;
812 db->lookaside.pStart = pStart;
813 db->lookaside.pInit = 0;
814 db->lookaside.pFree = 0;
815 db->lookaside.sz = (u16)sz;
816 db->lookaside.szTrue = (u16)sz;
817 if( pStart ){
818 int i;
819 LookasideSlot *p;
820 assert( sz > (int)sizeof(LookasideSlot*) );
821 p = (LookasideSlot*)pStart;
822 for(i=0; i<nBig; i++){
823 p->pNext = db->lookaside.pInit;
824 db->lookaside.pInit = p;
825 p = (LookasideSlot*)&((u8*)p)[sz];
827 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
828 db->lookaside.pSmallInit = 0;
829 db->lookaside.pSmallFree = 0;
830 db->lookaside.pMiddle = p;
831 for(i=0; i<nSm; i++){
832 p->pNext = db->lookaside.pSmallInit;
833 db->lookaside.pSmallInit = p;
834 p = (LookasideSlot*)&((u8*)p)[LOOKASIDE_SMALL];
836 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
837 assert( ((uptr)p)<=szAlloc + (uptr)pStart );
838 db->lookaside.pEnd = p;
839 db->lookaside.bDisable = 0;
840 db->lookaside.bMalloced = pBuf==0 ?1:0;
841 db->lookaside.nSlot = nBig+nSm;
842 }else{
843 db->lookaside.pStart = 0;
844 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
845 db->lookaside.pSmallInit = 0;
846 db->lookaside.pSmallFree = 0;
847 db->lookaside.pMiddle = 0;
848 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
849 db->lookaside.pEnd = 0;
850 db->lookaside.bDisable = 1;
851 db->lookaside.sz = 0;
852 db->lookaside.bMalloced = 0;
853 db->lookaside.nSlot = 0;
855 db->lookaside.pTrueEnd = db->lookaside.pEnd;
856 assert( sqlite3LookasideUsed(db,0)==0 );
857 #endif /* SQLITE_OMIT_LOOKASIDE */
858 return SQLITE_OK;
862 ** Return the mutex associated with a database connection.
864 sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
865 #ifdef SQLITE_ENABLE_API_ARMOR
866 if( !sqlite3SafetyCheckOk(db) ){
867 (void)SQLITE_MISUSE_BKPT;
868 return 0;
870 #endif
871 return db->mutex;
875 ** Free up as much memory as we can from the given database
876 ** connection.
878 int sqlite3_db_release_memory(sqlite3 *db){
879 int i;
881 #ifdef SQLITE_ENABLE_API_ARMOR
882 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
883 #endif
884 sqlite3_mutex_enter(db->mutex);
885 sqlite3BtreeEnterAll(db);
886 for(i=0; i<db->nDb; i++){
887 Btree *pBt = db->aDb[i].pBt;
888 if( pBt ){
889 Pager *pPager = sqlite3BtreePager(pBt);
890 sqlite3PagerShrink(pPager);
893 sqlite3BtreeLeaveAll(db);
894 sqlite3_mutex_leave(db->mutex);
895 return SQLITE_OK;
899 ** Flush any dirty pages in the pager-cache for any attached database
900 ** to disk.
902 int sqlite3_db_cacheflush(sqlite3 *db){
903 int i;
904 int rc = SQLITE_OK;
905 int bSeenBusy = 0;
907 #ifdef SQLITE_ENABLE_API_ARMOR
908 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
909 #endif
910 sqlite3_mutex_enter(db->mutex);
911 sqlite3BtreeEnterAll(db);
912 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
913 Btree *pBt = db->aDb[i].pBt;
914 if( pBt && sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
915 Pager *pPager = sqlite3BtreePager(pBt);
916 rc = sqlite3PagerFlush(pPager);
917 if( rc==SQLITE_BUSY ){
918 bSeenBusy = 1;
919 rc = SQLITE_OK;
923 sqlite3BtreeLeaveAll(db);
924 sqlite3_mutex_leave(db->mutex);
925 return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
929 ** Configuration settings for an individual database connection
931 int sqlite3_db_config(sqlite3 *db, int op, ...){
932 va_list ap;
933 int rc;
934 sqlite3_mutex_enter(db->mutex);
935 va_start(ap, op);
936 switch( op ){
937 case SQLITE_DBCONFIG_MAINDBNAME: {
938 /* IMP: R-06824-28531 */
939 /* IMP: R-36257-52125 */
940 db->aDb[0].zDbSName = va_arg(ap,char*);
941 rc = SQLITE_OK;
942 break;
944 case SQLITE_DBCONFIG_LOOKASIDE: {
945 void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
946 int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
947 int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
948 rc = setupLookaside(db, pBuf, sz, cnt);
949 break;
951 default: {
952 static const struct {
953 int op; /* The opcode */
954 u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
955 } aFlagOp[] = {
956 { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
957 { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
958 { SQLITE_DBCONFIG_ENABLE_VIEW, SQLITE_EnableView },
959 { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
960 { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension },
961 { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose },
962 { SQLITE_DBCONFIG_ENABLE_QPSG, SQLITE_EnableQPSG },
963 { SQLITE_DBCONFIG_TRIGGER_EQP, SQLITE_TriggerEQP },
964 { SQLITE_DBCONFIG_RESET_DATABASE, SQLITE_ResetDatabase },
965 { SQLITE_DBCONFIG_DEFENSIVE, SQLITE_Defensive },
966 { SQLITE_DBCONFIG_WRITABLE_SCHEMA, SQLITE_WriteSchema|
967 SQLITE_NoSchemaError },
968 { SQLITE_DBCONFIG_LEGACY_ALTER_TABLE, SQLITE_LegacyAlter },
969 { SQLITE_DBCONFIG_DQS_DDL, SQLITE_DqsDDL },
970 { SQLITE_DBCONFIG_DQS_DML, SQLITE_DqsDML },
971 { SQLITE_DBCONFIG_LEGACY_FILE_FORMAT, SQLITE_LegacyFileFmt },
972 { SQLITE_DBCONFIG_TRUSTED_SCHEMA, SQLITE_TrustedSchema },
973 { SQLITE_DBCONFIG_STMT_SCANSTATUS, SQLITE_StmtScanStatus },
974 { SQLITE_DBCONFIG_REVERSE_SCANORDER, SQLITE_ReverseOrder },
976 unsigned int i;
977 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
978 for(i=0; i<ArraySize(aFlagOp); i++){
979 if( aFlagOp[i].op==op ){
980 int onoff = va_arg(ap, int);
981 int *pRes = va_arg(ap, int*);
982 u64 oldFlags = db->flags;
983 if( onoff>0 ){
984 db->flags |= aFlagOp[i].mask;
985 }else if( onoff==0 ){
986 db->flags &= ~(u64)aFlagOp[i].mask;
988 if( oldFlags!=db->flags ){
989 sqlite3ExpirePreparedStatements(db, 0);
991 if( pRes ){
992 *pRes = (db->flags & aFlagOp[i].mask)!=0;
994 rc = SQLITE_OK;
995 break;
998 break;
1001 va_end(ap);
1002 sqlite3_mutex_leave(db->mutex);
1003 return rc;
1007 ** This is the default collating function named "BINARY" which is always
1008 ** available.
1010 static int binCollFunc(
1011 void *NotUsed,
1012 int nKey1, const void *pKey1,
1013 int nKey2, const void *pKey2
1015 int rc, n;
1016 UNUSED_PARAMETER(NotUsed);
1017 n = nKey1<nKey2 ? nKey1 : nKey2;
1018 /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
1019 ** strings byte by byte using the memcmp() function from the standard C
1020 ** library. */
1021 assert( pKey1 && pKey2 );
1022 rc = memcmp(pKey1, pKey2, n);
1023 if( rc==0 ){
1024 rc = nKey1 - nKey2;
1026 return rc;
1030 ** This is the collating function named "RTRIM" which is always
1031 ** available. Ignore trailing spaces.
1033 static int rtrimCollFunc(
1034 void *pUser,
1035 int nKey1, const void *pKey1,
1036 int nKey2, const void *pKey2
1038 const u8 *pK1 = (const u8*)pKey1;
1039 const u8 *pK2 = (const u8*)pKey2;
1040 while( nKey1 && pK1[nKey1-1]==' ' ) nKey1--;
1041 while( nKey2 && pK2[nKey2-1]==' ' ) nKey2--;
1042 return binCollFunc(pUser, nKey1, pKey1, nKey2, pKey2);
1046 ** Return true if CollSeq is the default built-in BINARY.
1048 int sqlite3IsBinary(const CollSeq *p){
1049 assert( p==0 || p->xCmp!=binCollFunc || strcmp(p->zName,"BINARY")==0 );
1050 return p==0 || p->xCmp==binCollFunc;
1054 ** Another built-in collating sequence: NOCASE.
1056 ** This collating sequence is intended to be used for "case independent
1057 ** comparison". SQLite's knowledge of upper and lower case equivalents
1058 ** extends only to the 26 characters used in the English language.
1060 ** At the moment there is only a UTF-8 implementation.
1062 static int nocaseCollatingFunc(
1063 void *NotUsed,
1064 int nKey1, const void *pKey1,
1065 int nKey2, const void *pKey2
1067 int r = sqlite3StrNICmp(
1068 (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
1069 UNUSED_PARAMETER(NotUsed);
1070 if( 0==r ){
1071 r = nKey1-nKey2;
1073 return r;
1077 ** Return the ROWID of the most recent insert
1079 sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
1080 #ifdef SQLITE_ENABLE_API_ARMOR
1081 if( !sqlite3SafetyCheckOk(db) ){
1082 (void)SQLITE_MISUSE_BKPT;
1083 return 0;
1085 #endif
1086 return db->lastRowid;
1090 ** Set the value returned by the sqlite3_last_insert_rowid() API function.
1092 void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
1093 #ifdef SQLITE_ENABLE_API_ARMOR
1094 if( !sqlite3SafetyCheckOk(db) ){
1095 (void)SQLITE_MISUSE_BKPT;
1096 return;
1098 #endif
1099 sqlite3_mutex_enter(db->mutex);
1100 db->lastRowid = iRowid;
1101 sqlite3_mutex_leave(db->mutex);
1105 ** Return the number of changes in the most recent call to sqlite3_exec().
1107 sqlite3_int64 sqlite3_changes64(sqlite3 *db){
1108 #ifdef SQLITE_ENABLE_API_ARMOR
1109 if( !sqlite3SafetyCheckOk(db) ){
1110 (void)SQLITE_MISUSE_BKPT;
1111 return 0;
1113 #endif
1114 return db->nChange;
1116 int sqlite3_changes(sqlite3 *db){
1117 return (int)sqlite3_changes64(db);
1121 ** Return the number of changes since the database handle was opened.
1123 sqlite3_int64 sqlite3_total_changes64(sqlite3 *db){
1124 #ifdef SQLITE_ENABLE_API_ARMOR
1125 if( !sqlite3SafetyCheckOk(db) ){
1126 (void)SQLITE_MISUSE_BKPT;
1127 return 0;
1129 #endif
1130 return db->nTotalChange;
1132 int sqlite3_total_changes(sqlite3 *db){
1133 return (int)sqlite3_total_changes64(db);
1137 ** Close all open savepoints. This function only manipulates fields of the
1138 ** database handle object, it does not close any savepoints that may be open
1139 ** at the b-tree/pager level.
1141 void sqlite3CloseSavepoints(sqlite3 *db){
1142 while( db->pSavepoint ){
1143 Savepoint *pTmp = db->pSavepoint;
1144 db->pSavepoint = pTmp->pNext;
1145 sqlite3DbFree(db, pTmp);
1147 db->nSavepoint = 0;
1148 db->nStatement = 0;
1149 db->isTransactionSavepoint = 0;
1153 ** Invoke the destructor function associated with FuncDef p, if any. Except,
1154 ** if this is not the last copy of the function, do not invoke it. Multiple
1155 ** copies of a single function are created when create_function() is called
1156 ** with SQLITE_ANY as the encoding.
1158 static void functionDestroy(sqlite3 *db, FuncDef *p){
1159 FuncDestructor *pDestructor;
1160 assert( (p->funcFlags & SQLITE_FUNC_BUILTIN)==0 );
1161 pDestructor = p->u.pDestructor;
1162 if( pDestructor ){
1163 pDestructor->nRef--;
1164 if( pDestructor->nRef==0 ){
1165 pDestructor->xDestroy(pDestructor->pUserData);
1166 sqlite3DbFree(db, pDestructor);
1172 ** Disconnect all sqlite3_vtab objects that belong to database connection
1173 ** db. This is called when db is being closed.
1175 static void disconnectAllVtab(sqlite3 *db){
1176 #ifndef SQLITE_OMIT_VIRTUALTABLE
1177 int i;
1178 HashElem *p;
1179 sqlite3BtreeEnterAll(db);
1180 for(i=0; i<db->nDb; i++){
1181 Schema *pSchema = db->aDb[i].pSchema;
1182 if( pSchema ){
1183 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
1184 Table *pTab = (Table *)sqliteHashData(p);
1185 if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
1189 for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
1190 Module *pMod = (Module *)sqliteHashData(p);
1191 if( pMod->pEpoTab ){
1192 sqlite3VtabDisconnect(db, pMod->pEpoTab);
1195 sqlite3VtabUnlockList(db);
1196 sqlite3BtreeLeaveAll(db);
1197 #else
1198 UNUSED_PARAMETER(db);
1199 #endif
1203 ** Return TRUE if database connection db has unfinalized prepared
1204 ** statements or unfinished sqlite3_backup objects.
1206 static int connectionIsBusy(sqlite3 *db){
1207 int j;
1208 assert( sqlite3_mutex_held(db->mutex) );
1209 if( db->pVdbe ) return 1;
1210 for(j=0; j<db->nDb; j++){
1211 Btree *pBt = db->aDb[j].pBt;
1212 if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
1214 return 0;
1218 ** Close an existing SQLite database
1220 static int sqlite3Close(sqlite3 *db, int forceZombie){
1221 if( !db ){
1222 /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
1223 ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
1224 return SQLITE_OK;
1226 if( !sqlite3SafetyCheckSickOrOk(db) ){
1227 return SQLITE_MISUSE_BKPT;
1229 sqlite3_mutex_enter(db->mutex);
1230 if( db->mTrace & SQLITE_TRACE_CLOSE ){
1231 db->trace.xV2(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
1234 /* Force xDisconnect calls on all virtual tables */
1235 disconnectAllVtab(db);
1237 /* If a transaction is open, the disconnectAllVtab() call above
1238 ** will not have called the xDisconnect() method on any virtual
1239 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
1240 ** call will do so. We need to do this before the check for active
1241 ** SQL statements below, as the v-table implementation may be storing
1242 ** some prepared statements internally.
1244 sqlite3VtabRollback(db);
1246 /* Legacy behavior (sqlite3_close() behavior) is to return
1247 ** SQLITE_BUSY if the connection can not be closed immediately.
1249 if( !forceZombie && connectionIsBusy(db) ){
1250 sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
1251 "statements or unfinished backups");
1252 sqlite3_mutex_leave(db->mutex);
1253 return SQLITE_BUSY;
1256 #ifdef SQLITE_ENABLE_SQLLOG
1257 if( sqlite3GlobalConfig.xSqllog ){
1258 /* Closing the handle. Fourth parameter is passed the value 2. */
1259 sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
1261 #endif
1263 /* Convert the connection into a zombie and then close it.
1265 db->eOpenState = SQLITE_STATE_ZOMBIE;
1266 sqlite3LeaveMutexAndCloseZombie(db);
1267 return SQLITE_OK;
1271 ** Return the transaction state for a single databse, or the maximum
1272 ** transaction state over all attached databases if zSchema is null.
1274 int sqlite3_txn_state(sqlite3 *db, const char *zSchema){
1275 int iDb, nDb;
1276 int iTxn = -1;
1277 #ifdef SQLITE_ENABLE_API_ARMOR
1278 if( !sqlite3SafetyCheckOk(db) ){
1279 (void)SQLITE_MISUSE_BKPT;
1280 return -1;
1282 #endif
1283 sqlite3_mutex_enter(db->mutex);
1284 if( zSchema ){
1285 nDb = iDb = sqlite3FindDbName(db, zSchema);
1286 if( iDb<0 ) nDb--;
1287 }else{
1288 iDb = 0;
1289 nDb = db->nDb-1;
1291 for(; iDb<=nDb; iDb++){
1292 Btree *pBt = db->aDb[iDb].pBt;
1293 int x = pBt!=0 ? sqlite3BtreeTxnState(pBt) : SQLITE_TXN_NONE;
1294 if( x>iTxn ) iTxn = x;
1296 sqlite3_mutex_leave(db->mutex);
1297 return iTxn;
1301 ** Two variations on the public interface for closing a database
1302 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
1303 ** leaves the connection open if there are unfinalized prepared
1304 ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
1305 ** version forces the connection to become a zombie if there are
1306 ** unclosed resources, and arranges for deallocation when the last
1307 ** prepare statement or sqlite3_backup closes.
1309 int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
1310 int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
1314 ** Close the mutex on database connection db.
1316 ** Furthermore, if database connection db is a zombie (meaning that there
1317 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
1318 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
1319 ** finished, then free all resources.
1321 void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
1322 HashElem *i; /* Hash table iterator */
1323 int j;
1325 /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
1326 ** or if the connection has not yet been closed by sqlite3_close_v2(),
1327 ** then just leave the mutex and return.
1329 if( db->eOpenState!=SQLITE_STATE_ZOMBIE || connectionIsBusy(db) ){
1330 sqlite3_mutex_leave(db->mutex);
1331 return;
1334 /* If we reach this point, it means that the database connection has
1335 ** closed all sqlite3_stmt and sqlite3_backup objects and has been
1336 ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
1337 ** go ahead and free all resources.
1340 /* If a transaction is open, roll it back. This also ensures that if
1341 ** any database schemas have been modified by an uncommitted transaction
1342 ** they are reset. And that the required b-tree mutex is held to make
1343 ** the pager rollback and schema reset an atomic operation. */
1344 sqlite3RollbackAll(db, SQLITE_OK);
1346 /* Free any outstanding Savepoint structures. */
1347 sqlite3CloseSavepoints(db);
1349 /* Close all database connections */
1350 for(j=0; j<db->nDb; j++){
1351 struct Db *pDb = &db->aDb[j];
1352 if( pDb->pBt ){
1353 sqlite3BtreeClose(pDb->pBt);
1354 pDb->pBt = 0;
1355 if( j!=1 ){
1356 pDb->pSchema = 0;
1360 /* Clear the TEMP schema separately and last */
1361 if( db->aDb[1].pSchema ){
1362 sqlite3SchemaClear(db->aDb[1].pSchema);
1364 sqlite3VtabUnlockList(db);
1366 /* Free up the array of auxiliary databases */
1367 sqlite3CollapseDatabaseArray(db);
1368 assert( db->nDb<=2 );
1369 assert( db->aDb==db->aDbStatic );
1371 /* Tell the code in notify.c that the connection no longer holds any
1372 ** locks and does not require any further unlock-notify callbacks.
1374 sqlite3ConnectionClosed(db);
1376 for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
1377 FuncDef *pNext, *p;
1378 p = sqliteHashData(i);
1380 functionDestroy(db, p);
1381 pNext = p->pNext;
1382 sqlite3DbFree(db, p);
1383 p = pNext;
1384 }while( p );
1386 sqlite3HashClear(&db->aFunc);
1387 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
1388 CollSeq *pColl = (CollSeq *)sqliteHashData(i);
1389 /* Invoke any destructors registered for collation sequence user data. */
1390 for(j=0; j<3; j++){
1391 if( pColl[j].xDel ){
1392 pColl[j].xDel(pColl[j].pUser);
1395 sqlite3DbFree(db, pColl);
1397 sqlite3HashClear(&db->aCollSeq);
1398 #ifndef SQLITE_OMIT_VIRTUALTABLE
1399 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
1400 Module *pMod = (Module *)sqliteHashData(i);
1401 sqlite3VtabEponymousTableClear(db, pMod);
1402 sqlite3VtabModuleUnref(db, pMod);
1404 sqlite3HashClear(&db->aModule);
1405 #endif
1407 sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
1408 sqlite3ValueFree(db->pErr);
1409 sqlite3CloseExtensions(db);
1410 #if SQLITE_USER_AUTHENTICATION
1411 sqlite3_free(db->auth.zAuthUser);
1412 sqlite3_free(db->auth.zAuthPW);
1413 #endif
1415 db->eOpenState = SQLITE_STATE_ERROR;
1417 /* The temp-database schema is allocated differently from the other schema
1418 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
1419 ** So it needs to be freed here. Todo: Why not roll the temp schema into
1420 ** the same sqliteMalloc() as the one that allocates the database
1421 ** structure?
1423 sqlite3DbFree(db, db->aDb[1].pSchema);
1424 if( db->xAutovacDestr ){
1425 db->xAutovacDestr(db->pAutovacPagesArg);
1427 sqlite3_mutex_leave(db->mutex);
1428 db->eOpenState = SQLITE_STATE_CLOSED;
1429 sqlite3_mutex_free(db->mutex);
1430 assert( sqlite3LookasideUsed(db,0)==0 );
1431 if( db->lookaside.bMalloced ){
1432 sqlite3_free(db->lookaside.pStart);
1434 sqlite3_free(db);
1438 ** Rollback all database files. If tripCode is not SQLITE_OK, then
1439 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
1440 ** breaker") and made to return tripCode if there are any further
1441 ** attempts to use that cursor. Read cursors remain open and valid
1442 ** but are "saved" in case the table pages are moved around.
1444 void sqlite3RollbackAll(sqlite3 *db, int tripCode){
1445 int i;
1446 int inTrans = 0;
1447 int schemaChange;
1448 assert( sqlite3_mutex_held(db->mutex) );
1449 sqlite3BeginBenignMalloc();
1451 /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
1452 ** This is important in case the transaction being rolled back has
1453 ** modified the database schema. If the b-tree mutexes are not taken
1454 ** here, then another shared-cache connection might sneak in between
1455 ** the database rollback and schema reset, which can cause false
1456 ** corruption reports in some cases. */
1457 sqlite3BtreeEnterAll(db);
1458 schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
1460 for(i=0; i<db->nDb; i++){
1461 Btree *p = db->aDb[i].pBt;
1462 if( p ){
1463 if( sqlite3BtreeTxnState(p)==SQLITE_TXN_WRITE ){
1464 inTrans = 1;
1466 sqlite3BtreeRollback(p, tripCode, !schemaChange);
1469 sqlite3VtabRollback(db);
1470 sqlite3EndBenignMalloc();
1472 if( schemaChange ){
1473 sqlite3ExpirePreparedStatements(db, 0);
1474 sqlite3ResetAllSchemasOfConnection(db);
1476 sqlite3BtreeLeaveAll(db);
1478 /* Any deferred constraint violations have now been resolved. */
1479 db->nDeferredCons = 0;
1480 db->nDeferredImmCons = 0;
1481 db->flags &= ~(u64)(SQLITE_DeferFKs|SQLITE_CorruptRdOnly);
1483 /* If one has been configured, invoke the rollback-hook callback */
1484 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
1485 db->xRollbackCallback(db->pRollbackArg);
1490 ** Return a static string containing the name corresponding to the error code
1491 ** specified in the argument.
1493 #if defined(SQLITE_NEED_ERR_NAME)
1494 const char *sqlite3ErrName(int rc){
1495 const char *zName = 0;
1496 int i, origRc = rc;
1497 for(i=0; i<2 && zName==0; i++, rc &= 0xff){
1498 switch( rc ){
1499 case SQLITE_OK: zName = "SQLITE_OK"; break;
1500 case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
1501 case SQLITE_ERROR_SNAPSHOT: zName = "SQLITE_ERROR_SNAPSHOT"; break;
1502 case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
1503 case SQLITE_PERM: zName = "SQLITE_PERM"; break;
1504 case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
1505 case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
1506 case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
1507 case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
1508 case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
1509 case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
1510 case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
1511 case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
1512 case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
1513 case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
1514 case SQLITE_READONLY_CANTINIT: zName = "SQLITE_READONLY_CANTINIT"; break;
1515 case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
1516 case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
1517 case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break;
1518 case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
1519 case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
1520 case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
1521 case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
1522 case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
1523 case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
1524 case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
1525 case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
1526 case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
1527 case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
1528 case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
1529 case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
1530 case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
1531 case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
1532 case SQLITE_IOERR_CHECKRESERVEDLOCK:
1533 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
1534 case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
1535 case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
1536 case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
1537 case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
1538 case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
1539 case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
1540 case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
1541 case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
1542 case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
1543 case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
1544 case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
1545 case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
1546 case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
1547 case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
1548 case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
1549 case SQLITE_FULL: zName = "SQLITE_FULL"; break;
1550 case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
1551 case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
1552 case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
1553 case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
1554 case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
1555 case SQLITE_CANTOPEN_SYMLINK: zName = "SQLITE_CANTOPEN_SYMLINK"; break;
1556 case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
1557 case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
1558 case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
1559 case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
1560 case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
1561 case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
1562 case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
1563 case SQLITE_CONSTRAINT_FOREIGNKEY:
1564 zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
1565 case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
1566 case SQLITE_CONSTRAINT_PRIMARYKEY:
1567 zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
1568 case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
1569 case SQLITE_CONSTRAINT_COMMITHOOK:
1570 zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
1571 case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
1572 case SQLITE_CONSTRAINT_FUNCTION:
1573 zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
1574 case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
1575 case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
1576 case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
1577 case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
1578 case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
1579 case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
1580 case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
1581 case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
1582 case SQLITE_ROW: zName = "SQLITE_ROW"; break;
1583 case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
1584 case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
1585 case SQLITE_NOTICE_RECOVER_ROLLBACK:
1586 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
1587 case SQLITE_NOTICE_RBU: zName = "SQLITE_NOTICE_RBU"; break;
1588 case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
1589 case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
1590 case SQLITE_DONE: zName = "SQLITE_DONE"; break;
1593 if( zName==0 ){
1594 static char zBuf[50];
1595 sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
1596 zName = zBuf;
1598 return zName;
1600 #endif
1603 ** Return a static string that describes the kind of error specified in the
1604 ** argument.
1606 const char *sqlite3ErrStr(int rc){
1607 static const char* const aMsg[] = {
1608 /* SQLITE_OK */ "not an error",
1609 /* SQLITE_ERROR */ "SQL logic error",
1610 /* SQLITE_INTERNAL */ 0,
1611 /* SQLITE_PERM */ "access permission denied",
1612 /* SQLITE_ABORT */ "query aborted",
1613 /* SQLITE_BUSY */ "database is locked",
1614 /* SQLITE_LOCKED */ "database table is locked",
1615 /* SQLITE_NOMEM */ "out of memory",
1616 /* SQLITE_READONLY */ "attempt to write a readonly database",
1617 /* SQLITE_INTERRUPT */ "interrupted",
1618 /* SQLITE_IOERR */ "disk I/O error",
1619 /* SQLITE_CORRUPT */ "database disk image is malformed",
1620 /* SQLITE_NOTFOUND */ "unknown operation",
1621 /* SQLITE_FULL */ "database or disk is full",
1622 /* SQLITE_CANTOPEN */ "unable to open database file",
1623 /* SQLITE_PROTOCOL */ "locking protocol",
1624 /* SQLITE_EMPTY */ 0,
1625 /* SQLITE_SCHEMA */ "database schema has changed",
1626 /* SQLITE_TOOBIG */ "string or blob too big",
1627 /* SQLITE_CONSTRAINT */ "constraint failed",
1628 /* SQLITE_MISMATCH */ "datatype mismatch",
1629 /* SQLITE_MISUSE */ "bad parameter or other API misuse",
1630 #ifdef SQLITE_DISABLE_LFS
1631 /* SQLITE_NOLFS */ "large file support is disabled",
1632 #else
1633 /* SQLITE_NOLFS */ 0,
1634 #endif
1635 /* SQLITE_AUTH */ "authorization denied",
1636 /* SQLITE_FORMAT */ 0,
1637 /* SQLITE_RANGE */ "column index out of range",
1638 /* SQLITE_NOTADB */ "file is not a database",
1639 /* SQLITE_NOTICE */ "notification message",
1640 /* SQLITE_WARNING */ "warning message",
1642 const char *zErr = "unknown error";
1643 switch( rc ){
1644 case SQLITE_ABORT_ROLLBACK: {
1645 zErr = "abort due to ROLLBACK";
1646 break;
1648 case SQLITE_ROW: {
1649 zErr = "another row available";
1650 break;
1652 case SQLITE_DONE: {
1653 zErr = "no more rows available";
1654 break;
1656 default: {
1657 rc &= 0xff;
1658 if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
1659 zErr = aMsg[rc];
1661 break;
1664 return zErr;
1668 ** This routine implements a busy callback that sleeps and tries
1669 ** again until a timeout value is reached. The timeout value is
1670 ** an integer number of milliseconds passed in as the first
1671 ** argument.
1673 ** Return non-zero to retry the lock. Return zero to stop trying
1674 ** and cause SQLite to return SQLITE_BUSY.
1676 static int sqliteDefaultBusyCallback(
1677 void *ptr, /* Database connection */
1678 int count /* Number of times table has been busy */
1680 #if SQLITE_OS_WIN || HAVE_USLEEP
1681 /* This case is for systems that have support for sleeping for fractions of
1682 ** a second. Examples: All windows systems, unix systems with usleep() */
1683 static const u8 delays[] =
1684 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
1685 static const u8 totals[] =
1686 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
1687 # define NDELAY ArraySize(delays)
1688 sqlite3 *db = (sqlite3 *)ptr;
1689 int tmout = db->busyTimeout;
1690 int delay, prior;
1692 assert( count>=0 );
1693 if( count < NDELAY ){
1694 delay = delays[count];
1695 prior = totals[count];
1696 }else{
1697 delay = delays[NDELAY-1];
1698 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
1700 if( prior + delay > tmout ){
1701 delay = tmout - prior;
1702 if( delay<=0 ) return 0;
1704 sqlite3OsSleep(db->pVfs, delay*1000);
1705 return 1;
1706 #else
1707 /* This case for unix systems that lack usleep() support. Sleeping
1708 ** must be done in increments of whole seconds */
1709 sqlite3 *db = (sqlite3 *)ptr;
1710 int tmout = ((sqlite3 *)ptr)->busyTimeout;
1711 if( (count+1)*1000 > tmout ){
1712 return 0;
1714 sqlite3OsSleep(db->pVfs, 1000000);
1715 return 1;
1716 #endif
1720 ** Invoke the given busy handler.
1722 ** This routine is called when an operation failed to acquire a
1723 ** lock on VFS file pFile.
1725 ** If this routine returns non-zero, the lock is retried. If it
1726 ** returns 0, the operation aborts with an SQLITE_BUSY error.
1728 int sqlite3InvokeBusyHandler(BusyHandler *p){
1729 int rc;
1730 if( p->xBusyHandler==0 || p->nBusy<0 ) return 0;
1731 rc = p->xBusyHandler(p->pBusyArg, p->nBusy);
1732 if( rc==0 ){
1733 p->nBusy = -1;
1734 }else{
1735 p->nBusy++;
1737 return rc;
1741 ** This routine sets the busy callback for an Sqlite database to the
1742 ** given callback function with the given argument.
1744 int sqlite3_busy_handler(
1745 sqlite3 *db,
1746 int (*xBusy)(void*,int),
1747 void *pArg
1749 #ifdef SQLITE_ENABLE_API_ARMOR
1750 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
1751 #endif
1752 sqlite3_mutex_enter(db->mutex);
1753 db->busyHandler.xBusyHandler = xBusy;
1754 db->busyHandler.pBusyArg = pArg;
1755 db->busyHandler.nBusy = 0;
1756 db->busyTimeout = 0;
1757 sqlite3_mutex_leave(db->mutex);
1758 return SQLITE_OK;
1761 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1763 ** This routine sets the progress callback for an Sqlite database to the
1764 ** given callback function with the given argument. The progress callback will
1765 ** be invoked every nOps opcodes.
1767 void sqlite3_progress_handler(
1768 sqlite3 *db,
1769 int nOps,
1770 int (*xProgress)(void*),
1771 void *pArg
1773 #ifdef SQLITE_ENABLE_API_ARMOR
1774 if( !sqlite3SafetyCheckOk(db) ){
1775 (void)SQLITE_MISUSE_BKPT;
1776 return;
1778 #endif
1779 sqlite3_mutex_enter(db->mutex);
1780 if( nOps>0 ){
1781 db->xProgress = xProgress;
1782 db->nProgressOps = (unsigned)nOps;
1783 db->pProgressArg = pArg;
1784 }else{
1785 db->xProgress = 0;
1786 db->nProgressOps = 0;
1787 db->pProgressArg = 0;
1789 sqlite3_mutex_leave(db->mutex);
1791 #endif
1795 ** This routine installs a default busy handler that waits for the
1796 ** specified number of milliseconds before returning 0.
1798 int sqlite3_busy_timeout(sqlite3 *db, int ms){
1799 #ifdef SQLITE_ENABLE_API_ARMOR
1800 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
1801 #endif
1802 if( ms>0 ){
1803 sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
1804 (void*)db);
1805 db->busyTimeout = ms;
1806 }else{
1807 sqlite3_busy_handler(db, 0, 0);
1809 return SQLITE_OK;
1813 ** Cause any pending operation to stop at its earliest opportunity.
1815 void sqlite3_interrupt(sqlite3 *db){
1816 #ifdef SQLITE_ENABLE_API_ARMOR
1817 if( !sqlite3SafetyCheckOk(db)
1818 && (db==0 || db->eOpenState!=SQLITE_STATE_ZOMBIE)
1820 (void)SQLITE_MISUSE_BKPT;
1821 return;
1823 #endif
1824 AtomicStore(&db->u1.isInterrupted, 1);
1828 ** Return true or false depending on whether or not an interrupt is
1829 ** pending on connection db.
1831 int sqlite3_is_interrupted(sqlite3 *db){
1832 #ifdef SQLITE_ENABLE_API_ARMOR
1833 if( !sqlite3SafetyCheckOk(db)
1834 && (db==0 || db->eOpenState!=SQLITE_STATE_ZOMBIE)
1836 (void)SQLITE_MISUSE_BKPT;
1837 return 0;
1839 #endif
1840 return AtomicLoad(&db->u1.isInterrupted)!=0;
1844 ** This function is exactly the same as sqlite3_create_function(), except
1845 ** that it is designed to be called by internal code. The difference is
1846 ** that if a malloc() fails in sqlite3_create_function(), an error code
1847 ** is returned and the mallocFailed flag cleared.
1849 int sqlite3CreateFunc(
1850 sqlite3 *db,
1851 const char *zFunctionName,
1852 int nArg,
1853 int enc,
1854 void *pUserData,
1855 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
1856 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
1857 void (*xFinal)(sqlite3_context*),
1858 void (*xValue)(sqlite3_context*),
1859 void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
1860 FuncDestructor *pDestructor
1862 FuncDef *p;
1863 int extraFlags;
1865 assert( sqlite3_mutex_held(db->mutex) );
1866 assert( xValue==0 || xSFunc==0 );
1867 if( zFunctionName==0 /* Must have a valid name */
1868 || (xSFunc!=0 && xFinal!=0) /* Not both xSFunc and xFinal */
1869 || ((xFinal==0)!=(xStep==0)) /* Both or neither of xFinal and xStep */
1870 || ((xValue==0)!=(xInverse==0)) /* Both or neither of xValue, xInverse */
1871 || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG)
1872 || (255<sqlite3Strlen30(zFunctionName))
1874 return SQLITE_MISUSE_BKPT;
1877 assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
1878 assert( SQLITE_FUNC_DIRECT==SQLITE_DIRECTONLY );
1879 extraFlags = enc & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY|
1880 SQLITE_SUBTYPE|SQLITE_INNOCUOUS);
1881 enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
1883 /* The SQLITE_INNOCUOUS flag is the same bit as SQLITE_FUNC_UNSAFE. But
1884 ** the meaning is inverted. So flip the bit. */
1885 assert( SQLITE_FUNC_UNSAFE==SQLITE_INNOCUOUS );
1886 extraFlags ^= SQLITE_FUNC_UNSAFE; /* tag-20230109-1 */
1889 #ifndef SQLITE_OMIT_UTF16
1890 /* If SQLITE_UTF16 is specified as the encoding type, transform this
1891 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
1892 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
1894 ** If SQLITE_ANY is specified, add three versions of the function
1895 ** to the hash table.
1897 switch( enc ){
1898 case SQLITE_UTF16:
1899 enc = SQLITE_UTF16NATIVE;
1900 break;
1901 case SQLITE_ANY: {
1902 int rc;
1903 rc = sqlite3CreateFunc(db, zFunctionName, nArg,
1904 (SQLITE_UTF8|extraFlags)^SQLITE_FUNC_UNSAFE, /* tag-20230109-1 */
1905 pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
1906 if( rc==SQLITE_OK ){
1907 rc = sqlite3CreateFunc(db, zFunctionName, nArg,
1908 (SQLITE_UTF16LE|extraFlags)^SQLITE_FUNC_UNSAFE, /* tag-20230109-1*/
1909 pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
1911 if( rc!=SQLITE_OK ){
1912 return rc;
1914 enc = SQLITE_UTF16BE;
1915 break;
1917 case SQLITE_UTF8:
1918 case SQLITE_UTF16LE:
1919 case SQLITE_UTF16BE:
1920 break;
1921 default:
1922 enc = SQLITE_UTF8;
1923 break;
1925 #else
1926 enc = SQLITE_UTF8;
1927 #endif
1929 /* Check if an existing function is being overridden or deleted. If so,
1930 ** and there are active VMs, then return SQLITE_BUSY. If a function
1931 ** is being overridden/deleted but there are no active VMs, allow the
1932 ** operation to continue but invalidate all precompiled statements.
1934 p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
1935 if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){
1936 if( db->nVdbeActive ){
1937 sqlite3ErrorWithMsg(db, SQLITE_BUSY,
1938 "unable to delete/modify user-function due to active statements");
1939 assert( !db->mallocFailed );
1940 return SQLITE_BUSY;
1941 }else{
1942 sqlite3ExpirePreparedStatements(db, 0);
1944 }else if( xSFunc==0 && xFinal==0 ){
1945 /* Trying to delete a function that does not exist. This is a no-op.
1946 ** https://sqlite.org/forum/forumpost/726219164b */
1947 return SQLITE_OK;
1950 p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
1951 assert(p || db->mallocFailed);
1952 if( !p ){
1953 return SQLITE_NOMEM_BKPT;
1956 /* If an older version of the function with a configured destructor is
1957 ** being replaced invoke the destructor function here. */
1958 functionDestroy(db, p);
1960 if( pDestructor ){
1961 pDestructor->nRef++;
1963 p->u.pDestructor = pDestructor;
1964 p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
1965 testcase( p->funcFlags & SQLITE_DETERMINISTIC );
1966 testcase( p->funcFlags & SQLITE_DIRECTONLY );
1967 p->xSFunc = xSFunc ? xSFunc : xStep;
1968 p->xFinalize = xFinal;
1969 p->xValue = xValue;
1970 p->xInverse = xInverse;
1971 p->pUserData = pUserData;
1972 p->nArg = (u16)nArg;
1973 return SQLITE_OK;
1977 ** Worker function used by utf-8 APIs that create new functions:
1979 ** sqlite3_create_function()
1980 ** sqlite3_create_function_v2()
1981 ** sqlite3_create_window_function()
1983 static int createFunctionApi(
1984 sqlite3 *db,
1985 const char *zFunc,
1986 int nArg,
1987 int enc,
1988 void *p,
1989 void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
1990 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
1991 void (*xFinal)(sqlite3_context*),
1992 void (*xValue)(sqlite3_context*),
1993 void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
1994 void(*xDestroy)(void*)
1996 int rc = SQLITE_ERROR;
1997 FuncDestructor *pArg = 0;
1999 #ifdef SQLITE_ENABLE_API_ARMOR
2000 if( !sqlite3SafetyCheckOk(db) ){
2001 return SQLITE_MISUSE_BKPT;
2003 #endif
2004 sqlite3_mutex_enter(db->mutex);
2005 if( xDestroy ){
2006 pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor));
2007 if( !pArg ){
2008 sqlite3OomFault(db);
2009 xDestroy(p);
2010 goto out;
2012 pArg->nRef = 0;
2013 pArg->xDestroy = xDestroy;
2014 pArg->pUserData = p;
2016 rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p,
2017 xSFunc, xStep, xFinal, xValue, xInverse, pArg
2019 if( pArg && pArg->nRef==0 ){
2020 assert( rc!=SQLITE_OK || (xStep==0 && xFinal==0) );
2021 xDestroy(p);
2022 sqlite3_free(pArg);
2025 out:
2026 rc = sqlite3ApiExit(db, rc);
2027 sqlite3_mutex_leave(db->mutex);
2028 return rc;
2032 ** Create new user functions.
2034 int sqlite3_create_function(
2035 sqlite3 *db,
2036 const char *zFunc,
2037 int nArg,
2038 int enc,
2039 void *p,
2040 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
2041 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
2042 void (*xFinal)(sqlite3_context*)
2044 return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
2045 xFinal, 0, 0, 0);
2047 int sqlite3_create_function_v2(
2048 sqlite3 *db,
2049 const char *zFunc,
2050 int nArg,
2051 int enc,
2052 void *p,
2053 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
2054 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
2055 void (*xFinal)(sqlite3_context*),
2056 void (*xDestroy)(void *)
2058 return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
2059 xFinal, 0, 0, xDestroy);
2061 int sqlite3_create_window_function(
2062 sqlite3 *db,
2063 const char *zFunc,
2064 int nArg,
2065 int enc,
2066 void *p,
2067 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
2068 void (*xFinal)(sqlite3_context*),
2069 void (*xValue)(sqlite3_context*),
2070 void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
2071 void (*xDestroy)(void *)
2073 return createFunctionApi(db, zFunc, nArg, enc, p, 0, xStep,
2074 xFinal, xValue, xInverse, xDestroy);
2077 #ifndef SQLITE_OMIT_UTF16
2078 int sqlite3_create_function16(
2079 sqlite3 *db,
2080 const void *zFunctionName,
2081 int nArg,
2082 int eTextRep,
2083 void *p,
2084 void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
2085 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
2086 void (*xFinal)(sqlite3_context*)
2088 int rc;
2089 char *zFunc8;
2091 #ifdef SQLITE_ENABLE_API_ARMOR
2092 if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
2093 #endif
2094 sqlite3_mutex_enter(db->mutex);
2095 assert( !db->mallocFailed );
2096 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
2097 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0,0,0);
2098 sqlite3DbFree(db, zFunc8);
2099 rc = sqlite3ApiExit(db, rc);
2100 sqlite3_mutex_leave(db->mutex);
2101 return rc;
2103 #endif
2107 ** The following is the implementation of an SQL function that always
2108 ** fails with an error message stating that the function is used in the
2109 ** wrong context. The sqlite3_overload_function() API might construct
2110 ** SQL function that use this routine so that the functions will exist
2111 ** for name resolution but are actually overloaded by the xFindFunction
2112 ** method of virtual tables.
2114 static void sqlite3InvalidFunction(
2115 sqlite3_context *context, /* The function calling context */
2116 int NotUsed, /* Number of arguments to the function */
2117 sqlite3_value **NotUsed2 /* Value of each argument */
2119 const char *zName = (const char*)sqlite3_user_data(context);
2120 char *zErr;
2121 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2122 zErr = sqlite3_mprintf(
2123 "unable to use function %s in the requested context", zName);
2124 sqlite3_result_error(context, zErr, -1);
2125 sqlite3_free(zErr);
2129 ** Declare that a function has been overloaded by a virtual table.
2131 ** If the function already exists as a regular global function, then
2132 ** this routine is a no-op. If the function does not exist, then create
2133 ** a new one that always throws a run-time error.
2135 ** When virtual tables intend to provide an overloaded function, they
2136 ** should call this routine to make sure the global function exists.
2137 ** A global function must exist in order for name resolution to work
2138 ** properly.
2140 int sqlite3_overload_function(
2141 sqlite3 *db,
2142 const char *zName,
2143 int nArg
2145 int rc;
2146 char *zCopy;
2148 #ifdef SQLITE_ENABLE_API_ARMOR
2149 if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
2150 return SQLITE_MISUSE_BKPT;
2152 #endif
2153 sqlite3_mutex_enter(db->mutex);
2154 rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0;
2155 sqlite3_mutex_leave(db->mutex);
2156 if( rc ) return SQLITE_OK;
2157 zCopy = sqlite3_mprintf("%s", zName);
2158 if( zCopy==0 ) return SQLITE_NOMEM;
2159 return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8,
2160 zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free);
2163 #ifndef SQLITE_OMIT_TRACE
2165 ** Register a trace function. The pArg from the previously registered trace
2166 ** is returned.
2168 ** A NULL trace function means that no tracing is executes. A non-NULL
2169 ** trace is a pointer to a function that is invoked at the start of each
2170 ** SQL statement.
2172 #ifndef SQLITE_OMIT_DEPRECATED
2173 void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
2174 void *pOld;
2176 #ifdef SQLITE_ENABLE_API_ARMOR
2177 if( !sqlite3SafetyCheckOk(db) ){
2178 (void)SQLITE_MISUSE_BKPT;
2179 return 0;
2181 #endif
2182 sqlite3_mutex_enter(db->mutex);
2183 pOld = db->pTraceArg;
2184 db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
2185 db->trace.xLegacy = xTrace;
2186 db->pTraceArg = pArg;
2187 sqlite3_mutex_leave(db->mutex);
2188 return pOld;
2190 #endif /* SQLITE_OMIT_DEPRECATED */
2192 /* Register a trace callback using the version-2 interface.
2194 int sqlite3_trace_v2(
2195 sqlite3 *db, /* Trace this connection */
2196 unsigned mTrace, /* Mask of events to be traced */
2197 int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */
2198 void *pArg /* Context */
2200 #ifdef SQLITE_ENABLE_API_ARMOR
2201 if( !sqlite3SafetyCheckOk(db) ){
2202 return SQLITE_MISUSE_BKPT;
2204 #endif
2205 sqlite3_mutex_enter(db->mutex);
2206 if( mTrace==0 ) xTrace = 0;
2207 if( xTrace==0 ) mTrace = 0;
2208 db->mTrace = mTrace;
2209 db->trace.xV2 = xTrace;
2210 db->pTraceArg = pArg;
2211 sqlite3_mutex_leave(db->mutex);
2212 return SQLITE_OK;
2215 #ifndef SQLITE_OMIT_DEPRECATED
2217 ** Register a profile function. The pArg from the previously registered
2218 ** profile function is returned.
2220 ** A NULL profile function means that no profiling is executes. A non-NULL
2221 ** profile is a pointer to a function that is invoked at the conclusion of
2222 ** each SQL statement that is run.
2224 void *sqlite3_profile(
2225 sqlite3 *db,
2226 void (*xProfile)(void*,const char*,sqlite_uint64),
2227 void *pArg
2229 void *pOld;
2231 #ifdef SQLITE_ENABLE_API_ARMOR
2232 if( !sqlite3SafetyCheckOk(db) ){
2233 (void)SQLITE_MISUSE_BKPT;
2234 return 0;
2236 #endif
2237 sqlite3_mutex_enter(db->mutex);
2238 pOld = db->pProfileArg;
2239 db->xProfile = xProfile;
2240 db->pProfileArg = pArg;
2241 db->mTrace &= SQLITE_TRACE_NONLEGACY_MASK;
2242 if( db->xProfile ) db->mTrace |= SQLITE_TRACE_XPROFILE;
2243 sqlite3_mutex_leave(db->mutex);
2244 return pOld;
2246 #endif /* SQLITE_OMIT_DEPRECATED */
2247 #endif /* SQLITE_OMIT_TRACE */
2250 ** Register a function to be invoked when a transaction commits.
2251 ** If the invoked function returns non-zero, then the commit becomes a
2252 ** rollback.
2254 void *sqlite3_commit_hook(
2255 sqlite3 *db, /* Attach the hook to this database */
2256 int (*xCallback)(void*), /* Function to invoke on each commit */
2257 void *pArg /* Argument to the function */
2259 void *pOld;
2261 #ifdef SQLITE_ENABLE_API_ARMOR
2262 if( !sqlite3SafetyCheckOk(db) ){
2263 (void)SQLITE_MISUSE_BKPT;
2264 return 0;
2266 #endif
2267 sqlite3_mutex_enter(db->mutex);
2268 pOld = db->pCommitArg;
2269 db->xCommitCallback = xCallback;
2270 db->pCommitArg = pArg;
2271 sqlite3_mutex_leave(db->mutex);
2272 return pOld;
2276 ** Register a callback to be invoked each time a row is updated,
2277 ** inserted or deleted using this database connection.
2279 void *sqlite3_update_hook(
2280 sqlite3 *db, /* Attach the hook to this database */
2281 void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
2282 void *pArg /* Argument to the function */
2284 void *pRet;
2286 #ifdef SQLITE_ENABLE_API_ARMOR
2287 if( !sqlite3SafetyCheckOk(db) ){
2288 (void)SQLITE_MISUSE_BKPT;
2289 return 0;
2291 #endif
2292 sqlite3_mutex_enter(db->mutex);
2293 pRet = db->pUpdateArg;
2294 db->xUpdateCallback = xCallback;
2295 db->pUpdateArg = pArg;
2296 sqlite3_mutex_leave(db->mutex);
2297 return pRet;
2301 ** Register a callback to be invoked each time a transaction is rolled
2302 ** back by this database connection.
2304 void *sqlite3_rollback_hook(
2305 sqlite3 *db, /* Attach the hook to this database */
2306 void (*xCallback)(void*), /* Callback function */
2307 void *pArg /* Argument to the function */
2309 void *pRet;
2311 #ifdef SQLITE_ENABLE_API_ARMOR
2312 if( !sqlite3SafetyCheckOk(db) ){
2313 (void)SQLITE_MISUSE_BKPT;
2314 return 0;
2316 #endif
2317 sqlite3_mutex_enter(db->mutex);
2318 pRet = db->pRollbackArg;
2319 db->xRollbackCallback = xCallback;
2320 db->pRollbackArg = pArg;
2321 sqlite3_mutex_leave(db->mutex);
2322 return pRet;
2325 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2327 ** Register a callback to be invoked each time a row is updated,
2328 ** inserted or deleted using this database connection.
2330 void *sqlite3_preupdate_hook(
2331 sqlite3 *db, /* Attach the hook to this database */
2332 void(*xCallback)( /* Callback function */
2333 void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
2334 void *pArg /* First callback argument */
2336 void *pRet;
2337 sqlite3_mutex_enter(db->mutex);
2338 pRet = db->pPreUpdateArg;
2339 db->xPreUpdateCallback = xCallback;
2340 db->pPreUpdateArg = pArg;
2341 sqlite3_mutex_leave(db->mutex);
2342 return pRet;
2344 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2347 ** Register a function to be invoked prior to each autovacuum that
2348 ** determines the number of pages to vacuum.
2350 int sqlite3_autovacuum_pages(
2351 sqlite3 *db, /* Attach the hook to this database */
2352 unsigned int (*xCallback)(void*,const char*,u32,u32,u32),
2353 void *pArg, /* Argument to the function */
2354 void (*xDestructor)(void*) /* Destructor for pArg */
2356 #ifdef SQLITE_ENABLE_API_ARMOR
2357 if( !sqlite3SafetyCheckOk(db) ){
2358 if( xDestructor ) xDestructor(pArg);
2359 return SQLITE_MISUSE_BKPT;
2361 #endif
2362 sqlite3_mutex_enter(db->mutex);
2363 if( db->xAutovacDestr ){
2364 db->xAutovacDestr(db->pAutovacPagesArg);
2366 db->xAutovacPages = xCallback;
2367 db->pAutovacPagesArg = pArg;
2368 db->xAutovacDestr = xDestructor;
2369 sqlite3_mutex_leave(db->mutex);
2370 return SQLITE_OK;
2374 #ifndef SQLITE_OMIT_WAL
2376 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
2377 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
2378 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
2379 ** wal_autocheckpoint()).
2381 int sqlite3WalDefaultHook(
2382 void *pClientData, /* Argument */
2383 sqlite3 *db, /* Connection */
2384 const char *zDb, /* Database */
2385 int nFrame /* Size of WAL */
2387 if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
2388 sqlite3BeginBenignMalloc();
2389 sqlite3_wal_checkpoint(db, zDb);
2390 sqlite3EndBenignMalloc();
2392 return SQLITE_OK;
2394 #endif /* SQLITE_OMIT_WAL */
2397 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
2398 ** a database after committing a transaction if there are nFrame or
2399 ** more frames in the log file. Passing zero or a negative value as the
2400 ** nFrame parameter disables automatic checkpoints entirely.
2402 ** The callback registered by this function replaces any existing callback
2403 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
2404 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
2405 ** configured by this function.
2407 int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
2408 #ifdef SQLITE_OMIT_WAL
2409 UNUSED_PARAMETER(db);
2410 UNUSED_PARAMETER(nFrame);
2411 #else
2412 #ifdef SQLITE_ENABLE_API_ARMOR
2413 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
2414 #endif
2415 if( nFrame>0 ){
2416 sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
2417 }else{
2418 sqlite3_wal_hook(db, 0, 0);
2420 #endif
2421 return SQLITE_OK;
2425 ** Register a callback to be invoked each time a transaction is written
2426 ** into the write-ahead-log by this database connection.
2428 void *sqlite3_wal_hook(
2429 sqlite3 *db, /* Attach the hook to this db handle */
2430 int(*xCallback)(void *, sqlite3*, const char*, int),
2431 void *pArg /* First argument passed to xCallback() */
2433 #ifndef SQLITE_OMIT_WAL
2434 void *pRet;
2435 #ifdef SQLITE_ENABLE_API_ARMOR
2436 if( !sqlite3SafetyCheckOk(db) ){
2437 (void)SQLITE_MISUSE_BKPT;
2438 return 0;
2440 #endif
2441 sqlite3_mutex_enter(db->mutex);
2442 pRet = db->pWalArg;
2443 db->xWalCallback = xCallback;
2444 db->pWalArg = pArg;
2445 sqlite3_mutex_leave(db->mutex);
2446 return pRet;
2447 #else
2448 return 0;
2449 #endif
2453 ** Checkpoint database zDb.
2455 int sqlite3_wal_checkpoint_v2(
2456 sqlite3 *db, /* Database handle */
2457 const char *zDb, /* Name of attached database (or NULL) */
2458 int eMode, /* SQLITE_CHECKPOINT_* value */
2459 int *pnLog, /* OUT: Size of WAL log in frames */
2460 int *pnCkpt /* OUT: Total number of frames checkpointed */
2462 #ifdef SQLITE_OMIT_WAL
2463 return SQLITE_OK;
2464 #else
2465 int rc; /* Return code */
2466 int iDb; /* Schema to checkpoint */
2468 #ifdef SQLITE_ENABLE_API_ARMOR
2469 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
2470 #endif
2472 /* Initialize the output variables to -1 in case an error occurs. */
2473 if( pnLog ) *pnLog = -1;
2474 if( pnCkpt ) *pnCkpt = -1;
2476 assert( SQLITE_CHECKPOINT_PASSIVE==0 );
2477 assert( SQLITE_CHECKPOINT_FULL==1 );
2478 assert( SQLITE_CHECKPOINT_RESTART==2 );
2479 assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
2480 if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
2481 /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
2482 ** mode: */
2483 return SQLITE_MISUSE;
2486 sqlite3_mutex_enter(db->mutex);
2487 if( zDb && zDb[0] ){
2488 iDb = sqlite3FindDbName(db, zDb);
2489 }else{
2490 iDb = SQLITE_MAX_DB; /* This means process all schemas */
2492 if( iDb<0 ){
2493 rc = SQLITE_ERROR;
2494 sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
2495 }else{
2496 db->busyHandler.nBusy = 0;
2497 rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
2498 sqlite3Error(db, rc);
2500 rc = sqlite3ApiExit(db, rc);
2502 /* If there are no active statements, clear the interrupt flag at this
2503 ** point. */
2504 if( db->nVdbeActive==0 ){
2505 AtomicStore(&db->u1.isInterrupted, 0);
2508 sqlite3_mutex_leave(db->mutex);
2509 return rc;
2510 #endif
2515 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
2516 ** to contains a zero-length string, all attached databases are
2517 ** checkpointed.
2519 int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
2520 /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
2521 ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
2522 return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
2525 #ifndef SQLITE_OMIT_WAL
2527 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
2528 ** not currently open in WAL mode.
2530 ** If a transaction is open on the database being checkpointed, this
2531 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
2532 ** an error occurs while running the checkpoint, an SQLite error code is
2533 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
2535 ** The mutex on database handle db should be held by the caller. The mutex
2536 ** associated with the specific b-tree being checkpointed is taken by
2537 ** this function while the checkpoint is running.
2539 ** If iDb is passed SQLITE_MAX_DB then all attached databases are
2540 ** checkpointed. If an error is encountered it is returned immediately -
2541 ** no attempt is made to checkpoint any remaining databases.
2543 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
2544 ** or TRUNCATE.
2546 int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
2547 int rc = SQLITE_OK; /* Return code */
2548 int i; /* Used to iterate through attached dbs */
2549 int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
2551 assert( sqlite3_mutex_held(db->mutex) );
2552 assert( !pnLog || *pnLog==-1 );
2553 assert( !pnCkpt || *pnCkpt==-1 );
2554 testcase( iDb==SQLITE_MAX_ATTACHED ); /* See forum post a006d86f72 */
2555 testcase( iDb==SQLITE_MAX_DB );
2557 for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
2558 if( i==iDb || iDb==SQLITE_MAX_DB ){
2559 rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
2560 pnLog = 0;
2561 pnCkpt = 0;
2562 if( rc==SQLITE_BUSY ){
2563 bBusy = 1;
2564 rc = SQLITE_OK;
2569 return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
2571 #endif /* SQLITE_OMIT_WAL */
2574 ** This function returns true if main-memory should be used instead of
2575 ** a temporary file for transient pager files and statement journals.
2576 ** The value returned depends on the value of db->temp_store (runtime
2577 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
2578 ** following table describes the relationship between these two values
2579 ** and this functions return value.
2581 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
2582 ** ----------------- -------------- ------------------------------
2583 ** 0 any file (return 0)
2584 ** 1 1 file (return 0)
2585 ** 1 2 memory (return 1)
2586 ** 1 0 file (return 0)
2587 ** 2 1 file (return 0)
2588 ** 2 2 memory (return 1)
2589 ** 2 0 memory (return 1)
2590 ** 3 any memory (return 1)
2592 int sqlite3TempInMemory(const sqlite3 *db){
2593 #if SQLITE_TEMP_STORE==1
2594 return ( db->temp_store==2 );
2595 #endif
2596 #if SQLITE_TEMP_STORE==2
2597 return ( db->temp_store!=1 );
2598 #endif
2599 #if SQLITE_TEMP_STORE==3
2600 UNUSED_PARAMETER(db);
2601 return 1;
2602 #endif
2603 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
2604 UNUSED_PARAMETER(db);
2605 return 0;
2606 #endif
2610 ** Return UTF-8 encoded English language explanation of the most recent
2611 ** error.
2613 const char *sqlite3_errmsg(sqlite3 *db){
2614 const char *z;
2615 if( !db ){
2616 return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
2618 if( !sqlite3SafetyCheckSickOrOk(db) ){
2619 return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
2621 sqlite3_mutex_enter(db->mutex);
2622 if( db->mallocFailed ){
2623 z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
2624 }else{
2625 testcase( db->pErr==0 );
2626 z = db->errCode ? (char*)sqlite3_value_text(db->pErr) : 0;
2627 assert( !db->mallocFailed );
2628 if( z==0 ){
2629 z = sqlite3ErrStr(db->errCode);
2632 sqlite3_mutex_leave(db->mutex);
2633 return z;
2637 ** Return the byte offset of the most recent error
2639 int sqlite3_error_offset(sqlite3 *db){
2640 int iOffset = -1;
2641 if( db && sqlite3SafetyCheckSickOrOk(db) && db->errCode ){
2642 sqlite3_mutex_enter(db->mutex);
2643 iOffset = db->errByteOffset;
2644 sqlite3_mutex_leave(db->mutex);
2646 return iOffset;
2649 #ifndef SQLITE_OMIT_UTF16
2651 ** Return UTF-16 encoded English language explanation of the most recent
2652 ** error.
2654 const void *sqlite3_errmsg16(sqlite3 *db){
2655 static const u16 outOfMem[] = {
2656 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
2658 static const u16 misuse[] = {
2659 'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
2660 'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
2661 'm', 'i', 's', 'u', 's', 'e', 0
2664 const void *z;
2665 if( !db ){
2666 return (void *)outOfMem;
2668 if( !sqlite3SafetyCheckSickOrOk(db) ){
2669 return (void *)misuse;
2671 sqlite3_mutex_enter(db->mutex);
2672 if( db->mallocFailed ){
2673 z = (void *)outOfMem;
2674 }else{
2675 z = sqlite3_value_text16(db->pErr);
2676 if( z==0 ){
2677 sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
2678 z = sqlite3_value_text16(db->pErr);
2680 /* A malloc() may have failed within the call to sqlite3_value_text16()
2681 ** above. If this is the case, then the db->mallocFailed flag needs to
2682 ** be cleared before returning. Do this directly, instead of via
2683 ** sqlite3ApiExit(), to avoid setting the database handle error message.
2685 sqlite3OomClear(db);
2687 sqlite3_mutex_leave(db->mutex);
2688 return z;
2690 #endif /* SQLITE_OMIT_UTF16 */
2693 ** Return the most recent error code generated by an SQLite routine. If NULL is
2694 ** passed to this function, we assume a malloc() failed during sqlite3_open().
2696 int sqlite3_errcode(sqlite3 *db){
2697 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
2698 return SQLITE_MISUSE_BKPT;
2700 if( !db || db->mallocFailed ){
2701 return SQLITE_NOMEM_BKPT;
2703 return db->errCode & db->errMask;
2705 int sqlite3_extended_errcode(sqlite3 *db){
2706 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
2707 return SQLITE_MISUSE_BKPT;
2709 if( !db || db->mallocFailed ){
2710 return SQLITE_NOMEM_BKPT;
2712 return db->errCode;
2714 int sqlite3_system_errno(sqlite3 *db){
2715 return db ? db->iSysErrno : 0;
2719 ** Return a string that describes the kind of error specified in the
2720 ** argument. For now, this simply calls the internal sqlite3ErrStr()
2721 ** function.
2723 const char *sqlite3_errstr(int rc){
2724 return sqlite3ErrStr(rc);
2728 ** Create a new collating function for database "db". The name is zName
2729 ** and the encoding is enc.
2731 static int createCollation(
2732 sqlite3* db,
2733 const char *zName,
2734 u8 enc,
2735 void* pCtx,
2736 int(*xCompare)(void*,int,const void*,int,const void*),
2737 void(*xDel)(void*)
2739 CollSeq *pColl;
2740 int enc2;
2742 assert( sqlite3_mutex_held(db->mutex) );
2744 /* If SQLITE_UTF16 is specified as the encoding type, transform this
2745 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
2746 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
2748 enc2 = enc;
2749 testcase( enc2==SQLITE_UTF16 );
2750 testcase( enc2==SQLITE_UTF16_ALIGNED );
2751 if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
2752 enc2 = SQLITE_UTF16NATIVE;
2754 if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
2755 return SQLITE_MISUSE_BKPT;
2758 /* Check if this call is removing or replacing an existing collation
2759 ** sequence. If so, and there are active VMs, return busy. If there
2760 ** are no active VMs, invalidate any pre-compiled statements.
2762 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
2763 if( pColl && pColl->xCmp ){
2764 if( db->nVdbeActive ){
2765 sqlite3ErrorWithMsg(db, SQLITE_BUSY,
2766 "unable to delete/modify collation sequence due to active statements");
2767 return SQLITE_BUSY;
2769 sqlite3ExpirePreparedStatements(db, 0);
2771 /* If collation sequence pColl was created directly by a call to
2772 ** sqlite3_create_collation, and not generated by synthCollSeq(),
2773 ** then any copies made by synthCollSeq() need to be invalidated.
2774 ** Also, collation destructor - CollSeq.xDel() - function may need
2775 ** to be called.
2777 if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
2778 CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
2779 int j;
2780 for(j=0; j<3; j++){
2781 CollSeq *p = &aColl[j];
2782 if( p->enc==pColl->enc ){
2783 if( p->xDel ){
2784 p->xDel(p->pUser);
2786 p->xCmp = 0;
2792 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
2793 if( pColl==0 ) return SQLITE_NOMEM_BKPT;
2794 pColl->xCmp = xCompare;
2795 pColl->pUser = pCtx;
2796 pColl->xDel = xDel;
2797 pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
2798 sqlite3Error(db, SQLITE_OK);
2799 return SQLITE_OK;
2804 ** This array defines hard upper bounds on limit values. The
2805 ** initializer must be kept in sync with the SQLITE_LIMIT_*
2806 ** #defines in sqlite3.h.
2808 static const int aHardLimit[] = {
2809 SQLITE_MAX_LENGTH,
2810 SQLITE_MAX_SQL_LENGTH,
2811 SQLITE_MAX_COLUMN,
2812 SQLITE_MAX_EXPR_DEPTH,
2813 SQLITE_MAX_COMPOUND_SELECT,
2814 SQLITE_MAX_VDBE_OP,
2815 SQLITE_MAX_FUNCTION_ARG,
2816 SQLITE_MAX_ATTACHED,
2817 SQLITE_MAX_LIKE_PATTERN_LENGTH,
2818 SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
2819 SQLITE_MAX_TRIGGER_DEPTH,
2820 SQLITE_MAX_WORKER_THREADS,
2824 ** Make sure the hard limits are set to reasonable values
2826 #if SQLITE_MAX_LENGTH<100
2827 # error SQLITE_MAX_LENGTH must be at least 100
2828 #endif
2829 #if SQLITE_MAX_SQL_LENGTH<100
2830 # error SQLITE_MAX_SQL_LENGTH must be at least 100
2831 #endif
2832 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
2833 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
2834 #endif
2835 #if SQLITE_MAX_COMPOUND_SELECT<2
2836 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
2837 #endif
2838 #if SQLITE_MAX_VDBE_OP<40
2839 # error SQLITE_MAX_VDBE_OP must be at least 40
2840 #endif
2841 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
2842 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
2843 #endif
2844 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
2845 # error SQLITE_MAX_ATTACHED must be between 0 and 125
2846 #endif
2847 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
2848 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
2849 #endif
2850 #if SQLITE_MAX_COLUMN>32767
2851 # error SQLITE_MAX_COLUMN must not exceed 32767
2852 #endif
2853 #if SQLITE_MAX_TRIGGER_DEPTH<1
2854 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
2855 #endif
2856 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
2857 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
2858 #endif
2862 ** Change the value of a limit. Report the old value.
2863 ** If an invalid limit index is supplied, report -1.
2864 ** Make no changes but still report the old value if the
2865 ** new limit is negative.
2867 ** A new lower limit does not shrink existing constructs.
2868 ** It merely prevents new constructs that exceed the limit
2869 ** from forming.
2871 int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
2872 int oldLimit;
2874 #ifdef SQLITE_ENABLE_API_ARMOR
2875 if( !sqlite3SafetyCheckOk(db) ){
2876 (void)SQLITE_MISUSE_BKPT;
2877 return -1;
2879 #endif
2881 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
2882 ** there is a hard upper bound set at compile-time by a C preprocessor
2883 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
2884 ** "_MAX_".)
2886 assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
2887 assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
2888 assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
2889 assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
2890 assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
2891 assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
2892 assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
2893 assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
2894 assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
2895 SQLITE_MAX_LIKE_PATTERN_LENGTH );
2896 assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
2897 assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
2898 assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
2899 assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
2902 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
2903 return -1;
2905 oldLimit = db->aLimit[limitId];
2906 if( newLimit>=0 ){ /* IMP: R-52476-28732 */
2907 if( newLimit>aHardLimit[limitId] ){
2908 newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
2909 }else if( newLimit<1 && limitId==SQLITE_LIMIT_LENGTH ){
2910 newLimit = 1;
2912 db->aLimit[limitId] = newLimit;
2914 return oldLimit; /* IMP: R-53341-35419 */
2918 ** This function is used to parse both URIs and non-URI filenames passed by the
2919 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
2920 ** URIs specified as part of ATTACH statements.
2922 ** The first argument to this function is the name of the VFS to use (or
2923 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
2924 ** query parameter. The second argument contains the URI (or non-URI filename)
2925 ** itself. When this function is called the *pFlags variable should contain
2926 ** the default flags to open the database handle with. The value stored in
2927 ** *pFlags may be updated before returning if the URI filename contains
2928 ** "cache=xxx" or "mode=xxx" query parameters.
2930 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
2931 ** the VFS that should be used to open the database file. *pzFile is set to
2932 ** point to a buffer containing the name of the file to open. The value
2933 ** stored in *pzFile is a database name acceptable to sqlite3_uri_parameter()
2934 ** and is in the same format as names created using sqlite3_create_filename().
2935 ** The caller must invoke sqlite3_free_filename() (not sqlite3_free()!) on
2936 ** the value returned in *pzFile to avoid a memory leak.
2938 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
2939 ** may be set to point to a buffer containing an English language error
2940 ** message. It is the responsibility of the caller to eventually release
2941 ** this buffer by calling sqlite3_free().
2943 int sqlite3ParseUri(
2944 const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
2945 const char *zUri, /* Nul-terminated URI to parse */
2946 unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
2947 sqlite3_vfs **ppVfs, /* OUT: VFS to use */
2948 char **pzFile, /* OUT: Filename component of URI */
2949 char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
2951 int rc = SQLITE_OK;
2952 unsigned int flags = *pFlags;
2953 const char *zVfs = zDefaultVfs;
2954 char *zFile;
2955 char c;
2956 int nUri = sqlite3Strlen30(zUri);
2958 assert( *pzErrMsg==0 );
2960 if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
2961 || AtomicLoad(&sqlite3GlobalConfig.bOpenUri)) /* IMP: R-51689-46548 */
2962 && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
2964 char *zOpt;
2965 int eState; /* Parser state when parsing URI */
2966 int iIn; /* Input character index */
2967 int iOut = 0; /* Output character index */
2968 u64 nByte = nUri+8; /* Bytes of space to allocate */
2970 /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
2971 ** method that there may be extra parameters following the file-name. */
2972 flags |= SQLITE_OPEN_URI;
2974 for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
2975 zFile = sqlite3_malloc64(nByte);
2976 if( !zFile ) return SQLITE_NOMEM_BKPT;
2978 memset(zFile, 0, 4); /* 4-byte of 0x00 is the start of DB name marker */
2979 zFile += 4;
2981 iIn = 5;
2982 #ifdef SQLITE_ALLOW_URI_AUTHORITY
2983 if( strncmp(zUri+5, "///", 3)==0 ){
2984 iIn = 7;
2985 /* The following condition causes URIs with five leading / characters
2986 ** like file://///host/path to be converted into UNCs like //host/path.
2987 ** The correct URI for that UNC has only two or four leading / characters
2988 ** file://host/path or file:////host/path. But 5 leading slashes is a
2989 ** common error, we are told, so we handle it as a special case. */
2990 if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
2991 }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
2992 iIn = 16;
2994 #else
2995 /* Discard the scheme and authority segments of the URI. */
2996 if( zUri[5]=='/' && zUri[6]=='/' ){
2997 iIn = 7;
2998 while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
2999 if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
3000 *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
3001 iIn-7, &zUri[7]);
3002 rc = SQLITE_ERROR;
3003 goto parse_uri_out;
3006 #endif
3008 /* Copy the filename and any query parameters into the zFile buffer.
3009 ** Decode %HH escape codes along the way.
3011 ** Within this loop, variable eState may be set to 0, 1 or 2, depending
3012 ** on the parsing context. As follows:
3014 ** 0: Parsing file-name.
3015 ** 1: Parsing name section of a name=value query parameter.
3016 ** 2: Parsing value section of a name=value query parameter.
3018 eState = 0;
3019 while( (c = zUri[iIn])!=0 && c!='#' ){
3020 iIn++;
3021 if( c=='%'
3022 && sqlite3Isxdigit(zUri[iIn])
3023 && sqlite3Isxdigit(zUri[iIn+1])
3025 int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
3026 octet += sqlite3HexToInt(zUri[iIn++]);
3028 assert( octet>=0 && octet<256 );
3029 if( octet==0 ){
3030 #ifndef SQLITE_ENABLE_URI_00_ERROR
3031 /* This branch is taken when "%00" appears within the URI. In this
3032 ** case we ignore all text in the remainder of the path, name or
3033 ** value currently being parsed. So ignore the current character
3034 ** and skip to the next "?", "=" or "&", as appropriate. */
3035 while( (c = zUri[iIn])!=0 && c!='#'
3036 && (eState!=0 || c!='?')
3037 && (eState!=1 || (c!='=' && c!='&'))
3038 && (eState!=2 || c!='&')
3040 iIn++;
3042 continue;
3043 #else
3044 /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
3045 *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
3046 rc = SQLITE_ERROR;
3047 goto parse_uri_out;
3048 #endif
3050 c = octet;
3051 }else if( eState==1 && (c=='&' || c=='=') ){
3052 if( zFile[iOut-1]==0 ){
3053 /* An empty option name. Ignore this option altogether. */
3054 while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
3055 continue;
3057 if( c=='&' ){
3058 zFile[iOut++] = '\0';
3059 }else{
3060 eState = 2;
3062 c = 0;
3063 }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
3064 c = 0;
3065 eState = 1;
3067 zFile[iOut++] = c;
3069 if( eState==1 ) zFile[iOut++] = '\0';
3070 memset(zFile+iOut, 0, 4); /* end-of-options + empty journal filenames */
3072 /* Check if there were any options specified that should be interpreted
3073 ** here. Options that are interpreted here include "vfs" and those that
3074 ** correspond to flags that may be passed to the sqlite3_open_v2()
3075 ** method. */
3076 zOpt = &zFile[sqlite3Strlen30(zFile)+1];
3077 while( zOpt[0] ){
3078 int nOpt = sqlite3Strlen30(zOpt);
3079 char *zVal = &zOpt[nOpt+1];
3080 int nVal = sqlite3Strlen30(zVal);
3082 if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
3083 zVfs = zVal;
3084 }else{
3085 struct OpenMode {
3086 const char *z;
3087 int mode;
3088 } *aMode = 0;
3089 char *zModeType = 0;
3090 int mask = 0;
3091 int limit = 0;
3093 if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
3094 static struct OpenMode aCacheMode[] = {
3095 { "shared", SQLITE_OPEN_SHAREDCACHE },
3096 { "private", SQLITE_OPEN_PRIVATECACHE },
3097 { 0, 0 }
3100 mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
3101 aMode = aCacheMode;
3102 limit = mask;
3103 zModeType = "cache";
3105 if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
3106 static struct OpenMode aOpenMode[] = {
3107 { "ro", SQLITE_OPEN_READONLY },
3108 { "rw", SQLITE_OPEN_READWRITE },
3109 { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
3110 { "memory", SQLITE_OPEN_MEMORY },
3111 { 0, 0 }
3114 mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
3115 | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
3116 aMode = aOpenMode;
3117 limit = mask & flags;
3118 zModeType = "access";
3121 if( aMode ){
3122 int i;
3123 int mode = 0;
3124 for(i=0; aMode[i].z; i++){
3125 const char *z = aMode[i].z;
3126 if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
3127 mode = aMode[i].mode;
3128 break;
3131 if( mode==0 ){
3132 *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
3133 rc = SQLITE_ERROR;
3134 goto parse_uri_out;
3136 if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
3137 *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
3138 zModeType, zVal);
3139 rc = SQLITE_PERM;
3140 goto parse_uri_out;
3142 flags = (flags & ~mask) | mode;
3146 zOpt = &zVal[nVal+1];
3149 }else{
3150 zFile = sqlite3_malloc64(nUri+8);
3151 if( !zFile ) return SQLITE_NOMEM_BKPT;
3152 memset(zFile, 0, 4);
3153 zFile += 4;
3154 if( nUri ){
3155 memcpy(zFile, zUri, nUri);
3157 memset(zFile+nUri, 0, 4);
3158 flags &= ~SQLITE_OPEN_URI;
3161 *ppVfs = sqlite3_vfs_find(zVfs);
3162 if( *ppVfs==0 ){
3163 *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
3164 rc = SQLITE_ERROR;
3166 parse_uri_out:
3167 if( rc!=SQLITE_OK ){
3168 sqlite3_free_filename(zFile);
3169 zFile = 0;
3171 *pFlags = flags;
3172 *pzFile = zFile;
3173 return rc;
3177 ** This routine does the core work of extracting URI parameters from a
3178 ** database filename for the sqlite3_uri_parameter() interface.
3180 static const char *uriParameter(const char *zFilename, const char *zParam){
3181 zFilename += sqlite3Strlen30(zFilename) + 1;
3182 while( ALWAYS(zFilename!=0) && zFilename[0] ){
3183 int x = strcmp(zFilename, zParam);
3184 zFilename += sqlite3Strlen30(zFilename) + 1;
3185 if( x==0 ) return zFilename;
3186 zFilename += sqlite3Strlen30(zFilename) + 1;
3188 return 0;
3194 ** This routine does the work of opening a database on behalf of
3195 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
3196 ** is UTF-8 encoded.
3198 static int openDatabase(
3199 const char *zFilename, /* Database filename UTF-8 encoded */
3200 sqlite3 **ppDb, /* OUT: Returned database handle */
3201 unsigned int flags, /* Operational flags */
3202 const char *zVfs /* Name of the VFS to use */
3204 sqlite3 *db; /* Store allocated handle here */
3205 int rc; /* Return code */
3206 int isThreadsafe; /* True for threadsafe connections */
3207 char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
3208 char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
3209 int i; /* Loop counter */
3211 #ifdef SQLITE_ENABLE_API_ARMOR
3212 if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
3213 #endif
3214 *ppDb = 0;
3215 #ifndef SQLITE_OMIT_AUTOINIT
3216 rc = sqlite3_initialize();
3217 if( rc ) return rc;
3218 #endif
3220 if( sqlite3GlobalConfig.bCoreMutex==0 ){
3221 isThreadsafe = 0;
3222 }else if( flags & SQLITE_OPEN_NOMUTEX ){
3223 isThreadsafe = 0;
3224 }else if( flags & SQLITE_OPEN_FULLMUTEX ){
3225 isThreadsafe = 1;
3226 }else{
3227 isThreadsafe = sqlite3GlobalConfig.bFullMutex;
3230 if( flags & SQLITE_OPEN_PRIVATECACHE ){
3231 flags &= ~SQLITE_OPEN_SHAREDCACHE;
3232 }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
3233 flags |= SQLITE_OPEN_SHAREDCACHE;
3236 /* Remove harmful bits from the flags parameter
3238 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
3239 ** dealt with in the previous code block. Besides these, the only
3240 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
3241 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
3242 ** SQLITE_OPEN_PRIVATECACHE, SQLITE_OPEN_EXRESCODE, and some reserved
3243 ** bits. Silently mask off all other flags.
3245 flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
3246 SQLITE_OPEN_EXCLUSIVE |
3247 SQLITE_OPEN_MAIN_DB |
3248 SQLITE_OPEN_TEMP_DB |
3249 SQLITE_OPEN_TRANSIENT_DB |
3250 SQLITE_OPEN_MAIN_JOURNAL |
3251 SQLITE_OPEN_TEMP_JOURNAL |
3252 SQLITE_OPEN_SUBJOURNAL |
3253 SQLITE_OPEN_SUPER_JOURNAL |
3254 SQLITE_OPEN_NOMUTEX |
3255 SQLITE_OPEN_FULLMUTEX |
3256 SQLITE_OPEN_WAL
3259 /* Allocate the sqlite data structure */
3260 db = sqlite3MallocZero( sizeof(sqlite3) );
3261 if( db==0 ) goto opendb_out;
3262 if( isThreadsafe
3263 #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
3264 || sqlite3GlobalConfig.bCoreMutex
3265 #endif
3267 db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
3268 if( db->mutex==0 ){
3269 sqlite3_free(db);
3270 db = 0;
3271 goto opendb_out;
3273 if( isThreadsafe==0 ){
3274 sqlite3MutexWarnOnContention(db->mutex);
3277 sqlite3_mutex_enter(db->mutex);
3278 db->errMask = (flags & SQLITE_OPEN_EXRESCODE)!=0 ? 0xffffffff : 0xff;
3279 db->nDb = 2;
3280 db->eOpenState = SQLITE_STATE_BUSY;
3281 db->aDb = db->aDbStatic;
3282 db->lookaside.bDisable = 1;
3283 db->lookaside.sz = 0;
3285 assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
3286 memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
3287 db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
3288 db->autoCommit = 1;
3289 db->nextAutovac = -1;
3290 db->szMmap = sqlite3GlobalConfig.szMmap;
3291 db->nextPagesize = 0;
3292 db->init.azInit = sqlite3StdType; /* Any array of string ptrs will do */
3293 #ifdef SQLITE_ENABLE_SORTER_MMAP
3294 /* Beginning with version 3.37.0, using the VFS xFetch() API to memory-map
3295 ** the temporary files used to do external sorts (see code in vdbesort.c)
3296 ** is disabled. It can still be used either by defining
3297 ** SQLITE_ENABLE_SORTER_MMAP at compile time or by using the
3298 ** SQLITE_TESTCTRL_SORTER_MMAP test-control at runtime. */
3299 db->nMaxSorterMmap = 0x7FFFFFFF;
3300 #endif
3301 db->flags |= SQLITE_ShortColNames
3302 | SQLITE_EnableTrigger
3303 | SQLITE_EnableView
3304 | SQLITE_CacheSpill
3305 #if !defined(SQLITE_TRUSTED_SCHEMA) || SQLITE_TRUSTED_SCHEMA+0!=0
3306 | SQLITE_TrustedSchema
3307 #endif
3308 /* The SQLITE_DQS compile-time option determines the default settings
3309 ** for SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML.
3311 ** SQLITE_DQS SQLITE_DBCONFIG_DQS_DDL SQLITE_DBCONFIG_DQS_DML
3312 ** ---------- ----------------------- -----------------------
3313 ** undefined on on
3314 ** 3 on on
3315 ** 2 on off
3316 ** 1 off on
3317 ** 0 off off
3319 ** Legacy behavior is 3 (double-quoted string literals are allowed anywhere)
3320 ** and so that is the default. But developers are encouranged to use
3321 ** -DSQLITE_DQS=0 (best) or -DSQLITE_DQS=1 (second choice) if possible.
3323 #if !defined(SQLITE_DQS)
3324 # define SQLITE_DQS 3
3325 #endif
3326 #if (SQLITE_DQS&1)==1
3327 | SQLITE_DqsDML
3328 #endif
3329 #if (SQLITE_DQS&2)==2
3330 | SQLITE_DqsDDL
3331 #endif
3333 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
3334 | SQLITE_AutoIndex
3335 #endif
3336 #if SQLITE_DEFAULT_CKPTFULLFSYNC
3337 | SQLITE_CkptFullFSync
3338 #endif
3339 #if SQLITE_DEFAULT_FILE_FORMAT<4
3340 | SQLITE_LegacyFileFmt
3341 #endif
3342 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
3343 | SQLITE_LoadExtension
3344 #endif
3345 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
3346 | SQLITE_RecTriggers
3347 #endif
3348 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
3349 | SQLITE_ForeignKeys
3350 #endif
3351 #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
3352 | SQLITE_ReverseOrder
3353 #endif
3354 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
3355 | SQLITE_CellSizeCk
3356 #endif
3357 #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
3358 | SQLITE_Fts3Tokenizer
3359 #endif
3360 #if defined(SQLITE_ENABLE_QPSG)
3361 | SQLITE_EnableQPSG
3362 #endif
3363 #if defined(SQLITE_DEFAULT_DEFENSIVE)
3364 | SQLITE_Defensive
3365 #endif
3366 #if defined(SQLITE_DEFAULT_LEGACY_ALTER_TABLE)
3367 | SQLITE_LegacyAlter
3368 #endif
3369 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
3370 | SQLITE_StmtScanStatus
3371 #endif
3373 sqlite3HashInit(&db->aCollSeq);
3374 #ifndef SQLITE_OMIT_VIRTUALTABLE
3375 sqlite3HashInit(&db->aModule);
3376 #endif
3378 /* Add the default collation sequence BINARY. BINARY works for both UTF-8
3379 ** and UTF-16, so add a version for each to avoid any unnecessary
3380 ** conversions. The only error that can occur here is a malloc() failure.
3382 ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
3383 ** functions:
3385 createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
3386 createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
3387 createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
3388 createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
3389 createCollation(db, "RTRIM", SQLITE_UTF8, 0, rtrimCollFunc, 0);
3390 if( db->mallocFailed ){
3391 goto opendb_out;
3394 #if SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL)
3395 /* Process magic filenames ":localStorage:" and ":sessionStorage:" */
3396 if( zFilename && zFilename[0]==':' ){
3397 if( strcmp(zFilename, ":localStorage:")==0 ){
3398 zFilename = "file:local?vfs=kvvfs";
3399 flags |= SQLITE_OPEN_URI;
3400 }else if( strcmp(zFilename, ":sessionStorage:")==0 ){
3401 zFilename = "file:session?vfs=kvvfs";
3402 flags |= SQLITE_OPEN_URI;
3405 #endif /* SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL) */
3407 /* Parse the filename/URI argument
3409 ** Only allow sensible combinations of bits in the flags argument.
3410 ** Throw an error if any non-sense combination is used. If we
3411 ** do not block illegal combinations here, it could trigger
3412 ** assert() statements in deeper layers. Sensible combinations
3413 ** are:
3415 ** 1: SQLITE_OPEN_READONLY
3416 ** 2: SQLITE_OPEN_READWRITE
3417 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
3419 db->openFlags = flags;
3420 assert( SQLITE_OPEN_READONLY == 0x01 );
3421 assert( SQLITE_OPEN_READWRITE == 0x02 );
3422 assert( SQLITE_OPEN_CREATE == 0x04 );
3423 testcase( (1<<(flags&7))==0x02 ); /* READONLY */
3424 testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
3425 testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
3426 if( ((1<<(flags&7)) & 0x46)==0 ){
3427 rc = SQLITE_MISUSE_BKPT; /* IMP: R-18321-05872 */
3428 }else{
3429 rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
3431 if( rc!=SQLITE_OK ){
3432 if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
3433 sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
3434 sqlite3_free(zErrMsg);
3435 goto opendb_out;
3437 assert( db->pVfs!=0 );
3438 #if SQLITE_OS_KV || defined(SQLITE_OS_KV_OPTIONAL)
3439 if( sqlite3_stricmp(db->pVfs->zName, "kvvfs")==0 ){
3440 db->temp_store = 2;
3442 #endif
3444 /* Open the backend database driver */
3445 rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
3446 flags | SQLITE_OPEN_MAIN_DB);
3447 if( rc!=SQLITE_OK ){
3448 if( rc==SQLITE_IOERR_NOMEM ){
3449 rc = SQLITE_NOMEM_BKPT;
3451 sqlite3Error(db, rc);
3452 goto opendb_out;
3454 sqlite3BtreeEnter(db->aDb[0].pBt);
3455 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
3456 if( !db->mallocFailed ){
3457 sqlite3SetTextEncoding(db, SCHEMA_ENC(db));
3459 sqlite3BtreeLeave(db->aDb[0].pBt);
3460 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
3462 /* The default safety_level for the main database is FULL; for the temp
3463 ** database it is OFF. This matches the pager layer defaults.
3465 db->aDb[0].zDbSName = "main";
3466 db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
3467 db->aDb[1].zDbSName = "temp";
3468 db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
3470 db->eOpenState = SQLITE_STATE_OPEN;
3471 if( db->mallocFailed ){
3472 goto opendb_out;
3475 /* Register all built-in functions, but do not attempt to read the
3476 ** database schema yet. This is delayed until the first time the database
3477 ** is accessed.
3479 sqlite3Error(db, SQLITE_OK);
3480 sqlite3RegisterPerConnectionBuiltinFunctions(db);
3481 rc = sqlite3_errcode(db);
3484 /* Load compiled-in extensions */
3485 for(i=0; rc==SQLITE_OK && i<ArraySize(sqlite3BuiltinExtensions); i++){
3486 rc = sqlite3BuiltinExtensions[i](db);
3489 /* Load automatic extensions - extensions that have been registered
3490 ** using the sqlite3_automatic_extension() API.
3492 if( rc==SQLITE_OK ){
3493 sqlite3AutoLoadExtensions(db);
3494 rc = sqlite3_errcode(db);
3495 if( rc!=SQLITE_OK ){
3496 goto opendb_out;
3500 #ifdef SQLITE_ENABLE_INTERNAL_FUNCTIONS
3501 /* Testing use only!!! The -DSQLITE_ENABLE_INTERNAL_FUNCTIONS=1 compile-time
3502 ** option gives access to internal functions by default.
3503 ** Testing use only!!! */
3504 db->mDbFlags |= DBFLAG_InternalFunc;
3505 #endif
3507 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
3508 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
3509 ** mode. Doing nothing at all also makes NORMAL the default.
3511 #ifdef SQLITE_DEFAULT_LOCKING_MODE
3512 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
3513 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
3514 SQLITE_DEFAULT_LOCKING_MODE);
3515 #endif
3517 if( rc ) sqlite3Error(db, rc);
3519 /* Enable the lookaside-malloc subsystem */
3520 setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
3521 sqlite3GlobalConfig.nLookaside);
3523 sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
3525 opendb_out:
3526 if( db ){
3527 assert( db->mutex!=0 || isThreadsafe==0
3528 || sqlite3GlobalConfig.bFullMutex==0 );
3529 sqlite3_mutex_leave(db->mutex);
3531 rc = sqlite3_errcode(db);
3532 assert( db!=0 || (rc&0xff)==SQLITE_NOMEM );
3533 if( (rc&0xff)==SQLITE_NOMEM ){
3534 sqlite3_close(db);
3535 db = 0;
3536 }else if( rc!=SQLITE_OK ){
3537 db->eOpenState = SQLITE_STATE_SICK;
3539 *ppDb = db;
3540 #ifdef SQLITE_ENABLE_SQLLOG
3541 if( sqlite3GlobalConfig.xSqllog ){
3542 /* Opening a db handle. Fourth parameter is passed 0. */
3543 void *pArg = sqlite3GlobalConfig.pSqllogArg;
3544 sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
3546 #endif
3547 sqlite3_free_filename(zOpen);
3548 return rc;
3553 ** Open a new database handle.
3555 int sqlite3_open(
3556 const char *zFilename,
3557 sqlite3 **ppDb
3559 return openDatabase(zFilename, ppDb,
3560 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
3562 int sqlite3_open_v2(
3563 const char *filename, /* Database filename (UTF-8) */
3564 sqlite3 **ppDb, /* OUT: SQLite db handle */
3565 int flags, /* Flags */
3566 const char *zVfs /* Name of VFS module to use */
3568 return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
3571 #ifndef SQLITE_OMIT_UTF16
3573 ** Open a new database handle.
3575 int sqlite3_open16(
3576 const void *zFilename,
3577 sqlite3 **ppDb
3579 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
3580 sqlite3_value *pVal;
3581 int rc;
3583 #ifdef SQLITE_ENABLE_API_ARMOR
3584 if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
3585 #endif
3586 *ppDb = 0;
3587 #ifndef SQLITE_OMIT_AUTOINIT
3588 rc = sqlite3_initialize();
3589 if( rc ) return rc;
3590 #endif
3591 if( zFilename==0 ) zFilename = "\000\000";
3592 pVal = sqlite3ValueNew(0);
3593 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
3594 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
3595 if( zFilename8 ){
3596 rc = openDatabase(zFilename8, ppDb,
3597 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
3598 assert( *ppDb || rc==SQLITE_NOMEM );
3599 if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
3600 SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
3602 }else{
3603 rc = SQLITE_NOMEM_BKPT;
3605 sqlite3ValueFree(pVal);
3607 return rc & 0xff;
3609 #endif /* SQLITE_OMIT_UTF16 */
3612 ** Register a new collation sequence with the database handle db.
3614 int sqlite3_create_collation(
3615 sqlite3* db,
3616 const char *zName,
3617 int enc,
3618 void* pCtx,
3619 int(*xCompare)(void*,int,const void*,int,const void*)
3621 return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
3625 ** Register a new collation sequence with the database handle db.
3627 int sqlite3_create_collation_v2(
3628 sqlite3* db,
3629 const char *zName,
3630 int enc,
3631 void* pCtx,
3632 int(*xCompare)(void*,int,const void*,int,const void*),
3633 void(*xDel)(void*)
3635 int rc;
3637 #ifdef SQLITE_ENABLE_API_ARMOR
3638 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
3639 #endif
3640 sqlite3_mutex_enter(db->mutex);
3641 assert( !db->mallocFailed );
3642 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
3643 rc = sqlite3ApiExit(db, rc);
3644 sqlite3_mutex_leave(db->mutex);
3645 return rc;
3648 #ifndef SQLITE_OMIT_UTF16
3650 ** Register a new collation sequence with the database handle db.
3652 int sqlite3_create_collation16(
3653 sqlite3* db,
3654 const void *zName,
3655 int enc,
3656 void* pCtx,
3657 int(*xCompare)(void*,int,const void*,int,const void*)
3659 int rc = SQLITE_OK;
3660 char *zName8;
3662 #ifdef SQLITE_ENABLE_API_ARMOR
3663 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
3664 #endif
3665 sqlite3_mutex_enter(db->mutex);
3666 assert( !db->mallocFailed );
3667 zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
3668 if( zName8 ){
3669 rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
3670 sqlite3DbFree(db, zName8);
3672 rc = sqlite3ApiExit(db, rc);
3673 sqlite3_mutex_leave(db->mutex);
3674 return rc;
3676 #endif /* SQLITE_OMIT_UTF16 */
3679 ** Register a collation sequence factory callback with the database handle
3680 ** db. Replace any previously installed collation sequence factory.
3682 int sqlite3_collation_needed(
3683 sqlite3 *db,
3684 void *pCollNeededArg,
3685 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
3687 #ifdef SQLITE_ENABLE_API_ARMOR
3688 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3689 #endif
3690 sqlite3_mutex_enter(db->mutex);
3691 db->xCollNeeded = xCollNeeded;
3692 db->xCollNeeded16 = 0;
3693 db->pCollNeededArg = pCollNeededArg;
3694 sqlite3_mutex_leave(db->mutex);
3695 return SQLITE_OK;
3698 #ifndef SQLITE_OMIT_UTF16
3700 ** Register a collation sequence factory callback with the database handle
3701 ** db. Replace any previously installed collation sequence factory.
3703 int sqlite3_collation_needed16(
3704 sqlite3 *db,
3705 void *pCollNeededArg,
3706 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
3708 #ifdef SQLITE_ENABLE_API_ARMOR
3709 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3710 #endif
3711 sqlite3_mutex_enter(db->mutex);
3712 db->xCollNeeded = 0;
3713 db->xCollNeeded16 = xCollNeeded16;
3714 db->pCollNeededArg = pCollNeededArg;
3715 sqlite3_mutex_leave(db->mutex);
3716 return SQLITE_OK;
3718 #endif /* SQLITE_OMIT_UTF16 */
3720 #ifndef SQLITE_OMIT_DEPRECATED
3722 ** This function is now an anachronism. It used to be used to recover from a
3723 ** malloc() failure, but SQLite now does this automatically.
3725 int sqlite3_global_recover(void){
3726 return SQLITE_OK;
3728 #endif
3731 ** Test to see whether or not the database connection is in autocommit
3732 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
3733 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
3734 ** by the next COMMIT or ROLLBACK.
3736 int sqlite3_get_autocommit(sqlite3 *db){
3737 #ifdef SQLITE_ENABLE_API_ARMOR
3738 if( !sqlite3SafetyCheckOk(db) ){
3739 (void)SQLITE_MISUSE_BKPT;
3740 return 0;
3742 #endif
3743 return db->autoCommit;
3747 ** The following routines are substitutes for constants SQLITE_CORRUPT,
3748 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
3749 ** constants. They serve two purposes:
3751 ** 1. Serve as a convenient place to set a breakpoint in a debugger
3752 ** to detect when version error conditions occurs.
3754 ** 2. Invoke sqlite3_log() to provide the source code location where
3755 ** a low-level error is first detected.
3757 int sqlite3ReportError(int iErr, int lineno, const char *zType){
3758 sqlite3_log(iErr, "%s at line %d of [%.10s]",
3759 zType, lineno, 20+sqlite3_sourceid());
3760 return iErr;
3762 int sqlite3CorruptError(int lineno){
3763 testcase( sqlite3GlobalConfig.xLog!=0 );
3764 return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
3766 int sqlite3MisuseError(int lineno){
3767 testcase( sqlite3GlobalConfig.xLog!=0 );
3768 return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
3770 int sqlite3CantopenError(int lineno){
3771 testcase( sqlite3GlobalConfig.xLog!=0 );
3772 return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
3774 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
3775 int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
3776 char zMsg[100];
3777 sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
3778 testcase( sqlite3GlobalConfig.xLog!=0 );
3779 return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
3781 #endif
3782 #ifdef SQLITE_DEBUG
3783 int sqlite3NomemError(int lineno){
3784 testcase( sqlite3GlobalConfig.xLog!=0 );
3785 return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
3787 int sqlite3IoerrnomemError(int lineno){
3788 testcase( sqlite3GlobalConfig.xLog!=0 );
3789 return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
3791 #endif
3793 #ifndef SQLITE_OMIT_DEPRECATED
3795 ** This is a convenience routine that makes sure that all thread-specific
3796 ** data for this thread has been deallocated.
3798 ** SQLite no longer uses thread-specific data so this routine is now a
3799 ** no-op. It is retained for historical compatibility.
3801 void sqlite3_thread_cleanup(void){
3803 #endif
3806 ** Return meta information about a specific column of a database table.
3807 ** See comment in sqlite3.h (sqlite.h.in) for details.
3809 int sqlite3_table_column_metadata(
3810 sqlite3 *db, /* Connection handle */
3811 const char *zDbName, /* Database name or NULL */
3812 const char *zTableName, /* Table name */
3813 const char *zColumnName, /* Column name */
3814 char const **pzDataType, /* OUTPUT: Declared data type */
3815 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
3816 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
3817 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
3818 int *pAutoinc /* OUTPUT: True if column is auto-increment */
3820 int rc;
3821 char *zErrMsg = 0;
3822 Table *pTab = 0;
3823 Column *pCol = 0;
3824 int iCol = 0;
3825 char const *zDataType = 0;
3826 char const *zCollSeq = 0;
3827 int notnull = 0;
3828 int primarykey = 0;
3829 int autoinc = 0;
3832 #ifdef SQLITE_ENABLE_API_ARMOR
3833 if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
3834 return SQLITE_MISUSE_BKPT;
3836 #endif
3838 /* Ensure the database schema has been loaded */
3839 sqlite3_mutex_enter(db->mutex);
3840 sqlite3BtreeEnterAll(db);
3841 rc = sqlite3Init(db, &zErrMsg);
3842 if( SQLITE_OK!=rc ){
3843 goto error_out;
3846 /* Locate the table in question */
3847 pTab = sqlite3FindTable(db, zTableName, zDbName);
3848 if( !pTab || IsView(pTab) ){
3849 pTab = 0;
3850 goto error_out;
3853 /* Find the column for which info is requested */
3854 if( zColumnName==0 ){
3855 /* Query for existance of table only */
3856 }else{
3857 for(iCol=0; iCol<pTab->nCol; iCol++){
3858 pCol = &pTab->aCol[iCol];
3859 if( 0==sqlite3StrICmp(pCol->zCnName, zColumnName) ){
3860 break;
3863 if( iCol==pTab->nCol ){
3864 if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
3865 iCol = pTab->iPKey;
3866 pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
3867 }else{
3868 pTab = 0;
3869 goto error_out;
3874 /* The following block stores the meta information that will be returned
3875 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
3876 ** and autoinc. At this point there are two possibilities:
3878 ** 1. The specified column name was rowid", "oid" or "_rowid_"
3879 ** and there is no explicitly declared IPK column.
3881 ** 2. The table is not a view and the column name identified an
3882 ** explicitly declared column. Copy meta information from *pCol.
3884 if( pCol ){
3885 zDataType = sqlite3ColumnType(pCol,0);
3886 zCollSeq = sqlite3ColumnColl(pCol);
3887 notnull = pCol->notNull!=0;
3888 primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
3889 autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
3890 }else{
3891 zDataType = "INTEGER";
3892 primarykey = 1;
3894 if( !zCollSeq ){
3895 zCollSeq = sqlite3StrBINARY;
3898 error_out:
3899 sqlite3BtreeLeaveAll(db);
3901 /* Whether the function call succeeded or failed, set the output parameters
3902 ** to whatever their local counterparts contain. If an error did occur,
3903 ** this has the effect of zeroing all output parameters.
3905 if( pzDataType ) *pzDataType = zDataType;
3906 if( pzCollSeq ) *pzCollSeq = zCollSeq;
3907 if( pNotNull ) *pNotNull = notnull;
3908 if( pPrimaryKey ) *pPrimaryKey = primarykey;
3909 if( pAutoinc ) *pAutoinc = autoinc;
3911 if( SQLITE_OK==rc && !pTab ){
3912 sqlite3DbFree(db, zErrMsg);
3913 zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
3914 zColumnName);
3915 rc = SQLITE_ERROR;
3917 sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
3918 sqlite3DbFree(db, zErrMsg);
3919 rc = sqlite3ApiExit(db, rc);
3920 sqlite3_mutex_leave(db->mutex);
3921 return rc;
3925 ** Sleep for a little while. Return the amount of time slept.
3927 int sqlite3_sleep(int ms){
3928 sqlite3_vfs *pVfs;
3929 int rc;
3930 pVfs = sqlite3_vfs_find(0);
3931 if( pVfs==0 ) return 0;
3933 /* This function works in milliseconds, but the underlying OsSleep()
3934 ** API uses microseconds. Hence the 1000's.
3936 rc = (sqlite3OsSleep(pVfs, ms<0 ? 0 : 1000*ms)/1000);
3937 return rc;
3941 ** Enable or disable the extended result codes.
3943 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
3944 #ifdef SQLITE_ENABLE_API_ARMOR
3945 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3946 #endif
3947 sqlite3_mutex_enter(db->mutex);
3948 db->errMask = onoff ? 0xffffffff : 0xff;
3949 sqlite3_mutex_leave(db->mutex);
3950 return SQLITE_OK;
3954 ** Invoke the xFileControl method on a particular database.
3956 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
3957 int rc = SQLITE_ERROR;
3958 Btree *pBtree;
3960 #ifdef SQLITE_ENABLE_API_ARMOR
3961 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3962 #endif
3963 sqlite3_mutex_enter(db->mutex);
3964 pBtree = sqlite3DbNameToBtree(db, zDbName);
3965 if( pBtree ){
3966 Pager *pPager;
3967 sqlite3_file *fd;
3968 sqlite3BtreeEnter(pBtree);
3969 pPager = sqlite3BtreePager(pBtree);
3970 assert( pPager!=0 );
3971 fd = sqlite3PagerFile(pPager);
3972 assert( fd!=0 );
3973 if( op==SQLITE_FCNTL_FILE_POINTER ){
3974 *(sqlite3_file**)pArg = fd;
3975 rc = SQLITE_OK;
3976 }else if( op==SQLITE_FCNTL_VFS_POINTER ){
3977 *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
3978 rc = SQLITE_OK;
3979 }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
3980 *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
3981 rc = SQLITE_OK;
3982 }else if( op==SQLITE_FCNTL_DATA_VERSION ){
3983 *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager);
3984 rc = SQLITE_OK;
3985 }else if( op==SQLITE_FCNTL_RESERVE_BYTES ){
3986 int iNew = *(int*)pArg;
3987 *(int*)pArg = sqlite3BtreeGetRequestedReserve(pBtree);
3988 if( iNew>=0 && iNew<=255 ){
3989 sqlite3BtreeSetPageSize(pBtree, 0, iNew, 0);
3991 rc = SQLITE_OK;
3992 }else if( op==SQLITE_FCNTL_RESET_CACHE ){
3993 sqlite3BtreeClearCache(pBtree);
3994 rc = SQLITE_OK;
3995 }else{
3996 int nSave = db->busyHandler.nBusy;
3997 rc = sqlite3OsFileControl(fd, op, pArg);
3998 db->busyHandler.nBusy = nSave;
4000 sqlite3BtreeLeave(pBtree);
4002 sqlite3_mutex_leave(db->mutex);
4003 return rc;
4007 ** Interface to the testing logic.
4009 int sqlite3_test_control(int op, ...){
4010 int rc = 0;
4011 #ifdef SQLITE_UNTESTABLE
4012 UNUSED_PARAMETER(op);
4013 #else
4014 va_list ap;
4015 va_start(ap, op);
4016 switch( op ){
4019 ** Save the current state of the PRNG.
4021 case SQLITE_TESTCTRL_PRNG_SAVE: {
4022 sqlite3PrngSaveState();
4023 break;
4027 ** Restore the state of the PRNG to the last state saved using
4028 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
4029 ** this verb acts like PRNG_RESET.
4031 case SQLITE_TESTCTRL_PRNG_RESTORE: {
4032 sqlite3PrngRestoreState();
4033 break;
4036 /* sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, int x, sqlite3 *db);
4038 ** Control the seed for the pseudo-random number generator (PRNG) that
4039 ** is built into SQLite. Cases:
4041 ** x!=0 && db!=0 Seed the PRNG to the current value of the
4042 ** schema cookie in the main database for db, or
4043 ** x if the schema cookie is zero. This case
4044 ** is convenient to use with database fuzzers
4045 ** as it allows the fuzzer some control over the
4046 ** the PRNG seed.
4048 ** x!=0 && db==0 Seed the PRNG to the value of x.
4050 ** x==0 && db==0 Revert to default behavior of using the
4051 ** xRandomness method on the primary VFS.
4053 ** This test-control also resets the PRNG so that the new seed will
4054 ** be used for the next call to sqlite3_randomness().
4056 #ifndef SQLITE_OMIT_WSD
4057 case SQLITE_TESTCTRL_PRNG_SEED: {
4058 int x = va_arg(ap, int);
4059 int y;
4060 sqlite3 *db = va_arg(ap, sqlite3*);
4061 assert( db==0 || db->aDb[0].pSchema!=0 );
4062 if( db && (y = db->aDb[0].pSchema->schema_cookie)!=0 ){ x = y; }
4063 sqlite3Config.iPrngSeed = x;
4064 sqlite3_randomness(0,0);
4065 break;
4067 #endif
4070 ** sqlite3_test_control(BITVEC_TEST, size, program)
4072 ** Run a test against a Bitvec object of size. The program argument
4073 ** is an array of integers that defines the test. Return -1 on a
4074 ** memory allocation error, 0 on success, or non-zero for an error.
4075 ** See the sqlite3BitvecBuiltinTest() for additional information.
4077 case SQLITE_TESTCTRL_BITVEC_TEST: {
4078 int sz = va_arg(ap, int);
4079 int *aProg = va_arg(ap, int*);
4080 rc = sqlite3BitvecBuiltinTest(sz, aProg);
4081 break;
4085 ** sqlite3_test_control(FAULT_INSTALL, xCallback)
4087 ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
4088 ** if xCallback is not NULL.
4090 ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
4091 ** is called immediately after installing the new callback and the return
4092 ** value from sqlite3FaultSim(0) becomes the return from
4093 ** sqlite3_test_control().
4095 case SQLITE_TESTCTRL_FAULT_INSTALL: {
4096 /* A bug in MSVC prevents it from understanding pointers to functions
4097 ** types in the second argument to va_arg(). Work around the problem
4098 ** using a typedef.
4099 ** http://support.microsoft.com/kb/47961 <-- dead hyperlink
4100 ** Search at http://web.archive.org/ to find the 2015-03-16 archive
4101 ** of the link above to see the original text.
4102 ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
4104 typedef int(*sqlite3FaultFuncType)(int);
4105 sqlite3GlobalConfig.xTestCallback = va_arg(ap, sqlite3FaultFuncType);
4106 rc = sqlite3FaultSim(0);
4107 break;
4111 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
4113 ** Register hooks to call to indicate which malloc() failures
4114 ** are benign.
4116 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
4117 typedef void (*void_function)(void);
4118 void_function xBenignBegin;
4119 void_function xBenignEnd;
4120 xBenignBegin = va_arg(ap, void_function);
4121 xBenignEnd = va_arg(ap, void_function);
4122 sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
4123 break;
4127 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
4129 ** Set the PENDING byte to the value in the argument, if X>0.
4130 ** Make no changes if X==0. Return the value of the pending byte
4131 ** as it existing before this routine was called.
4133 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
4134 ** an incompatible database file format. Changing the PENDING byte
4135 ** while any database connection is open results in undefined and
4136 ** deleterious behavior.
4138 case SQLITE_TESTCTRL_PENDING_BYTE: {
4139 rc = PENDING_BYTE;
4140 #ifndef SQLITE_OMIT_WSD
4142 unsigned int newVal = va_arg(ap, unsigned int);
4143 if( newVal ) sqlite3PendingByte = newVal;
4145 #endif
4146 break;
4150 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
4152 ** This action provides a run-time test to see whether or not
4153 ** assert() was enabled at compile-time. If X is true and assert()
4154 ** is enabled, then the return value is true. If X is true and
4155 ** assert() is disabled, then the return value is zero. If X is
4156 ** false and assert() is enabled, then the assertion fires and the
4157 ** process aborts. If X is false and assert() is disabled, then the
4158 ** return value is zero.
4160 case SQLITE_TESTCTRL_ASSERT: {
4161 volatile int x = 0;
4162 assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
4163 rc = x;
4164 #if defined(SQLITE_DEBUG)
4165 /* Invoke these debugging routines so that the compiler does not
4166 ** issue "defined but not used" warnings. */
4167 if( x==9999 ){
4168 sqlite3ShowExpr(0);
4169 sqlite3ShowExpr(0);
4170 sqlite3ShowExprList(0);
4171 sqlite3ShowIdList(0);
4172 sqlite3ShowSrcList(0);
4173 sqlite3ShowWith(0);
4174 sqlite3ShowUpsert(0);
4175 sqlite3ShowTriggerStep(0);
4176 sqlite3ShowTriggerStepList(0);
4177 sqlite3ShowTrigger(0);
4178 sqlite3ShowTriggerList(0);
4179 #ifndef SQLITE_OMIT_WINDOWFUNC
4180 sqlite3ShowWindow(0);
4181 sqlite3ShowWinFunc(0);
4182 #endif
4183 sqlite3ShowSelect(0);
4185 #endif
4186 break;
4191 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
4193 ** This action provides a run-time test to see how the ALWAYS and
4194 ** NEVER macros were defined at compile-time.
4196 ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
4198 ** The recommended test is X==2. If the return value is 2, that means
4199 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
4200 ** default setting. If the return value is 1, then ALWAYS() is either
4201 ** hard-coded to true or else it asserts if its argument is false.
4202 ** The first behavior (hard-coded to true) is the case if
4203 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
4204 ** behavior (assert if the argument to ALWAYS() is false) is the case if
4205 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
4207 ** The run-time test procedure might look something like this:
4209 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
4210 ** // ALWAYS() and NEVER() are no-op pass-through macros
4211 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
4212 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
4213 ** }else{
4214 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
4215 ** }
4217 case SQLITE_TESTCTRL_ALWAYS: {
4218 int x = va_arg(ap,int);
4219 rc = x ? ALWAYS(x) : 0;
4220 break;
4224 ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
4226 ** The integer returned reveals the byte-order of the computer on which
4227 ** SQLite is running:
4229 ** 1 big-endian, determined at run-time
4230 ** 10 little-endian, determined at run-time
4231 ** 432101 big-endian, determined at compile-time
4232 ** 123410 little-endian, determined at compile-time
4234 case SQLITE_TESTCTRL_BYTEORDER: {
4235 rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
4236 break;
4239 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
4241 ** Enable or disable various optimizations for testing purposes. The
4242 ** argument N is a bitmask of optimizations to be disabled. For normal
4243 ** operation N should be 0. The idea is that a test program (like the
4244 ** SQL Logic Test or SLT test module) can run the same SQL multiple times
4245 ** with various optimizations disabled to verify that the same answer
4246 ** is obtained in every case.
4248 case SQLITE_TESTCTRL_OPTIMIZATIONS: {
4249 sqlite3 *db = va_arg(ap, sqlite3*);
4250 db->dbOptFlags = va_arg(ap, u32);
4251 break;
4254 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, onoff, xAlt);
4256 ** If parameter onoff is 1, subsequent calls to localtime() fail.
4257 ** If 2, then invoke xAlt() instead of localtime(). If 0, normal
4258 ** processing.
4260 ** xAlt arguments are void pointers, but they really want to be:
4262 ** int xAlt(const time_t*, struct tm*);
4264 ** xAlt should write results in to struct tm object of its 2nd argument
4265 ** and return zero on success, or return non-zero on failure.
4267 case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
4268 sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
4269 if( sqlite3GlobalConfig.bLocaltimeFault==2 ){
4270 typedef int(*sqlite3LocaltimeType)(const void*,void*);
4271 sqlite3GlobalConfig.xAltLocaltime = va_arg(ap, sqlite3LocaltimeType);
4272 }else{
4273 sqlite3GlobalConfig.xAltLocaltime = 0;
4275 break;
4278 /* sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, sqlite3*);
4280 ** Toggle the ability to use internal functions on or off for
4281 ** the database connection given in the argument.
4283 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: {
4284 sqlite3 *db = va_arg(ap, sqlite3*);
4285 db->mDbFlags ^= DBFLAG_InternalFunc;
4286 break;
4289 /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
4291 ** Set or clear a flag that indicates that the database file is always well-
4292 ** formed and never corrupt. This flag is clear by default, indicating that
4293 ** database files might have arbitrary corruption. Setting the flag during
4294 ** testing causes certain assert() statements in the code to be activated
4295 ** that demonstrat invariants on well-formed database files.
4297 case SQLITE_TESTCTRL_NEVER_CORRUPT: {
4298 sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
4299 break;
4302 /* sqlite3_test_control(SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS, int);
4304 ** Set or clear a flag that causes SQLite to verify that type, name,
4305 ** and tbl_name fields of the sqlite_schema table. This is normally
4306 ** on, but it is sometimes useful to turn it off for testing.
4308 ** 2020-07-22: Disabling EXTRA_SCHEMA_CHECKS also disables the
4309 ** verification of rootpage numbers when parsing the schema. This
4310 ** is useful to make it easier to reach strange internal error states
4311 ** during testing. The EXTRA_SCHEMA_CHECKS setting is always enabled
4312 ** in production.
4314 case SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS: {
4315 sqlite3GlobalConfig.bExtraSchemaChecks = va_arg(ap, int);
4316 break;
4319 /* Set the threshold at which OP_Once counters reset back to zero.
4320 ** By default this is 0x7ffffffe (over 2 billion), but that value is
4321 ** too big to test in a reasonable amount of time, so this control is
4322 ** provided to set a small and easily reachable reset value.
4324 case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
4325 sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
4326 break;
4329 /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
4331 ** Set the VDBE coverage callback function to xCallback with context
4332 ** pointer ptr.
4334 case SQLITE_TESTCTRL_VDBE_COVERAGE: {
4335 #ifdef SQLITE_VDBE_COVERAGE
4336 typedef void (*branch_callback)(void*,unsigned int,
4337 unsigned char,unsigned char);
4338 sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
4339 sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
4340 #endif
4341 break;
4344 /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
4345 case SQLITE_TESTCTRL_SORTER_MMAP: {
4346 sqlite3 *db = va_arg(ap, sqlite3*);
4347 db->nMaxSorterMmap = va_arg(ap, int);
4348 break;
4351 /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
4353 ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
4354 ** not.
4356 case SQLITE_TESTCTRL_ISINIT: {
4357 if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
4358 break;
4361 /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
4363 ** This test control is used to create imposter tables. "db" is a pointer
4364 ** to the database connection. dbName is the database name (ex: "main" or
4365 ** "temp") which will receive the imposter. "onOff" turns imposter mode on
4366 ** or off. "tnum" is the root page of the b-tree to which the imposter
4367 ** table should connect.
4369 ** Enable imposter mode only when the schema has already been parsed. Then
4370 ** run a single CREATE TABLE statement to construct the imposter table in
4371 ** the parsed schema. Then turn imposter mode back off again.
4373 ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
4374 ** the schema to be reparsed the next time it is needed. This has the
4375 ** effect of erasing all imposter tables.
4377 case SQLITE_TESTCTRL_IMPOSTER: {
4378 sqlite3 *db = va_arg(ap, sqlite3*);
4379 int iDb;
4380 sqlite3_mutex_enter(db->mutex);
4381 iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
4382 if( iDb>=0 ){
4383 db->init.iDb = iDb;
4384 db->init.busy = db->init.imposterTable = va_arg(ap,int);
4385 db->init.newTnum = va_arg(ap,int);
4386 if( db->init.busy==0 && db->init.newTnum>0 ){
4387 sqlite3ResetAllSchemasOfConnection(db);
4390 sqlite3_mutex_leave(db->mutex);
4391 break;
4394 #if defined(YYCOVERAGE)
4395 /* sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
4397 ** This test control (only available when SQLite is compiled with
4398 ** -DYYCOVERAGE) writes a report onto "out" that shows all
4399 ** state/lookahead combinations in the parser state machine
4400 ** which are never exercised. If any state is missed, make the
4401 ** return code SQLITE_ERROR.
4403 case SQLITE_TESTCTRL_PARSER_COVERAGE: {
4404 FILE *out = va_arg(ap, FILE*);
4405 if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
4406 break;
4408 #endif /* defined(YYCOVERAGE) */
4410 /* sqlite3_test_control(SQLITE_TESTCTRL_RESULT_INTREAL, sqlite3_context*);
4412 ** This test-control causes the most recent sqlite3_result_int64() value
4413 ** to be interpreted as a MEM_IntReal instead of as an MEM_Int. Normally,
4414 ** MEM_IntReal values only arise during an INSERT operation of integer
4415 ** values into a REAL column, so they can be challenging to test. This
4416 ** test-control enables us to write an intreal() SQL function that can
4417 ** inject an intreal() value at arbitrary places in an SQL statement,
4418 ** for testing purposes.
4420 case SQLITE_TESTCTRL_RESULT_INTREAL: {
4421 sqlite3_context *pCtx = va_arg(ap, sqlite3_context*);
4422 sqlite3ResultIntReal(pCtx);
4423 break;
4426 /* sqlite3_test_control(SQLITE_TESTCTRL_SEEK_COUNT,
4427 ** sqlite3 *db, // Database connection
4428 ** u64 *pnSeek // Write seek count here
4429 ** );
4431 ** This test-control queries the seek-counter on the "main" database
4432 ** file. The seek-counter is written into *pnSeek and is then reset.
4433 ** The seek-count is only available if compiled with SQLITE_DEBUG.
4435 case SQLITE_TESTCTRL_SEEK_COUNT: {
4436 sqlite3 *db = va_arg(ap, sqlite3*);
4437 u64 *pn = va_arg(ap, sqlite3_uint64*);
4438 *pn = sqlite3BtreeSeekCount(db->aDb->pBt);
4439 (void)db; /* Silence harmless unused variable warning */
4440 break;
4443 /* sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, op, ptr)
4445 ** "ptr" is a pointer to a u32.
4447 ** op==0 Store the current sqlite3TreeTrace in *ptr
4448 ** op==1 Set sqlite3TreeTrace to the value *ptr
4449 ** op==3 Store the current sqlite3WhereTrace in *ptr
4450 ** op==3 Set sqlite3WhereTrace to the value *ptr
4452 case SQLITE_TESTCTRL_TRACEFLAGS: {
4453 int opTrace = va_arg(ap, int);
4454 u32 *ptr = va_arg(ap, u32*);
4455 switch( opTrace ){
4456 case 0: *ptr = sqlite3TreeTrace; break;
4457 case 1: sqlite3TreeTrace = *ptr; break;
4458 case 2: *ptr = sqlite3WhereTrace; break;
4459 case 3: sqlite3WhereTrace = *ptr; break;
4461 break;
4464 /* sqlite3_test_control(SQLITE_TESTCTRL_LOGEST,
4465 ** double fIn, // Input value
4466 ** int *pLogEst, // sqlite3LogEstFromDouble(fIn)
4467 ** u64 *pInt, // sqlite3LogEstToInt(*pLogEst)
4468 ** int *pLogEst2 // sqlite3LogEst(*pInt)
4469 ** );
4471 ** Test access for the LogEst conversion routines.
4473 case SQLITE_TESTCTRL_LOGEST: {
4474 double rIn = va_arg(ap, double);
4475 LogEst rLogEst = sqlite3LogEstFromDouble(rIn);
4476 int *pI1 = va_arg(ap,int*);
4477 u64 *pU64 = va_arg(ap,u64*);
4478 int *pI2 = va_arg(ap,int*);
4479 *pI1 = rLogEst;
4480 *pU64 = sqlite3LogEstToInt(rLogEst);
4481 *pI2 = sqlite3LogEst(*pU64);
4482 break;
4486 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
4487 /* sqlite3_test_control(SQLITE_TESTCTRL_TUNE, id, *piValue)
4489 ** If "id" is an integer between 1 and SQLITE_NTUNE then set the value
4490 ** of the id-th tuning parameter to *piValue. If "id" is between -1
4491 ** and -SQLITE_NTUNE, then write the current value of the (-id)-th
4492 ** tuning parameter into *piValue.
4494 ** Tuning parameters are for use during transient development builds,
4495 ** to help find the best values for constants in the query planner.
4496 ** Access tuning parameters using the Tuning(ID) macro. Set the
4497 ** parameters in the CLI using ".testctrl tune ID VALUE".
4499 ** Transient use only. Tuning parameters should not be used in
4500 ** checked-in code.
4502 case SQLITE_TESTCTRL_TUNE: {
4503 int id = va_arg(ap, int);
4504 int *piValue = va_arg(ap, int*);
4505 if( id>0 && id<=SQLITE_NTUNE ){
4506 Tuning(id) = *piValue;
4507 }else if( id<0 && id>=-SQLITE_NTUNE ){
4508 *piValue = Tuning(-id);
4509 }else{
4510 rc = SQLITE_NOTFOUND;
4512 break;
4514 #endif
4516 va_end(ap);
4517 #endif /* SQLITE_UNTESTABLE */
4518 return rc;
4522 ** The Pager stores the Database filename, Journal filename, and WAL filename
4523 ** consecutively in memory, in that order. The database filename is prefixed
4524 ** by four zero bytes. Locate the start of the database filename by searching
4525 ** backwards for the first byte following four consecutive zero bytes.
4527 ** This only works if the filename passed in was obtained from the Pager.
4529 static const char *databaseName(const char *zName){
4530 while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
4531 zName--;
4533 return zName;
4537 ** Append text z[] to the end of p[]. Return a pointer to the first
4538 ** character after then zero terminator on the new text in p[].
4540 static char *appendText(char *p, const char *z){
4541 size_t n = strlen(z);
4542 memcpy(p, z, n+1);
4543 return p+n+1;
4547 ** Allocate memory to hold names for a database, journal file, WAL file,
4548 ** and query parameters. The pointer returned is valid for use by
4549 ** sqlite3_filename_database() and sqlite3_uri_parameter() and related
4550 ** functions.
4552 ** Memory layout must be compatible with that generated by the pager
4553 ** and expected by sqlite3_uri_parameter() and databaseName().
4555 const char *sqlite3_create_filename(
4556 const char *zDatabase,
4557 const char *zJournal,
4558 const char *zWal,
4559 int nParam,
4560 const char **azParam
4562 sqlite3_int64 nByte;
4563 int i;
4564 char *pResult, *p;
4565 nByte = strlen(zDatabase) + strlen(zJournal) + strlen(zWal) + 10;
4566 for(i=0; i<nParam*2; i++){
4567 nByte += strlen(azParam[i])+1;
4569 pResult = p = sqlite3_malloc64( nByte );
4570 if( p==0 ) return 0;
4571 memset(p, 0, 4);
4572 p += 4;
4573 p = appendText(p, zDatabase);
4574 for(i=0; i<nParam*2; i++){
4575 p = appendText(p, azParam[i]);
4577 *(p++) = 0;
4578 p = appendText(p, zJournal);
4579 p = appendText(p, zWal);
4580 *(p++) = 0;
4581 *(p++) = 0;
4582 assert( (sqlite3_int64)(p - pResult)==nByte );
4583 return pResult + 4;
4587 ** Free memory obtained from sqlite3_create_filename(). It is a severe
4588 ** error to call this routine with any parameter other than a pointer
4589 ** previously obtained from sqlite3_create_filename() or a NULL pointer.
4591 void sqlite3_free_filename(const char *p){
4592 if( p==0 ) return;
4593 p = databaseName(p);
4594 sqlite3_free((char*)p - 4);
4599 ** This is a utility routine, useful to VFS implementations, that checks
4600 ** to see if a database file was a URI that contained a specific query
4601 ** parameter, and if so obtains the value of the query parameter.
4603 ** The zFilename argument is the filename pointer passed into the xOpen()
4604 ** method of a VFS implementation. The zParam argument is the name of the
4605 ** query parameter we seek. This routine returns the value of the zParam
4606 ** parameter if it exists. If the parameter does not exist, this routine
4607 ** returns a NULL pointer.
4609 const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
4610 if( zFilename==0 || zParam==0 ) return 0;
4611 zFilename = databaseName(zFilename);
4612 return uriParameter(zFilename, zParam);
4616 ** Return a pointer to the name of Nth query parameter of the filename.
4618 const char *sqlite3_uri_key(const char *zFilename, int N){
4619 if( zFilename==0 || N<0 ) return 0;
4620 zFilename = databaseName(zFilename);
4621 zFilename += sqlite3Strlen30(zFilename) + 1;
4622 while( ALWAYS(zFilename) && zFilename[0] && (N--)>0 ){
4623 zFilename += sqlite3Strlen30(zFilename) + 1;
4624 zFilename += sqlite3Strlen30(zFilename) + 1;
4626 return zFilename[0] ? zFilename : 0;
4630 ** Return a boolean value for a query parameter.
4632 int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
4633 const char *z = sqlite3_uri_parameter(zFilename, zParam);
4634 bDflt = bDflt!=0;
4635 return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
4639 ** Return a 64-bit integer value for a query parameter.
4641 sqlite3_int64 sqlite3_uri_int64(
4642 const char *zFilename, /* Filename as passed to xOpen */
4643 const char *zParam, /* URI parameter sought */
4644 sqlite3_int64 bDflt /* return if parameter is missing */
4646 const char *z = sqlite3_uri_parameter(zFilename, zParam);
4647 sqlite3_int64 v;
4648 if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
4649 bDflt = v;
4651 return bDflt;
4655 ** Translate a filename that was handed to a VFS routine into the corresponding
4656 ** database, journal, or WAL file.
4658 ** It is an error to pass this routine a filename string that was not
4659 ** passed into the VFS from the SQLite core. Doing so is similar to
4660 ** passing free() a pointer that was not obtained from malloc() - it is
4661 ** an error that we cannot easily detect but that will likely cause memory
4662 ** corruption.
4664 const char *sqlite3_filename_database(const char *zFilename){
4665 if( zFilename==0 ) return 0;
4666 return databaseName(zFilename);
4668 const char *sqlite3_filename_journal(const char *zFilename){
4669 if( zFilename==0 ) return 0;
4670 zFilename = databaseName(zFilename);
4671 zFilename += sqlite3Strlen30(zFilename) + 1;
4672 while( ALWAYS(zFilename) && zFilename[0] ){
4673 zFilename += sqlite3Strlen30(zFilename) + 1;
4674 zFilename += sqlite3Strlen30(zFilename) + 1;
4676 return zFilename + 1;
4678 const char *sqlite3_filename_wal(const char *zFilename){
4679 #ifdef SQLITE_OMIT_WAL
4680 return 0;
4681 #else
4682 zFilename = sqlite3_filename_journal(zFilename);
4683 if( zFilename ) zFilename += sqlite3Strlen30(zFilename) + 1;
4684 return zFilename;
4685 #endif
4689 ** Return the Btree pointer identified by zDbName. Return NULL if not found.
4691 Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
4692 int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
4693 return iDb<0 ? 0 : db->aDb[iDb].pBt;
4697 ** Return the name of the N-th database schema. Return NULL if N is out
4698 ** of range.
4700 const char *sqlite3_db_name(sqlite3 *db, int N){
4701 #ifdef SQLITE_ENABLE_API_ARMOR
4702 if( !sqlite3SafetyCheckOk(db) ){
4703 (void)SQLITE_MISUSE_BKPT;
4704 return 0;
4706 #endif
4707 if( N<0 || N>=db->nDb ){
4708 return 0;
4709 }else{
4710 return db->aDb[N].zDbSName;
4715 ** Return the filename of the database associated with a database
4716 ** connection.
4718 const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
4719 Btree *pBt;
4720 #ifdef SQLITE_ENABLE_API_ARMOR
4721 if( !sqlite3SafetyCheckOk(db) ){
4722 (void)SQLITE_MISUSE_BKPT;
4723 return 0;
4725 #endif
4726 pBt = sqlite3DbNameToBtree(db, zDbName);
4727 return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
4731 ** Return 1 if database is read-only or 0 if read/write. Return -1 if
4732 ** no such database exists.
4734 int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
4735 Btree *pBt;
4736 #ifdef SQLITE_ENABLE_API_ARMOR
4737 if( !sqlite3SafetyCheckOk(db) ){
4738 (void)SQLITE_MISUSE_BKPT;
4739 return -1;
4741 #endif
4742 pBt = sqlite3DbNameToBtree(db, zDbName);
4743 return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
4746 #ifdef SQLITE_ENABLE_SNAPSHOT
4748 ** Obtain a snapshot handle for the snapshot of database zDb currently
4749 ** being read by handle db.
4751 int sqlite3_snapshot_get(
4752 sqlite3 *db,
4753 const char *zDb,
4754 sqlite3_snapshot **ppSnapshot
4756 int rc = SQLITE_ERROR;
4757 #ifndef SQLITE_OMIT_WAL
4759 #ifdef SQLITE_ENABLE_API_ARMOR
4760 if( !sqlite3SafetyCheckOk(db) ){
4761 return SQLITE_MISUSE_BKPT;
4763 #endif
4764 sqlite3_mutex_enter(db->mutex);
4766 if( db->autoCommit==0 ){
4767 int iDb = sqlite3FindDbName(db, zDb);
4768 if( iDb==0 || iDb>1 ){
4769 Btree *pBt = db->aDb[iDb].pBt;
4770 if( SQLITE_TXN_WRITE!=sqlite3BtreeTxnState(pBt) ){
4771 rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
4772 if( rc==SQLITE_OK ){
4773 rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
4779 sqlite3_mutex_leave(db->mutex);
4780 #endif /* SQLITE_OMIT_WAL */
4781 return rc;
4785 ** Open a read-transaction on the snapshot idendified by pSnapshot.
4787 int sqlite3_snapshot_open(
4788 sqlite3 *db,
4789 const char *zDb,
4790 sqlite3_snapshot *pSnapshot
4792 int rc = SQLITE_ERROR;
4793 #ifndef SQLITE_OMIT_WAL
4795 #ifdef SQLITE_ENABLE_API_ARMOR
4796 if( !sqlite3SafetyCheckOk(db) ){
4797 return SQLITE_MISUSE_BKPT;
4799 #endif
4800 sqlite3_mutex_enter(db->mutex);
4801 if( db->autoCommit==0 ){
4802 int iDb;
4803 iDb = sqlite3FindDbName(db, zDb);
4804 if( iDb==0 || iDb>1 ){
4805 Btree *pBt = db->aDb[iDb].pBt;
4806 if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE ){
4807 Pager *pPager = sqlite3BtreePager(pBt);
4808 int bUnlock = 0;
4809 if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_NONE ){
4810 if( db->nVdbeActive==0 ){
4811 rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot);
4812 if( rc==SQLITE_OK ){
4813 bUnlock = 1;
4814 rc = sqlite3BtreeCommit(pBt);
4817 }else{
4818 rc = SQLITE_OK;
4820 if( rc==SQLITE_OK ){
4821 rc = sqlite3PagerSnapshotOpen(pPager, pSnapshot);
4823 if( rc==SQLITE_OK ){
4824 rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
4825 sqlite3PagerSnapshotOpen(pPager, 0);
4827 if( bUnlock ){
4828 sqlite3PagerSnapshotUnlock(pPager);
4834 sqlite3_mutex_leave(db->mutex);
4835 #endif /* SQLITE_OMIT_WAL */
4836 return rc;
4840 ** Recover as many snapshots as possible from the wal file associated with
4841 ** schema zDb of database db.
4843 int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
4844 int rc = SQLITE_ERROR;
4845 #ifndef SQLITE_OMIT_WAL
4846 int iDb;
4848 #ifdef SQLITE_ENABLE_API_ARMOR
4849 if( !sqlite3SafetyCheckOk(db) ){
4850 return SQLITE_MISUSE_BKPT;
4852 #endif
4854 sqlite3_mutex_enter(db->mutex);
4855 iDb = sqlite3FindDbName(db, zDb);
4856 if( iDb==0 || iDb>1 ){
4857 Btree *pBt = db->aDb[iDb].pBt;
4858 if( SQLITE_TXN_NONE==sqlite3BtreeTxnState(pBt) ){
4859 rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
4860 if( rc==SQLITE_OK ){
4861 rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
4862 sqlite3BtreeCommit(pBt);
4866 sqlite3_mutex_leave(db->mutex);
4867 #endif /* SQLITE_OMIT_WAL */
4868 return rc;
4872 ** Free a snapshot handle obtained from sqlite3_snapshot_get().
4874 void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
4875 sqlite3_free(pSnapshot);
4877 #endif /* SQLITE_ENABLE_SNAPSHOT */
4879 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
4881 ** Given the name of a compile-time option, return true if that option
4882 ** was used and false if not.
4884 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
4885 ** is not required for a match.
4887 int sqlite3_compileoption_used(const char *zOptName){
4888 int i, n;
4889 int nOpt;
4890 const char **azCompileOpt;
4892 #if SQLITE_ENABLE_API_ARMOR
4893 if( zOptName==0 ){
4894 (void)SQLITE_MISUSE_BKPT;
4895 return 0;
4897 #endif
4899 azCompileOpt = sqlite3CompileOptions(&nOpt);
4901 if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
4902 n = sqlite3Strlen30(zOptName);
4904 /* Since nOpt is normally in single digits, a linear search is
4905 ** adequate. No need for a binary search. */
4906 for(i=0; i<nOpt; i++){
4907 if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
4908 && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
4910 return 1;
4913 return 0;
4917 ** Return the N-th compile-time option string. If N is out of range,
4918 ** return a NULL pointer.
4920 const char *sqlite3_compileoption_get(int N){
4921 int nOpt;
4922 const char **azCompileOpt;
4923 azCompileOpt = sqlite3CompileOptions(&nOpt);
4924 if( N>=0 && N<nOpt ){
4925 return azCompileOpt[N];
4927 return 0;
4929 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */