Merge sqlite-release(3.42.0) into prerelease-integration
[sqlcipher.git] / src / main.c
blob0c589881845633b071a5d213a72f050172c82f9d
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;
3191 /* BEGIN SQLCIPHER */
3192 #if defined(SQLITE_HAS_CODEC)
3194 ** Process URI filename query parameters relevant to the SQLite Encryption
3195 ** Extension. Return true if any of the relevant query parameters are
3196 ** seen and return false if not.
3198 int sqlite3CodecQueryParameters(
3199 sqlite3 *db, /* Database connection */
3200 const char *zDb, /* Which schema is being created/attached */
3201 const char *zUri /* URI filename */
3203 const char *zKey;
3204 if( zUri==0 ){
3205 return 0;
3206 }else if( (zKey = uriParameter(zUri, "hexkey"))!=0 && zKey[0] ){
3207 u8 iByte;
3208 int i;
3209 char zDecoded[40];
3210 for(i=0, iByte=0; i<sizeof(zDecoded)*2 && sqlite3Isxdigit(zKey[i]); i++){
3211 iByte = (iByte<<4) + sqlite3HexToInt(zKey[i]);
3212 if( (i&1)!=0 ) zDecoded[i/2] = iByte;
3214 sqlite3_key_v2(db, zDb, zDecoded, i/2);
3215 return 1;
3216 }else if( (zKey = uriParameter(zUri, "key"))!=0 ){
3217 sqlite3_key_v2(db, zDb, zKey, sqlite3Strlen30(zKey));
3218 return 1;
3219 }else if( (zKey = uriParameter(zUri, "textkey"))!=0 ){
3220 sqlite3_key_v2(db, zDb, zKey, -1);
3221 return 1;
3222 }else{
3223 return 0;
3226 #endif
3227 /* END SQLCIPHER */
3231 ** This routine does the work of opening a database on behalf of
3232 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
3233 ** is UTF-8 encoded.
3235 static int openDatabase(
3236 const char *zFilename, /* Database filename UTF-8 encoded */
3237 sqlite3 **ppDb, /* OUT: Returned database handle */
3238 unsigned int flags, /* Operational flags */
3239 const char *zVfs /* Name of the VFS to use */
3241 sqlite3 *db; /* Store allocated handle here */
3242 int rc; /* Return code */
3243 int isThreadsafe; /* True for threadsafe connections */
3244 char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
3245 char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
3246 int i; /* Loop counter */
3248 #ifdef SQLITE_ENABLE_API_ARMOR
3249 if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
3250 #endif
3251 *ppDb = 0;
3252 #ifndef SQLITE_OMIT_AUTOINIT
3253 rc = sqlite3_initialize();
3254 if( rc ) return rc;
3255 #endif
3257 if( sqlite3GlobalConfig.bCoreMutex==0 ){
3258 isThreadsafe = 0;
3259 }else if( flags & SQLITE_OPEN_NOMUTEX ){
3260 isThreadsafe = 0;
3261 }else if( flags & SQLITE_OPEN_FULLMUTEX ){
3262 isThreadsafe = 1;
3263 }else{
3264 isThreadsafe = sqlite3GlobalConfig.bFullMutex;
3267 if( flags & SQLITE_OPEN_PRIVATECACHE ){
3268 flags &= ~SQLITE_OPEN_SHAREDCACHE;
3269 }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
3270 flags |= SQLITE_OPEN_SHAREDCACHE;
3273 /* Remove harmful bits from the flags parameter
3275 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
3276 ** dealt with in the previous code block. Besides these, the only
3277 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
3278 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
3279 ** SQLITE_OPEN_PRIVATECACHE, SQLITE_OPEN_EXRESCODE, and some reserved
3280 ** bits. Silently mask off all other flags.
3282 flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
3283 SQLITE_OPEN_EXCLUSIVE |
3284 SQLITE_OPEN_MAIN_DB |
3285 SQLITE_OPEN_TEMP_DB |
3286 SQLITE_OPEN_TRANSIENT_DB |
3287 SQLITE_OPEN_MAIN_JOURNAL |
3288 SQLITE_OPEN_TEMP_JOURNAL |
3289 SQLITE_OPEN_SUBJOURNAL |
3290 SQLITE_OPEN_SUPER_JOURNAL |
3291 SQLITE_OPEN_NOMUTEX |
3292 SQLITE_OPEN_FULLMUTEX |
3293 SQLITE_OPEN_WAL
3296 /* Allocate the sqlite data structure */
3297 db = sqlite3MallocZero( sizeof(sqlite3) );
3298 if( db==0 ) goto opendb_out;
3299 if( isThreadsafe
3300 #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
3301 || sqlite3GlobalConfig.bCoreMutex
3302 #endif
3304 db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
3305 if( db->mutex==0 ){
3306 sqlite3_free(db);
3307 db = 0;
3308 goto opendb_out;
3310 if( isThreadsafe==0 ){
3311 sqlite3MutexWarnOnContention(db->mutex);
3314 sqlite3_mutex_enter(db->mutex);
3315 db->errMask = (flags & SQLITE_OPEN_EXRESCODE)!=0 ? 0xffffffff : 0xff;
3316 db->nDb = 2;
3317 db->eOpenState = SQLITE_STATE_BUSY;
3318 db->aDb = db->aDbStatic;
3319 db->lookaside.bDisable = 1;
3320 db->lookaside.sz = 0;
3322 assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
3323 memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
3324 db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
3325 db->autoCommit = 1;
3326 db->nextAutovac = -1;
3327 db->szMmap = sqlite3GlobalConfig.szMmap;
3328 db->nextPagesize = 0;
3329 db->init.azInit = sqlite3StdType; /* Any array of string ptrs will do */
3330 #ifdef SQLITE_ENABLE_SORTER_MMAP
3331 /* Beginning with version 3.37.0, using the VFS xFetch() API to memory-map
3332 ** the temporary files used to do external sorts (see code in vdbesort.c)
3333 ** is disabled. It can still be used either by defining
3334 ** SQLITE_ENABLE_SORTER_MMAP at compile time or by using the
3335 ** SQLITE_TESTCTRL_SORTER_MMAP test-control at runtime. */
3336 db->nMaxSorterMmap = 0x7FFFFFFF;
3337 #endif
3338 db->flags |= SQLITE_ShortColNames
3339 | SQLITE_EnableTrigger
3340 | SQLITE_EnableView
3341 | SQLITE_CacheSpill
3342 #if !defined(SQLITE_TRUSTED_SCHEMA) || SQLITE_TRUSTED_SCHEMA+0!=0
3343 | SQLITE_TrustedSchema
3344 #endif
3345 /* The SQLITE_DQS compile-time option determines the default settings
3346 ** for SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML.
3348 ** SQLITE_DQS SQLITE_DBCONFIG_DQS_DDL SQLITE_DBCONFIG_DQS_DML
3349 ** ---------- ----------------------- -----------------------
3350 ** undefined on on
3351 ** 3 on on
3352 ** 2 on off
3353 ** 1 off on
3354 ** 0 off off
3356 ** Legacy behavior is 3 (double-quoted string literals are allowed anywhere)
3357 ** and so that is the default. But developers are encouranged to use
3358 ** -DSQLITE_DQS=0 (best) or -DSQLITE_DQS=1 (second choice) if possible.
3360 #if !defined(SQLITE_DQS)
3361 # define SQLITE_DQS 3
3362 #endif
3363 #if (SQLITE_DQS&1)==1
3364 | SQLITE_DqsDML
3365 #endif
3366 #if (SQLITE_DQS&2)==2
3367 | SQLITE_DqsDDL
3368 #endif
3370 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
3371 | SQLITE_AutoIndex
3372 #endif
3373 #if SQLITE_DEFAULT_CKPTFULLFSYNC
3374 | SQLITE_CkptFullFSync
3375 #endif
3376 #if SQLITE_DEFAULT_FILE_FORMAT<4
3377 | SQLITE_LegacyFileFmt
3378 #endif
3379 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
3380 | SQLITE_LoadExtension
3381 #endif
3382 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
3383 | SQLITE_RecTriggers
3384 #endif
3385 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
3386 | SQLITE_ForeignKeys
3387 #endif
3388 #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
3389 | SQLITE_ReverseOrder
3390 #endif
3391 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
3392 | SQLITE_CellSizeCk
3393 #endif
3394 #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
3395 | SQLITE_Fts3Tokenizer
3396 #endif
3397 #if defined(SQLITE_ENABLE_QPSG)
3398 | SQLITE_EnableQPSG
3399 #endif
3400 #if defined(SQLITE_DEFAULT_DEFENSIVE)
3401 | SQLITE_Defensive
3402 #endif
3403 #if defined(SQLITE_DEFAULT_LEGACY_ALTER_TABLE)
3404 | SQLITE_LegacyAlter
3405 #endif
3406 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
3407 | SQLITE_StmtScanStatus
3408 #endif
3410 sqlite3HashInit(&db->aCollSeq);
3411 #ifndef SQLITE_OMIT_VIRTUALTABLE
3412 sqlite3HashInit(&db->aModule);
3413 #endif
3415 /* Add the default collation sequence BINARY. BINARY works for both UTF-8
3416 ** and UTF-16, so add a version for each to avoid any unnecessary
3417 ** conversions. The only error that can occur here is a malloc() failure.
3419 ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
3420 ** functions:
3422 createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
3423 createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
3424 createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
3425 createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
3426 createCollation(db, "RTRIM", SQLITE_UTF8, 0, rtrimCollFunc, 0);
3427 if( db->mallocFailed ){
3428 goto opendb_out;
3431 #if SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL)
3432 /* Process magic filenames ":localStorage:" and ":sessionStorage:" */
3433 if( zFilename && zFilename[0]==':' ){
3434 if( strcmp(zFilename, ":localStorage:")==0 ){
3435 zFilename = "file:local?vfs=kvvfs";
3436 flags |= SQLITE_OPEN_URI;
3437 }else if( strcmp(zFilename, ":sessionStorage:")==0 ){
3438 zFilename = "file:session?vfs=kvvfs";
3439 flags |= SQLITE_OPEN_URI;
3442 #endif /* SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL) */
3444 /* Parse the filename/URI argument
3446 ** Only allow sensible combinations of bits in the flags argument.
3447 ** Throw an error if any non-sense combination is used. If we
3448 ** do not block illegal combinations here, it could trigger
3449 ** assert() statements in deeper layers. Sensible combinations
3450 ** are:
3452 ** 1: SQLITE_OPEN_READONLY
3453 ** 2: SQLITE_OPEN_READWRITE
3454 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
3456 db->openFlags = flags;
3457 assert( SQLITE_OPEN_READONLY == 0x01 );
3458 assert( SQLITE_OPEN_READWRITE == 0x02 );
3459 assert( SQLITE_OPEN_CREATE == 0x04 );
3460 testcase( (1<<(flags&7))==0x02 ); /* READONLY */
3461 testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
3462 testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
3463 if( ((1<<(flags&7)) & 0x46)==0 ){
3464 rc = SQLITE_MISUSE_BKPT; /* IMP: R-18321-05872 */
3465 }else{
3466 rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
3468 if( rc!=SQLITE_OK ){
3469 if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
3470 sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
3471 sqlite3_free(zErrMsg);
3472 goto opendb_out;
3474 assert( db->pVfs!=0 );
3475 #if SQLITE_OS_KV || defined(SQLITE_OS_KV_OPTIONAL)
3476 if( sqlite3_stricmp(db->pVfs->zName, "kvvfs")==0 ){
3477 db->temp_store = 2;
3479 #endif
3481 /* Open the backend database driver */
3482 rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
3483 flags | SQLITE_OPEN_MAIN_DB);
3484 if( rc!=SQLITE_OK ){
3485 if( rc==SQLITE_IOERR_NOMEM ){
3486 rc = SQLITE_NOMEM_BKPT;
3488 sqlite3Error(db, rc);
3489 goto opendb_out;
3491 sqlite3BtreeEnter(db->aDb[0].pBt);
3492 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
3493 if( !db->mallocFailed ){
3494 sqlite3SetTextEncoding(db, SCHEMA_ENC(db));
3496 sqlite3BtreeLeave(db->aDb[0].pBt);
3497 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
3499 /* The default safety_level for the main database is FULL; for the temp
3500 ** database it is OFF. This matches the pager layer defaults.
3502 db->aDb[0].zDbSName = "main";
3503 db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
3504 db->aDb[1].zDbSName = "temp";
3505 db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
3507 db->eOpenState = SQLITE_STATE_OPEN;
3508 if( db->mallocFailed ){
3509 goto opendb_out;
3512 /* Register all built-in functions, but do not attempt to read the
3513 ** database schema yet. This is delayed until the first time the database
3514 ** is accessed.
3516 sqlite3Error(db, SQLITE_OK);
3517 sqlite3RegisterPerConnectionBuiltinFunctions(db);
3518 rc = sqlite3_errcode(db);
3521 /* Load compiled-in extensions */
3522 for(i=0; rc==SQLITE_OK && i<ArraySize(sqlite3BuiltinExtensions); i++){
3523 rc = sqlite3BuiltinExtensions[i](db);
3526 /* Load automatic extensions - extensions that have been registered
3527 ** using the sqlite3_automatic_extension() API.
3529 if( rc==SQLITE_OK ){
3530 sqlite3AutoLoadExtensions(db);
3531 rc = sqlite3_errcode(db);
3532 if( rc!=SQLITE_OK ){
3533 goto opendb_out;
3537 #ifdef SQLCIPHER_EXT
3538 if( !db->mallocFailed && rc==SQLITE_OK ){
3539 extern int sqlcipherVtabInit(sqlite3 *);
3540 rc = sqlcipherVtabInit(db);
3542 #endif
3544 #ifdef SQLITE_ENABLE_INTERNAL_FUNCTIONS
3545 /* Testing use only!!! The -DSQLITE_ENABLE_INTERNAL_FUNCTIONS=1 compile-time
3546 ** option gives access to internal functions by default.
3547 ** Testing use only!!! */
3548 db->mDbFlags |= DBFLAG_InternalFunc;
3549 #endif
3551 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
3552 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
3553 ** mode. Doing nothing at all also makes NORMAL the default.
3555 #ifdef SQLITE_DEFAULT_LOCKING_MODE
3556 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
3557 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
3558 SQLITE_DEFAULT_LOCKING_MODE);
3559 #endif
3561 if( rc ) sqlite3Error(db, rc);
3563 /* Enable the lookaside-malloc subsystem */
3564 setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
3565 sqlite3GlobalConfig.nLookaside);
3567 sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
3569 opendb_out:
3570 if( db ){
3571 assert( db->mutex!=0 || isThreadsafe==0
3572 || sqlite3GlobalConfig.bFullMutex==0 );
3573 sqlite3_mutex_leave(db->mutex);
3575 rc = sqlite3_errcode(db);
3576 assert( db!=0 || (rc&0xff)==SQLITE_NOMEM );
3577 if( (rc&0xff)==SQLITE_NOMEM ){
3578 sqlite3_close(db);
3579 db = 0;
3580 }else if( rc!=SQLITE_OK ){
3581 db->eOpenState = SQLITE_STATE_SICK;
3583 *ppDb = db;
3584 #ifdef SQLITE_ENABLE_SQLLOG
3585 if( sqlite3GlobalConfig.xSqllog ){
3586 /* Opening a db handle. Fourth parameter is passed 0. */
3587 void *pArg = sqlite3GlobalConfig.pSqllogArg;
3588 sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
3590 #endif
3591 /* BEGIN SQLCIPHER */
3592 #if defined(SQLITE_HAS_CODEC)
3593 if( rc==SQLITE_OK ) sqlite3CodecQueryParameters(db, 0, zOpen);
3594 #endif
3595 /* END SQLCIPHER */
3596 sqlite3_free_filename(zOpen);
3597 return rc;
3602 ** Open a new database handle.
3604 int sqlite3_open(
3605 const char *zFilename,
3606 sqlite3 **ppDb
3608 return openDatabase(zFilename, ppDb,
3609 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
3611 int sqlite3_open_v2(
3612 const char *filename, /* Database filename (UTF-8) */
3613 sqlite3 **ppDb, /* OUT: SQLite db handle */
3614 int flags, /* Flags */
3615 const char *zVfs /* Name of VFS module to use */
3617 return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
3620 #ifndef SQLITE_OMIT_UTF16
3622 ** Open a new database handle.
3624 int sqlite3_open16(
3625 const void *zFilename,
3626 sqlite3 **ppDb
3628 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
3629 sqlite3_value *pVal;
3630 int rc;
3632 #ifdef SQLITE_ENABLE_API_ARMOR
3633 if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
3634 #endif
3635 *ppDb = 0;
3636 #ifndef SQLITE_OMIT_AUTOINIT
3637 rc = sqlite3_initialize();
3638 if( rc ) return rc;
3639 #endif
3640 if( zFilename==0 ) zFilename = "\000\000";
3641 pVal = sqlite3ValueNew(0);
3642 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
3643 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
3644 if( zFilename8 ){
3645 rc = openDatabase(zFilename8, ppDb,
3646 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
3647 assert( *ppDb || rc==SQLITE_NOMEM );
3648 if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
3649 SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
3651 }else{
3652 rc = SQLITE_NOMEM_BKPT;
3654 sqlite3ValueFree(pVal);
3656 return rc & 0xff;
3658 #endif /* SQLITE_OMIT_UTF16 */
3661 ** Register a new collation sequence with the database handle db.
3663 int sqlite3_create_collation(
3664 sqlite3* db,
3665 const char *zName,
3666 int enc,
3667 void* pCtx,
3668 int(*xCompare)(void*,int,const void*,int,const void*)
3670 return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
3674 ** Register a new collation sequence with the database handle db.
3676 int sqlite3_create_collation_v2(
3677 sqlite3* db,
3678 const char *zName,
3679 int enc,
3680 void* pCtx,
3681 int(*xCompare)(void*,int,const void*,int,const void*),
3682 void(*xDel)(void*)
3684 int rc;
3686 #ifdef SQLITE_ENABLE_API_ARMOR
3687 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
3688 #endif
3689 sqlite3_mutex_enter(db->mutex);
3690 assert( !db->mallocFailed );
3691 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
3692 rc = sqlite3ApiExit(db, rc);
3693 sqlite3_mutex_leave(db->mutex);
3694 return rc;
3697 #ifndef SQLITE_OMIT_UTF16
3699 ** Register a new collation sequence with the database handle db.
3701 int sqlite3_create_collation16(
3702 sqlite3* db,
3703 const void *zName,
3704 int enc,
3705 void* pCtx,
3706 int(*xCompare)(void*,int,const void*,int,const void*)
3708 int rc = SQLITE_OK;
3709 char *zName8;
3711 #ifdef SQLITE_ENABLE_API_ARMOR
3712 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
3713 #endif
3714 sqlite3_mutex_enter(db->mutex);
3715 assert( !db->mallocFailed );
3716 zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
3717 if( zName8 ){
3718 rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
3719 sqlite3DbFree(db, zName8);
3721 rc = sqlite3ApiExit(db, rc);
3722 sqlite3_mutex_leave(db->mutex);
3723 return rc;
3725 #endif /* SQLITE_OMIT_UTF16 */
3728 ** Register a collation sequence factory callback with the database handle
3729 ** db. Replace any previously installed collation sequence factory.
3731 int sqlite3_collation_needed(
3732 sqlite3 *db,
3733 void *pCollNeededArg,
3734 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
3736 #ifdef SQLITE_ENABLE_API_ARMOR
3737 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3738 #endif
3739 sqlite3_mutex_enter(db->mutex);
3740 db->xCollNeeded = xCollNeeded;
3741 db->xCollNeeded16 = 0;
3742 db->pCollNeededArg = pCollNeededArg;
3743 sqlite3_mutex_leave(db->mutex);
3744 return SQLITE_OK;
3747 #ifndef SQLITE_OMIT_UTF16
3749 ** Register a collation sequence factory callback with the database handle
3750 ** db. Replace any previously installed collation sequence factory.
3752 int sqlite3_collation_needed16(
3753 sqlite3 *db,
3754 void *pCollNeededArg,
3755 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
3757 #ifdef SQLITE_ENABLE_API_ARMOR
3758 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3759 #endif
3760 sqlite3_mutex_enter(db->mutex);
3761 db->xCollNeeded = 0;
3762 db->xCollNeeded16 = xCollNeeded16;
3763 db->pCollNeededArg = pCollNeededArg;
3764 sqlite3_mutex_leave(db->mutex);
3765 return SQLITE_OK;
3767 #endif /* SQLITE_OMIT_UTF16 */
3769 #ifndef SQLITE_OMIT_DEPRECATED
3771 ** This function is now an anachronism. It used to be used to recover from a
3772 ** malloc() failure, but SQLite now does this automatically.
3774 int sqlite3_global_recover(void){
3775 return SQLITE_OK;
3777 #endif
3780 ** Test to see whether or not the database connection is in autocommit
3781 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
3782 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
3783 ** by the next COMMIT or ROLLBACK.
3785 int sqlite3_get_autocommit(sqlite3 *db){
3786 #ifdef SQLITE_ENABLE_API_ARMOR
3787 if( !sqlite3SafetyCheckOk(db) ){
3788 (void)SQLITE_MISUSE_BKPT;
3789 return 0;
3791 #endif
3792 return db->autoCommit;
3796 ** The following routines are substitutes for constants SQLITE_CORRUPT,
3797 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
3798 ** constants. They serve two purposes:
3800 ** 1. Serve as a convenient place to set a breakpoint in a debugger
3801 ** to detect when version error conditions occurs.
3803 ** 2. Invoke sqlite3_log() to provide the source code location where
3804 ** a low-level error is first detected.
3806 int sqlite3ReportError(int iErr, int lineno, const char *zType){
3807 sqlite3_log(iErr, "%s at line %d of [%.10s]",
3808 zType, lineno, 20+sqlite3_sourceid());
3809 return iErr;
3811 int sqlite3CorruptError(int lineno){
3812 testcase( sqlite3GlobalConfig.xLog!=0 );
3813 return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
3815 int sqlite3MisuseError(int lineno){
3816 testcase( sqlite3GlobalConfig.xLog!=0 );
3817 return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
3819 int sqlite3CantopenError(int lineno){
3820 testcase( sqlite3GlobalConfig.xLog!=0 );
3821 return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
3823 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
3824 int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
3825 char zMsg[100];
3826 sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
3827 testcase( sqlite3GlobalConfig.xLog!=0 );
3828 return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
3830 #endif
3831 #ifdef SQLITE_DEBUG
3832 int sqlite3NomemError(int lineno){
3833 testcase( sqlite3GlobalConfig.xLog!=0 );
3834 return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
3836 int sqlite3IoerrnomemError(int lineno){
3837 testcase( sqlite3GlobalConfig.xLog!=0 );
3838 return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
3840 #endif
3842 #ifndef SQLITE_OMIT_DEPRECATED
3844 ** This is a convenience routine that makes sure that all thread-specific
3845 ** data for this thread has been deallocated.
3847 ** SQLite no longer uses thread-specific data so this routine is now a
3848 ** no-op. It is retained for historical compatibility.
3850 void sqlite3_thread_cleanup(void){
3852 #endif
3855 ** Return meta information about a specific column of a database table.
3856 ** See comment in sqlite3.h (sqlite.h.in) for details.
3858 int sqlite3_table_column_metadata(
3859 sqlite3 *db, /* Connection handle */
3860 const char *zDbName, /* Database name or NULL */
3861 const char *zTableName, /* Table name */
3862 const char *zColumnName, /* Column name */
3863 char const **pzDataType, /* OUTPUT: Declared data type */
3864 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
3865 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
3866 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
3867 int *pAutoinc /* OUTPUT: True if column is auto-increment */
3869 int rc;
3870 char *zErrMsg = 0;
3871 Table *pTab = 0;
3872 Column *pCol = 0;
3873 int iCol = 0;
3874 char const *zDataType = 0;
3875 char const *zCollSeq = 0;
3876 int notnull = 0;
3877 int primarykey = 0;
3878 int autoinc = 0;
3881 #ifdef SQLITE_ENABLE_API_ARMOR
3882 if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
3883 return SQLITE_MISUSE_BKPT;
3885 #endif
3887 /* Ensure the database schema has been loaded */
3888 sqlite3_mutex_enter(db->mutex);
3889 sqlite3BtreeEnterAll(db);
3890 rc = sqlite3Init(db, &zErrMsg);
3891 if( SQLITE_OK!=rc ){
3892 goto error_out;
3895 /* Locate the table in question */
3896 pTab = sqlite3FindTable(db, zTableName, zDbName);
3897 if( !pTab || IsView(pTab) ){
3898 pTab = 0;
3899 goto error_out;
3902 /* Find the column for which info is requested */
3903 if( zColumnName==0 ){
3904 /* Query for existance of table only */
3905 }else{
3906 for(iCol=0; iCol<pTab->nCol; iCol++){
3907 pCol = &pTab->aCol[iCol];
3908 if( 0==sqlite3StrICmp(pCol->zCnName, zColumnName) ){
3909 break;
3912 if( iCol==pTab->nCol ){
3913 if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
3914 iCol = pTab->iPKey;
3915 pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
3916 }else{
3917 pTab = 0;
3918 goto error_out;
3923 /* The following block stores the meta information that will be returned
3924 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
3925 ** and autoinc. At this point there are two possibilities:
3927 ** 1. The specified column name was rowid", "oid" or "_rowid_"
3928 ** and there is no explicitly declared IPK column.
3930 ** 2. The table is not a view and the column name identified an
3931 ** explicitly declared column. Copy meta information from *pCol.
3933 if( pCol ){
3934 zDataType = sqlite3ColumnType(pCol,0);
3935 zCollSeq = sqlite3ColumnColl(pCol);
3936 notnull = pCol->notNull!=0;
3937 primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
3938 autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
3939 }else{
3940 zDataType = "INTEGER";
3941 primarykey = 1;
3943 if( !zCollSeq ){
3944 zCollSeq = sqlite3StrBINARY;
3947 error_out:
3948 sqlite3BtreeLeaveAll(db);
3950 /* Whether the function call succeeded or failed, set the output parameters
3951 ** to whatever their local counterparts contain. If an error did occur,
3952 ** this has the effect of zeroing all output parameters.
3954 if( pzDataType ) *pzDataType = zDataType;
3955 if( pzCollSeq ) *pzCollSeq = zCollSeq;
3956 if( pNotNull ) *pNotNull = notnull;
3957 if( pPrimaryKey ) *pPrimaryKey = primarykey;
3958 if( pAutoinc ) *pAutoinc = autoinc;
3960 if( SQLITE_OK==rc && !pTab ){
3961 sqlite3DbFree(db, zErrMsg);
3962 zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
3963 zColumnName);
3964 rc = SQLITE_ERROR;
3966 sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
3967 sqlite3DbFree(db, zErrMsg);
3968 rc = sqlite3ApiExit(db, rc);
3969 sqlite3_mutex_leave(db->mutex);
3970 return rc;
3974 ** Sleep for a little while. Return the amount of time slept.
3976 int sqlite3_sleep(int ms){
3977 sqlite3_vfs *pVfs;
3978 int rc;
3979 pVfs = sqlite3_vfs_find(0);
3980 if( pVfs==0 ) return 0;
3982 /* This function works in milliseconds, but the underlying OsSleep()
3983 ** API uses microseconds. Hence the 1000's.
3985 rc = (sqlite3OsSleep(pVfs, ms<0 ? 0 : 1000*ms)/1000);
3986 return rc;
3990 ** Enable or disable the extended result codes.
3992 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
3993 #ifdef SQLITE_ENABLE_API_ARMOR
3994 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3995 #endif
3996 sqlite3_mutex_enter(db->mutex);
3997 db->errMask = onoff ? 0xffffffff : 0xff;
3998 sqlite3_mutex_leave(db->mutex);
3999 return SQLITE_OK;
4003 ** Invoke the xFileControl method on a particular database.
4005 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
4006 int rc = SQLITE_ERROR;
4007 Btree *pBtree;
4009 #ifdef SQLITE_ENABLE_API_ARMOR
4010 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
4011 #endif
4012 sqlite3_mutex_enter(db->mutex);
4013 pBtree = sqlite3DbNameToBtree(db, zDbName);
4014 if( pBtree ){
4015 Pager *pPager;
4016 sqlite3_file *fd;
4017 sqlite3BtreeEnter(pBtree);
4018 pPager = sqlite3BtreePager(pBtree);
4019 assert( pPager!=0 );
4020 fd = sqlite3PagerFile(pPager);
4021 assert( fd!=0 );
4022 if( op==SQLITE_FCNTL_FILE_POINTER ){
4023 *(sqlite3_file**)pArg = fd;
4024 rc = SQLITE_OK;
4025 }else if( op==SQLITE_FCNTL_VFS_POINTER ){
4026 *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
4027 rc = SQLITE_OK;
4028 }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
4029 *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
4030 rc = SQLITE_OK;
4031 }else if( op==SQLITE_FCNTL_DATA_VERSION ){
4032 *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager);
4033 rc = SQLITE_OK;
4034 }else if( op==SQLITE_FCNTL_RESERVE_BYTES ){
4035 int iNew = *(int*)pArg;
4036 *(int*)pArg = sqlite3BtreeGetRequestedReserve(pBtree);
4037 if( iNew>=0 && iNew<=255 ){
4038 sqlite3BtreeSetPageSize(pBtree, 0, iNew, 0);
4040 rc = SQLITE_OK;
4041 }else if( op==SQLITE_FCNTL_RESET_CACHE ){
4042 sqlite3BtreeClearCache(pBtree);
4043 rc = SQLITE_OK;
4044 }else{
4045 int nSave = db->busyHandler.nBusy;
4046 rc = sqlite3OsFileControl(fd, op, pArg);
4047 db->busyHandler.nBusy = nSave;
4049 sqlite3BtreeLeave(pBtree);
4051 sqlite3_mutex_leave(db->mutex);
4052 return rc;
4056 ** Interface to the testing logic.
4058 int sqlite3_test_control(int op, ...){
4059 int rc = 0;
4060 #ifdef SQLITE_UNTESTABLE
4061 UNUSED_PARAMETER(op);
4062 #else
4063 va_list ap;
4064 va_start(ap, op);
4065 switch( op ){
4068 ** Save the current state of the PRNG.
4070 case SQLITE_TESTCTRL_PRNG_SAVE: {
4071 sqlite3PrngSaveState();
4072 break;
4076 ** Restore the state of the PRNG to the last state saved using
4077 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
4078 ** this verb acts like PRNG_RESET.
4080 case SQLITE_TESTCTRL_PRNG_RESTORE: {
4081 sqlite3PrngRestoreState();
4082 break;
4085 /* sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, int x, sqlite3 *db);
4087 ** Control the seed for the pseudo-random number generator (PRNG) that
4088 ** is built into SQLite. Cases:
4090 ** x!=0 && db!=0 Seed the PRNG to the current value of the
4091 ** schema cookie in the main database for db, or
4092 ** x if the schema cookie is zero. This case
4093 ** is convenient to use with database fuzzers
4094 ** as it allows the fuzzer some control over the
4095 ** the PRNG seed.
4097 ** x!=0 && db==0 Seed the PRNG to the value of x.
4099 ** x==0 && db==0 Revert to default behavior of using the
4100 ** xRandomness method on the primary VFS.
4102 ** This test-control also resets the PRNG so that the new seed will
4103 ** be used for the next call to sqlite3_randomness().
4105 #ifndef SQLITE_OMIT_WSD
4106 case SQLITE_TESTCTRL_PRNG_SEED: {
4107 int x = va_arg(ap, int);
4108 int y;
4109 sqlite3 *db = va_arg(ap, sqlite3*);
4110 assert( db==0 || db->aDb[0].pSchema!=0 );
4111 if( db && (y = db->aDb[0].pSchema->schema_cookie)!=0 ){ x = y; }
4112 sqlite3Config.iPrngSeed = x;
4113 sqlite3_randomness(0,0);
4114 break;
4116 #endif
4119 ** sqlite3_test_control(BITVEC_TEST, size, program)
4121 ** Run a test against a Bitvec object of size. The program argument
4122 ** is an array of integers that defines the test. Return -1 on a
4123 ** memory allocation error, 0 on success, or non-zero for an error.
4124 ** See the sqlite3BitvecBuiltinTest() for additional information.
4126 case SQLITE_TESTCTRL_BITVEC_TEST: {
4127 int sz = va_arg(ap, int);
4128 int *aProg = va_arg(ap, int*);
4129 rc = sqlite3BitvecBuiltinTest(sz, aProg);
4130 break;
4134 ** sqlite3_test_control(FAULT_INSTALL, xCallback)
4136 ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
4137 ** if xCallback is not NULL.
4139 ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
4140 ** is called immediately after installing the new callback and the return
4141 ** value from sqlite3FaultSim(0) becomes the return from
4142 ** sqlite3_test_control().
4144 case SQLITE_TESTCTRL_FAULT_INSTALL: {
4145 /* A bug in MSVC prevents it from understanding pointers to functions
4146 ** types in the second argument to va_arg(). Work around the problem
4147 ** using a typedef.
4148 ** http://support.microsoft.com/kb/47961 <-- dead hyperlink
4149 ** Search at http://web.archive.org/ to find the 2015-03-16 archive
4150 ** of the link above to see the original text.
4151 ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
4153 typedef int(*sqlite3FaultFuncType)(int);
4154 sqlite3GlobalConfig.xTestCallback = va_arg(ap, sqlite3FaultFuncType);
4155 rc = sqlite3FaultSim(0);
4156 break;
4160 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
4162 ** Register hooks to call to indicate which malloc() failures
4163 ** are benign.
4165 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
4166 typedef void (*void_function)(void);
4167 void_function xBenignBegin;
4168 void_function xBenignEnd;
4169 xBenignBegin = va_arg(ap, void_function);
4170 xBenignEnd = va_arg(ap, void_function);
4171 sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
4172 break;
4176 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
4178 ** Set the PENDING byte to the value in the argument, if X>0.
4179 ** Make no changes if X==0. Return the value of the pending byte
4180 ** as it existing before this routine was called.
4182 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
4183 ** an incompatible database file format. Changing the PENDING byte
4184 ** while any database connection is open results in undefined and
4185 ** deleterious behavior.
4187 case SQLITE_TESTCTRL_PENDING_BYTE: {
4188 rc = PENDING_BYTE;
4189 #ifndef SQLITE_OMIT_WSD
4191 unsigned int newVal = va_arg(ap, unsigned int);
4192 if( newVal ) sqlite3PendingByte = newVal;
4194 #endif
4195 break;
4199 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
4201 ** This action provides a run-time test to see whether or not
4202 ** assert() was enabled at compile-time. If X is true and assert()
4203 ** is enabled, then the return value is true. If X is true and
4204 ** assert() is disabled, then the return value is zero. If X is
4205 ** false and assert() is enabled, then the assertion fires and the
4206 ** process aborts. If X is false and assert() is disabled, then the
4207 ** return value is zero.
4209 case SQLITE_TESTCTRL_ASSERT: {
4210 volatile int x = 0;
4211 assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
4212 rc = x;
4213 #if defined(SQLITE_DEBUG)
4214 /* Invoke these debugging routines so that the compiler does not
4215 ** issue "defined but not used" warnings. */
4216 if( x==9999 ){
4217 sqlite3ShowExpr(0);
4218 sqlite3ShowExpr(0);
4219 sqlite3ShowExprList(0);
4220 sqlite3ShowIdList(0);
4221 sqlite3ShowSrcList(0);
4222 sqlite3ShowWith(0);
4223 sqlite3ShowUpsert(0);
4224 sqlite3ShowTriggerStep(0);
4225 sqlite3ShowTriggerStepList(0);
4226 sqlite3ShowTrigger(0);
4227 sqlite3ShowTriggerList(0);
4228 #ifndef SQLITE_OMIT_WINDOWFUNC
4229 sqlite3ShowWindow(0);
4230 sqlite3ShowWinFunc(0);
4231 #endif
4232 sqlite3ShowSelect(0);
4234 #endif
4235 break;
4240 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
4242 ** This action provides a run-time test to see how the ALWAYS and
4243 ** NEVER macros were defined at compile-time.
4245 ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
4247 ** The recommended test is X==2. If the return value is 2, that means
4248 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
4249 ** default setting. If the return value is 1, then ALWAYS() is either
4250 ** hard-coded to true or else it asserts if its argument is false.
4251 ** The first behavior (hard-coded to true) is the case if
4252 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
4253 ** behavior (assert if the argument to ALWAYS() is false) is the case if
4254 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
4256 ** The run-time test procedure might look something like this:
4258 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
4259 ** // ALWAYS() and NEVER() are no-op pass-through macros
4260 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
4261 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
4262 ** }else{
4263 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
4264 ** }
4266 case SQLITE_TESTCTRL_ALWAYS: {
4267 int x = va_arg(ap,int);
4268 rc = x ? ALWAYS(x) : 0;
4269 break;
4273 ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
4275 ** The integer returned reveals the byte-order of the computer on which
4276 ** SQLite is running:
4278 ** 1 big-endian, determined at run-time
4279 ** 10 little-endian, determined at run-time
4280 ** 432101 big-endian, determined at compile-time
4281 ** 123410 little-endian, determined at compile-time
4283 case SQLITE_TESTCTRL_BYTEORDER: {
4284 rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
4285 break;
4288 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
4290 ** Enable or disable various optimizations for testing purposes. The
4291 ** argument N is a bitmask of optimizations to be disabled. For normal
4292 ** operation N should be 0. The idea is that a test program (like the
4293 ** SQL Logic Test or SLT test module) can run the same SQL multiple times
4294 ** with various optimizations disabled to verify that the same answer
4295 ** is obtained in every case.
4297 case SQLITE_TESTCTRL_OPTIMIZATIONS: {
4298 sqlite3 *db = va_arg(ap, sqlite3*);
4299 db->dbOptFlags = va_arg(ap, u32);
4300 break;
4303 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, onoff, xAlt);
4305 ** If parameter onoff is 1, subsequent calls to localtime() fail.
4306 ** If 2, then invoke xAlt() instead of localtime(). If 0, normal
4307 ** processing.
4309 ** xAlt arguments are void pointers, but they really want to be:
4311 ** int xAlt(const time_t*, struct tm*);
4313 ** xAlt should write results in to struct tm object of its 2nd argument
4314 ** and return zero on success, or return non-zero on failure.
4316 case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
4317 sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
4318 if( sqlite3GlobalConfig.bLocaltimeFault==2 ){
4319 typedef int(*sqlite3LocaltimeType)(const void*,void*);
4320 sqlite3GlobalConfig.xAltLocaltime = va_arg(ap, sqlite3LocaltimeType);
4321 }else{
4322 sqlite3GlobalConfig.xAltLocaltime = 0;
4324 break;
4327 /* sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, sqlite3*);
4329 ** Toggle the ability to use internal functions on or off for
4330 ** the database connection given in the argument.
4332 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: {
4333 sqlite3 *db = va_arg(ap, sqlite3*);
4334 db->mDbFlags ^= DBFLAG_InternalFunc;
4335 break;
4338 /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
4340 ** Set or clear a flag that indicates that the database file is always well-
4341 ** formed and never corrupt. This flag is clear by default, indicating that
4342 ** database files might have arbitrary corruption. Setting the flag during
4343 ** testing causes certain assert() statements in the code to be activated
4344 ** that demonstrat invariants on well-formed database files.
4346 case SQLITE_TESTCTRL_NEVER_CORRUPT: {
4347 sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
4348 break;
4351 /* sqlite3_test_control(SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS, int);
4353 ** Set or clear a flag that causes SQLite to verify that type, name,
4354 ** and tbl_name fields of the sqlite_schema table. This is normally
4355 ** on, but it is sometimes useful to turn it off for testing.
4357 ** 2020-07-22: Disabling EXTRA_SCHEMA_CHECKS also disables the
4358 ** verification of rootpage numbers when parsing the schema. This
4359 ** is useful to make it easier to reach strange internal error states
4360 ** during testing. The EXTRA_SCHEMA_CHECKS setting is always enabled
4361 ** in production.
4363 case SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS: {
4364 sqlite3GlobalConfig.bExtraSchemaChecks = va_arg(ap, int);
4365 break;
4368 /* Set the threshold at which OP_Once counters reset back to zero.
4369 ** By default this is 0x7ffffffe (over 2 billion), but that value is
4370 ** too big to test in a reasonable amount of time, so this control is
4371 ** provided to set a small and easily reachable reset value.
4373 case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
4374 sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
4375 break;
4378 /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
4380 ** Set the VDBE coverage callback function to xCallback with context
4381 ** pointer ptr.
4383 case SQLITE_TESTCTRL_VDBE_COVERAGE: {
4384 #ifdef SQLITE_VDBE_COVERAGE
4385 typedef void (*branch_callback)(void*,unsigned int,
4386 unsigned char,unsigned char);
4387 sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
4388 sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
4389 #endif
4390 break;
4393 /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
4394 case SQLITE_TESTCTRL_SORTER_MMAP: {
4395 sqlite3 *db = va_arg(ap, sqlite3*);
4396 db->nMaxSorterMmap = va_arg(ap, int);
4397 break;
4400 /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
4402 ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
4403 ** not.
4405 case SQLITE_TESTCTRL_ISINIT: {
4406 if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
4407 break;
4410 /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
4412 ** This test control is used to create imposter tables. "db" is a pointer
4413 ** to the database connection. dbName is the database name (ex: "main" or
4414 ** "temp") which will receive the imposter. "onOff" turns imposter mode on
4415 ** or off. "tnum" is the root page of the b-tree to which the imposter
4416 ** table should connect.
4418 ** Enable imposter mode only when the schema has already been parsed. Then
4419 ** run a single CREATE TABLE statement to construct the imposter table in
4420 ** the parsed schema. Then turn imposter mode back off again.
4422 ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
4423 ** the schema to be reparsed the next time it is needed. This has the
4424 ** effect of erasing all imposter tables.
4426 case SQLITE_TESTCTRL_IMPOSTER: {
4427 sqlite3 *db = va_arg(ap, sqlite3*);
4428 int iDb;
4429 sqlite3_mutex_enter(db->mutex);
4430 iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
4431 if( iDb>=0 ){
4432 db->init.iDb = iDb;
4433 db->init.busy = db->init.imposterTable = va_arg(ap,int);
4434 db->init.newTnum = va_arg(ap,int);
4435 if( db->init.busy==0 && db->init.newTnum>0 ){
4436 sqlite3ResetAllSchemasOfConnection(db);
4439 sqlite3_mutex_leave(db->mutex);
4440 break;
4443 #if defined(YYCOVERAGE)
4444 /* sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
4446 ** This test control (only available when SQLite is compiled with
4447 ** -DYYCOVERAGE) writes a report onto "out" that shows all
4448 ** state/lookahead combinations in the parser state machine
4449 ** which are never exercised. If any state is missed, make the
4450 ** return code SQLITE_ERROR.
4452 case SQLITE_TESTCTRL_PARSER_COVERAGE: {
4453 FILE *out = va_arg(ap, FILE*);
4454 if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
4455 break;
4457 #endif /* defined(YYCOVERAGE) */
4459 /* sqlite3_test_control(SQLITE_TESTCTRL_RESULT_INTREAL, sqlite3_context*);
4461 ** This test-control causes the most recent sqlite3_result_int64() value
4462 ** to be interpreted as a MEM_IntReal instead of as an MEM_Int. Normally,
4463 ** MEM_IntReal values only arise during an INSERT operation of integer
4464 ** values into a REAL column, so they can be challenging to test. This
4465 ** test-control enables us to write an intreal() SQL function that can
4466 ** inject an intreal() value at arbitrary places in an SQL statement,
4467 ** for testing purposes.
4469 case SQLITE_TESTCTRL_RESULT_INTREAL: {
4470 sqlite3_context *pCtx = va_arg(ap, sqlite3_context*);
4471 sqlite3ResultIntReal(pCtx);
4472 break;
4475 /* sqlite3_test_control(SQLITE_TESTCTRL_SEEK_COUNT,
4476 ** sqlite3 *db, // Database connection
4477 ** u64 *pnSeek // Write seek count here
4478 ** );
4480 ** This test-control queries the seek-counter on the "main" database
4481 ** file. The seek-counter is written into *pnSeek and is then reset.
4482 ** The seek-count is only available if compiled with SQLITE_DEBUG.
4484 case SQLITE_TESTCTRL_SEEK_COUNT: {
4485 sqlite3 *db = va_arg(ap, sqlite3*);
4486 u64 *pn = va_arg(ap, sqlite3_uint64*);
4487 *pn = sqlite3BtreeSeekCount(db->aDb->pBt);
4488 (void)db; /* Silence harmless unused variable warning */
4489 break;
4492 /* sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, op, ptr)
4494 ** "ptr" is a pointer to a u32.
4496 ** op==0 Store the current sqlite3TreeTrace in *ptr
4497 ** op==1 Set sqlite3TreeTrace to the value *ptr
4498 ** op==3 Store the current sqlite3WhereTrace in *ptr
4499 ** op==3 Set sqlite3WhereTrace to the value *ptr
4501 case SQLITE_TESTCTRL_TRACEFLAGS: {
4502 int opTrace = va_arg(ap, int);
4503 u32 *ptr = va_arg(ap, u32*);
4504 switch( opTrace ){
4505 case 0: *ptr = sqlite3TreeTrace; break;
4506 case 1: sqlite3TreeTrace = *ptr; break;
4507 case 2: *ptr = sqlite3WhereTrace; break;
4508 case 3: sqlite3WhereTrace = *ptr; break;
4510 break;
4513 /* sqlite3_test_control(SQLITE_TESTCTRL_LOGEST,
4514 ** double fIn, // Input value
4515 ** int *pLogEst, // sqlite3LogEstFromDouble(fIn)
4516 ** u64 *pInt, // sqlite3LogEstToInt(*pLogEst)
4517 ** int *pLogEst2 // sqlite3LogEst(*pInt)
4518 ** );
4520 ** Test access for the LogEst conversion routines.
4522 case SQLITE_TESTCTRL_LOGEST: {
4523 double rIn = va_arg(ap, double);
4524 LogEst rLogEst = sqlite3LogEstFromDouble(rIn);
4525 int *pI1 = va_arg(ap,int*);
4526 u64 *pU64 = va_arg(ap,u64*);
4527 int *pI2 = va_arg(ap,int*);
4528 *pI1 = rLogEst;
4529 *pU64 = sqlite3LogEstToInt(rLogEst);
4530 *pI2 = sqlite3LogEst(*pU64);
4531 break;
4535 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
4536 /* sqlite3_test_control(SQLITE_TESTCTRL_TUNE, id, *piValue)
4538 ** If "id" is an integer between 1 and SQLITE_NTUNE then set the value
4539 ** of the id-th tuning parameter to *piValue. If "id" is between -1
4540 ** and -SQLITE_NTUNE, then write the current value of the (-id)-th
4541 ** tuning parameter into *piValue.
4543 ** Tuning parameters are for use during transient development builds,
4544 ** to help find the best values for constants in the query planner.
4545 ** Access tuning parameters using the Tuning(ID) macro. Set the
4546 ** parameters in the CLI using ".testctrl tune ID VALUE".
4548 ** Transient use only. Tuning parameters should not be used in
4549 ** checked-in code.
4551 case SQLITE_TESTCTRL_TUNE: {
4552 int id = va_arg(ap, int);
4553 int *piValue = va_arg(ap, int*);
4554 if( id>0 && id<=SQLITE_NTUNE ){
4555 Tuning(id) = *piValue;
4556 }else if( id<0 && id>=-SQLITE_NTUNE ){
4557 *piValue = Tuning(-id);
4558 }else{
4559 rc = SQLITE_NOTFOUND;
4561 break;
4563 #endif
4565 va_end(ap);
4566 #endif /* SQLITE_UNTESTABLE */
4567 return rc;
4571 ** The Pager stores the Database filename, Journal filename, and WAL filename
4572 ** consecutively in memory, in that order. The database filename is prefixed
4573 ** by four zero bytes. Locate the start of the database filename by searching
4574 ** backwards for the first byte following four consecutive zero bytes.
4576 ** This only works if the filename passed in was obtained from the Pager.
4578 static const char *databaseName(const char *zName){
4579 while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
4580 zName--;
4582 return zName;
4586 ** Append text z[] to the end of p[]. Return a pointer to the first
4587 ** character after then zero terminator on the new text in p[].
4589 static char *appendText(char *p, const char *z){
4590 size_t n = strlen(z);
4591 memcpy(p, z, n+1);
4592 return p+n+1;
4596 ** Allocate memory to hold names for a database, journal file, WAL file,
4597 ** and query parameters. The pointer returned is valid for use by
4598 ** sqlite3_filename_database() and sqlite3_uri_parameter() and related
4599 ** functions.
4601 ** Memory layout must be compatible with that generated by the pager
4602 ** and expected by sqlite3_uri_parameter() and databaseName().
4604 const char *sqlite3_create_filename(
4605 const char *zDatabase,
4606 const char *zJournal,
4607 const char *zWal,
4608 int nParam,
4609 const char **azParam
4611 sqlite3_int64 nByte;
4612 int i;
4613 char *pResult, *p;
4614 nByte = strlen(zDatabase) + strlen(zJournal) + strlen(zWal) + 10;
4615 for(i=0; i<nParam*2; i++){
4616 nByte += strlen(azParam[i])+1;
4618 pResult = p = sqlite3_malloc64( nByte );
4619 if( p==0 ) return 0;
4620 memset(p, 0, 4);
4621 p += 4;
4622 p = appendText(p, zDatabase);
4623 for(i=0; i<nParam*2; i++){
4624 p = appendText(p, azParam[i]);
4626 *(p++) = 0;
4627 p = appendText(p, zJournal);
4628 p = appendText(p, zWal);
4629 *(p++) = 0;
4630 *(p++) = 0;
4631 assert( (sqlite3_int64)(p - pResult)==nByte );
4632 return pResult + 4;
4636 ** Free memory obtained from sqlite3_create_filename(). It is a severe
4637 ** error to call this routine with any parameter other than a pointer
4638 ** previously obtained from sqlite3_create_filename() or a NULL pointer.
4640 void sqlite3_free_filename(const char *p){
4641 if( p==0 ) return;
4642 p = databaseName(p);
4643 sqlite3_free((char*)p - 4);
4648 ** This is a utility routine, useful to VFS implementations, that checks
4649 ** to see if a database file was a URI that contained a specific query
4650 ** parameter, and if so obtains the value of the query parameter.
4652 ** The zFilename argument is the filename pointer passed into the xOpen()
4653 ** method of a VFS implementation. The zParam argument is the name of the
4654 ** query parameter we seek. This routine returns the value of the zParam
4655 ** parameter if it exists. If the parameter does not exist, this routine
4656 ** returns a NULL pointer.
4658 const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
4659 if( zFilename==0 || zParam==0 ) return 0;
4660 zFilename = databaseName(zFilename);
4661 return uriParameter(zFilename, zParam);
4665 ** Return a pointer to the name of Nth query parameter of the filename.
4667 const char *sqlite3_uri_key(const char *zFilename, int N){
4668 if( zFilename==0 || N<0 ) return 0;
4669 zFilename = databaseName(zFilename);
4670 zFilename += sqlite3Strlen30(zFilename) + 1;
4671 while( ALWAYS(zFilename) && zFilename[0] && (N--)>0 ){
4672 zFilename += sqlite3Strlen30(zFilename) + 1;
4673 zFilename += sqlite3Strlen30(zFilename) + 1;
4675 return zFilename[0] ? zFilename : 0;
4679 ** Return a boolean value for a query parameter.
4681 int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
4682 const char *z = sqlite3_uri_parameter(zFilename, zParam);
4683 bDflt = bDflt!=0;
4684 return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
4688 ** Return a 64-bit integer value for a query parameter.
4690 sqlite3_int64 sqlite3_uri_int64(
4691 const char *zFilename, /* Filename as passed to xOpen */
4692 const char *zParam, /* URI parameter sought */
4693 sqlite3_int64 bDflt /* return if parameter is missing */
4695 const char *z = sqlite3_uri_parameter(zFilename, zParam);
4696 sqlite3_int64 v;
4697 if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
4698 bDflt = v;
4700 return bDflt;
4704 ** Translate a filename that was handed to a VFS routine into the corresponding
4705 ** database, journal, or WAL file.
4707 ** It is an error to pass this routine a filename string that was not
4708 ** passed into the VFS from the SQLite core. Doing so is similar to
4709 ** passing free() a pointer that was not obtained from malloc() - it is
4710 ** an error that we cannot easily detect but that will likely cause memory
4711 ** corruption.
4713 const char *sqlite3_filename_database(const char *zFilename){
4714 if( zFilename==0 ) return 0;
4715 return databaseName(zFilename);
4717 const char *sqlite3_filename_journal(const char *zFilename){
4718 if( zFilename==0 ) return 0;
4719 zFilename = databaseName(zFilename);
4720 zFilename += sqlite3Strlen30(zFilename) + 1;
4721 while( ALWAYS(zFilename) && zFilename[0] ){
4722 zFilename += sqlite3Strlen30(zFilename) + 1;
4723 zFilename += sqlite3Strlen30(zFilename) + 1;
4725 return zFilename + 1;
4727 const char *sqlite3_filename_wal(const char *zFilename){
4728 #ifdef SQLITE_OMIT_WAL
4729 return 0;
4730 #else
4731 zFilename = sqlite3_filename_journal(zFilename);
4732 if( zFilename ) zFilename += sqlite3Strlen30(zFilename) + 1;
4733 return zFilename;
4734 #endif
4738 ** Return the Btree pointer identified by zDbName. Return NULL if not found.
4740 Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
4741 int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
4742 return iDb<0 ? 0 : db->aDb[iDb].pBt;
4746 ** Return the name of the N-th database schema. Return NULL if N is out
4747 ** of range.
4749 const char *sqlite3_db_name(sqlite3 *db, int N){
4750 #ifdef SQLITE_ENABLE_API_ARMOR
4751 if( !sqlite3SafetyCheckOk(db) ){
4752 (void)SQLITE_MISUSE_BKPT;
4753 return 0;
4755 #endif
4756 if( N<0 || N>=db->nDb ){
4757 return 0;
4758 }else{
4759 return db->aDb[N].zDbSName;
4764 ** Return the filename of the database associated with a database
4765 ** connection.
4767 const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
4768 Btree *pBt;
4769 #ifdef SQLITE_ENABLE_API_ARMOR
4770 if( !sqlite3SafetyCheckOk(db) ){
4771 (void)SQLITE_MISUSE_BKPT;
4772 return 0;
4774 #endif
4775 pBt = sqlite3DbNameToBtree(db, zDbName);
4776 return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
4780 ** Return 1 if database is read-only or 0 if read/write. Return -1 if
4781 ** no such database exists.
4783 int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
4784 Btree *pBt;
4785 #ifdef SQLITE_ENABLE_API_ARMOR
4786 if( !sqlite3SafetyCheckOk(db) ){
4787 (void)SQLITE_MISUSE_BKPT;
4788 return -1;
4790 #endif
4791 pBt = sqlite3DbNameToBtree(db, zDbName);
4792 return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
4795 #ifdef SQLITE_ENABLE_SNAPSHOT
4797 ** Obtain a snapshot handle for the snapshot of database zDb currently
4798 ** being read by handle db.
4800 int sqlite3_snapshot_get(
4801 sqlite3 *db,
4802 const char *zDb,
4803 sqlite3_snapshot **ppSnapshot
4805 int rc = SQLITE_ERROR;
4806 #ifndef SQLITE_OMIT_WAL
4808 #ifdef SQLITE_ENABLE_API_ARMOR
4809 if( !sqlite3SafetyCheckOk(db) ){
4810 return SQLITE_MISUSE_BKPT;
4812 #endif
4813 sqlite3_mutex_enter(db->mutex);
4815 if( db->autoCommit==0 ){
4816 int iDb = sqlite3FindDbName(db, zDb);
4817 if( iDb==0 || iDb>1 ){
4818 Btree *pBt = db->aDb[iDb].pBt;
4819 if( SQLITE_TXN_WRITE!=sqlite3BtreeTxnState(pBt) ){
4820 rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
4821 if( rc==SQLITE_OK ){
4822 rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
4828 sqlite3_mutex_leave(db->mutex);
4829 #endif /* SQLITE_OMIT_WAL */
4830 return rc;
4834 ** Open a read-transaction on the snapshot idendified by pSnapshot.
4836 int sqlite3_snapshot_open(
4837 sqlite3 *db,
4838 const char *zDb,
4839 sqlite3_snapshot *pSnapshot
4841 int rc = SQLITE_ERROR;
4842 #ifndef SQLITE_OMIT_WAL
4844 #ifdef SQLITE_ENABLE_API_ARMOR
4845 if( !sqlite3SafetyCheckOk(db) ){
4846 return SQLITE_MISUSE_BKPT;
4848 #endif
4849 sqlite3_mutex_enter(db->mutex);
4850 if( db->autoCommit==0 ){
4851 int iDb;
4852 iDb = sqlite3FindDbName(db, zDb);
4853 if( iDb==0 || iDb>1 ){
4854 Btree *pBt = db->aDb[iDb].pBt;
4855 if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE ){
4856 Pager *pPager = sqlite3BtreePager(pBt);
4857 int bUnlock = 0;
4858 if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_NONE ){
4859 if( db->nVdbeActive==0 ){
4860 rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot);
4861 if( rc==SQLITE_OK ){
4862 bUnlock = 1;
4863 rc = sqlite3BtreeCommit(pBt);
4866 }else{
4867 rc = SQLITE_OK;
4869 if( rc==SQLITE_OK ){
4870 rc = sqlite3PagerSnapshotOpen(pPager, pSnapshot);
4872 if( rc==SQLITE_OK ){
4873 rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
4874 sqlite3PagerSnapshotOpen(pPager, 0);
4876 if( bUnlock ){
4877 sqlite3PagerSnapshotUnlock(pPager);
4883 sqlite3_mutex_leave(db->mutex);
4884 #endif /* SQLITE_OMIT_WAL */
4885 return rc;
4889 ** Recover as many snapshots as possible from the wal file associated with
4890 ** schema zDb of database db.
4892 int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
4893 int rc = SQLITE_ERROR;
4894 #ifndef SQLITE_OMIT_WAL
4895 int iDb;
4897 #ifdef SQLITE_ENABLE_API_ARMOR
4898 if( !sqlite3SafetyCheckOk(db) ){
4899 return SQLITE_MISUSE_BKPT;
4901 #endif
4903 sqlite3_mutex_enter(db->mutex);
4904 iDb = sqlite3FindDbName(db, zDb);
4905 if( iDb==0 || iDb>1 ){
4906 Btree *pBt = db->aDb[iDb].pBt;
4907 if( SQLITE_TXN_NONE==sqlite3BtreeTxnState(pBt) ){
4908 rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
4909 if( rc==SQLITE_OK ){
4910 rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
4911 sqlite3BtreeCommit(pBt);
4915 sqlite3_mutex_leave(db->mutex);
4916 #endif /* SQLITE_OMIT_WAL */
4917 return rc;
4921 ** Free a snapshot handle obtained from sqlite3_snapshot_get().
4923 void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
4924 sqlite3_free(pSnapshot);
4926 #endif /* SQLITE_ENABLE_SNAPSHOT */
4928 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
4930 ** Given the name of a compile-time option, return true if that option
4931 ** was used and false if not.
4933 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
4934 ** is not required for a match.
4936 int sqlite3_compileoption_used(const char *zOptName){
4937 int i, n;
4938 int nOpt;
4939 const char **azCompileOpt;
4941 #if SQLITE_ENABLE_API_ARMOR
4942 if( zOptName==0 ){
4943 (void)SQLITE_MISUSE_BKPT;
4944 return 0;
4946 #endif
4948 azCompileOpt = sqlite3CompileOptions(&nOpt);
4950 if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
4951 n = sqlite3Strlen30(zOptName);
4953 /* Since nOpt is normally in single digits, a linear search is
4954 ** adequate. No need for a binary search. */
4955 for(i=0; i<nOpt; i++){
4956 if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
4957 && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
4959 return 1;
4962 return 0;
4966 ** Return the N-th compile-time option string. If N is out of range,
4967 ** return a NULL pointer.
4969 const char *sqlite3_compileoption_get(int N){
4970 int nOpt;
4971 const char **azCompileOpt;
4972 azCompileOpt = sqlite3CompileOptions(&nOpt);
4973 if( N>=0 && N<nOpt ){
4974 return azCompileOpt[N];
4976 return 0;
4978 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */