cipher_integrity check will report expected page size if invalid
[sqlcipher.git] / src / main.c
blobeea2600f274c8f7069e7da06ea55937a15a5166b
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_FTS5
45 int sqlite3Fts5Init(sqlite3*);
46 #endif
47 #ifdef SQLITE_ENABLE_STMTVTAB
48 int sqlite3StmtVtabInit(sqlite3*);
49 #endif
50 #ifdef SQLITE_EXTRA_AUTOEXT
51 int SQLITE_EXTRA_AUTOEXT(sqlite3*);
52 #endif
54 ** An array of pointers to extension initializer functions for
55 ** built-in extensions.
57 static int (*const sqlite3BuiltinExtensions[])(sqlite3*) = {
58 #ifdef SQLITE_ENABLE_FTS3
59 sqlite3Fts3Init,
60 #endif
61 #ifdef SQLITE_ENABLE_FTS5
62 sqlite3Fts5Init,
63 #endif
64 #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
65 sqlite3IcuInit,
66 #endif
67 #ifdef SQLITE_ENABLE_RTREE
68 sqlite3RtreeInit,
69 #endif
70 #ifdef SQLITE_ENABLE_DBPAGE_VTAB
71 sqlite3DbpageRegister,
72 #endif
73 #ifdef SQLITE_ENABLE_DBSTAT_VTAB
74 sqlite3DbstatRegister,
75 #endif
76 sqlite3TestExtInit,
77 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
78 sqlite3JsonTableFunctions,
79 #endif
80 #ifdef SQLITE_ENABLE_STMTVTAB
81 sqlite3StmtVtabInit,
82 #endif
83 #ifdef SQLITE_ENABLE_BYTECODE_VTAB
84 sqlite3VdbeBytecodeVtabInit,
85 #endif
86 #ifdef SQLITE_EXTRA_AUTOEXT
87 SQLITE_EXTRA_AUTOEXT,
88 #endif
91 #ifndef SQLITE_AMALGAMATION
92 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
93 ** contains the text of SQLITE_VERSION macro.
95 const char sqlite3_version[] = SQLITE_VERSION;
96 #endif
98 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
99 ** a pointer to the to the sqlite3_version[] string constant.
101 const char *sqlite3_libversion(void){ return sqlite3_version; }
103 /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
104 ** pointer to a string constant whose value is the same as the
105 ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
106 ** an edited copy of the amalgamation, then the last four characters of
107 ** the hash might be different from SQLITE_SOURCE_ID.
109 const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
111 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
112 ** returns an integer equal to SQLITE_VERSION_NUMBER.
114 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
116 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
117 ** zero if and only if SQLite was compiled with mutexing code omitted due to
118 ** the SQLITE_THREADSAFE compile-time option being set to 0.
120 int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
123 ** When compiling the test fixture or with debugging enabled (on Win32),
124 ** this variable being set to non-zero will cause OSTRACE macros to emit
125 ** extra diagnostic information.
127 #ifdef SQLITE_HAVE_OS_TRACE
128 # ifndef SQLITE_DEBUG_OS_TRACE
129 # define SQLITE_DEBUG_OS_TRACE 0
130 # endif
131 int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
132 #endif
134 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
136 ** If the following function pointer is not NULL and if
137 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
138 ** I/O active are written using this function. These messages
139 ** are intended for debugging activity only.
141 SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
142 #endif
145 ** If the following global variable points to a string which is the
146 ** name of a directory, then that directory will be used to store
147 ** temporary files.
149 ** See also the "PRAGMA temp_store_directory" SQL command.
151 char *sqlite3_temp_directory = 0;
154 ** If the following global variable points to a string which is the
155 ** name of a directory, then that directory will be used to store
156 ** all database files specified with a relative pathname.
158 ** See also the "PRAGMA data_store_directory" SQL command.
160 char *sqlite3_data_directory = 0;
163 ** Determine whether or not high-precision (long double) floating point
164 ** math works correctly on CPU currently running.
166 static SQLITE_NOINLINE int hasHighPrecisionDouble(int rc){
167 if( sizeof(LONGDOUBLE_TYPE)<=8 ){
168 /* If the size of "long double" is not more than 8, then
169 ** high-precision math is not possible. */
170 return 0;
171 }else{
172 /* Just because sizeof(long double)>8 does not mean that the underlying
173 ** hardware actually supports high-precision floating point. For example,
174 ** clearing the 0x100 bit in the floating-point control word on Intel
175 ** processors will make long double work like double, even though long
176 ** double takes up more space. The only way to determine if long double
177 ** actually works is to run an experiment. */
178 LONGDOUBLE_TYPE a, b, c;
179 rc++;
180 a = 1.0+rc*0.1;
181 b = 1.0e+18+rc*25.0;
182 c = a+b;
183 return b!=c;
189 ** Initialize SQLite.
191 ** This routine must be called to initialize the memory allocation,
192 ** VFS, and mutex subsystems prior to doing any serious work with
193 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
194 ** this routine will be called automatically by key routines such as
195 ** sqlite3_open().
197 ** This routine is a no-op except on its very first call for the process,
198 ** or for the first call after a call to sqlite3_shutdown.
200 ** The first thread to call this routine runs the initialization to
201 ** completion. If subsequent threads call this routine before the first
202 ** thread has finished the initialization process, then the subsequent
203 ** threads must block until the first thread finishes with the initialization.
205 ** The first thread might call this routine recursively. Recursive
206 ** calls to this routine should not block, of course. Otherwise the
207 ** initialization process would never complete.
209 ** Let X be the first thread to enter this routine. Let Y be some other
210 ** thread. Then while the initial invocation of this routine by X is
211 ** incomplete, it is required that:
213 ** * Calls to this routine from Y must block until the outer-most
214 ** call by X completes.
216 ** * Recursive calls to this routine from thread X return immediately
217 ** without blocking.
219 int sqlite3_initialize(void){
220 MUTEX_LOGIC( sqlite3_mutex *pMainMtx; ) /* The main static mutex */
221 int rc; /* Result code */
222 #ifdef SQLITE_EXTRA_INIT
223 int bRunExtraInit = 0; /* Extra initialization needed */
224 #endif
226 #ifdef SQLITE_OMIT_WSD
227 rc = sqlite3_wsd_init(4096, 24);
228 if( rc!=SQLITE_OK ){
229 return rc;
231 #endif
233 /* If the following assert() fails on some obscure processor/compiler
234 ** combination, the work-around is to set the correct pointer
235 ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
236 assert( SQLITE_PTRSIZE==sizeof(char*) );
238 /* If SQLite is already completely initialized, then this call
239 ** to sqlite3_initialize() should be a no-op. But the initialization
240 ** must be complete. So isInit must not be set until the very end
241 ** of this routine.
243 if( sqlite3GlobalConfig.isInit ){
244 sqlite3MemoryBarrier();
245 return SQLITE_OK;
248 /* Make sure the mutex subsystem is initialized. If unable to
249 ** initialize the mutex subsystem, return early with the error.
250 ** If the system is so sick that we are unable to allocate a mutex,
251 ** there is not much SQLite is going to be able to do.
253 ** The mutex subsystem must take care of serializing its own
254 ** initialization.
256 rc = sqlite3MutexInit();
257 if( rc ) return rc;
259 /* Initialize the malloc() system and the recursive pInitMutex mutex.
260 ** This operation is protected by the STATIC_MAIN mutex. Note that
261 ** MutexAlloc() is called for a static mutex prior to initializing the
262 ** malloc subsystem - this implies that the allocation of a static
263 ** mutex must not require support from the malloc subsystem.
265 MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
266 sqlite3_mutex_enter(pMainMtx);
267 sqlite3GlobalConfig.isMutexInit = 1;
268 if( !sqlite3GlobalConfig.isMallocInit ){
269 rc = sqlite3MallocInit();
271 if( rc==SQLITE_OK ){
272 sqlite3GlobalConfig.isMallocInit = 1;
273 if( !sqlite3GlobalConfig.pInitMutex ){
274 sqlite3GlobalConfig.pInitMutex =
275 sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
276 if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
277 rc = SQLITE_NOMEM_BKPT;
281 if( rc==SQLITE_OK ){
282 sqlite3GlobalConfig.nRefInitMutex++;
284 sqlite3_mutex_leave(pMainMtx);
286 /* If rc is not SQLITE_OK at this point, then either the malloc
287 ** subsystem could not be initialized or the system failed to allocate
288 ** the pInitMutex mutex. Return an error in either case. */
289 if( rc!=SQLITE_OK ){
290 return rc;
293 /* Do the rest of the initialization under the recursive mutex so
294 ** that we will be able to handle recursive calls into
295 ** sqlite3_initialize(). The recursive calls normally come through
296 ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
297 ** recursive calls might also be possible.
299 ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
300 ** to the xInit method, so the xInit method need not be threadsafe.
302 ** The following mutex is what serializes access to the appdef pcache xInit
303 ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
304 ** call to sqlite3PcacheInitialize().
306 sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
307 if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
308 sqlite3GlobalConfig.inProgress = 1;
309 #ifdef SQLITE_ENABLE_SQLLOG
311 extern void sqlite3_init_sqllog(void);
312 sqlite3_init_sqllog();
314 #endif
315 memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
316 sqlite3RegisterBuiltinFunctions();
317 if( sqlite3GlobalConfig.isPCacheInit==0 ){
318 rc = sqlite3PcacheInitialize();
320 if( rc==SQLITE_OK ){
321 sqlite3GlobalConfig.isPCacheInit = 1;
322 rc = sqlite3OsInit();
324 #ifndef SQLITE_OMIT_DESERIALIZE
325 if( rc==SQLITE_OK ){
326 rc = sqlite3MemdbInit();
328 #endif
329 if( rc==SQLITE_OK ){
330 sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
331 sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
332 sqlite3MemoryBarrier();
333 sqlite3GlobalConfig.isInit = 1;
334 #ifdef SQLITE_EXTRA_INIT
335 bRunExtraInit = 1;
336 #endif
338 sqlite3GlobalConfig.inProgress = 0;
340 sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
342 /* Go back under the static mutex and clean up the recursive
343 ** mutex to prevent a resource leak.
345 sqlite3_mutex_enter(pMainMtx);
346 sqlite3GlobalConfig.nRefInitMutex--;
347 if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
348 assert( sqlite3GlobalConfig.nRefInitMutex==0 );
349 sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
350 sqlite3GlobalConfig.pInitMutex = 0;
352 sqlite3_mutex_leave(pMainMtx);
354 /* The following is just a sanity check to make sure SQLite has
355 ** been compiled correctly. It is important to run this code, but
356 ** we don't want to run it too often and soak up CPU cycles for no
357 ** reason. So we run it once during initialization.
359 #ifndef NDEBUG
360 #ifndef SQLITE_OMIT_FLOATING_POINT
361 /* This section of code's only "output" is via assert() statements. */
362 if( rc==SQLITE_OK ){
363 u64 x = (((u64)1)<<63)-1;
364 double y;
365 assert(sizeof(x)==8);
366 assert(sizeof(x)==sizeof(y));
367 memcpy(&y, &x, 8);
368 assert( sqlite3IsNaN(y) );
370 #endif
371 #endif
373 /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
374 ** compile-time option.
376 #ifdef SQLITE_EXTRA_INIT
377 if( bRunExtraInit ){
378 int SQLITE_EXTRA_INIT(const char*);
379 rc = SQLITE_EXTRA_INIT(0);
381 #endif
383 /* Experimentally determine if high-precision floating point is
384 ** available. */
385 #ifndef SQLITE_OMIT_WSD
386 sqlite3Config.bUseLongDouble = hasHighPrecisionDouble(rc);
387 #endif
389 return rc;
393 ** Undo the effects of sqlite3_initialize(). Must not be called while
394 ** there are outstanding database connections or memory allocations or
395 ** while any part of SQLite is otherwise in use in any thread. This
396 ** routine is not threadsafe. But it is safe to invoke this routine
397 ** on when SQLite is already shut down. If SQLite is already shut down
398 ** when this routine is invoked, then this routine is a harmless no-op.
400 int sqlite3_shutdown(void){
401 #ifdef SQLITE_OMIT_WSD
402 int rc = sqlite3_wsd_init(4096, 24);
403 if( rc!=SQLITE_OK ){
404 return rc;
406 #endif
408 if( sqlite3GlobalConfig.isInit ){
409 #ifdef SQLITE_EXTRA_SHUTDOWN
410 void SQLITE_EXTRA_SHUTDOWN(void);
411 SQLITE_EXTRA_SHUTDOWN();
412 #endif
413 sqlite3_os_end();
414 sqlite3_reset_auto_extension();
415 sqlite3GlobalConfig.isInit = 0;
417 if( sqlite3GlobalConfig.isPCacheInit ){
418 sqlite3PcacheShutdown();
419 sqlite3GlobalConfig.isPCacheInit = 0;
421 if( sqlite3GlobalConfig.isMallocInit ){
422 sqlite3MallocEnd();
423 sqlite3GlobalConfig.isMallocInit = 0;
425 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
426 /* The heap subsystem has now been shutdown and these values are supposed
427 ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
428 ** which would rely on that heap subsystem; therefore, make sure these
429 ** values cannot refer to heap memory that was just invalidated when the
430 ** heap subsystem was shutdown. This is only done if the current call to
431 ** this function resulted in the heap subsystem actually being shutdown.
433 sqlite3_data_directory = 0;
434 sqlite3_temp_directory = 0;
435 #endif
437 if( sqlite3GlobalConfig.isMutexInit ){
438 sqlite3MutexEnd();
439 sqlite3GlobalConfig.isMutexInit = 0;
442 return SQLITE_OK;
446 ** This API allows applications to modify the global configuration of
447 ** the SQLite library at run-time.
449 ** This routine should only be called when there are no outstanding
450 ** database connections or memory allocations. This routine is not
451 ** threadsafe. Failure to heed these warnings can lead to unpredictable
452 ** behavior.
454 int sqlite3_config(int op, ...){
455 va_list ap;
456 int rc = SQLITE_OK;
458 /* sqlite3_config() normally returns SQLITE_MISUSE if it is invoked while
459 ** the SQLite library is in use. Except, a few selected opcodes
460 ** are allowed.
462 if( sqlite3GlobalConfig.isInit ){
463 static const u64 mAnytimeConfigOption = 0
464 | MASKBIT64( SQLITE_CONFIG_LOG )
465 | MASKBIT64( SQLITE_CONFIG_PCACHE_HDRSZ )
467 if( op<0 || op>63 || (MASKBIT64(op) & mAnytimeConfigOption)==0 ){
468 return SQLITE_MISUSE_BKPT;
470 testcase( op==SQLITE_CONFIG_LOG );
471 testcase( op==SQLITE_CONFIG_PCACHE_HDRSZ );
474 va_start(ap, op);
475 switch( op ){
477 /* Mutex configuration options are only available in a threadsafe
478 ** compile.
480 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
481 case SQLITE_CONFIG_SINGLETHREAD: {
482 /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
483 ** Single-thread. */
484 sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
485 sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
486 break;
488 #endif
489 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
490 case SQLITE_CONFIG_MULTITHREAD: {
491 /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
492 ** Multi-thread. */
493 sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
494 sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
495 break;
497 #endif
498 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
499 case SQLITE_CONFIG_SERIALIZED: {
500 /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
501 ** Serialized. */
502 sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
503 sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
504 break;
506 #endif
507 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
508 case SQLITE_CONFIG_MUTEX: {
509 /* Specify an alternative mutex implementation */
510 sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
511 break;
513 #endif
514 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
515 case SQLITE_CONFIG_GETMUTEX: {
516 /* Retrieve the current mutex implementation */
517 *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
518 break;
520 #endif
522 case SQLITE_CONFIG_MALLOC: {
523 /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
524 ** single argument which is a pointer to an instance of the
525 ** sqlite3_mem_methods structure. The argument specifies alternative
526 ** low-level memory allocation routines to be used in place of the memory
527 ** allocation routines built into SQLite. */
528 sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
529 break;
531 case SQLITE_CONFIG_GETMALLOC: {
532 /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
533 ** single argument which is a pointer to an instance of the
534 ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
535 ** filled with the currently defined memory allocation routines. */
536 if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
537 *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
538 break;
540 case SQLITE_CONFIG_MEMSTATUS: {
541 assert( !sqlite3GlobalConfig.isInit ); /* Cannot change at runtime */
542 /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
543 ** single argument of type int, interpreted as a boolean, which enables
544 ** or disables the collection of memory allocation statistics. */
545 sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
546 break;
548 case SQLITE_CONFIG_SMALL_MALLOC: {
549 sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
550 break;
552 case SQLITE_CONFIG_PAGECACHE: {
553 /* EVIDENCE-OF: R-18761-36601 There are three arguments to
554 ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
555 ** the size of each page cache line (sz), and the number of cache lines
556 ** (N). */
557 sqlite3GlobalConfig.pPage = va_arg(ap, void*);
558 sqlite3GlobalConfig.szPage = va_arg(ap, int);
559 sqlite3GlobalConfig.nPage = va_arg(ap, int);
560 break;
562 case SQLITE_CONFIG_PCACHE_HDRSZ: {
563 /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
564 ** a single parameter which is a pointer to an integer and writes into
565 ** that integer the number of extra bytes per page required for each page
566 ** in SQLITE_CONFIG_PAGECACHE. */
567 *va_arg(ap, int*) =
568 sqlite3HeaderSizeBtree() +
569 sqlite3HeaderSizePcache() +
570 sqlite3HeaderSizePcache1();
571 break;
574 case SQLITE_CONFIG_PCACHE: {
575 /* no-op */
576 break;
578 case SQLITE_CONFIG_GETPCACHE: {
579 /* now an error */
580 rc = SQLITE_ERROR;
581 break;
584 case SQLITE_CONFIG_PCACHE2: {
585 /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
586 ** single argument which is a pointer to an sqlite3_pcache_methods2
587 ** object. This object specifies the interface to a custom page cache
588 ** implementation. */
589 sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
590 break;
592 case SQLITE_CONFIG_GETPCACHE2: {
593 /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
594 ** single argument which is a pointer to an sqlite3_pcache_methods2
595 ** object. SQLite copies of the current page cache implementation into
596 ** that object. */
597 if( sqlite3GlobalConfig.pcache2.xInit==0 ){
598 sqlite3PCacheSetDefault();
600 *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
601 break;
604 /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
605 ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
606 ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
607 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
608 case SQLITE_CONFIG_HEAP: {
609 /* EVIDENCE-OF: R-19854-42126 There are three arguments to
610 ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
611 ** number of bytes in the memory buffer, and the minimum allocation size.
613 sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
614 sqlite3GlobalConfig.nHeap = va_arg(ap, int);
615 sqlite3GlobalConfig.mnReq = va_arg(ap, int);
617 if( sqlite3GlobalConfig.mnReq<1 ){
618 sqlite3GlobalConfig.mnReq = 1;
619 }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
620 /* cap min request size at 2^12 */
621 sqlite3GlobalConfig.mnReq = (1<<12);
624 if( sqlite3GlobalConfig.pHeap==0 ){
625 /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
626 ** is NULL, then SQLite reverts to using its default memory allocator
627 ** (the system malloc() implementation), undoing any prior invocation of
628 ** SQLITE_CONFIG_MALLOC.
630 ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
631 ** revert to its default implementation when sqlite3_initialize() is run
633 memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
634 }else{
635 /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
636 ** alternative memory allocator is engaged to handle all of SQLites
637 ** memory allocation needs. */
638 #ifdef SQLITE_ENABLE_MEMSYS3
639 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
640 #endif
641 #ifdef SQLITE_ENABLE_MEMSYS5
642 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
643 #endif
645 break;
647 #endif
649 case SQLITE_CONFIG_LOOKASIDE: {
650 sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
651 sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
652 break;
655 /* Record a pointer to the logger function and its first argument.
656 ** The default is NULL. Logging is disabled if the function pointer is
657 ** NULL.
659 case SQLITE_CONFIG_LOG: {
660 /* MSVC is picky about pulling func ptrs from va lists.
661 ** http://support.microsoft.com/kb/47961
662 ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
664 typedef void(*LOGFUNC_t)(void*,int,const char*);
665 LOGFUNC_t xLog = va_arg(ap, LOGFUNC_t);
666 void *pLogArg = va_arg(ap, void*);
667 AtomicStore(&sqlite3GlobalConfig.xLog, xLog);
668 AtomicStore(&sqlite3GlobalConfig.pLogArg, pLogArg);
669 break;
672 /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
673 ** can be changed at start-time using the
674 ** sqlite3_config(SQLITE_CONFIG_URI,1) or
675 ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
677 case SQLITE_CONFIG_URI: {
678 /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
679 ** argument of type int. If non-zero, then URI handling is globally
680 ** enabled. If the parameter is zero, then URI handling is globally
681 ** disabled. */
682 int bOpenUri = va_arg(ap, int);
683 AtomicStore(&sqlite3GlobalConfig.bOpenUri, bOpenUri);
684 break;
687 case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
688 /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
689 ** option takes a single integer argument which is interpreted as a
690 ** boolean in order to enable or disable the use of covering indices for
691 ** full table scans in the query optimizer. */
692 sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
693 break;
696 #ifdef SQLITE_ENABLE_SQLLOG
697 case SQLITE_CONFIG_SQLLOG: {
698 typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
699 sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
700 sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
701 break;
703 #endif
705 case SQLITE_CONFIG_MMAP_SIZE: {
706 /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
707 ** integer (sqlite3_int64) values that are the default mmap size limit
708 ** (the default setting for PRAGMA mmap_size) and the maximum allowed
709 ** mmap size limit. */
710 sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
711 sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
712 /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
713 ** negative, then that argument is changed to its compile-time default.
715 ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
716 ** silently truncated if necessary so that it does not exceed the
717 ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
718 ** compile-time option.
720 if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
721 mxMmap = SQLITE_MAX_MMAP_SIZE;
723 if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
724 if( szMmap>mxMmap) szMmap = mxMmap;
725 sqlite3GlobalConfig.mxMmap = mxMmap;
726 sqlite3GlobalConfig.szMmap = szMmap;
727 break;
730 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
731 case SQLITE_CONFIG_WIN32_HEAPSIZE: {
732 /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
733 ** unsigned integer value that specifies the maximum size of the created
734 ** heap. */
735 sqlite3GlobalConfig.nHeap = va_arg(ap, int);
736 break;
738 #endif
740 case SQLITE_CONFIG_PMASZ: {
741 sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
742 break;
745 case SQLITE_CONFIG_STMTJRNL_SPILL: {
746 sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
747 break;
750 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
751 case SQLITE_CONFIG_SORTERREF_SIZE: {
752 int iVal = va_arg(ap, int);
753 if( iVal<0 ){
754 iVal = SQLITE_DEFAULT_SORTERREF_SIZE;
756 sqlite3GlobalConfig.szSorterRef = (u32)iVal;
757 break;
759 #endif /* SQLITE_ENABLE_SORTER_REFERENCES */
761 #ifndef SQLITE_OMIT_DESERIALIZE
762 case SQLITE_CONFIG_MEMDB_MAXSIZE: {
763 sqlite3GlobalConfig.mxMemdbSize = va_arg(ap, sqlite3_int64);
764 break;
766 #endif /* SQLITE_OMIT_DESERIALIZE */
768 default: {
769 rc = SQLITE_ERROR;
770 break;
773 va_end(ap);
774 return rc;
778 ** Set up the lookaside buffers for a database connection.
779 ** Return SQLITE_OK on success.
780 ** If lookaside is already active, return SQLITE_BUSY.
782 ** The sz parameter is the number of bytes in each lookaside slot.
783 ** The cnt parameter is the number of slots. If pStart is NULL the
784 ** space for the lookaside memory is obtained from sqlite3_malloc().
785 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
786 ** the lookaside memory.
788 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
789 #ifndef SQLITE_OMIT_LOOKASIDE
790 void *pStart;
791 sqlite3_int64 szAlloc = sz*(sqlite3_int64)cnt;
792 int nBig; /* Number of full-size slots */
793 int nSm; /* Number smaller LOOKASIDE_SMALL-byte slots */
795 if( sqlite3LookasideUsed(db,0)>0 ){
796 return SQLITE_BUSY;
798 /* Free any existing lookaside buffer for this handle before
799 ** allocating a new one so we don't have to have space for
800 ** both at the same time.
802 if( db->lookaside.bMalloced ){
803 sqlite3_free(db->lookaside.pStart);
805 /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
806 ** than a pointer to be useful.
808 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
809 if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
810 if( cnt<0 ) cnt = 0;
811 if( sz==0 || cnt==0 ){
812 sz = 0;
813 pStart = 0;
814 }else if( pBuf==0 ){
815 sqlite3BeginBenignMalloc();
816 pStart = sqlite3Malloc( szAlloc ); /* IMP: R-61949-35727 */
817 sqlite3EndBenignMalloc();
818 if( pStart ) szAlloc = sqlite3MallocSize(pStart);
819 }else{
820 pStart = pBuf;
822 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
823 if( sz>=LOOKASIDE_SMALL*3 ){
824 nBig = szAlloc/(3*LOOKASIDE_SMALL+sz);
825 nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
826 }else if( sz>=LOOKASIDE_SMALL*2 ){
827 nBig = szAlloc/(LOOKASIDE_SMALL+sz);
828 nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
829 }else
830 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
831 if( sz>0 ){
832 nBig = szAlloc/sz;
833 nSm = 0;
834 }else{
835 nBig = nSm = 0;
837 db->lookaside.pStart = pStart;
838 db->lookaside.pInit = 0;
839 db->lookaside.pFree = 0;
840 db->lookaside.sz = (u16)sz;
841 db->lookaside.szTrue = (u16)sz;
842 if( pStart ){
843 int i;
844 LookasideSlot *p;
845 assert( sz > (int)sizeof(LookasideSlot*) );
846 p = (LookasideSlot*)pStart;
847 for(i=0; i<nBig; i++){
848 p->pNext = db->lookaside.pInit;
849 db->lookaside.pInit = p;
850 p = (LookasideSlot*)&((u8*)p)[sz];
852 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
853 db->lookaside.pSmallInit = 0;
854 db->lookaside.pSmallFree = 0;
855 db->lookaside.pMiddle = p;
856 for(i=0; i<nSm; i++){
857 p->pNext = db->lookaside.pSmallInit;
858 db->lookaside.pSmallInit = p;
859 p = (LookasideSlot*)&((u8*)p)[LOOKASIDE_SMALL];
861 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
862 assert( ((uptr)p)<=szAlloc + (uptr)pStart );
863 db->lookaside.pEnd = p;
864 db->lookaside.bDisable = 0;
865 db->lookaside.bMalloced = pBuf==0 ?1:0;
866 db->lookaside.nSlot = nBig+nSm;
867 }else{
868 db->lookaside.pStart = 0;
869 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
870 db->lookaside.pSmallInit = 0;
871 db->lookaside.pSmallFree = 0;
872 db->lookaside.pMiddle = 0;
873 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
874 db->lookaside.pEnd = 0;
875 db->lookaside.bDisable = 1;
876 db->lookaside.sz = 0;
877 db->lookaside.bMalloced = 0;
878 db->lookaside.nSlot = 0;
880 db->lookaside.pTrueEnd = db->lookaside.pEnd;
881 assert( sqlite3LookasideUsed(db,0)==0 );
882 #endif /* SQLITE_OMIT_LOOKASIDE */
883 return SQLITE_OK;
887 ** Return the mutex associated with a database connection.
889 sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
890 #ifdef SQLITE_ENABLE_API_ARMOR
891 if( !sqlite3SafetyCheckOk(db) ){
892 (void)SQLITE_MISUSE_BKPT;
893 return 0;
895 #endif
896 return db->mutex;
900 ** Free up as much memory as we can from the given database
901 ** connection.
903 int sqlite3_db_release_memory(sqlite3 *db){
904 int i;
906 #ifdef SQLITE_ENABLE_API_ARMOR
907 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
908 #endif
909 sqlite3_mutex_enter(db->mutex);
910 sqlite3BtreeEnterAll(db);
911 for(i=0; i<db->nDb; i++){
912 Btree *pBt = db->aDb[i].pBt;
913 if( pBt ){
914 Pager *pPager = sqlite3BtreePager(pBt);
915 sqlite3PagerShrink(pPager);
918 sqlite3BtreeLeaveAll(db);
919 sqlite3_mutex_leave(db->mutex);
920 return SQLITE_OK;
924 ** Flush any dirty pages in the pager-cache for any attached database
925 ** to disk.
927 int sqlite3_db_cacheflush(sqlite3 *db){
928 int i;
929 int rc = SQLITE_OK;
930 int bSeenBusy = 0;
932 #ifdef SQLITE_ENABLE_API_ARMOR
933 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
934 #endif
935 sqlite3_mutex_enter(db->mutex);
936 sqlite3BtreeEnterAll(db);
937 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
938 Btree *pBt = db->aDb[i].pBt;
939 if( pBt && sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
940 Pager *pPager = sqlite3BtreePager(pBt);
941 rc = sqlite3PagerFlush(pPager);
942 if( rc==SQLITE_BUSY ){
943 bSeenBusy = 1;
944 rc = SQLITE_OK;
948 sqlite3BtreeLeaveAll(db);
949 sqlite3_mutex_leave(db->mutex);
950 return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
954 ** Configuration settings for an individual database connection
956 int sqlite3_db_config(sqlite3 *db, int op, ...){
957 va_list ap;
958 int rc;
960 #ifdef SQLITE_ENABLE_API_ARMOR
961 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
962 #endif
963 sqlite3_mutex_enter(db->mutex);
964 va_start(ap, op);
965 switch( op ){
966 case SQLITE_DBCONFIG_MAINDBNAME: {
967 /* IMP: R-06824-28531 */
968 /* IMP: R-36257-52125 */
969 db->aDb[0].zDbSName = va_arg(ap,char*);
970 rc = SQLITE_OK;
971 break;
973 case SQLITE_DBCONFIG_LOOKASIDE: {
974 void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
975 int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
976 int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
977 rc = setupLookaside(db, pBuf, sz, cnt);
978 break;
980 default: {
981 static const struct {
982 int op; /* The opcode */
983 u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
984 } aFlagOp[] = {
985 { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
986 { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
987 { SQLITE_DBCONFIG_ENABLE_VIEW, SQLITE_EnableView },
988 { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
989 { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension },
990 { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose },
991 { SQLITE_DBCONFIG_ENABLE_QPSG, SQLITE_EnableQPSG },
992 { SQLITE_DBCONFIG_TRIGGER_EQP, SQLITE_TriggerEQP },
993 { SQLITE_DBCONFIG_RESET_DATABASE, SQLITE_ResetDatabase },
994 { SQLITE_DBCONFIG_DEFENSIVE, SQLITE_Defensive },
995 { SQLITE_DBCONFIG_WRITABLE_SCHEMA, SQLITE_WriteSchema|
996 SQLITE_NoSchemaError },
997 { SQLITE_DBCONFIG_LEGACY_ALTER_TABLE, SQLITE_LegacyAlter },
998 { SQLITE_DBCONFIG_DQS_DDL, SQLITE_DqsDDL },
999 { SQLITE_DBCONFIG_DQS_DML, SQLITE_DqsDML },
1000 { SQLITE_DBCONFIG_LEGACY_FILE_FORMAT, SQLITE_LegacyFileFmt },
1001 { SQLITE_DBCONFIG_TRUSTED_SCHEMA, SQLITE_TrustedSchema },
1002 { SQLITE_DBCONFIG_STMT_SCANSTATUS, SQLITE_StmtScanStatus },
1003 { SQLITE_DBCONFIG_REVERSE_SCANORDER, SQLITE_ReverseOrder },
1005 unsigned int i;
1006 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
1007 for(i=0; i<ArraySize(aFlagOp); i++){
1008 if( aFlagOp[i].op==op ){
1009 int onoff = va_arg(ap, int);
1010 int *pRes = va_arg(ap, int*);
1011 u64 oldFlags = db->flags;
1012 if( onoff>0 ){
1013 db->flags |= aFlagOp[i].mask;
1014 }else if( onoff==0 ){
1015 db->flags &= ~(u64)aFlagOp[i].mask;
1017 if( oldFlags!=db->flags ){
1018 sqlite3ExpirePreparedStatements(db, 0);
1020 if( pRes ){
1021 *pRes = (db->flags & aFlagOp[i].mask)!=0;
1023 rc = SQLITE_OK;
1024 break;
1027 break;
1030 va_end(ap);
1031 sqlite3_mutex_leave(db->mutex);
1032 return rc;
1036 ** This is the default collating function named "BINARY" which is always
1037 ** available.
1039 static int binCollFunc(
1040 void *NotUsed,
1041 int nKey1, const void *pKey1,
1042 int nKey2, const void *pKey2
1044 int rc, n;
1045 UNUSED_PARAMETER(NotUsed);
1046 n = nKey1<nKey2 ? nKey1 : nKey2;
1047 /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
1048 ** strings byte by byte using the memcmp() function from the standard C
1049 ** library. */
1050 assert( pKey1 && pKey2 );
1051 rc = memcmp(pKey1, pKey2, n);
1052 if( rc==0 ){
1053 rc = nKey1 - nKey2;
1055 return rc;
1059 ** This is the collating function named "RTRIM" which is always
1060 ** available. Ignore trailing spaces.
1062 static int rtrimCollFunc(
1063 void *pUser,
1064 int nKey1, const void *pKey1,
1065 int nKey2, const void *pKey2
1067 const u8 *pK1 = (const u8*)pKey1;
1068 const u8 *pK2 = (const u8*)pKey2;
1069 while( nKey1 && pK1[nKey1-1]==' ' ) nKey1--;
1070 while( nKey2 && pK2[nKey2-1]==' ' ) nKey2--;
1071 return binCollFunc(pUser, nKey1, pKey1, nKey2, pKey2);
1075 ** Return true if CollSeq is the default built-in BINARY.
1077 int sqlite3IsBinary(const CollSeq *p){
1078 assert( p==0 || p->xCmp!=binCollFunc || strcmp(p->zName,"BINARY")==0 );
1079 return p==0 || p->xCmp==binCollFunc;
1083 ** Another built-in collating sequence: NOCASE.
1085 ** This collating sequence is intended to be used for "case independent
1086 ** comparison". SQLite's knowledge of upper and lower case equivalents
1087 ** extends only to the 26 characters used in the English language.
1089 ** At the moment there is only a UTF-8 implementation.
1091 static int nocaseCollatingFunc(
1092 void *NotUsed,
1093 int nKey1, const void *pKey1,
1094 int nKey2, const void *pKey2
1096 int r = sqlite3StrNICmp(
1097 (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
1098 UNUSED_PARAMETER(NotUsed);
1099 if( 0==r ){
1100 r = nKey1-nKey2;
1102 return r;
1106 ** Return the ROWID of the most recent insert
1108 sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
1109 #ifdef SQLITE_ENABLE_API_ARMOR
1110 if( !sqlite3SafetyCheckOk(db) ){
1111 (void)SQLITE_MISUSE_BKPT;
1112 return 0;
1114 #endif
1115 return db->lastRowid;
1119 ** Set the value returned by the sqlite3_last_insert_rowid() API function.
1121 void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
1122 #ifdef SQLITE_ENABLE_API_ARMOR
1123 if( !sqlite3SafetyCheckOk(db) ){
1124 (void)SQLITE_MISUSE_BKPT;
1125 return;
1127 #endif
1128 sqlite3_mutex_enter(db->mutex);
1129 db->lastRowid = iRowid;
1130 sqlite3_mutex_leave(db->mutex);
1134 ** Return the number of changes in the most recent call to sqlite3_exec().
1136 sqlite3_int64 sqlite3_changes64(sqlite3 *db){
1137 #ifdef SQLITE_ENABLE_API_ARMOR
1138 if( !sqlite3SafetyCheckOk(db) ){
1139 (void)SQLITE_MISUSE_BKPT;
1140 return 0;
1142 #endif
1143 return db->nChange;
1145 int sqlite3_changes(sqlite3 *db){
1146 return (int)sqlite3_changes64(db);
1150 ** Return the number of changes since the database handle was opened.
1152 sqlite3_int64 sqlite3_total_changes64(sqlite3 *db){
1153 #ifdef SQLITE_ENABLE_API_ARMOR
1154 if( !sqlite3SafetyCheckOk(db) ){
1155 (void)SQLITE_MISUSE_BKPT;
1156 return 0;
1158 #endif
1159 return db->nTotalChange;
1161 int sqlite3_total_changes(sqlite3 *db){
1162 return (int)sqlite3_total_changes64(db);
1166 ** Close all open savepoints. This function only manipulates fields of the
1167 ** database handle object, it does not close any savepoints that may be open
1168 ** at the b-tree/pager level.
1170 void sqlite3CloseSavepoints(sqlite3 *db){
1171 while( db->pSavepoint ){
1172 Savepoint *pTmp = db->pSavepoint;
1173 db->pSavepoint = pTmp->pNext;
1174 sqlite3DbFree(db, pTmp);
1176 db->nSavepoint = 0;
1177 db->nStatement = 0;
1178 db->isTransactionSavepoint = 0;
1182 ** Invoke the destructor function associated with FuncDef p, if any. Except,
1183 ** if this is not the last copy of the function, do not invoke it. Multiple
1184 ** copies of a single function are created when create_function() is called
1185 ** with SQLITE_ANY as the encoding.
1187 static void functionDestroy(sqlite3 *db, FuncDef *p){
1188 FuncDestructor *pDestructor;
1189 assert( (p->funcFlags & SQLITE_FUNC_BUILTIN)==0 );
1190 pDestructor = p->u.pDestructor;
1191 if( pDestructor ){
1192 pDestructor->nRef--;
1193 if( pDestructor->nRef==0 ){
1194 pDestructor->xDestroy(pDestructor->pUserData);
1195 sqlite3DbFree(db, pDestructor);
1201 ** Disconnect all sqlite3_vtab objects that belong to database connection
1202 ** db. This is called when db is being closed.
1204 static void disconnectAllVtab(sqlite3 *db){
1205 #ifndef SQLITE_OMIT_VIRTUALTABLE
1206 int i;
1207 HashElem *p;
1208 sqlite3BtreeEnterAll(db);
1209 for(i=0; i<db->nDb; i++){
1210 Schema *pSchema = db->aDb[i].pSchema;
1211 if( pSchema ){
1212 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
1213 Table *pTab = (Table *)sqliteHashData(p);
1214 if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
1218 for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
1219 Module *pMod = (Module *)sqliteHashData(p);
1220 if( pMod->pEpoTab ){
1221 sqlite3VtabDisconnect(db, pMod->pEpoTab);
1224 sqlite3VtabUnlockList(db);
1225 sqlite3BtreeLeaveAll(db);
1226 #else
1227 UNUSED_PARAMETER(db);
1228 #endif
1232 ** Return TRUE if database connection db has unfinalized prepared
1233 ** statements or unfinished sqlite3_backup objects.
1235 static int connectionIsBusy(sqlite3 *db){
1236 int j;
1237 assert( sqlite3_mutex_held(db->mutex) );
1238 if( db->pVdbe ) return 1;
1239 for(j=0; j<db->nDb; j++){
1240 Btree *pBt = db->aDb[j].pBt;
1241 if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
1243 return 0;
1247 ** Close an existing SQLite database
1249 static int sqlite3Close(sqlite3 *db, int forceZombie){
1250 if( !db ){
1251 /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
1252 ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
1253 return SQLITE_OK;
1255 if( !sqlite3SafetyCheckSickOrOk(db) ){
1256 return SQLITE_MISUSE_BKPT;
1258 sqlite3_mutex_enter(db->mutex);
1259 if( db->mTrace & SQLITE_TRACE_CLOSE ){
1260 db->trace.xV2(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
1263 /* Force xDisconnect calls on all virtual tables */
1264 disconnectAllVtab(db);
1266 /* If a transaction is open, the disconnectAllVtab() call above
1267 ** will not have called the xDisconnect() method on any virtual
1268 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
1269 ** call will do so. We need to do this before the check for active
1270 ** SQL statements below, as the v-table implementation may be storing
1271 ** some prepared statements internally.
1273 sqlite3VtabRollback(db);
1275 /* Legacy behavior (sqlite3_close() behavior) is to return
1276 ** SQLITE_BUSY if the connection can not be closed immediately.
1278 if( !forceZombie && connectionIsBusy(db) ){
1279 sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
1280 "statements or unfinished backups");
1281 sqlite3_mutex_leave(db->mutex);
1282 return SQLITE_BUSY;
1285 #ifdef SQLITE_ENABLE_SQLLOG
1286 if( sqlite3GlobalConfig.xSqllog ){
1287 /* Closing the handle. Fourth parameter is passed the value 2. */
1288 sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
1290 #endif
1292 while( db->pDbData ){
1293 DbClientData *p = db->pDbData;
1294 db->pDbData = p->pNext;
1295 assert( p->pData!=0 );
1296 if( p->xDestructor ) p->xDestructor(p->pData);
1297 sqlite3_free(p);
1300 /* Convert the connection into a zombie and then close it.
1302 db->eOpenState = SQLITE_STATE_ZOMBIE;
1303 sqlite3LeaveMutexAndCloseZombie(db);
1304 return SQLITE_OK;
1308 ** Return the transaction state for a single databse, or the maximum
1309 ** transaction state over all attached databases if zSchema is null.
1311 int sqlite3_txn_state(sqlite3 *db, const char *zSchema){
1312 int iDb, nDb;
1313 int iTxn = -1;
1314 #ifdef SQLITE_ENABLE_API_ARMOR
1315 if( !sqlite3SafetyCheckOk(db) ){
1316 (void)SQLITE_MISUSE_BKPT;
1317 return -1;
1319 #endif
1320 sqlite3_mutex_enter(db->mutex);
1321 if( zSchema ){
1322 nDb = iDb = sqlite3FindDbName(db, zSchema);
1323 if( iDb<0 ) nDb--;
1324 }else{
1325 iDb = 0;
1326 nDb = db->nDb-1;
1328 for(; iDb<=nDb; iDb++){
1329 Btree *pBt = db->aDb[iDb].pBt;
1330 int x = pBt!=0 ? sqlite3BtreeTxnState(pBt) : SQLITE_TXN_NONE;
1331 if( x>iTxn ) iTxn = x;
1333 sqlite3_mutex_leave(db->mutex);
1334 return iTxn;
1338 ** Two variations on the public interface for closing a database
1339 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
1340 ** leaves the connection open if there are unfinalized prepared
1341 ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
1342 ** version forces the connection to become a zombie if there are
1343 ** unclosed resources, and arranges for deallocation when the last
1344 ** prepare statement or sqlite3_backup closes.
1346 int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
1347 int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
1351 ** Close the mutex on database connection db.
1353 ** Furthermore, if database connection db is a zombie (meaning that there
1354 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
1355 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
1356 ** finished, then free all resources.
1358 void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
1359 HashElem *i; /* Hash table iterator */
1360 int j;
1362 /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
1363 ** or if the connection has not yet been closed by sqlite3_close_v2(),
1364 ** then just leave the mutex and return.
1366 if( db->eOpenState!=SQLITE_STATE_ZOMBIE || connectionIsBusy(db) ){
1367 sqlite3_mutex_leave(db->mutex);
1368 return;
1371 /* If we reach this point, it means that the database connection has
1372 ** closed all sqlite3_stmt and sqlite3_backup objects and has been
1373 ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
1374 ** go ahead and free all resources.
1377 /* If a transaction is open, roll it back. This also ensures that if
1378 ** any database schemas have been modified by an uncommitted transaction
1379 ** they are reset. And that the required b-tree mutex is held to make
1380 ** the pager rollback and schema reset an atomic operation. */
1381 sqlite3RollbackAll(db, SQLITE_OK);
1383 /* Free any outstanding Savepoint structures. */
1384 sqlite3CloseSavepoints(db);
1386 /* Close all database connections */
1387 for(j=0; j<db->nDb; j++){
1388 struct Db *pDb = &db->aDb[j];
1389 if( pDb->pBt ){
1390 sqlite3BtreeClose(pDb->pBt);
1391 pDb->pBt = 0;
1392 if( j!=1 ){
1393 pDb->pSchema = 0;
1397 /* Clear the TEMP schema separately and last */
1398 if( db->aDb[1].pSchema ){
1399 sqlite3SchemaClear(db->aDb[1].pSchema);
1401 sqlite3VtabUnlockList(db);
1403 /* Free up the array of auxiliary databases */
1404 sqlite3CollapseDatabaseArray(db);
1405 assert( db->nDb<=2 );
1406 assert( db->aDb==db->aDbStatic );
1408 /* Tell the code in notify.c that the connection no longer holds any
1409 ** locks and does not require any further unlock-notify callbacks.
1411 sqlite3ConnectionClosed(db);
1413 for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
1414 FuncDef *pNext, *p;
1415 p = sqliteHashData(i);
1417 functionDestroy(db, p);
1418 pNext = p->pNext;
1419 sqlite3DbFree(db, p);
1420 p = pNext;
1421 }while( p );
1423 sqlite3HashClear(&db->aFunc);
1424 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
1425 CollSeq *pColl = (CollSeq *)sqliteHashData(i);
1426 /* Invoke any destructors registered for collation sequence user data. */
1427 for(j=0; j<3; j++){
1428 if( pColl[j].xDel ){
1429 pColl[j].xDel(pColl[j].pUser);
1432 sqlite3DbFree(db, pColl);
1434 sqlite3HashClear(&db->aCollSeq);
1435 #ifndef SQLITE_OMIT_VIRTUALTABLE
1436 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
1437 Module *pMod = (Module *)sqliteHashData(i);
1438 sqlite3VtabEponymousTableClear(db, pMod);
1439 sqlite3VtabModuleUnref(db, pMod);
1441 sqlite3HashClear(&db->aModule);
1442 #endif
1444 sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
1445 sqlite3ValueFree(db->pErr);
1446 sqlite3CloseExtensions(db);
1447 #if SQLITE_USER_AUTHENTICATION
1448 sqlite3_free(db->auth.zAuthUser);
1449 sqlite3_free(db->auth.zAuthPW);
1450 #endif
1452 db->eOpenState = SQLITE_STATE_ERROR;
1454 /* The temp-database schema is allocated differently from the other schema
1455 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
1456 ** So it needs to be freed here. Todo: Why not roll the temp schema into
1457 ** the same sqliteMalloc() as the one that allocates the database
1458 ** structure?
1460 sqlite3DbFree(db, db->aDb[1].pSchema);
1461 if( db->xAutovacDestr ){
1462 db->xAutovacDestr(db->pAutovacPagesArg);
1464 sqlite3_mutex_leave(db->mutex);
1465 db->eOpenState = SQLITE_STATE_CLOSED;
1466 sqlite3_mutex_free(db->mutex);
1467 assert( sqlite3LookasideUsed(db,0)==0 );
1468 if( db->lookaside.bMalloced ){
1469 sqlite3_free(db->lookaside.pStart);
1471 sqlite3_free(db);
1475 ** Rollback all database files. If tripCode is not SQLITE_OK, then
1476 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
1477 ** breaker") and made to return tripCode if there are any further
1478 ** attempts to use that cursor. Read cursors remain open and valid
1479 ** but are "saved" in case the table pages are moved around.
1481 void sqlite3RollbackAll(sqlite3 *db, int tripCode){
1482 int i;
1483 int inTrans = 0;
1484 int schemaChange;
1485 assert( sqlite3_mutex_held(db->mutex) );
1486 sqlite3BeginBenignMalloc();
1488 /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
1489 ** This is important in case the transaction being rolled back has
1490 ** modified the database schema. If the b-tree mutexes are not taken
1491 ** here, then another shared-cache connection might sneak in between
1492 ** the database rollback and schema reset, which can cause false
1493 ** corruption reports in some cases. */
1494 sqlite3BtreeEnterAll(db);
1495 schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
1497 for(i=0; i<db->nDb; i++){
1498 Btree *p = db->aDb[i].pBt;
1499 if( p ){
1500 if( sqlite3BtreeTxnState(p)==SQLITE_TXN_WRITE ){
1501 inTrans = 1;
1503 sqlite3BtreeRollback(p, tripCode, !schemaChange);
1506 sqlite3VtabRollback(db);
1507 sqlite3EndBenignMalloc();
1509 if( schemaChange ){
1510 sqlite3ExpirePreparedStatements(db, 0);
1511 sqlite3ResetAllSchemasOfConnection(db);
1513 sqlite3BtreeLeaveAll(db);
1515 /* Any deferred constraint violations have now been resolved. */
1516 db->nDeferredCons = 0;
1517 db->nDeferredImmCons = 0;
1518 db->flags &= ~(u64)(SQLITE_DeferFKs|SQLITE_CorruptRdOnly);
1520 /* If one has been configured, invoke the rollback-hook callback */
1521 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
1522 db->xRollbackCallback(db->pRollbackArg);
1527 ** Return a static string containing the name corresponding to the error code
1528 ** specified in the argument.
1530 #if defined(SQLITE_NEED_ERR_NAME)
1531 const char *sqlite3ErrName(int rc){
1532 const char *zName = 0;
1533 int i, origRc = rc;
1534 for(i=0; i<2 && zName==0; i++, rc &= 0xff){
1535 switch( rc ){
1536 case SQLITE_OK: zName = "SQLITE_OK"; break;
1537 case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
1538 case SQLITE_ERROR_SNAPSHOT: zName = "SQLITE_ERROR_SNAPSHOT"; break;
1539 case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
1540 case SQLITE_PERM: zName = "SQLITE_PERM"; break;
1541 case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
1542 case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
1543 case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
1544 case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
1545 case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
1546 case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
1547 case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
1548 case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
1549 case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
1550 case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
1551 case SQLITE_READONLY_CANTINIT: zName = "SQLITE_READONLY_CANTINIT"; break;
1552 case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
1553 case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
1554 case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break;
1555 case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
1556 case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
1557 case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
1558 case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
1559 case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
1560 case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
1561 case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
1562 case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
1563 case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
1564 case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
1565 case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
1566 case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
1567 case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
1568 case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
1569 case SQLITE_IOERR_CHECKRESERVEDLOCK:
1570 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
1571 case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
1572 case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
1573 case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
1574 case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
1575 case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
1576 case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
1577 case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
1578 case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
1579 case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
1580 case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
1581 case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
1582 case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
1583 case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
1584 case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
1585 case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
1586 case SQLITE_FULL: zName = "SQLITE_FULL"; break;
1587 case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
1588 case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
1589 case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
1590 case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
1591 case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
1592 case SQLITE_CANTOPEN_SYMLINK: zName = "SQLITE_CANTOPEN_SYMLINK"; break;
1593 case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
1594 case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
1595 case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
1596 case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
1597 case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
1598 case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
1599 case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
1600 case SQLITE_CONSTRAINT_FOREIGNKEY:
1601 zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
1602 case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
1603 case SQLITE_CONSTRAINT_PRIMARYKEY:
1604 zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
1605 case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
1606 case SQLITE_CONSTRAINT_COMMITHOOK:
1607 zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
1608 case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
1609 case SQLITE_CONSTRAINT_FUNCTION:
1610 zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
1611 case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
1612 case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
1613 case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
1614 case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
1615 case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
1616 case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
1617 case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
1618 case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
1619 case SQLITE_ROW: zName = "SQLITE_ROW"; break;
1620 case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
1621 case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
1622 case SQLITE_NOTICE_RECOVER_ROLLBACK:
1623 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
1624 case SQLITE_NOTICE_RBU: zName = "SQLITE_NOTICE_RBU"; break;
1625 case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
1626 case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
1627 case SQLITE_DONE: zName = "SQLITE_DONE"; break;
1630 if( zName==0 ){
1631 static char zBuf[50];
1632 sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
1633 zName = zBuf;
1635 return zName;
1637 #endif
1640 ** Return a static string that describes the kind of error specified in the
1641 ** argument.
1643 const char *sqlite3ErrStr(int rc){
1644 static const char* const aMsg[] = {
1645 /* SQLITE_OK */ "not an error",
1646 /* SQLITE_ERROR */ "SQL logic error",
1647 /* SQLITE_INTERNAL */ 0,
1648 /* SQLITE_PERM */ "access permission denied",
1649 /* SQLITE_ABORT */ "query aborted",
1650 /* SQLITE_BUSY */ "database is locked",
1651 /* SQLITE_LOCKED */ "database table is locked",
1652 /* SQLITE_NOMEM */ "out of memory",
1653 /* SQLITE_READONLY */ "attempt to write a readonly database",
1654 /* SQLITE_INTERRUPT */ "interrupted",
1655 /* SQLITE_IOERR */ "disk I/O error",
1656 /* SQLITE_CORRUPT */ "database disk image is malformed",
1657 /* SQLITE_NOTFOUND */ "unknown operation",
1658 /* SQLITE_FULL */ "database or disk is full",
1659 /* SQLITE_CANTOPEN */ "unable to open database file",
1660 /* SQLITE_PROTOCOL */ "locking protocol",
1661 /* SQLITE_EMPTY */ 0,
1662 /* SQLITE_SCHEMA */ "database schema has changed",
1663 /* SQLITE_TOOBIG */ "string or blob too big",
1664 /* SQLITE_CONSTRAINT */ "constraint failed",
1665 /* SQLITE_MISMATCH */ "datatype mismatch",
1666 /* SQLITE_MISUSE */ "bad parameter or other API misuse",
1667 #ifdef SQLITE_DISABLE_LFS
1668 /* SQLITE_NOLFS */ "large file support is disabled",
1669 #else
1670 /* SQLITE_NOLFS */ 0,
1671 #endif
1672 /* SQLITE_AUTH */ "authorization denied",
1673 /* SQLITE_FORMAT */ 0,
1674 /* SQLITE_RANGE */ "column index out of range",
1675 /* SQLITE_NOTADB */ "file is not a database",
1676 /* SQLITE_NOTICE */ "notification message",
1677 /* SQLITE_WARNING */ "warning message",
1679 const char *zErr = "unknown error";
1680 switch( rc ){
1681 case SQLITE_ABORT_ROLLBACK: {
1682 zErr = "abort due to ROLLBACK";
1683 break;
1685 case SQLITE_ROW: {
1686 zErr = "another row available";
1687 break;
1689 case SQLITE_DONE: {
1690 zErr = "no more rows available";
1691 break;
1693 default: {
1694 rc &= 0xff;
1695 if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
1696 zErr = aMsg[rc];
1698 break;
1701 return zErr;
1705 ** This routine implements a busy callback that sleeps and tries
1706 ** again until a timeout value is reached. The timeout value is
1707 ** an integer number of milliseconds passed in as the first
1708 ** argument.
1710 ** Return non-zero to retry the lock. Return zero to stop trying
1711 ** and cause SQLite to return SQLITE_BUSY.
1713 static int sqliteDefaultBusyCallback(
1714 void *ptr, /* Database connection */
1715 int count /* Number of times table has been busy */
1717 #if SQLITE_OS_WIN || !defined(HAVE_NANOSLEEP) || HAVE_NANOSLEEP
1718 /* This case is for systems that have support for sleeping for fractions of
1719 ** a second. Examples: All windows systems, unix systems with nanosleep() */
1720 static const u8 delays[] =
1721 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
1722 static const u8 totals[] =
1723 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
1724 # define NDELAY ArraySize(delays)
1725 sqlite3 *db = (sqlite3 *)ptr;
1726 int tmout = db->busyTimeout;
1727 int delay, prior;
1729 assert( count>=0 );
1730 if( count < NDELAY ){
1731 delay = delays[count];
1732 prior = totals[count];
1733 }else{
1734 delay = delays[NDELAY-1];
1735 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
1737 if( prior + delay > tmout ){
1738 delay = tmout - prior;
1739 if( delay<=0 ) return 0;
1741 sqlite3OsSleep(db->pVfs, delay*1000);
1742 return 1;
1743 #else
1744 /* This case for unix systems that lack usleep() support. Sleeping
1745 ** must be done in increments of whole seconds */
1746 sqlite3 *db = (sqlite3 *)ptr;
1747 int tmout = ((sqlite3 *)ptr)->busyTimeout;
1748 if( (count+1)*1000 > tmout ){
1749 return 0;
1751 sqlite3OsSleep(db->pVfs, 1000000);
1752 return 1;
1753 #endif
1757 ** Invoke the given busy handler.
1759 ** This routine is called when an operation failed to acquire a
1760 ** lock on VFS file pFile.
1762 ** If this routine returns non-zero, the lock is retried. If it
1763 ** returns 0, the operation aborts with an SQLITE_BUSY error.
1765 int sqlite3InvokeBusyHandler(BusyHandler *p){
1766 int rc;
1767 if( p->xBusyHandler==0 || p->nBusy<0 ) return 0;
1768 rc = p->xBusyHandler(p->pBusyArg, p->nBusy);
1769 if( rc==0 ){
1770 p->nBusy = -1;
1771 }else{
1772 p->nBusy++;
1774 return rc;
1778 ** This routine sets the busy callback for an Sqlite database to the
1779 ** given callback function with the given argument.
1781 int sqlite3_busy_handler(
1782 sqlite3 *db,
1783 int (*xBusy)(void*,int),
1784 void *pArg
1786 #ifdef SQLITE_ENABLE_API_ARMOR
1787 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
1788 #endif
1789 sqlite3_mutex_enter(db->mutex);
1790 db->busyHandler.xBusyHandler = xBusy;
1791 db->busyHandler.pBusyArg = pArg;
1792 db->busyHandler.nBusy = 0;
1793 db->busyTimeout = 0;
1794 sqlite3_mutex_leave(db->mutex);
1795 return SQLITE_OK;
1798 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1800 ** This routine sets the progress callback for an Sqlite database to the
1801 ** given callback function with the given argument. The progress callback will
1802 ** be invoked every nOps opcodes.
1804 void sqlite3_progress_handler(
1805 sqlite3 *db,
1806 int nOps,
1807 int (*xProgress)(void*),
1808 void *pArg
1810 #ifdef SQLITE_ENABLE_API_ARMOR
1811 if( !sqlite3SafetyCheckOk(db) ){
1812 (void)SQLITE_MISUSE_BKPT;
1813 return;
1815 #endif
1816 sqlite3_mutex_enter(db->mutex);
1817 if( nOps>0 ){
1818 db->xProgress = xProgress;
1819 db->nProgressOps = (unsigned)nOps;
1820 db->pProgressArg = pArg;
1821 }else{
1822 db->xProgress = 0;
1823 db->nProgressOps = 0;
1824 db->pProgressArg = 0;
1826 sqlite3_mutex_leave(db->mutex);
1828 #endif
1832 ** This routine installs a default busy handler that waits for the
1833 ** specified number of milliseconds before returning 0.
1835 int sqlite3_busy_timeout(sqlite3 *db, int ms){
1836 #ifdef SQLITE_ENABLE_API_ARMOR
1837 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
1838 #endif
1839 if( ms>0 ){
1840 sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
1841 (void*)db);
1842 db->busyTimeout = ms;
1843 }else{
1844 sqlite3_busy_handler(db, 0, 0);
1846 return SQLITE_OK;
1850 ** Cause any pending operation to stop at its earliest opportunity.
1852 void sqlite3_interrupt(sqlite3 *db){
1853 #ifdef SQLITE_ENABLE_API_ARMOR
1854 if( !sqlite3SafetyCheckOk(db)
1855 && (db==0 || db->eOpenState!=SQLITE_STATE_ZOMBIE)
1857 (void)SQLITE_MISUSE_BKPT;
1858 return;
1860 #endif
1861 AtomicStore(&db->u1.isInterrupted, 1);
1865 ** Return true or false depending on whether or not an interrupt is
1866 ** pending on connection db.
1868 int sqlite3_is_interrupted(sqlite3 *db){
1869 #ifdef SQLITE_ENABLE_API_ARMOR
1870 if( !sqlite3SafetyCheckOk(db)
1871 && (db==0 || db->eOpenState!=SQLITE_STATE_ZOMBIE)
1873 (void)SQLITE_MISUSE_BKPT;
1874 return 0;
1876 #endif
1877 return AtomicLoad(&db->u1.isInterrupted)!=0;
1881 ** This function is exactly the same as sqlite3_create_function(), except
1882 ** that it is designed to be called by internal code. The difference is
1883 ** that if a malloc() fails in sqlite3_create_function(), an error code
1884 ** is returned and the mallocFailed flag cleared.
1886 int sqlite3CreateFunc(
1887 sqlite3 *db,
1888 const char *zFunctionName,
1889 int nArg,
1890 int enc,
1891 void *pUserData,
1892 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
1893 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
1894 void (*xFinal)(sqlite3_context*),
1895 void (*xValue)(sqlite3_context*),
1896 void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
1897 FuncDestructor *pDestructor
1899 FuncDef *p;
1900 int extraFlags;
1902 assert( sqlite3_mutex_held(db->mutex) );
1903 assert( xValue==0 || xSFunc==0 );
1904 if( zFunctionName==0 /* Must have a valid name */
1905 || (xSFunc!=0 && xFinal!=0) /* Not both xSFunc and xFinal */
1906 || ((xFinal==0)!=(xStep==0)) /* Both or neither of xFinal and xStep */
1907 || ((xValue==0)!=(xInverse==0)) /* Both or neither of xValue, xInverse */
1908 || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG)
1909 || (255<sqlite3Strlen30(zFunctionName))
1911 return SQLITE_MISUSE_BKPT;
1914 assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
1915 assert( SQLITE_FUNC_DIRECT==SQLITE_DIRECTONLY );
1916 extraFlags = enc & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY|
1917 SQLITE_SUBTYPE|SQLITE_INNOCUOUS);
1918 enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
1920 /* The SQLITE_INNOCUOUS flag is the same bit as SQLITE_FUNC_UNSAFE. But
1921 ** the meaning is inverted. So flip the bit. */
1922 assert( SQLITE_FUNC_UNSAFE==SQLITE_INNOCUOUS );
1923 extraFlags ^= SQLITE_FUNC_UNSAFE; /* tag-20230109-1 */
1926 #ifndef SQLITE_OMIT_UTF16
1927 /* If SQLITE_UTF16 is specified as the encoding type, transform this
1928 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
1929 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
1931 ** If SQLITE_ANY is specified, add three versions of the function
1932 ** to the hash table.
1934 switch( enc ){
1935 case SQLITE_UTF16:
1936 enc = SQLITE_UTF16NATIVE;
1937 break;
1938 case SQLITE_ANY: {
1939 int rc;
1940 rc = sqlite3CreateFunc(db, zFunctionName, nArg,
1941 (SQLITE_UTF8|extraFlags)^SQLITE_FUNC_UNSAFE, /* tag-20230109-1 */
1942 pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
1943 if( rc==SQLITE_OK ){
1944 rc = sqlite3CreateFunc(db, zFunctionName, nArg,
1945 (SQLITE_UTF16LE|extraFlags)^SQLITE_FUNC_UNSAFE, /* tag-20230109-1*/
1946 pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
1948 if( rc!=SQLITE_OK ){
1949 return rc;
1951 enc = SQLITE_UTF16BE;
1952 break;
1954 case SQLITE_UTF8:
1955 case SQLITE_UTF16LE:
1956 case SQLITE_UTF16BE:
1957 break;
1958 default:
1959 enc = SQLITE_UTF8;
1960 break;
1962 #else
1963 enc = SQLITE_UTF8;
1964 #endif
1966 /* Check if an existing function is being overridden or deleted. If so,
1967 ** and there are active VMs, then return SQLITE_BUSY. If a function
1968 ** is being overridden/deleted but there are no active VMs, allow the
1969 ** operation to continue but invalidate all precompiled statements.
1971 p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
1972 if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){
1973 if( db->nVdbeActive ){
1974 sqlite3ErrorWithMsg(db, SQLITE_BUSY,
1975 "unable to delete/modify user-function due to active statements");
1976 assert( !db->mallocFailed );
1977 return SQLITE_BUSY;
1978 }else{
1979 sqlite3ExpirePreparedStatements(db, 0);
1981 }else if( xSFunc==0 && xFinal==0 ){
1982 /* Trying to delete a function that does not exist. This is a no-op.
1983 ** https://sqlite.org/forum/forumpost/726219164b */
1984 return SQLITE_OK;
1987 p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
1988 assert(p || db->mallocFailed);
1989 if( !p ){
1990 return SQLITE_NOMEM_BKPT;
1993 /* If an older version of the function with a configured destructor is
1994 ** being replaced invoke the destructor function here. */
1995 functionDestroy(db, p);
1997 if( pDestructor ){
1998 pDestructor->nRef++;
2000 p->u.pDestructor = pDestructor;
2001 p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
2002 testcase( p->funcFlags & SQLITE_DETERMINISTIC );
2003 testcase( p->funcFlags & SQLITE_DIRECTONLY );
2004 p->xSFunc = xSFunc ? xSFunc : xStep;
2005 p->xFinalize = xFinal;
2006 p->xValue = xValue;
2007 p->xInverse = xInverse;
2008 p->pUserData = pUserData;
2009 p->nArg = (u16)nArg;
2010 return SQLITE_OK;
2014 ** Worker function used by utf-8 APIs that create new functions:
2016 ** sqlite3_create_function()
2017 ** sqlite3_create_function_v2()
2018 ** sqlite3_create_window_function()
2020 static int createFunctionApi(
2021 sqlite3 *db,
2022 const char *zFunc,
2023 int nArg,
2024 int enc,
2025 void *p,
2026 void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
2027 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
2028 void (*xFinal)(sqlite3_context*),
2029 void (*xValue)(sqlite3_context*),
2030 void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
2031 void(*xDestroy)(void*)
2033 int rc = SQLITE_ERROR;
2034 FuncDestructor *pArg = 0;
2036 #ifdef SQLITE_ENABLE_API_ARMOR
2037 if( !sqlite3SafetyCheckOk(db) ){
2038 return SQLITE_MISUSE_BKPT;
2040 #endif
2041 sqlite3_mutex_enter(db->mutex);
2042 if( xDestroy ){
2043 pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor));
2044 if( !pArg ){
2045 sqlite3OomFault(db);
2046 xDestroy(p);
2047 goto out;
2049 pArg->nRef = 0;
2050 pArg->xDestroy = xDestroy;
2051 pArg->pUserData = p;
2053 rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p,
2054 xSFunc, xStep, xFinal, xValue, xInverse, pArg
2056 if( pArg && pArg->nRef==0 ){
2057 assert( rc!=SQLITE_OK || (xStep==0 && xFinal==0) );
2058 xDestroy(p);
2059 sqlite3_free(pArg);
2062 out:
2063 rc = sqlite3ApiExit(db, rc);
2064 sqlite3_mutex_leave(db->mutex);
2065 return rc;
2069 ** Create new user functions.
2071 int sqlite3_create_function(
2072 sqlite3 *db,
2073 const char *zFunc,
2074 int nArg,
2075 int enc,
2076 void *p,
2077 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
2078 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
2079 void (*xFinal)(sqlite3_context*)
2081 return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
2082 xFinal, 0, 0, 0);
2084 int sqlite3_create_function_v2(
2085 sqlite3 *db,
2086 const char *zFunc,
2087 int nArg,
2088 int enc,
2089 void *p,
2090 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
2091 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
2092 void (*xFinal)(sqlite3_context*),
2093 void (*xDestroy)(void *)
2095 return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
2096 xFinal, 0, 0, xDestroy);
2098 int sqlite3_create_window_function(
2099 sqlite3 *db,
2100 const char *zFunc,
2101 int nArg,
2102 int enc,
2103 void *p,
2104 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
2105 void (*xFinal)(sqlite3_context*),
2106 void (*xValue)(sqlite3_context*),
2107 void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
2108 void (*xDestroy)(void *)
2110 return createFunctionApi(db, zFunc, nArg, enc, p, 0, xStep,
2111 xFinal, xValue, xInverse, xDestroy);
2114 #ifndef SQLITE_OMIT_UTF16
2115 int sqlite3_create_function16(
2116 sqlite3 *db,
2117 const void *zFunctionName,
2118 int nArg,
2119 int eTextRep,
2120 void *p,
2121 void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
2122 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
2123 void (*xFinal)(sqlite3_context*)
2125 int rc;
2126 char *zFunc8;
2128 #ifdef SQLITE_ENABLE_API_ARMOR
2129 if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
2130 #endif
2131 sqlite3_mutex_enter(db->mutex);
2132 assert( !db->mallocFailed );
2133 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
2134 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0,0,0);
2135 sqlite3DbFree(db, zFunc8);
2136 rc = sqlite3ApiExit(db, rc);
2137 sqlite3_mutex_leave(db->mutex);
2138 return rc;
2140 #endif
2144 ** The following is the implementation of an SQL function that always
2145 ** fails with an error message stating that the function is used in the
2146 ** wrong context. The sqlite3_overload_function() API might construct
2147 ** SQL function that use this routine so that the functions will exist
2148 ** for name resolution but are actually overloaded by the xFindFunction
2149 ** method of virtual tables.
2151 static void sqlite3InvalidFunction(
2152 sqlite3_context *context, /* The function calling context */
2153 int NotUsed, /* Number of arguments to the function */
2154 sqlite3_value **NotUsed2 /* Value of each argument */
2156 const char *zName = (const char*)sqlite3_user_data(context);
2157 char *zErr;
2158 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2159 zErr = sqlite3_mprintf(
2160 "unable to use function %s in the requested context", zName);
2161 sqlite3_result_error(context, zErr, -1);
2162 sqlite3_free(zErr);
2166 ** Declare that a function has been overloaded by a virtual table.
2168 ** If the function already exists as a regular global function, then
2169 ** this routine is a no-op. If the function does not exist, then create
2170 ** a new one that always throws a run-time error.
2172 ** When virtual tables intend to provide an overloaded function, they
2173 ** should call this routine to make sure the global function exists.
2174 ** A global function must exist in order for name resolution to work
2175 ** properly.
2177 int sqlite3_overload_function(
2178 sqlite3 *db,
2179 const char *zName,
2180 int nArg
2182 int rc;
2183 char *zCopy;
2185 #ifdef SQLITE_ENABLE_API_ARMOR
2186 if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
2187 return SQLITE_MISUSE_BKPT;
2189 #endif
2190 sqlite3_mutex_enter(db->mutex);
2191 rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0;
2192 sqlite3_mutex_leave(db->mutex);
2193 if( rc ) return SQLITE_OK;
2194 zCopy = sqlite3_mprintf("%s", zName);
2195 if( zCopy==0 ) return SQLITE_NOMEM;
2196 return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8,
2197 zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free);
2200 #ifndef SQLITE_OMIT_TRACE
2202 ** Register a trace function. The pArg from the previously registered trace
2203 ** is returned.
2205 ** A NULL trace function means that no tracing is executes. A non-NULL
2206 ** trace is a pointer to a function that is invoked at the start of each
2207 ** SQL statement.
2209 #ifndef SQLITE_OMIT_DEPRECATED
2210 void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
2211 void *pOld;
2213 #ifdef SQLITE_ENABLE_API_ARMOR
2214 if( !sqlite3SafetyCheckOk(db) ){
2215 (void)SQLITE_MISUSE_BKPT;
2216 return 0;
2218 #endif
2219 sqlite3_mutex_enter(db->mutex);
2220 pOld = db->pTraceArg;
2221 db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
2222 db->trace.xLegacy = xTrace;
2223 db->pTraceArg = pArg;
2224 sqlite3_mutex_leave(db->mutex);
2225 return pOld;
2227 #endif /* SQLITE_OMIT_DEPRECATED */
2229 /* Register a trace callback using the version-2 interface.
2231 int sqlite3_trace_v2(
2232 sqlite3 *db, /* Trace this connection */
2233 unsigned mTrace, /* Mask of events to be traced */
2234 int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */
2235 void *pArg /* Context */
2237 #ifdef SQLITE_ENABLE_API_ARMOR
2238 if( !sqlite3SafetyCheckOk(db) ){
2239 return SQLITE_MISUSE_BKPT;
2241 #endif
2242 sqlite3_mutex_enter(db->mutex);
2243 if( mTrace==0 ) xTrace = 0;
2244 if( xTrace==0 ) mTrace = 0;
2245 db->mTrace = mTrace;
2246 db->trace.xV2 = xTrace;
2247 db->pTraceArg = pArg;
2248 sqlite3_mutex_leave(db->mutex);
2249 return SQLITE_OK;
2252 #ifndef SQLITE_OMIT_DEPRECATED
2254 ** Register a profile function. The pArg from the previously registered
2255 ** profile function is returned.
2257 ** A NULL profile function means that no profiling is executes. A non-NULL
2258 ** profile is a pointer to a function that is invoked at the conclusion of
2259 ** each SQL statement that is run.
2261 void *sqlite3_profile(
2262 sqlite3 *db,
2263 void (*xProfile)(void*,const char*,sqlite_uint64),
2264 void *pArg
2266 void *pOld;
2268 #ifdef SQLITE_ENABLE_API_ARMOR
2269 if( !sqlite3SafetyCheckOk(db) ){
2270 (void)SQLITE_MISUSE_BKPT;
2271 return 0;
2273 #endif
2274 sqlite3_mutex_enter(db->mutex);
2275 pOld = db->pProfileArg;
2276 db->xProfile = xProfile;
2277 db->pProfileArg = pArg;
2278 db->mTrace &= SQLITE_TRACE_NONLEGACY_MASK;
2279 if( db->xProfile ) db->mTrace |= SQLITE_TRACE_XPROFILE;
2280 sqlite3_mutex_leave(db->mutex);
2281 return pOld;
2283 #endif /* SQLITE_OMIT_DEPRECATED */
2284 #endif /* SQLITE_OMIT_TRACE */
2287 ** Register a function to be invoked when a transaction commits.
2288 ** If the invoked function returns non-zero, then the commit becomes a
2289 ** rollback.
2291 void *sqlite3_commit_hook(
2292 sqlite3 *db, /* Attach the hook to this database */
2293 int (*xCallback)(void*), /* Function to invoke on each commit */
2294 void *pArg /* Argument to the function */
2296 void *pOld;
2298 #ifdef SQLITE_ENABLE_API_ARMOR
2299 if( !sqlite3SafetyCheckOk(db) ){
2300 (void)SQLITE_MISUSE_BKPT;
2301 return 0;
2303 #endif
2304 sqlite3_mutex_enter(db->mutex);
2305 pOld = db->pCommitArg;
2306 db->xCommitCallback = xCallback;
2307 db->pCommitArg = pArg;
2308 sqlite3_mutex_leave(db->mutex);
2309 return pOld;
2313 ** Register a callback to be invoked each time a row is updated,
2314 ** inserted or deleted using this database connection.
2316 void *sqlite3_update_hook(
2317 sqlite3 *db, /* Attach the hook to this database */
2318 void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
2319 void *pArg /* Argument to the function */
2321 void *pRet;
2323 #ifdef SQLITE_ENABLE_API_ARMOR
2324 if( !sqlite3SafetyCheckOk(db) ){
2325 (void)SQLITE_MISUSE_BKPT;
2326 return 0;
2328 #endif
2329 sqlite3_mutex_enter(db->mutex);
2330 pRet = db->pUpdateArg;
2331 db->xUpdateCallback = xCallback;
2332 db->pUpdateArg = pArg;
2333 sqlite3_mutex_leave(db->mutex);
2334 return pRet;
2338 ** Register a callback to be invoked each time a transaction is rolled
2339 ** back by this database connection.
2341 void *sqlite3_rollback_hook(
2342 sqlite3 *db, /* Attach the hook to this database */
2343 void (*xCallback)(void*), /* Callback function */
2344 void *pArg /* Argument to the function */
2346 void *pRet;
2348 #ifdef SQLITE_ENABLE_API_ARMOR
2349 if( !sqlite3SafetyCheckOk(db) ){
2350 (void)SQLITE_MISUSE_BKPT;
2351 return 0;
2353 #endif
2354 sqlite3_mutex_enter(db->mutex);
2355 pRet = db->pRollbackArg;
2356 db->xRollbackCallback = xCallback;
2357 db->pRollbackArg = pArg;
2358 sqlite3_mutex_leave(db->mutex);
2359 return pRet;
2362 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2364 ** Register a callback to be invoked each time a row is updated,
2365 ** inserted or deleted using this database connection.
2367 void *sqlite3_preupdate_hook(
2368 sqlite3 *db, /* Attach the hook to this database */
2369 void(*xCallback)( /* Callback function */
2370 void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
2371 void *pArg /* First callback argument */
2373 void *pRet;
2375 #ifdef SQLITE_ENABLE_API_ARMOR
2376 if( db==0 ){
2377 return 0;
2379 #endif
2380 sqlite3_mutex_enter(db->mutex);
2381 pRet = db->pPreUpdateArg;
2382 db->xPreUpdateCallback = xCallback;
2383 db->pPreUpdateArg = pArg;
2384 sqlite3_mutex_leave(db->mutex);
2385 return pRet;
2387 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2390 ** Register a function to be invoked prior to each autovacuum that
2391 ** determines the number of pages to vacuum.
2393 int sqlite3_autovacuum_pages(
2394 sqlite3 *db, /* Attach the hook to this database */
2395 unsigned int (*xCallback)(void*,const char*,u32,u32,u32),
2396 void *pArg, /* Argument to the function */
2397 void (*xDestructor)(void*) /* Destructor for pArg */
2399 #ifdef SQLITE_ENABLE_API_ARMOR
2400 if( !sqlite3SafetyCheckOk(db) ){
2401 if( xDestructor ) xDestructor(pArg);
2402 return SQLITE_MISUSE_BKPT;
2404 #endif
2405 sqlite3_mutex_enter(db->mutex);
2406 if( db->xAutovacDestr ){
2407 db->xAutovacDestr(db->pAutovacPagesArg);
2409 db->xAutovacPages = xCallback;
2410 db->pAutovacPagesArg = pArg;
2411 db->xAutovacDestr = xDestructor;
2412 sqlite3_mutex_leave(db->mutex);
2413 return SQLITE_OK;
2417 #ifndef SQLITE_OMIT_WAL
2419 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
2420 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
2421 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
2422 ** wal_autocheckpoint()).
2424 int sqlite3WalDefaultHook(
2425 void *pClientData, /* Argument */
2426 sqlite3 *db, /* Connection */
2427 const char *zDb, /* Database */
2428 int nFrame /* Size of WAL */
2430 if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
2431 sqlite3BeginBenignMalloc();
2432 sqlite3_wal_checkpoint(db, zDb);
2433 sqlite3EndBenignMalloc();
2435 return SQLITE_OK;
2437 #endif /* SQLITE_OMIT_WAL */
2440 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
2441 ** a database after committing a transaction if there are nFrame or
2442 ** more frames in the log file. Passing zero or a negative value as the
2443 ** nFrame parameter disables automatic checkpoints entirely.
2445 ** The callback registered by this function replaces any existing callback
2446 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
2447 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
2448 ** configured by this function.
2450 int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
2451 #ifdef SQLITE_OMIT_WAL
2452 UNUSED_PARAMETER(db);
2453 UNUSED_PARAMETER(nFrame);
2454 #else
2455 #ifdef SQLITE_ENABLE_API_ARMOR
2456 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
2457 #endif
2458 if( nFrame>0 ){
2459 sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
2460 }else{
2461 sqlite3_wal_hook(db, 0, 0);
2463 #endif
2464 return SQLITE_OK;
2468 ** Register a callback to be invoked each time a transaction is written
2469 ** into the write-ahead-log by this database connection.
2471 void *sqlite3_wal_hook(
2472 sqlite3 *db, /* Attach the hook to this db handle */
2473 int(*xCallback)(void *, sqlite3*, const char*, int),
2474 void *pArg /* First argument passed to xCallback() */
2476 #ifndef SQLITE_OMIT_WAL
2477 void *pRet;
2478 #ifdef SQLITE_ENABLE_API_ARMOR
2479 if( !sqlite3SafetyCheckOk(db) ){
2480 (void)SQLITE_MISUSE_BKPT;
2481 return 0;
2483 #endif
2484 sqlite3_mutex_enter(db->mutex);
2485 pRet = db->pWalArg;
2486 db->xWalCallback = xCallback;
2487 db->pWalArg = pArg;
2488 sqlite3_mutex_leave(db->mutex);
2489 return pRet;
2490 #else
2491 return 0;
2492 #endif
2496 ** Checkpoint database zDb.
2498 int sqlite3_wal_checkpoint_v2(
2499 sqlite3 *db, /* Database handle */
2500 const char *zDb, /* Name of attached database (or NULL) */
2501 int eMode, /* SQLITE_CHECKPOINT_* value */
2502 int *pnLog, /* OUT: Size of WAL log in frames */
2503 int *pnCkpt /* OUT: Total number of frames checkpointed */
2505 #ifdef SQLITE_OMIT_WAL
2506 return SQLITE_OK;
2507 #else
2508 int rc; /* Return code */
2509 int iDb; /* Schema to checkpoint */
2511 #ifdef SQLITE_ENABLE_API_ARMOR
2512 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
2513 #endif
2515 /* Initialize the output variables to -1 in case an error occurs. */
2516 if( pnLog ) *pnLog = -1;
2517 if( pnCkpt ) *pnCkpt = -1;
2519 assert( SQLITE_CHECKPOINT_PASSIVE==0 );
2520 assert( SQLITE_CHECKPOINT_FULL==1 );
2521 assert( SQLITE_CHECKPOINT_RESTART==2 );
2522 assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
2523 if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
2524 /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
2525 ** mode: */
2526 return SQLITE_MISUSE_BKPT;
2529 sqlite3_mutex_enter(db->mutex);
2530 if( zDb && zDb[0] ){
2531 iDb = sqlite3FindDbName(db, zDb);
2532 }else{
2533 iDb = SQLITE_MAX_DB; /* This means process all schemas */
2535 if( iDb<0 ){
2536 rc = SQLITE_ERROR;
2537 sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
2538 }else{
2539 db->busyHandler.nBusy = 0;
2540 rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
2541 sqlite3Error(db, rc);
2543 rc = sqlite3ApiExit(db, rc);
2545 /* If there are no active statements, clear the interrupt flag at this
2546 ** point. */
2547 if( db->nVdbeActive==0 ){
2548 AtomicStore(&db->u1.isInterrupted, 0);
2551 sqlite3_mutex_leave(db->mutex);
2552 return rc;
2553 #endif
2558 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
2559 ** to contains a zero-length string, all attached databases are
2560 ** checkpointed.
2562 int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
2563 /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
2564 ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
2565 return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
2568 #ifndef SQLITE_OMIT_WAL
2570 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
2571 ** not currently open in WAL mode.
2573 ** If a transaction is open on the database being checkpointed, this
2574 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
2575 ** an error occurs while running the checkpoint, an SQLite error code is
2576 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
2578 ** The mutex on database handle db should be held by the caller. The mutex
2579 ** associated with the specific b-tree being checkpointed is taken by
2580 ** this function while the checkpoint is running.
2582 ** If iDb is passed SQLITE_MAX_DB then all attached databases are
2583 ** checkpointed. If an error is encountered it is returned immediately -
2584 ** no attempt is made to checkpoint any remaining databases.
2586 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
2587 ** or TRUNCATE.
2589 int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
2590 int rc = SQLITE_OK; /* Return code */
2591 int i; /* Used to iterate through attached dbs */
2592 int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
2594 assert( sqlite3_mutex_held(db->mutex) );
2595 assert( !pnLog || *pnLog==-1 );
2596 assert( !pnCkpt || *pnCkpt==-1 );
2597 testcase( iDb==SQLITE_MAX_ATTACHED ); /* See forum post a006d86f72 */
2598 testcase( iDb==SQLITE_MAX_DB );
2600 for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
2601 if( i==iDb || iDb==SQLITE_MAX_DB ){
2602 rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
2603 pnLog = 0;
2604 pnCkpt = 0;
2605 if( rc==SQLITE_BUSY ){
2606 bBusy = 1;
2607 rc = SQLITE_OK;
2612 return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
2614 #endif /* SQLITE_OMIT_WAL */
2617 ** This function returns true if main-memory should be used instead of
2618 ** a temporary file for transient pager files and statement journals.
2619 ** The value returned depends on the value of db->temp_store (runtime
2620 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
2621 ** following table describes the relationship between these two values
2622 ** and this functions return value.
2624 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
2625 ** ----------------- -------------- ------------------------------
2626 ** 0 any file (return 0)
2627 ** 1 1 file (return 0)
2628 ** 1 2 memory (return 1)
2629 ** 1 0 file (return 0)
2630 ** 2 1 file (return 0)
2631 ** 2 2 memory (return 1)
2632 ** 2 0 memory (return 1)
2633 ** 3 any memory (return 1)
2635 int sqlite3TempInMemory(const sqlite3 *db){
2636 #if SQLITE_TEMP_STORE==1
2637 return ( db->temp_store==2 );
2638 #endif
2639 #if SQLITE_TEMP_STORE==2
2640 return ( db->temp_store!=1 );
2641 #endif
2642 #if SQLITE_TEMP_STORE==3
2643 UNUSED_PARAMETER(db);
2644 return 1;
2645 #endif
2646 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
2647 UNUSED_PARAMETER(db);
2648 return 0;
2649 #endif
2653 ** Return UTF-8 encoded English language explanation of the most recent
2654 ** error.
2656 const char *sqlite3_errmsg(sqlite3 *db){
2657 const char *z;
2658 if( !db ){
2659 return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
2661 if( !sqlite3SafetyCheckSickOrOk(db) ){
2662 return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
2664 sqlite3_mutex_enter(db->mutex);
2665 if( db->mallocFailed ){
2666 z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
2667 }else{
2668 testcase( db->pErr==0 );
2669 z = db->errCode ? (char*)sqlite3_value_text(db->pErr) : 0;
2670 assert( !db->mallocFailed );
2671 if( z==0 ){
2672 z = sqlite3ErrStr(db->errCode);
2675 sqlite3_mutex_leave(db->mutex);
2676 return z;
2680 ** Return the byte offset of the most recent error
2682 int sqlite3_error_offset(sqlite3 *db){
2683 int iOffset = -1;
2684 if( db && sqlite3SafetyCheckSickOrOk(db) && db->errCode ){
2685 sqlite3_mutex_enter(db->mutex);
2686 iOffset = db->errByteOffset;
2687 sqlite3_mutex_leave(db->mutex);
2689 return iOffset;
2692 #ifndef SQLITE_OMIT_UTF16
2694 ** Return UTF-16 encoded English language explanation of the most recent
2695 ** error.
2697 const void *sqlite3_errmsg16(sqlite3 *db){
2698 static const u16 outOfMem[] = {
2699 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
2701 static const u16 misuse[] = {
2702 'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
2703 'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
2704 'm', 'i', 's', 'u', 's', 'e', 0
2707 const void *z;
2708 if( !db ){
2709 return (void *)outOfMem;
2711 if( !sqlite3SafetyCheckSickOrOk(db) ){
2712 return (void *)misuse;
2714 sqlite3_mutex_enter(db->mutex);
2715 if( db->mallocFailed ){
2716 z = (void *)outOfMem;
2717 }else{
2718 z = sqlite3_value_text16(db->pErr);
2719 if( z==0 ){
2720 sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
2721 z = sqlite3_value_text16(db->pErr);
2723 /* A malloc() may have failed within the call to sqlite3_value_text16()
2724 ** above. If this is the case, then the db->mallocFailed flag needs to
2725 ** be cleared before returning. Do this directly, instead of via
2726 ** sqlite3ApiExit(), to avoid setting the database handle error message.
2728 sqlite3OomClear(db);
2730 sqlite3_mutex_leave(db->mutex);
2731 return z;
2733 #endif /* SQLITE_OMIT_UTF16 */
2736 ** Return the most recent error code generated by an SQLite routine. If NULL is
2737 ** passed to this function, we assume a malloc() failed during sqlite3_open().
2739 int sqlite3_errcode(sqlite3 *db){
2740 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
2741 return SQLITE_MISUSE_BKPT;
2743 if( !db || db->mallocFailed ){
2744 return SQLITE_NOMEM_BKPT;
2746 return db->errCode & db->errMask;
2748 int sqlite3_extended_errcode(sqlite3 *db){
2749 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
2750 return SQLITE_MISUSE_BKPT;
2752 if( !db || db->mallocFailed ){
2753 return SQLITE_NOMEM_BKPT;
2755 return db->errCode;
2757 int sqlite3_system_errno(sqlite3 *db){
2758 return db ? db->iSysErrno : 0;
2762 ** Return a string that describes the kind of error specified in the
2763 ** argument. For now, this simply calls the internal sqlite3ErrStr()
2764 ** function.
2766 const char *sqlite3_errstr(int rc){
2767 return sqlite3ErrStr(rc);
2771 ** Create a new collating function for database "db". The name is zName
2772 ** and the encoding is enc.
2774 static int createCollation(
2775 sqlite3* db,
2776 const char *zName,
2777 u8 enc,
2778 void* pCtx,
2779 int(*xCompare)(void*,int,const void*,int,const void*),
2780 void(*xDel)(void*)
2782 CollSeq *pColl;
2783 int enc2;
2785 assert( sqlite3_mutex_held(db->mutex) );
2787 /* If SQLITE_UTF16 is specified as the encoding type, transform this
2788 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
2789 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
2791 enc2 = enc;
2792 testcase( enc2==SQLITE_UTF16 );
2793 testcase( enc2==SQLITE_UTF16_ALIGNED );
2794 if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
2795 enc2 = SQLITE_UTF16NATIVE;
2797 if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
2798 return SQLITE_MISUSE_BKPT;
2801 /* Check if this call is removing or replacing an existing collation
2802 ** sequence. If so, and there are active VMs, return busy. If there
2803 ** are no active VMs, invalidate any pre-compiled statements.
2805 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
2806 if( pColl && pColl->xCmp ){
2807 if( db->nVdbeActive ){
2808 sqlite3ErrorWithMsg(db, SQLITE_BUSY,
2809 "unable to delete/modify collation sequence due to active statements");
2810 return SQLITE_BUSY;
2812 sqlite3ExpirePreparedStatements(db, 0);
2814 /* If collation sequence pColl was created directly by a call to
2815 ** sqlite3_create_collation, and not generated by synthCollSeq(),
2816 ** then any copies made by synthCollSeq() need to be invalidated.
2817 ** Also, collation destructor - CollSeq.xDel() - function may need
2818 ** to be called.
2820 if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
2821 CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
2822 int j;
2823 for(j=0; j<3; j++){
2824 CollSeq *p = &aColl[j];
2825 if( p->enc==pColl->enc ){
2826 if( p->xDel ){
2827 p->xDel(p->pUser);
2829 p->xCmp = 0;
2835 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
2836 if( pColl==0 ) return SQLITE_NOMEM_BKPT;
2837 pColl->xCmp = xCompare;
2838 pColl->pUser = pCtx;
2839 pColl->xDel = xDel;
2840 pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
2841 sqlite3Error(db, SQLITE_OK);
2842 return SQLITE_OK;
2847 ** This array defines hard upper bounds on limit values. The
2848 ** initializer must be kept in sync with the SQLITE_LIMIT_*
2849 ** #defines in sqlite3.h.
2851 static const int aHardLimit[] = {
2852 SQLITE_MAX_LENGTH,
2853 SQLITE_MAX_SQL_LENGTH,
2854 SQLITE_MAX_COLUMN,
2855 SQLITE_MAX_EXPR_DEPTH,
2856 SQLITE_MAX_COMPOUND_SELECT,
2857 SQLITE_MAX_VDBE_OP,
2858 SQLITE_MAX_FUNCTION_ARG,
2859 SQLITE_MAX_ATTACHED,
2860 SQLITE_MAX_LIKE_PATTERN_LENGTH,
2861 SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
2862 SQLITE_MAX_TRIGGER_DEPTH,
2863 SQLITE_MAX_WORKER_THREADS,
2867 ** Make sure the hard limits are set to reasonable values
2869 #if SQLITE_MAX_LENGTH<100
2870 # error SQLITE_MAX_LENGTH must be at least 100
2871 #endif
2872 #if SQLITE_MAX_SQL_LENGTH<100
2873 # error SQLITE_MAX_SQL_LENGTH must be at least 100
2874 #endif
2875 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
2876 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
2877 #endif
2878 #if SQLITE_MAX_COMPOUND_SELECT<2
2879 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
2880 #endif
2881 #if SQLITE_MAX_VDBE_OP<40
2882 # error SQLITE_MAX_VDBE_OP must be at least 40
2883 #endif
2884 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
2885 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
2886 #endif
2887 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
2888 # error SQLITE_MAX_ATTACHED must be between 0 and 125
2889 #endif
2890 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
2891 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
2892 #endif
2893 #if SQLITE_MAX_COLUMN>32767
2894 # error SQLITE_MAX_COLUMN must not exceed 32767
2895 #endif
2896 #if SQLITE_MAX_TRIGGER_DEPTH<1
2897 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
2898 #endif
2899 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
2900 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
2901 #endif
2905 ** Change the value of a limit. Report the old value.
2906 ** If an invalid limit index is supplied, report -1.
2907 ** Make no changes but still report the old value if the
2908 ** new limit is negative.
2910 ** A new lower limit does not shrink existing constructs.
2911 ** It merely prevents new constructs that exceed the limit
2912 ** from forming.
2914 int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
2915 int oldLimit;
2917 #ifdef SQLITE_ENABLE_API_ARMOR
2918 if( !sqlite3SafetyCheckOk(db) ){
2919 (void)SQLITE_MISUSE_BKPT;
2920 return -1;
2922 #endif
2924 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
2925 ** there is a hard upper bound set at compile-time by a C preprocessor
2926 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
2927 ** "_MAX_".)
2929 assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
2930 assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
2931 assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
2932 assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
2933 assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
2934 assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
2935 assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
2936 assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
2937 assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
2938 SQLITE_MAX_LIKE_PATTERN_LENGTH );
2939 assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
2940 assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
2941 assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
2942 assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
2945 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
2946 return -1;
2948 oldLimit = db->aLimit[limitId];
2949 if( newLimit>=0 ){ /* IMP: R-52476-28732 */
2950 if( newLimit>aHardLimit[limitId] ){
2951 newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
2952 }else if( newLimit<1 && limitId==SQLITE_LIMIT_LENGTH ){
2953 newLimit = 1;
2955 db->aLimit[limitId] = newLimit;
2957 return oldLimit; /* IMP: R-53341-35419 */
2961 ** This function is used to parse both URIs and non-URI filenames passed by the
2962 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
2963 ** URIs specified as part of ATTACH statements.
2965 ** The first argument to this function is the name of the VFS to use (or
2966 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
2967 ** query parameter. The second argument contains the URI (or non-URI filename)
2968 ** itself. When this function is called the *pFlags variable should contain
2969 ** the default flags to open the database handle with. The value stored in
2970 ** *pFlags may be updated before returning if the URI filename contains
2971 ** "cache=xxx" or "mode=xxx" query parameters.
2973 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
2974 ** the VFS that should be used to open the database file. *pzFile is set to
2975 ** point to a buffer containing the name of the file to open. The value
2976 ** stored in *pzFile is a database name acceptable to sqlite3_uri_parameter()
2977 ** and is in the same format as names created using sqlite3_create_filename().
2978 ** The caller must invoke sqlite3_free_filename() (not sqlite3_free()!) on
2979 ** the value returned in *pzFile to avoid a memory leak.
2981 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
2982 ** may be set to point to a buffer containing an English language error
2983 ** message. It is the responsibility of the caller to eventually release
2984 ** this buffer by calling sqlite3_free().
2986 int sqlite3ParseUri(
2987 const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
2988 const char *zUri, /* Nul-terminated URI to parse */
2989 unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
2990 sqlite3_vfs **ppVfs, /* OUT: VFS to use */
2991 char **pzFile, /* OUT: Filename component of URI */
2992 char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
2994 int rc = SQLITE_OK;
2995 unsigned int flags = *pFlags;
2996 const char *zVfs = zDefaultVfs;
2997 char *zFile;
2998 char c;
2999 int nUri = sqlite3Strlen30(zUri);
3001 assert( *pzErrMsg==0 );
3003 if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
3004 || AtomicLoad(&sqlite3GlobalConfig.bOpenUri)) /* IMP: R-51689-46548 */
3005 && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
3007 char *zOpt;
3008 int eState; /* Parser state when parsing URI */
3009 int iIn; /* Input character index */
3010 int iOut = 0; /* Output character index */
3011 u64 nByte = nUri+8; /* Bytes of space to allocate */
3013 /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
3014 ** method that there may be extra parameters following the file-name. */
3015 flags |= SQLITE_OPEN_URI;
3017 for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
3018 zFile = sqlite3_malloc64(nByte);
3019 if( !zFile ) return SQLITE_NOMEM_BKPT;
3021 memset(zFile, 0, 4); /* 4-byte of 0x00 is the start of DB name marker */
3022 zFile += 4;
3024 iIn = 5;
3025 #ifdef SQLITE_ALLOW_URI_AUTHORITY
3026 if( strncmp(zUri+5, "///", 3)==0 ){
3027 iIn = 7;
3028 /* The following condition causes URIs with five leading / characters
3029 ** like file://///host/path to be converted into UNCs like //host/path.
3030 ** The correct URI for that UNC has only two or four leading / characters
3031 ** file://host/path or file:////host/path. But 5 leading slashes is a
3032 ** common error, we are told, so we handle it as a special case. */
3033 if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
3034 }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
3035 iIn = 16;
3037 #else
3038 /* Discard the scheme and authority segments of the URI. */
3039 if( zUri[5]=='/' && zUri[6]=='/' ){
3040 iIn = 7;
3041 while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
3042 if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
3043 *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
3044 iIn-7, &zUri[7]);
3045 rc = SQLITE_ERROR;
3046 goto parse_uri_out;
3049 #endif
3051 /* Copy the filename and any query parameters into the zFile buffer.
3052 ** Decode %HH escape codes along the way.
3054 ** Within this loop, variable eState may be set to 0, 1 or 2, depending
3055 ** on the parsing context. As follows:
3057 ** 0: Parsing file-name.
3058 ** 1: Parsing name section of a name=value query parameter.
3059 ** 2: Parsing value section of a name=value query parameter.
3061 eState = 0;
3062 while( (c = zUri[iIn])!=0 && c!='#' ){
3063 iIn++;
3064 if( c=='%'
3065 && sqlite3Isxdigit(zUri[iIn])
3066 && sqlite3Isxdigit(zUri[iIn+1])
3068 int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
3069 octet += sqlite3HexToInt(zUri[iIn++]);
3071 assert( octet>=0 && octet<256 );
3072 if( octet==0 ){
3073 #ifndef SQLITE_ENABLE_URI_00_ERROR
3074 /* This branch is taken when "%00" appears within the URI. In this
3075 ** case we ignore all text in the remainder of the path, name or
3076 ** value currently being parsed. So ignore the current character
3077 ** and skip to the next "?", "=" or "&", as appropriate. */
3078 while( (c = zUri[iIn])!=0 && c!='#'
3079 && (eState!=0 || c!='?')
3080 && (eState!=1 || (c!='=' && c!='&'))
3081 && (eState!=2 || c!='&')
3083 iIn++;
3085 continue;
3086 #else
3087 /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
3088 *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
3089 rc = SQLITE_ERROR;
3090 goto parse_uri_out;
3091 #endif
3093 c = octet;
3094 }else if( eState==1 && (c=='&' || c=='=') ){
3095 if( zFile[iOut-1]==0 ){
3096 /* An empty option name. Ignore this option altogether. */
3097 while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
3098 continue;
3100 if( c=='&' ){
3101 zFile[iOut++] = '\0';
3102 }else{
3103 eState = 2;
3105 c = 0;
3106 }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
3107 c = 0;
3108 eState = 1;
3110 zFile[iOut++] = c;
3112 if( eState==1 ) zFile[iOut++] = '\0';
3113 memset(zFile+iOut, 0, 4); /* end-of-options + empty journal filenames */
3115 /* Check if there were any options specified that should be interpreted
3116 ** here. Options that are interpreted here include "vfs" and those that
3117 ** correspond to flags that may be passed to the sqlite3_open_v2()
3118 ** method. */
3119 zOpt = &zFile[sqlite3Strlen30(zFile)+1];
3120 while( zOpt[0] ){
3121 int nOpt = sqlite3Strlen30(zOpt);
3122 char *zVal = &zOpt[nOpt+1];
3123 int nVal = sqlite3Strlen30(zVal);
3125 if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
3126 zVfs = zVal;
3127 }else{
3128 struct OpenMode {
3129 const char *z;
3130 int mode;
3131 } *aMode = 0;
3132 char *zModeType = 0;
3133 int mask = 0;
3134 int limit = 0;
3136 if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
3137 static struct OpenMode aCacheMode[] = {
3138 { "shared", SQLITE_OPEN_SHAREDCACHE },
3139 { "private", SQLITE_OPEN_PRIVATECACHE },
3140 { 0, 0 }
3143 mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
3144 aMode = aCacheMode;
3145 limit = mask;
3146 zModeType = "cache";
3148 if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
3149 static struct OpenMode aOpenMode[] = {
3150 { "ro", SQLITE_OPEN_READONLY },
3151 { "rw", SQLITE_OPEN_READWRITE },
3152 { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
3153 { "memory", SQLITE_OPEN_MEMORY },
3154 { 0, 0 }
3157 mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
3158 | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
3159 aMode = aOpenMode;
3160 limit = mask & flags;
3161 zModeType = "access";
3164 if( aMode ){
3165 int i;
3166 int mode = 0;
3167 for(i=0; aMode[i].z; i++){
3168 const char *z = aMode[i].z;
3169 if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
3170 mode = aMode[i].mode;
3171 break;
3174 if( mode==0 ){
3175 *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
3176 rc = SQLITE_ERROR;
3177 goto parse_uri_out;
3179 if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
3180 *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
3181 zModeType, zVal);
3182 rc = SQLITE_PERM;
3183 goto parse_uri_out;
3185 flags = (flags & ~mask) | mode;
3189 zOpt = &zVal[nVal+1];
3192 }else{
3193 zFile = sqlite3_malloc64(nUri+8);
3194 if( !zFile ) return SQLITE_NOMEM_BKPT;
3195 memset(zFile, 0, 4);
3196 zFile += 4;
3197 if( nUri ){
3198 memcpy(zFile, zUri, nUri);
3200 memset(zFile+nUri, 0, 4);
3201 flags &= ~SQLITE_OPEN_URI;
3204 *ppVfs = sqlite3_vfs_find(zVfs);
3205 if( *ppVfs==0 ){
3206 *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
3207 rc = SQLITE_ERROR;
3209 parse_uri_out:
3210 if( rc!=SQLITE_OK ){
3211 sqlite3_free_filename(zFile);
3212 zFile = 0;
3214 *pFlags = flags;
3215 *pzFile = zFile;
3216 return rc;
3220 ** This routine does the core work of extracting URI parameters from a
3221 ** database filename for the sqlite3_uri_parameter() interface.
3223 static const char *uriParameter(const char *zFilename, const char *zParam){
3224 zFilename += sqlite3Strlen30(zFilename) + 1;
3225 while( ALWAYS(zFilename!=0) && zFilename[0] ){
3226 int x = strcmp(zFilename, zParam);
3227 zFilename += sqlite3Strlen30(zFilename) + 1;
3228 if( x==0 ) return zFilename;
3229 zFilename += sqlite3Strlen30(zFilename) + 1;
3231 return 0;
3234 /* BEGIN SQLCIPHER */
3235 #if defined(SQLITE_HAS_CODEC)
3237 ** Process URI filename query parameters relevant to the SQLite Encryption
3238 ** Extension. Return true if any of the relevant query parameters are
3239 ** seen and return false if not.
3241 int sqlite3CodecQueryParameters(
3242 sqlite3 *db, /* Database connection */
3243 const char *zDb, /* Which schema is being created/attached */
3244 const char *zUri /* URI filename */
3246 const char *zKey;
3247 if( zUri==0 ){
3248 return 0;
3249 }else if( (zKey = uriParameter(zUri, "hexkey"))!=0 && zKey[0] ){
3250 u8 iByte;
3251 int i;
3252 char zDecoded[40];
3253 for(i=0, iByte=0; i<sizeof(zDecoded)*2 && sqlite3Isxdigit(zKey[i]); i++){
3254 iByte = (iByte<<4) + sqlite3HexToInt(zKey[i]);
3255 if( (i&1)!=0 ) zDecoded[i/2] = iByte;
3257 sqlite3_key_v2(db, zDb, zDecoded, i/2);
3258 return 1;
3259 }else if( (zKey = uriParameter(zUri, "key"))!=0 ){
3260 sqlite3_key_v2(db, zDb, zKey, sqlite3Strlen30(zKey));
3261 return 1;
3262 }else if( (zKey = uriParameter(zUri, "textkey"))!=0 ){
3263 sqlite3_key_v2(db, zDb, zKey, -1);
3264 return 1;
3265 }else{
3266 return 0;
3269 #endif
3270 /* END SQLCIPHER */
3274 ** This routine does the work of opening a database on behalf of
3275 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
3276 ** is UTF-8 encoded.
3278 static int openDatabase(
3279 const char *zFilename, /* Database filename UTF-8 encoded */
3280 sqlite3 **ppDb, /* OUT: Returned database handle */
3281 unsigned int flags, /* Operational flags */
3282 const char *zVfs /* Name of the VFS to use */
3284 sqlite3 *db; /* Store allocated handle here */
3285 int rc; /* Return code */
3286 int isThreadsafe; /* True for threadsafe connections */
3287 char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
3288 char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
3289 int i; /* Loop counter */
3291 #ifdef SQLITE_ENABLE_API_ARMOR
3292 if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
3293 #endif
3294 *ppDb = 0;
3295 #ifndef SQLITE_OMIT_AUTOINIT
3296 rc = sqlite3_initialize();
3297 if( rc ) return rc;
3298 #endif
3300 if( sqlite3GlobalConfig.bCoreMutex==0 ){
3301 isThreadsafe = 0;
3302 }else if( flags & SQLITE_OPEN_NOMUTEX ){
3303 isThreadsafe = 0;
3304 }else if( flags & SQLITE_OPEN_FULLMUTEX ){
3305 isThreadsafe = 1;
3306 }else{
3307 isThreadsafe = sqlite3GlobalConfig.bFullMutex;
3310 if( flags & SQLITE_OPEN_PRIVATECACHE ){
3311 flags &= ~SQLITE_OPEN_SHAREDCACHE;
3312 }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
3313 flags |= SQLITE_OPEN_SHAREDCACHE;
3316 /* Remove harmful bits from the flags parameter
3318 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
3319 ** dealt with in the previous code block. Besides these, the only
3320 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
3321 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
3322 ** SQLITE_OPEN_PRIVATECACHE, SQLITE_OPEN_EXRESCODE, and some reserved
3323 ** bits. Silently mask off all other flags.
3325 flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
3326 SQLITE_OPEN_EXCLUSIVE |
3327 SQLITE_OPEN_MAIN_DB |
3328 SQLITE_OPEN_TEMP_DB |
3329 SQLITE_OPEN_TRANSIENT_DB |
3330 SQLITE_OPEN_MAIN_JOURNAL |
3331 SQLITE_OPEN_TEMP_JOURNAL |
3332 SQLITE_OPEN_SUBJOURNAL |
3333 SQLITE_OPEN_SUPER_JOURNAL |
3334 SQLITE_OPEN_NOMUTEX |
3335 SQLITE_OPEN_FULLMUTEX |
3336 SQLITE_OPEN_WAL
3339 /* Allocate the sqlite data structure */
3340 db = sqlite3MallocZero( sizeof(sqlite3) );
3341 if( db==0 ) goto opendb_out;
3342 if( isThreadsafe
3343 #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
3344 || sqlite3GlobalConfig.bCoreMutex
3345 #endif
3347 db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
3348 if( db->mutex==0 ){
3349 sqlite3_free(db);
3350 db = 0;
3351 goto opendb_out;
3353 if( isThreadsafe==0 ){
3354 sqlite3MutexWarnOnContention(db->mutex);
3357 sqlite3_mutex_enter(db->mutex);
3358 db->errMask = (flags & SQLITE_OPEN_EXRESCODE)!=0 ? 0xffffffff : 0xff;
3359 db->nDb = 2;
3360 db->eOpenState = SQLITE_STATE_BUSY;
3361 db->aDb = db->aDbStatic;
3362 db->lookaside.bDisable = 1;
3363 db->lookaside.sz = 0;
3365 assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
3366 memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
3367 db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
3368 db->autoCommit = 1;
3369 db->nextAutovac = -1;
3370 db->szMmap = sqlite3GlobalConfig.szMmap;
3371 db->nextPagesize = 0;
3372 db->init.azInit = sqlite3StdType; /* Any array of string ptrs will do */
3373 #ifdef SQLITE_ENABLE_SORTER_MMAP
3374 /* Beginning with version 3.37.0, using the VFS xFetch() API to memory-map
3375 ** the temporary files used to do external sorts (see code in vdbesort.c)
3376 ** is disabled. It can still be used either by defining
3377 ** SQLITE_ENABLE_SORTER_MMAP at compile time or by using the
3378 ** SQLITE_TESTCTRL_SORTER_MMAP test-control at runtime. */
3379 db->nMaxSorterMmap = 0x7FFFFFFF;
3380 #endif
3381 db->flags |= SQLITE_ShortColNames
3382 | SQLITE_EnableTrigger
3383 | SQLITE_EnableView
3384 | SQLITE_CacheSpill
3385 #if !defined(SQLITE_TRUSTED_SCHEMA) || SQLITE_TRUSTED_SCHEMA+0!=0
3386 | SQLITE_TrustedSchema
3387 #endif
3388 /* The SQLITE_DQS compile-time option determines the default settings
3389 ** for SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML.
3391 ** SQLITE_DQS SQLITE_DBCONFIG_DQS_DDL SQLITE_DBCONFIG_DQS_DML
3392 ** ---------- ----------------------- -----------------------
3393 ** undefined on on
3394 ** 3 on on
3395 ** 2 on off
3396 ** 1 off on
3397 ** 0 off off
3399 ** Legacy behavior is 3 (double-quoted string literals are allowed anywhere)
3400 ** and so that is the default. But developers are encouraged to use
3401 ** -DSQLITE_DQS=0 (best) or -DSQLITE_DQS=1 (second choice) if possible.
3403 #if !defined(SQLITE_DQS)
3404 # define SQLITE_DQS 3
3405 #endif
3406 #if (SQLITE_DQS&1)==1
3407 | SQLITE_DqsDML
3408 #endif
3409 #if (SQLITE_DQS&2)==2
3410 | SQLITE_DqsDDL
3411 #endif
3413 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
3414 | SQLITE_AutoIndex
3415 #endif
3416 #if SQLITE_DEFAULT_CKPTFULLFSYNC
3417 | SQLITE_CkptFullFSync
3418 #endif
3419 #if SQLITE_DEFAULT_FILE_FORMAT<4
3420 | SQLITE_LegacyFileFmt
3421 #endif
3422 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
3423 | SQLITE_LoadExtension
3424 #endif
3425 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
3426 | SQLITE_RecTriggers
3427 #endif
3428 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
3429 | SQLITE_ForeignKeys
3430 #endif
3431 #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
3432 | SQLITE_ReverseOrder
3433 #endif
3434 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
3435 | SQLITE_CellSizeCk
3436 #endif
3437 #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
3438 | SQLITE_Fts3Tokenizer
3439 #endif
3440 #if defined(SQLITE_ENABLE_QPSG)
3441 | SQLITE_EnableQPSG
3442 #endif
3443 #if defined(SQLITE_DEFAULT_DEFENSIVE)
3444 | SQLITE_Defensive
3445 #endif
3446 #if defined(SQLITE_DEFAULT_LEGACY_ALTER_TABLE)
3447 | SQLITE_LegacyAlter
3448 #endif
3449 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
3450 | SQLITE_StmtScanStatus
3451 #endif
3453 sqlite3HashInit(&db->aCollSeq);
3454 #ifndef SQLITE_OMIT_VIRTUALTABLE
3455 sqlite3HashInit(&db->aModule);
3456 #endif
3458 /* Add the default collation sequence BINARY. BINARY works for both UTF-8
3459 ** and UTF-16, so add a version for each to avoid any unnecessary
3460 ** conversions. The only error that can occur here is a malloc() failure.
3462 ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
3463 ** functions:
3465 createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
3466 createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
3467 createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
3468 createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
3469 createCollation(db, "RTRIM", SQLITE_UTF8, 0, rtrimCollFunc, 0);
3470 if( db->mallocFailed ){
3471 goto opendb_out;
3474 #if SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL)
3475 /* Process magic filenames ":localStorage:" and ":sessionStorage:" */
3476 if( zFilename && zFilename[0]==':' ){
3477 if( strcmp(zFilename, ":localStorage:")==0 ){
3478 zFilename = "file:local?vfs=kvvfs";
3479 flags |= SQLITE_OPEN_URI;
3480 }else if( strcmp(zFilename, ":sessionStorage:")==0 ){
3481 zFilename = "file:session?vfs=kvvfs";
3482 flags |= SQLITE_OPEN_URI;
3485 #endif /* SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL) */
3487 /* Parse the filename/URI argument
3489 ** Only allow sensible combinations of bits in the flags argument.
3490 ** Throw an error if any non-sense combination is used. If we
3491 ** do not block illegal combinations here, it could trigger
3492 ** assert() statements in deeper layers. Sensible combinations
3493 ** are:
3495 ** 1: SQLITE_OPEN_READONLY
3496 ** 2: SQLITE_OPEN_READWRITE
3497 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
3499 db->openFlags = flags;
3500 assert( SQLITE_OPEN_READONLY == 0x01 );
3501 assert( SQLITE_OPEN_READWRITE == 0x02 );
3502 assert( SQLITE_OPEN_CREATE == 0x04 );
3503 testcase( (1<<(flags&7))==0x02 ); /* READONLY */
3504 testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
3505 testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
3506 if( ((1<<(flags&7)) & 0x46)==0 ){
3507 rc = SQLITE_MISUSE_BKPT; /* IMP: R-18321-05872 */
3508 }else{
3509 rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
3511 if( rc!=SQLITE_OK ){
3512 if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
3513 sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
3514 sqlite3_free(zErrMsg);
3515 goto opendb_out;
3517 assert( db->pVfs!=0 );
3518 #if SQLITE_OS_KV || defined(SQLITE_OS_KV_OPTIONAL)
3519 if( sqlite3_stricmp(db->pVfs->zName, "kvvfs")==0 ){
3520 db->temp_store = 2;
3522 #endif
3524 /* Open the backend database driver */
3525 rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
3526 flags | SQLITE_OPEN_MAIN_DB);
3527 if( rc!=SQLITE_OK ){
3528 if( rc==SQLITE_IOERR_NOMEM ){
3529 rc = SQLITE_NOMEM_BKPT;
3531 sqlite3Error(db, rc);
3532 goto opendb_out;
3534 sqlite3BtreeEnter(db->aDb[0].pBt);
3535 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
3536 if( !db->mallocFailed ){
3537 sqlite3SetTextEncoding(db, SCHEMA_ENC(db));
3539 sqlite3BtreeLeave(db->aDb[0].pBt);
3540 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
3542 /* The default safety_level for the main database is FULL; for the temp
3543 ** database it is OFF. This matches the pager layer defaults.
3545 db->aDb[0].zDbSName = "main";
3546 db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
3547 db->aDb[1].zDbSName = "temp";
3548 db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
3550 db->eOpenState = SQLITE_STATE_OPEN;
3551 if( db->mallocFailed ){
3552 goto opendb_out;
3555 /* Register all built-in functions, but do not attempt to read the
3556 ** database schema yet. This is delayed until the first time the database
3557 ** is accessed.
3559 sqlite3Error(db, SQLITE_OK);
3560 sqlite3RegisterPerConnectionBuiltinFunctions(db);
3561 rc = sqlite3_errcode(db);
3564 /* Load compiled-in extensions */
3565 for(i=0; rc==SQLITE_OK && i<ArraySize(sqlite3BuiltinExtensions); i++){
3566 rc = sqlite3BuiltinExtensions[i](db);
3569 /* Load automatic extensions - extensions that have been registered
3570 ** using the sqlite3_automatic_extension() API.
3572 if( rc==SQLITE_OK ){
3573 sqlite3AutoLoadExtensions(db);
3574 rc = sqlite3_errcode(db);
3575 if( rc!=SQLITE_OK ){
3576 goto opendb_out;
3580 #ifdef SQLCIPHER_EXT
3581 if( !db->mallocFailed && rc==SQLITE_OK ){
3582 extern int sqlcipherVtabInit(sqlite3 *);
3583 rc = sqlcipherVtabInit(db);
3585 #endif
3587 #ifdef SQLITE_ENABLE_INTERNAL_FUNCTIONS
3588 /* Testing use only!!! The -DSQLITE_ENABLE_INTERNAL_FUNCTIONS=1 compile-time
3589 ** option gives access to internal functions by default.
3590 ** Testing use only!!! */
3591 db->mDbFlags |= DBFLAG_InternalFunc;
3592 #endif
3594 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
3595 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
3596 ** mode. Doing nothing at all also makes NORMAL the default.
3598 #ifdef SQLITE_DEFAULT_LOCKING_MODE
3599 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
3600 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
3601 SQLITE_DEFAULT_LOCKING_MODE);
3602 #endif
3604 if( rc ) sqlite3Error(db, rc);
3606 /* Enable the lookaside-malloc subsystem */
3607 setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
3608 sqlite3GlobalConfig.nLookaside);
3610 sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
3612 opendb_out:
3613 if( db ){
3614 assert( db->mutex!=0 || isThreadsafe==0
3615 || sqlite3GlobalConfig.bFullMutex==0 );
3616 sqlite3_mutex_leave(db->mutex);
3618 rc = sqlite3_errcode(db);
3619 assert( db!=0 || (rc&0xff)==SQLITE_NOMEM );
3620 if( (rc&0xff)==SQLITE_NOMEM ){
3621 sqlite3_close(db);
3622 db = 0;
3623 }else if( rc!=SQLITE_OK ){
3624 db->eOpenState = SQLITE_STATE_SICK;
3626 *ppDb = db;
3627 #ifdef SQLITE_ENABLE_SQLLOG
3628 if( sqlite3GlobalConfig.xSqllog ){
3629 /* Opening a db handle. Fourth parameter is passed 0. */
3630 void *pArg = sqlite3GlobalConfig.pSqllogArg;
3631 sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
3633 #endif
3634 /* BEGIN SQLCIPHER */
3635 #if defined(SQLITE_HAS_CODEC)
3636 if( rc==SQLITE_OK ) sqlite3CodecQueryParameters(db, 0, zOpen);
3637 #endif
3638 /* END SQLCIPHER */
3639 sqlite3_free_filename(zOpen);
3640 return rc;
3645 ** Open a new database handle.
3647 int sqlite3_open(
3648 const char *zFilename,
3649 sqlite3 **ppDb
3651 return openDatabase(zFilename, ppDb,
3652 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
3654 int sqlite3_open_v2(
3655 const char *filename, /* Database filename (UTF-8) */
3656 sqlite3 **ppDb, /* OUT: SQLite db handle */
3657 int flags, /* Flags */
3658 const char *zVfs /* Name of VFS module to use */
3660 return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
3663 #ifndef SQLITE_OMIT_UTF16
3665 ** Open a new database handle.
3667 int sqlite3_open16(
3668 const void *zFilename,
3669 sqlite3 **ppDb
3671 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
3672 sqlite3_value *pVal;
3673 int rc;
3675 #ifdef SQLITE_ENABLE_API_ARMOR
3676 if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
3677 #endif
3678 *ppDb = 0;
3679 #ifndef SQLITE_OMIT_AUTOINIT
3680 rc = sqlite3_initialize();
3681 if( rc ) return rc;
3682 #endif
3683 if( zFilename==0 ) zFilename = "\000\000";
3684 pVal = sqlite3ValueNew(0);
3685 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
3686 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
3687 if( zFilename8 ){
3688 rc = openDatabase(zFilename8, ppDb,
3689 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
3690 assert( *ppDb || rc==SQLITE_NOMEM );
3691 if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
3692 SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
3694 }else{
3695 rc = SQLITE_NOMEM_BKPT;
3697 sqlite3ValueFree(pVal);
3699 return rc & 0xff;
3701 #endif /* SQLITE_OMIT_UTF16 */
3704 ** Register a new collation sequence with the database handle db.
3706 int sqlite3_create_collation(
3707 sqlite3* db,
3708 const char *zName,
3709 int enc,
3710 void* pCtx,
3711 int(*xCompare)(void*,int,const void*,int,const void*)
3713 return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
3717 ** Register a new collation sequence with the database handle db.
3719 int sqlite3_create_collation_v2(
3720 sqlite3* db,
3721 const char *zName,
3722 int enc,
3723 void* pCtx,
3724 int(*xCompare)(void*,int,const void*,int,const void*),
3725 void(*xDel)(void*)
3727 int rc;
3729 #ifdef SQLITE_ENABLE_API_ARMOR
3730 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
3731 #endif
3732 sqlite3_mutex_enter(db->mutex);
3733 assert( !db->mallocFailed );
3734 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
3735 rc = sqlite3ApiExit(db, rc);
3736 sqlite3_mutex_leave(db->mutex);
3737 return rc;
3740 #ifndef SQLITE_OMIT_UTF16
3742 ** Register a new collation sequence with the database handle db.
3744 int sqlite3_create_collation16(
3745 sqlite3* db,
3746 const void *zName,
3747 int enc,
3748 void* pCtx,
3749 int(*xCompare)(void*,int,const void*,int,const void*)
3751 int rc = SQLITE_OK;
3752 char *zName8;
3754 #ifdef SQLITE_ENABLE_API_ARMOR
3755 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
3756 #endif
3757 sqlite3_mutex_enter(db->mutex);
3758 assert( !db->mallocFailed );
3759 zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
3760 if( zName8 ){
3761 rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
3762 sqlite3DbFree(db, zName8);
3764 rc = sqlite3ApiExit(db, rc);
3765 sqlite3_mutex_leave(db->mutex);
3766 return rc;
3768 #endif /* SQLITE_OMIT_UTF16 */
3771 ** Register a collation sequence factory callback with the database handle
3772 ** db. Replace any previously installed collation sequence factory.
3774 int sqlite3_collation_needed(
3775 sqlite3 *db,
3776 void *pCollNeededArg,
3777 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
3779 #ifdef SQLITE_ENABLE_API_ARMOR
3780 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3781 #endif
3782 sqlite3_mutex_enter(db->mutex);
3783 db->xCollNeeded = xCollNeeded;
3784 db->xCollNeeded16 = 0;
3785 db->pCollNeededArg = pCollNeededArg;
3786 sqlite3_mutex_leave(db->mutex);
3787 return SQLITE_OK;
3790 #ifndef SQLITE_OMIT_UTF16
3792 ** Register a collation sequence factory callback with the database handle
3793 ** db. Replace any previously installed collation sequence factory.
3795 int sqlite3_collation_needed16(
3796 sqlite3 *db,
3797 void *pCollNeededArg,
3798 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
3800 #ifdef SQLITE_ENABLE_API_ARMOR
3801 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3802 #endif
3803 sqlite3_mutex_enter(db->mutex);
3804 db->xCollNeeded = 0;
3805 db->xCollNeeded16 = xCollNeeded16;
3806 db->pCollNeededArg = pCollNeededArg;
3807 sqlite3_mutex_leave(db->mutex);
3808 return SQLITE_OK;
3810 #endif /* SQLITE_OMIT_UTF16 */
3813 ** Find existing client data.
3815 void *sqlite3_get_clientdata(sqlite3 *db, const char *zName){
3816 DbClientData *p;
3817 sqlite3_mutex_enter(db->mutex);
3818 for(p=db->pDbData; p; p=p->pNext){
3819 if( strcmp(p->zName, zName)==0 ){
3820 void *pResult = p->pData;
3821 sqlite3_mutex_leave(db->mutex);
3822 return pResult;
3825 sqlite3_mutex_leave(db->mutex);
3826 return 0;
3830 ** Add new client data to a database connection.
3832 int sqlite3_set_clientdata(
3833 sqlite3 *db, /* Attach client data to this connection */
3834 const char *zName, /* Name of the client data */
3835 void *pData, /* The client data itself */
3836 void (*xDestructor)(void*) /* Destructor */
3838 DbClientData *p, **pp;
3839 sqlite3_mutex_enter(db->mutex);
3840 pp = &db->pDbData;
3841 for(p=db->pDbData; p && strcmp(p->zName,zName); p=p->pNext){
3842 pp = &p->pNext;
3844 if( p ){
3845 assert( p->pData!=0 );
3846 if( p->xDestructor ) p->xDestructor(p->pData);
3847 if( pData==0 ){
3848 *pp = p->pNext;
3849 sqlite3_free(p);
3850 sqlite3_mutex_leave(db->mutex);
3851 return SQLITE_OK;
3853 }else if( pData==0 ){
3854 sqlite3_mutex_leave(db->mutex);
3855 return SQLITE_OK;
3856 }else{
3857 size_t n = strlen(zName);
3858 p = sqlite3_malloc64( sizeof(DbClientData)+n+1 );
3859 if( p==0 ){
3860 if( xDestructor ) xDestructor(pData);
3861 sqlite3_mutex_leave(db->mutex);
3862 return SQLITE_NOMEM;
3864 memcpy(p->zName, zName, n+1);
3865 p->pNext = db->pDbData;
3866 db->pDbData = p;
3868 p->pData = pData;
3869 p->xDestructor = xDestructor;
3870 sqlite3_mutex_leave(db->mutex);
3871 return SQLITE_OK;
3875 #ifndef SQLITE_OMIT_DEPRECATED
3877 ** This function is now an anachronism. It used to be used to recover from a
3878 ** malloc() failure, but SQLite now does this automatically.
3880 int sqlite3_global_recover(void){
3881 return SQLITE_OK;
3883 #endif
3886 ** Test to see whether or not the database connection is in autocommit
3887 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
3888 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
3889 ** by the next COMMIT or ROLLBACK.
3891 int sqlite3_get_autocommit(sqlite3 *db){
3892 #ifdef SQLITE_ENABLE_API_ARMOR
3893 if( !sqlite3SafetyCheckOk(db) ){
3894 (void)SQLITE_MISUSE_BKPT;
3895 return 0;
3897 #endif
3898 return db->autoCommit;
3902 ** The following routines are substitutes for constants SQLITE_CORRUPT,
3903 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
3904 ** constants. They serve two purposes:
3906 ** 1. Serve as a convenient place to set a breakpoint in a debugger
3907 ** to detect when version error conditions occurs.
3909 ** 2. Invoke sqlite3_log() to provide the source code location where
3910 ** a low-level error is first detected.
3912 int sqlite3ReportError(int iErr, int lineno, const char *zType){
3913 sqlite3_log(iErr, "%s at line %d of [%.10s]",
3914 zType, lineno, 20+sqlite3_sourceid());
3915 return iErr;
3917 int sqlite3CorruptError(int lineno){
3918 testcase( sqlite3GlobalConfig.xLog!=0 );
3919 return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
3921 int sqlite3MisuseError(int lineno){
3922 testcase( sqlite3GlobalConfig.xLog!=0 );
3923 return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
3925 int sqlite3CantopenError(int lineno){
3926 testcase( sqlite3GlobalConfig.xLog!=0 );
3927 return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
3929 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
3930 int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
3931 char zMsg[100];
3932 sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
3933 testcase( sqlite3GlobalConfig.xLog!=0 );
3934 return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
3936 #endif
3937 #ifdef SQLITE_DEBUG
3938 int sqlite3NomemError(int lineno){
3939 testcase( sqlite3GlobalConfig.xLog!=0 );
3940 return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
3942 int sqlite3IoerrnomemError(int lineno){
3943 testcase( sqlite3GlobalConfig.xLog!=0 );
3944 return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
3946 #endif
3948 #ifndef SQLITE_OMIT_DEPRECATED
3950 ** This is a convenience routine that makes sure that all thread-specific
3951 ** data for this thread has been deallocated.
3953 ** SQLite no longer uses thread-specific data so this routine is now a
3954 ** no-op. It is retained for historical compatibility.
3956 void sqlite3_thread_cleanup(void){
3958 #endif
3961 ** Return meta information about a specific column of a database table.
3962 ** See comment in sqlite3.h (sqlite.h.in) for details.
3964 int sqlite3_table_column_metadata(
3965 sqlite3 *db, /* Connection handle */
3966 const char *zDbName, /* Database name or NULL */
3967 const char *zTableName, /* Table name */
3968 const char *zColumnName, /* Column name */
3969 char const **pzDataType, /* OUTPUT: Declared data type */
3970 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
3971 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
3972 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
3973 int *pAutoinc /* OUTPUT: True if column is auto-increment */
3975 int rc;
3976 char *zErrMsg = 0;
3977 Table *pTab = 0;
3978 Column *pCol = 0;
3979 int iCol = 0;
3980 char const *zDataType = 0;
3981 char const *zCollSeq = 0;
3982 int notnull = 0;
3983 int primarykey = 0;
3984 int autoinc = 0;
3987 #ifdef SQLITE_ENABLE_API_ARMOR
3988 if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
3989 return SQLITE_MISUSE_BKPT;
3991 #endif
3993 /* Ensure the database schema has been loaded */
3994 sqlite3_mutex_enter(db->mutex);
3995 sqlite3BtreeEnterAll(db);
3996 rc = sqlite3Init(db, &zErrMsg);
3997 if( SQLITE_OK!=rc ){
3998 goto error_out;
4001 /* Locate the table in question */
4002 pTab = sqlite3FindTable(db, zTableName, zDbName);
4003 if( !pTab || IsView(pTab) ){
4004 pTab = 0;
4005 goto error_out;
4008 /* Find the column for which info is requested */
4009 if( zColumnName==0 ){
4010 /* Query for existence of table only */
4011 }else{
4012 for(iCol=0; iCol<pTab->nCol; iCol++){
4013 pCol = &pTab->aCol[iCol];
4014 if( 0==sqlite3StrICmp(pCol->zCnName, zColumnName) ){
4015 break;
4018 if( iCol==pTab->nCol ){
4019 if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
4020 iCol = pTab->iPKey;
4021 pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
4022 }else{
4023 pTab = 0;
4024 goto error_out;
4029 /* The following block stores the meta information that will be returned
4030 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
4031 ** and autoinc. At this point there are two possibilities:
4033 ** 1. The specified column name was rowid", "oid" or "_rowid_"
4034 ** and there is no explicitly declared IPK column.
4036 ** 2. The table is not a view and the column name identified an
4037 ** explicitly declared column. Copy meta information from *pCol.
4039 if( pCol ){
4040 zDataType = sqlite3ColumnType(pCol,0);
4041 zCollSeq = sqlite3ColumnColl(pCol);
4042 notnull = pCol->notNull!=0;
4043 primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
4044 autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
4045 }else{
4046 zDataType = "INTEGER";
4047 primarykey = 1;
4049 if( !zCollSeq ){
4050 zCollSeq = sqlite3StrBINARY;
4053 error_out:
4054 sqlite3BtreeLeaveAll(db);
4056 /* Whether the function call succeeded or failed, set the output parameters
4057 ** to whatever their local counterparts contain. If an error did occur,
4058 ** this has the effect of zeroing all output parameters.
4060 if( pzDataType ) *pzDataType = zDataType;
4061 if( pzCollSeq ) *pzCollSeq = zCollSeq;
4062 if( pNotNull ) *pNotNull = notnull;
4063 if( pPrimaryKey ) *pPrimaryKey = primarykey;
4064 if( pAutoinc ) *pAutoinc = autoinc;
4066 if( SQLITE_OK==rc && !pTab ){
4067 sqlite3DbFree(db, zErrMsg);
4068 zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
4069 zColumnName);
4070 rc = SQLITE_ERROR;
4072 sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
4073 sqlite3DbFree(db, zErrMsg);
4074 rc = sqlite3ApiExit(db, rc);
4075 sqlite3_mutex_leave(db->mutex);
4076 return rc;
4080 ** Sleep for a little while. Return the amount of time slept.
4082 int sqlite3_sleep(int ms){
4083 sqlite3_vfs *pVfs;
4084 int rc;
4085 pVfs = sqlite3_vfs_find(0);
4086 if( pVfs==0 ) return 0;
4088 /* This function works in milliseconds, but the underlying OsSleep()
4089 ** API uses microseconds. Hence the 1000's.
4091 rc = (sqlite3OsSleep(pVfs, ms<0 ? 0 : 1000*ms)/1000);
4092 return rc;
4096 ** Enable or disable the extended result codes.
4098 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
4099 #ifdef SQLITE_ENABLE_API_ARMOR
4100 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
4101 #endif
4102 sqlite3_mutex_enter(db->mutex);
4103 db->errMask = onoff ? 0xffffffff : 0xff;
4104 sqlite3_mutex_leave(db->mutex);
4105 return SQLITE_OK;
4109 ** Invoke the xFileControl method on a particular database.
4111 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
4112 int rc = SQLITE_ERROR;
4113 Btree *pBtree;
4115 #ifdef SQLITE_ENABLE_API_ARMOR
4116 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
4117 #endif
4118 sqlite3_mutex_enter(db->mutex);
4119 pBtree = sqlite3DbNameToBtree(db, zDbName);
4120 if( pBtree ){
4121 Pager *pPager;
4122 sqlite3_file *fd;
4123 sqlite3BtreeEnter(pBtree);
4124 pPager = sqlite3BtreePager(pBtree);
4125 assert( pPager!=0 );
4126 fd = sqlite3PagerFile(pPager);
4127 assert( fd!=0 );
4128 if( op==SQLITE_FCNTL_FILE_POINTER ){
4129 *(sqlite3_file**)pArg = fd;
4130 rc = SQLITE_OK;
4131 }else if( op==SQLITE_FCNTL_VFS_POINTER ){
4132 *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
4133 rc = SQLITE_OK;
4134 }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
4135 *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
4136 rc = SQLITE_OK;
4137 }else if( op==SQLITE_FCNTL_DATA_VERSION ){
4138 *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager);
4139 rc = SQLITE_OK;
4140 }else if( op==SQLITE_FCNTL_RESERVE_BYTES ){
4141 int iNew = *(int*)pArg;
4142 *(int*)pArg = sqlite3BtreeGetRequestedReserve(pBtree);
4143 if( iNew>=0 && iNew<=255 ){
4144 sqlite3BtreeSetPageSize(pBtree, 0, iNew, 0);
4146 rc = SQLITE_OK;
4147 }else if( op==SQLITE_FCNTL_RESET_CACHE ){
4148 sqlite3BtreeClearCache(pBtree);
4149 rc = SQLITE_OK;
4150 }else{
4151 int nSave = db->busyHandler.nBusy;
4152 rc = sqlite3OsFileControl(fd, op, pArg);
4153 db->busyHandler.nBusy = nSave;
4155 sqlite3BtreeLeave(pBtree);
4157 sqlite3_mutex_leave(db->mutex);
4158 return rc;
4162 ** Interface to the testing logic.
4164 int sqlite3_test_control(int op, ...){
4165 int rc = 0;
4166 #ifdef SQLITE_UNTESTABLE
4167 UNUSED_PARAMETER(op);
4168 #else
4169 va_list ap;
4170 va_start(ap, op);
4171 switch( op ){
4174 ** Save the current state of the PRNG.
4176 case SQLITE_TESTCTRL_PRNG_SAVE: {
4177 sqlite3PrngSaveState();
4178 break;
4182 ** Restore the state of the PRNG to the last state saved using
4183 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
4184 ** this verb acts like PRNG_RESET.
4186 case SQLITE_TESTCTRL_PRNG_RESTORE: {
4187 sqlite3PrngRestoreState();
4188 break;
4191 /* sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, int x, sqlite3 *db);
4193 ** Control the seed for the pseudo-random number generator (PRNG) that
4194 ** is built into SQLite. Cases:
4196 ** x!=0 && db!=0 Seed the PRNG to the current value of the
4197 ** schema cookie in the main database for db, or
4198 ** x if the schema cookie is zero. This case
4199 ** is convenient to use with database fuzzers
4200 ** as it allows the fuzzer some control over the
4201 ** the PRNG seed.
4203 ** x!=0 && db==0 Seed the PRNG to the value of x.
4205 ** x==0 && db==0 Revert to default behavior of using the
4206 ** xRandomness method on the primary VFS.
4208 ** This test-control also resets the PRNG so that the new seed will
4209 ** be used for the next call to sqlite3_randomness().
4211 #ifndef SQLITE_OMIT_WSD
4212 case SQLITE_TESTCTRL_PRNG_SEED: {
4213 int x = va_arg(ap, int);
4214 int y;
4215 sqlite3 *db = va_arg(ap, sqlite3*);
4216 assert( db==0 || db->aDb[0].pSchema!=0 );
4217 if( db && (y = db->aDb[0].pSchema->schema_cookie)!=0 ){ x = y; }
4218 sqlite3Config.iPrngSeed = x;
4219 sqlite3_randomness(0,0);
4220 break;
4222 #endif
4224 /* sqlite3_test_control(SQLITE_TESTCTRL_FK_NO_ACTION, sqlite3 *db, int b);
4226 ** If b is true, then activate the SQLITE_FkNoAction setting. If b is
4227 ** false then clearn that setting. If the SQLITE_FkNoAction setting is
4228 ** abled, all foreign key ON DELETE and ON UPDATE actions behave as if
4229 ** they were NO ACTION, regardless of how they are defined.
4231 ** NB: One must usually run "PRAGMA writable_schema=RESET" after
4232 ** using this test-control, before it will take full effect. failing
4233 ** to reset the schema can result in some unexpected behavior.
4235 case SQLITE_TESTCTRL_FK_NO_ACTION: {
4236 sqlite3 *db = va_arg(ap, sqlite3*);
4237 int b = va_arg(ap, int);
4238 if( b ){
4239 db->flags |= SQLITE_FkNoAction;
4240 }else{
4241 db->flags &= ~SQLITE_FkNoAction;
4243 break;
4247 ** sqlite3_test_control(BITVEC_TEST, size, program)
4249 ** Run a test against a Bitvec object of size. The program argument
4250 ** is an array of integers that defines the test. Return -1 on a
4251 ** memory allocation error, 0 on success, or non-zero for an error.
4252 ** See the sqlite3BitvecBuiltinTest() for additional information.
4254 case SQLITE_TESTCTRL_BITVEC_TEST: {
4255 int sz = va_arg(ap, int);
4256 int *aProg = va_arg(ap, int*);
4257 rc = sqlite3BitvecBuiltinTest(sz, aProg);
4258 break;
4262 ** sqlite3_test_control(FAULT_INSTALL, xCallback)
4264 ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
4265 ** if xCallback is not NULL.
4267 ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
4268 ** is called immediately after installing the new callback and the return
4269 ** value from sqlite3FaultSim(0) becomes the return from
4270 ** sqlite3_test_control().
4272 case SQLITE_TESTCTRL_FAULT_INSTALL: {
4273 /* A bug in MSVC prevents it from understanding pointers to functions
4274 ** types in the second argument to va_arg(). Work around the problem
4275 ** using a typedef.
4276 ** http://support.microsoft.com/kb/47961 <-- dead hyperlink
4277 ** Search at http://web.archive.org/ to find the 2015-03-16 archive
4278 ** of the link above to see the original text.
4279 ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
4281 typedef int(*sqlite3FaultFuncType)(int);
4282 sqlite3GlobalConfig.xTestCallback = va_arg(ap, sqlite3FaultFuncType);
4283 rc = sqlite3FaultSim(0);
4284 break;
4288 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
4290 ** Register hooks to call to indicate which malloc() failures
4291 ** are benign.
4293 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
4294 typedef void (*void_function)(void);
4295 void_function xBenignBegin;
4296 void_function xBenignEnd;
4297 xBenignBegin = va_arg(ap, void_function);
4298 xBenignEnd = va_arg(ap, void_function);
4299 sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
4300 break;
4304 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
4306 ** Set the PENDING byte to the value in the argument, if X>0.
4307 ** Make no changes if X==0. Return the value of the pending byte
4308 ** as it existing before this routine was called.
4310 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
4311 ** an incompatible database file format. Changing the PENDING byte
4312 ** while any database connection is open results in undefined and
4313 ** deleterious behavior.
4315 case SQLITE_TESTCTRL_PENDING_BYTE: {
4316 rc = PENDING_BYTE;
4317 #ifndef SQLITE_OMIT_WSD
4319 unsigned int newVal = va_arg(ap, unsigned int);
4320 if( newVal ) sqlite3PendingByte = newVal;
4322 #endif
4323 break;
4327 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
4329 ** This action provides a run-time test to see whether or not
4330 ** assert() was enabled at compile-time. If X is true and assert()
4331 ** is enabled, then the return value is true. If X is true and
4332 ** assert() is disabled, then the return value is zero. If X is
4333 ** false and assert() is enabled, then the assertion fires and the
4334 ** process aborts. If X is false and assert() is disabled, then the
4335 ** return value is zero.
4337 case SQLITE_TESTCTRL_ASSERT: {
4338 volatile int x = 0;
4339 assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
4340 rc = x;
4341 #if defined(SQLITE_DEBUG)
4342 /* Invoke these debugging routines so that the compiler does not
4343 ** issue "defined but not used" warnings. */
4344 if( x==9999 ){
4345 sqlite3ShowExpr(0);
4346 sqlite3ShowExpr(0);
4347 sqlite3ShowExprList(0);
4348 sqlite3ShowIdList(0);
4349 sqlite3ShowSrcList(0);
4350 sqlite3ShowWith(0);
4351 sqlite3ShowUpsert(0);
4352 #ifndef SQLITE_OMIT_TRIGGER
4353 sqlite3ShowTriggerStep(0);
4354 sqlite3ShowTriggerStepList(0);
4355 sqlite3ShowTrigger(0);
4356 sqlite3ShowTriggerList(0);
4357 #endif
4358 #ifndef SQLITE_OMIT_WINDOWFUNC
4359 sqlite3ShowWindow(0);
4360 sqlite3ShowWinFunc(0);
4361 #endif
4362 sqlite3ShowSelect(0);
4364 #endif
4365 break;
4370 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
4372 ** This action provides a run-time test to see how the ALWAYS and
4373 ** NEVER macros were defined at compile-time.
4375 ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
4377 ** The recommended test is X==2. If the return value is 2, that means
4378 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
4379 ** default setting. If the return value is 1, then ALWAYS() is either
4380 ** hard-coded to true or else it asserts if its argument is false.
4381 ** The first behavior (hard-coded to true) is the case if
4382 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
4383 ** behavior (assert if the argument to ALWAYS() is false) is the case if
4384 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
4386 ** The run-time test procedure might look something like this:
4388 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
4389 ** // ALWAYS() and NEVER() are no-op pass-through macros
4390 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
4391 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
4392 ** }else{
4393 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
4394 ** }
4396 case SQLITE_TESTCTRL_ALWAYS: {
4397 int x = va_arg(ap,int);
4398 rc = x ? ALWAYS(x) : 0;
4399 break;
4403 ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
4405 ** The integer returned reveals the byte-order of the computer on which
4406 ** SQLite is running:
4408 ** 1 big-endian, determined at run-time
4409 ** 10 little-endian, determined at run-time
4410 ** 432101 big-endian, determined at compile-time
4411 ** 123410 little-endian, determined at compile-time
4413 case SQLITE_TESTCTRL_BYTEORDER: {
4414 rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
4415 break;
4418 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
4420 ** Enable or disable various optimizations for testing purposes. The
4421 ** argument N is a bitmask of optimizations to be disabled. For normal
4422 ** operation N should be 0. The idea is that a test program (like the
4423 ** SQL Logic Test or SLT test module) can run the same SQL multiple times
4424 ** with various optimizations disabled to verify that the same answer
4425 ** is obtained in every case.
4427 case SQLITE_TESTCTRL_OPTIMIZATIONS: {
4428 sqlite3 *db = va_arg(ap, sqlite3*);
4429 db->dbOptFlags = va_arg(ap, u32);
4430 break;
4433 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, onoff, xAlt);
4435 ** If parameter onoff is 1, subsequent calls to localtime() fail.
4436 ** If 2, then invoke xAlt() instead of localtime(). If 0, normal
4437 ** processing.
4439 ** xAlt arguments are void pointers, but they really want to be:
4441 ** int xAlt(const time_t*, struct tm*);
4443 ** xAlt should write results in to struct tm object of its 2nd argument
4444 ** and return zero on success, or return non-zero on failure.
4446 case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
4447 sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
4448 if( sqlite3GlobalConfig.bLocaltimeFault==2 ){
4449 typedef int(*sqlite3LocaltimeType)(const void*,void*);
4450 sqlite3GlobalConfig.xAltLocaltime = va_arg(ap, sqlite3LocaltimeType);
4451 }else{
4452 sqlite3GlobalConfig.xAltLocaltime = 0;
4454 break;
4457 /* sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, sqlite3*);
4459 ** Toggle the ability to use internal functions on or off for
4460 ** the database connection given in the argument.
4462 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: {
4463 sqlite3 *db = va_arg(ap, sqlite3*);
4464 db->mDbFlags ^= DBFLAG_InternalFunc;
4465 break;
4468 /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
4470 ** Set or clear a flag that indicates that the database file is always well-
4471 ** formed and never corrupt. This flag is clear by default, indicating that
4472 ** database files might have arbitrary corruption. Setting the flag during
4473 ** testing causes certain assert() statements in the code to be activated
4474 ** that demonstrate invariants on well-formed database files.
4476 case SQLITE_TESTCTRL_NEVER_CORRUPT: {
4477 sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
4478 break;
4481 /* sqlite3_test_control(SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS, int);
4483 ** Set or clear a flag that causes SQLite to verify that type, name,
4484 ** and tbl_name fields of the sqlite_schema table. This is normally
4485 ** on, but it is sometimes useful to turn it off for testing.
4487 ** 2020-07-22: Disabling EXTRA_SCHEMA_CHECKS also disables the
4488 ** verification of rootpage numbers when parsing the schema. This
4489 ** is useful to make it easier to reach strange internal error states
4490 ** during testing. The EXTRA_SCHEMA_CHECKS setting is always enabled
4491 ** in production.
4493 case SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS: {
4494 sqlite3GlobalConfig.bExtraSchemaChecks = va_arg(ap, int);
4495 break;
4498 /* Set the threshold at which OP_Once counters reset back to zero.
4499 ** By default this is 0x7ffffffe (over 2 billion), but that value is
4500 ** too big to test in a reasonable amount of time, so this control is
4501 ** provided to set a small and easily reachable reset value.
4503 case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
4504 sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
4505 break;
4508 /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
4510 ** Set the VDBE coverage callback function to xCallback with context
4511 ** pointer ptr.
4513 case SQLITE_TESTCTRL_VDBE_COVERAGE: {
4514 #ifdef SQLITE_VDBE_COVERAGE
4515 typedef void (*branch_callback)(void*,unsigned int,
4516 unsigned char,unsigned char);
4517 sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
4518 sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
4519 #endif
4520 break;
4523 /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
4524 case SQLITE_TESTCTRL_SORTER_MMAP: {
4525 sqlite3 *db = va_arg(ap, sqlite3*);
4526 db->nMaxSorterMmap = va_arg(ap, int);
4527 break;
4530 /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
4532 ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
4533 ** not.
4535 case SQLITE_TESTCTRL_ISINIT: {
4536 if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
4537 break;
4540 /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
4542 ** This test control is used to create imposter tables. "db" is a pointer
4543 ** to the database connection. dbName is the database name (ex: "main" or
4544 ** "temp") which will receive the imposter. "onOff" turns imposter mode on
4545 ** or off. "tnum" is the root page of the b-tree to which the imposter
4546 ** table should connect.
4548 ** Enable imposter mode only when the schema has already been parsed. Then
4549 ** run a single CREATE TABLE statement to construct the imposter table in
4550 ** the parsed schema. Then turn imposter mode back off again.
4552 ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
4553 ** the schema to be reparsed the next time it is needed. This has the
4554 ** effect of erasing all imposter tables.
4556 case SQLITE_TESTCTRL_IMPOSTER: {
4557 sqlite3 *db = va_arg(ap, sqlite3*);
4558 int iDb;
4559 sqlite3_mutex_enter(db->mutex);
4560 iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
4561 if( iDb>=0 ){
4562 db->init.iDb = iDb;
4563 db->init.busy = db->init.imposterTable = va_arg(ap,int);
4564 db->init.newTnum = va_arg(ap,int);
4565 if( db->init.busy==0 && db->init.newTnum>0 ){
4566 sqlite3ResetAllSchemasOfConnection(db);
4569 sqlite3_mutex_leave(db->mutex);
4570 break;
4573 #if defined(YYCOVERAGE)
4574 /* sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
4576 ** This test control (only available when SQLite is compiled with
4577 ** -DYYCOVERAGE) writes a report onto "out" that shows all
4578 ** state/lookahead combinations in the parser state machine
4579 ** which are never exercised. If any state is missed, make the
4580 ** return code SQLITE_ERROR.
4582 case SQLITE_TESTCTRL_PARSER_COVERAGE: {
4583 FILE *out = va_arg(ap, FILE*);
4584 if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
4585 break;
4587 #endif /* defined(YYCOVERAGE) */
4589 /* sqlite3_test_control(SQLITE_TESTCTRL_RESULT_INTREAL, sqlite3_context*);
4591 ** This test-control causes the most recent sqlite3_result_int64() value
4592 ** to be interpreted as a MEM_IntReal instead of as an MEM_Int. Normally,
4593 ** MEM_IntReal values only arise during an INSERT operation of integer
4594 ** values into a REAL column, so they can be challenging to test. This
4595 ** test-control enables us to write an intreal() SQL function that can
4596 ** inject an intreal() value at arbitrary places in an SQL statement,
4597 ** for testing purposes.
4599 case SQLITE_TESTCTRL_RESULT_INTREAL: {
4600 sqlite3_context *pCtx = va_arg(ap, sqlite3_context*);
4601 sqlite3ResultIntReal(pCtx);
4602 break;
4605 /* sqlite3_test_control(SQLITE_TESTCTRL_SEEK_COUNT,
4606 ** sqlite3 *db, // Database connection
4607 ** u64 *pnSeek // Write seek count here
4608 ** );
4610 ** This test-control queries the seek-counter on the "main" database
4611 ** file. The seek-counter is written into *pnSeek and is then reset.
4612 ** The seek-count is only available if compiled with SQLITE_DEBUG.
4614 case SQLITE_TESTCTRL_SEEK_COUNT: {
4615 sqlite3 *db = va_arg(ap, sqlite3*);
4616 u64 *pn = va_arg(ap, sqlite3_uint64*);
4617 *pn = sqlite3BtreeSeekCount(db->aDb->pBt);
4618 (void)db; /* Silence harmless unused variable warning */
4619 break;
4622 /* sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, op, ptr)
4624 ** "ptr" is a pointer to a u32.
4626 ** op==0 Store the current sqlite3TreeTrace in *ptr
4627 ** op==1 Set sqlite3TreeTrace to the value *ptr
4628 ** op==2 Store the current sqlite3WhereTrace in *ptr
4629 ** op==3 Set sqlite3WhereTrace to the value *ptr
4631 case SQLITE_TESTCTRL_TRACEFLAGS: {
4632 int opTrace = va_arg(ap, int);
4633 u32 *ptr = va_arg(ap, u32*);
4634 switch( opTrace ){
4635 case 0: *ptr = sqlite3TreeTrace; break;
4636 case 1: sqlite3TreeTrace = *ptr; break;
4637 case 2: *ptr = sqlite3WhereTrace; break;
4638 case 3: sqlite3WhereTrace = *ptr; break;
4640 break;
4643 /* sqlite3_test_control(SQLITE_TESTCTRL_LOGEST,
4644 ** double fIn, // Input value
4645 ** int *pLogEst, // sqlite3LogEstFromDouble(fIn)
4646 ** u64 *pInt, // sqlite3LogEstToInt(*pLogEst)
4647 ** int *pLogEst2 // sqlite3LogEst(*pInt)
4648 ** );
4650 ** Test access for the LogEst conversion routines.
4652 case SQLITE_TESTCTRL_LOGEST: {
4653 double rIn = va_arg(ap, double);
4654 LogEst rLogEst = sqlite3LogEstFromDouble(rIn);
4655 int *pI1 = va_arg(ap,int*);
4656 u64 *pU64 = va_arg(ap,u64*);
4657 int *pI2 = va_arg(ap,int*);
4658 *pI1 = rLogEst;
4659 *pU64 = sqlite3LogEstToInt(rLogEst);
4660 *pI2 = sqlite3LogEst(*pU64);
4661 break;
4664 #if !defined(SQLITE_OMIT_WSD)
4665 /* sqlite3_test_control(SQLITE_TESTCTRL_USELONGDOUBLE, int X);
4667 ** X<0 Make no changes to the bUseLongDouble. Just report value.
4668 ** X==0 Disable bUseLongDouble
4669 ** X==1 Enable bUseLongDouble
4670 ** X>=2 Set bUseLongDouble to its default value for this platform
4672 case SQLITE_TESTCTRL_USELONGDOUBLE: {
4673 int b = va_arg(ap, int);
4674 if( b>=2 ) b = hasHighPrecisionDouble(b);
4675 if( b>=0 ) sqlite3Config.bUseLongDouble = b>0;
4676 rc = sqlite3Config.bUseLongDouble!=0;
4677 break;
4679 #endif
4682 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
4683 /* sqlite3_test_control(SQLITE_TESTCTRL_TUNE, id, *piValue)
4685 ** If "id" is an integer between 1 and SQLITE_NTUNE then set the value
4686 ** of the id-th tuning parameter to *piValue. If "id" is between -1
4687 ** and -SQLITE_NTUNE, then write the current value of the (-id)-th
4688 ** tuning parameter into *piValue.
4690 ** Tuning parameters are for use during transient development builds,
4691 ** to help find the best values for constants in the query planner.
4692 ** Access tuning parameters using the Tuning(ID) macro. Set the
4693 ** parameters in the CLI using ".testctrl tune ID VALUE".
4695 ** Transient use only. Tuning parameters should not be used in
4696 ** checked-in code.
4698 case SQLITE_TESTCTRL_TUNE: {
4699 int id = va_arg(ap, int);
4700 int *piValue = va_arg(ap, int*);
4701 if( id>0 && id<=SQLITE_NTUNE ){
4702 Tuning(id) = *piValue;
4703 }else if( id<0 && id>=-SQLITE_NTUNE ){
4704 *piValue = Tuning(-id);
4705 }else{
4706 rc = SQLITE_NOTFOUND;
4708 break;
4710 #endif
4712 va_end(ap);
4713 #endif /* SQLITE_UNTESTABLE */
4714 return rc;
4718 ** The Pager stores the Database filename, Journal filename, and WAL filename
4719 ** consecutively in memory, in that order. The database filename is prefixed
4720 ** by four zero bytes. Locate the start of the database filename by searching
4721 ** backwards for the first byte following four consecutive zero bytes.
4723 ** This only works if the filename passed in was obtained from the Pager.
4725 static const char *databaseName(const char *zName){
4726 while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
4727 zName--;
4729 return zName;
4733 ** Append text z[] to the end of p[]. Return a pointer to the first
4734 ** character after then zero terminator on the new text in p[].
4736 static char *appendText(char *p, const char *z){
4737 size_t n = strlen(z);
4738 memcpy(p, z, n+1);
4739 return p+n+1;
4743 ** Allocate memory to hold names for a database, journal file, WAL file,
4744 ** and query parameters. The pointer returned is valid for use by
4745 ** sqlite3_filename_database() and sqlite3_uri_parameter() and related
4746 ** functions.
4748 ** Memory layout must be compatible with that generated by the pager
4749 ** and expected by sqlite3_uri_parameter() and databaseName().
4751 const char *sqlite3_create_filename(
4752 const char *zDatabase,
4753 const char *zJournal,
4754 const char *zWal,
4755 int nParam,
4756 const char **azParam
4758 sqlite3_int64 nByte;
4759 int i;
4760 char *pResult, *p;
4761 nByte = strlen(zDatabase) + strlen(zJournal) + strlen(zWal) + 10;
4762 for(i=0; i<nParam*2; i++){
4763 nByte += strlen(azParam[i])+1;
4765 pResult = p = sqlite3_malloc64( nByte );
4766 if( p==0 ) return 0;
4767 memset(p, 0, 4);
4768 p += 4;
4769 p = appendText(p, zDatabase);
4770 for(i=0; i<nParam*2; i++){
4771 p = appendText(p, azParam[i]);
4773 *(p++) = 0;
4774 p = appendText(p, zJournal);
4775 p = appendText(p, zWal);
4776 *(p++) = 0;
4777 *(p++) = 0;
4778 assert( (sqlite3_int64)(p - pResult)==nByte );
4779 return pResult + 4;
4783 ** Free memory obtained from sqlite3_create_filename(). It is a severe
4784 ** error to call this routine with any parameter other than a pointer
4785 ** previously obtained from sqlite3_create_filename() or a NULL pointer.
4787 void sqlite3_free_filename(const char *p){
4788 if( p==0 ) return;
4789 p = databaseName(p);
4790 sqlite3_free((char*)p - 4);
4795 ** This is a utility routine, useful to VFS implementations, that checks
4796 ** to see if a database file was a URI that contained a specific query
4797 ** parameter, and if so obtains the value of the query parameter.
4799 ** The zFilename argument is the filename pointer passed into the xOpen()
4800 ** method of a VFS implementation. The zParam argument is the name of the
4801 ** query parameter we seek. This routine returns the value of the zParam
4802 ** parameter if it exists. If the parameter does not exist, this routine
4803 ** returns a NULL pointer.
4805 const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
4806 if( zFilename==0 || zParam==0 ) return 0;
4807 zFilename = databaseName(zFilename);
4808 return uriParameter(zFilename, zParam);
4812 ** Return a pointer to the name of Nth query parameter of the filename.
4814 const char *sqlite3_uri_key(const char *zFilename, int N){
4815 if( zFilename==0 || N<0 ) return 0;
4816 zFilename = databaseName(zFilename);
4817 zFilename += sqlite3Strlen30(zFilename) + 1;
4818 while( ALWAYS(zFilename) && zFilename[0] && (N--)>0 ){
4819 zFilename += sqlite3Strlen30(zFilename) + 1;
4820 zFilename += sqlite3Strlen30(zFilename) + 1;
4822 return zFilename[0] ? zFilename : 0;
4826 ** Return a boolean value for a query parameter.
4828 int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
4829 const char *z = sqlite3_uri_parameter(zFilename, zParam);
4830 bDflt = bDflt!=0;
4831 return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
4835 ** Return a 64-bit integer value for a query parameter.
4837 sqlite3_int64 sqlite3_uri_int64(
4838 const char *zFilename, /* Filename as passed to xOpen */
4839 const char *zParam, /* URI parameter sought */
4840 sqlite3_int64 bDflt /* return if parameter is missing */
4842 const char *z = sqlite3_uri_parameter(zFilename, zParam);
4843 sqlite3_int64 v;
4844 if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
4845 bDflt = v;
4847 return bDflt;
4851 ** Translate a filename that was handed to a VFS routine into the corresponding
4852 ** database, journal, or WAL file.
4854 ** It is an error to pass this routine a filename string that was not
4855 ** passed into the VFS from the SQLite core. Doing so is similar to
4856 ** passing free() a pointer that was not obtained from malloc() - it is
4857 ** an error that we cannot easily detect but that will likely cause memory
4858 ** corruption.
4860 const char *sqlite3_filename_database(const char *zFilename){
4861 if( zFilename==0 ) return 0;
4862 return databaseName(zFilename);
4864 const char *sqlite3_filename_journal(const char *zFilename){
4865 if( zFilename==0 ) return 0;
4866 zFilename = databaseName(zFilename);
4867 zFilename += sqlite3Strlen30(zFilename) + 1;
4868 while( ALWAYS(zFilename) && zFilename[0] ){
4869 zFilename += sqlite3Strlen30(zFilename) + 1;
4870 zFilename += sqlite3Strlen30(zFilename) + 1;
4872 return zFilename + 1;
4874 const char *sqlite3_filename_wal(const char *zFilename){
4875 #ifdef SQLITE_OMIT_WAL
4876 return 0;
4877 #else
4878 zFilename = sqlite3_filename_journal(zFilename);
4879 if( zFilename ) zFilename += sqlite3Strlen30(zFilename) + 1;
4880 return zFilename;
4881 #endif
4885 ** Return the Btree pointer identified by zDbName. Return NULL if not found.
4887 Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
4888 int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
4889 return iDb<0 ? 0 : db->aDb[iDb].pBt;
4893 ** Return the name of the N-th database schema. Return NULL if N is out
4894 ** of range.
4896 const char *sqlite3_db_name(sqlite3 *db, int N){
4897 #ifdef SQLITE_ENABLE_API_ARMOR
4898 if( !sqlite3SafetyCheckOk(db) ){
4899 (void)SQLITE_MISUSE_BKPT;
4900 return 0;
4902 #endif
4903 if( N<0 || N>=db->nDb ){
4904 return 0;
4905 }else{
4906 return db->aDb[N].zDbSName;
4911 ** Return the filename of the database associated with a database
4912 ** connection.
4914 const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
4915 Btree *pBt;
4916 #ifdef SQLITE_ENABLE_API_ARMOR
4917 if( !sqlite3SafetyCheckOk(db) ){
4918 (void)SQLITE_MISUSE_BKPT;
4919 return 0;
4921 #endif
4922 pBt = sqlite3DbNameToBtree(db, zDbName);
4923 return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
4927 ** Return 1 if database is read-only or 0 if read/write. Return -1 if
4928 ** no such database exists.
4930 int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
4931 Btree *pBt;
4932 #ifdef SQLITE_ENABLE_API_ARMOR
4933 if( !sqlite3SafetyCheckOk(db) ){
4934 (void)SQLITE_MISUSE_BKPT;
4935 return -1;
4937 #endif
4938 pBt = sqlite3DbNameToBtree(db, zDbName);
4939 return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
4942 #ifdef SQLITE_ENABLE_SNAPSHOT
4944 ** Obtain a snapshot handle for the snapshot of database zDb currently
4945 ** being read by handle db.
4947 int sqlite3_snapshot_get(
4948 sqlite3 *db,
4949 const char *zDb,
4950 sqlite3_snapshot **ppSnapshot
4952 int rc = SQLITE_ERROR;
4953 #ifndef SQLITE_OMIT_WAL
4955 #ifdef SQLITE_ENABLE_API_ARMOR
4956 if( !sqlite3SafetyCheckOk(db) ){
4957 return SQLITE_MISUSE_BKPT;
4959 #endif
4960 sqlite3_mutex_enter(db->mutex);
4962 if( db->autoCommit==0 ){
4963 int iDb = sqlite3FindDbName(db, zDb);
4964 if( iDb==0 || iDb>1 ){
4965 Btree *pBt = db->aDb[iDb].pBt;
4966 if( SQLITE_TXN_WRITE!=sqlite3BtreeTxnState(pBt) ){
4967 rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
4968 if( rc==SQLITE_OK ){
4969 rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
4975 sqlite3_mutex_leave(db->mutex);
4976 #endif /* SQLITE_OMIT_WAL */
4977 return rc;
4981 ** Open a read-transaction on the snapshot identified by pSnapshot.
4983 int sqlite3_snapshot_open(
4984 sqlite3 *db,
4985 const char *zDb,
4986 sqlite3_snapshot *pSnapshot
4988 int rc = SQLITE_ERROR;
4989 #ifndef SQLITE_OMIT_WAL
4991 #ifdef SQLITE_ENABLE_API_ARMOR
4992 if( !sqlite3SafetyCheckOk(db) ){
4993 return SQLITE_MISUSE_BKPT;
4995 #endif
4996 sqlite3_mutex_enter(db->mutex);
4997 if( db->autoCommit==0 ){
4998 int iDb;
4999 iDb = sqlite3FindDbName(db, zDb);
5000 if( iDb==0 || iDb>1 ){
5001 Btree *pBt = db->aDb[iDb].pBt;
5002 if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE ){
5003 Pager *pPager = sqlite3BtreePager(pBt);
5004 int bUnlock = 0;
5005 if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_NONE ){
5006 if( db->nVdbeActive==0 ){
5007 rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot);
5008 if( rc==SQLITE_OK ){
5009 bUnlock = 1;
5010 rc = sqlite3BtreeCommit(pBt);
5013 }else{
5014 rc = SQLITE_OK;
5016 if( rc==SQLITE_OK ){
5017 rc = sqlite3PagerSnapshotOpen(pPager, pSnapshot);
5019 if( rc==SQLITE_OK ){
5020 rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
5021 sqlite3PagerSnapshotOpen(pPager, 0);
5023 if( bUnlock ){
5024 sqlite3PagerSnapshotUnlock(pPager);
5030 sqlite3_mutex_leave(db->mutex);
5031 #endif /* SQLITE_OMIT_WAL */
5032 return rc;
5036 ** Recover as many snapshots as possible from the wal file associated with
5037 ** schema zDb of database db.
5039 int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
5040 int rc = SQLITE_ERROR;
5041 #ifndef SQLITE_OMIT_WAL
5042 int iDb;
5044 #ifdef SQLITE_ENABLE_API_ARMOR
5045 if( !sqlite3SafetyCheckOk(db) ){
5046 return SQLITE_MISUSE_BKPT;
5048 #endif
5050 sqlite3_mutex_enter(db->mutex);
5051 iDb = sqlite3FindDbName(db, zDb);
5052 if( iDb==0 || iDb>1 ){
5053 Btree *pBt = db->aDb[iDb].pBt;
5054 if( SQLITE_TXN_NONE==sqlite3BtreeTxnState(pBt) ){
5055 rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
5056 if( rc==SQLITE_OK ){
5057 rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
5058 sqlite3BtreeCommit(pBt);
5062 sqlite3_mutex_leave(db->mutex);
5063 #endif /* SQLITE_OMIT_WAL */
5064 return rc;
5068 ** Free a snapshot handle obtained from sqlite3_snapshot_get().
5070 void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
5071 sqlite3_free(pSnapshot);
5073 #endif /* SQLITE_ENABLE_SNAPSHOT */
5075 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
5077 ** Given the name of a compile-time option, return true if that option
5078 ** was used and false if not.
5080 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
5081 ** is not required for a match.
5083 int sqlite3_compileoption_used(const char *zOptName){
5084 int i, n;
5085 int nOpt;
5086 const char **azCompileOpt;
5088 #ifdef SQLITE_ENABLE_API_ARMOR
5089 if( zOptName==0 ){
5090 (void)SQLITE_MISUSE_BKPT;
5091 return 0;
5093 #endif
5095 azCompileOpt = sqlite3CompileOptions(&nOpt);
5097 if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
5098 n = sqlite3Strlen30(zOptName);
5100 /* Since nOpt is normally in single digits, a linear search is
5101 ** adequate. No need for a binary search. */
5102 for(i=0; i<nOpt; i++){
5103 if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
5104 && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
5106 return 1;
5109 return 0;
5113 ** Return the N-th compile-time option string. If N is out of range,
5114 ** return a NULL pointer.
5116 const char *sqlite3_compileoption_get(int N){
5117 int nOpt;
5118 const char **azCompileOpt;
5119 azCompileOpt = sqlite3CompileOptions(&nOpt);
5120 if( N>=0 && N<nOpt ){
5121 return azCompileOpt[N];
5123 return 0;
5125 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */