Add tests for the new code on this branch.
[sqlite.git] / src / main.c
blob03429983d6ef2fcd291b4a3543c36433202c3de8
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|SQLITE_RESULT_SUBTYPE);
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;
3237 ** This routine does the work of opening a database on behalf of
3238 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
3239 ** is UTF-8 encoded.
3241 static int openDatabase(
3242 const char *zFilename, /* Database filename UTF-8 encoded */
3243 sqlite3 **ppDb, /* OUT: Returned database handle */
3244 unsigned int flags, /* Operational flags */
3245 const char *zVfs /* Name of the VFS to use */
3247 sqlite3 *db; /* Store allocated handle here */
3248 int rc; /* Return code */
3249 int isThreadsafe; /* True for threadsafe connections */
3250 char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
3251 char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
3252 int i; /* Loop counter */
3254 #ifdef SQLITE_ENABLE_API_ARMOR
3255 if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
3256 #endif
3257 *ppDb = 0;
3258 #ifndef SQLITE_OMIT_AUTOINIT
3259 rc = sqlite3_initialize();
3260 if( rc ) return rc;
3261 #endif
3263 if( sqlite3GlobalConfig.bCoreMutex==0 ){
3264 isThreadsafe = 0;
3265 }else if( flags & SQLITE_OPEN_NOMUTEX ){
3266 isThreadsafe = 0;
3267 }else if( flags & SQLITE_OPEN_FULLMUTEX ){
3268 isThreadsafe = 1;
3269 }else{
3270 isThreadsafe = sqlite3GlobalConfig.bFullMutex;
3273 if( flags & SQLITE_OPEN_PRIVATECACHE ){
3274 flags &= ~SQLITE_OPEN_SHAREDCACHE;
3275 }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
3276 flags |= SQLITE_OPEN_SHAREDCACHE;
3279 /* Remove harmful bits from the flags parameter
3281 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
3282 ** dealt with in the previous code block. Besides these, the only
3283 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
3284 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
3285 ** SQLITE_OPEN_PRIVATECACHE, SQLITE_OPEN_EXRESCODE, and some reserved
3286 ** bits. Silently mask off all other flags.
3288 flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
3289 SQLITE_OPEN_EXCLUSIVE |
3290 SQLITE_OPEN_MAIN_DB |
3291 SQLITE_OPEN_TEMP_DB |
3292 SQLITE_OPEN_TRANSIENT_DB |
3293 SQLITE_OPEN_MAIN_JOURNAL |
3294 SQLITE_OPEN_TEMP_JOURNAL |
3295 SQLITE_OPEN_SUBJOURNAL |
3296 SQLITE_OPEN_SUPER_JOURNAL |
3297 SQLITE_OPEN_NOMUTEX |
3298 SQLITE_OPEN_FULLMUTEX |
3299 SQLITE_OPEN_WAL
3302 /* Allocate the sqlite data structure */
3303 db = sqlite3MallocZero( sizeof(sqlite3) );
3304 if( db==0 ) goto opendb_out;
3305 if( isThreadsafe
3306 #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
3307 || sqlite3GlobalConfig.bCoreMutex
3308 #endif
3310 db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
3311 if( db->mutex==0 ){
3312 sqlite3_free(db);
3313 db = 0;
3314 goto opendb_out;
3316 if( isThreadsafe==0 ){
3317 sqlite3MutexWarnOnContention(db->mutex);
3320 sqlite3_mutex_enter(db->mutex);
3321 db->errMask = (flags & SQLITE_OPEN_EXRESCODE)!=0 ? 0xffffffff : 0xff;
3322 db->nDb = 2;
3323 db->eOpenState = SQLITE_STATE_BUSY;
3324 db->aDb = db->aDbStatic;
3325 db->lookaside.bDisable = 1;
3326 db->lookaside.sz = 0;
3328 assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
3329 memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
3330 db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
3331 db->autoCommit = 1;
3332 db->nextAutovac = -1;
3333 db->szMmap = sqlite3GlobalConfig.szMmap;
3334 db->nextPagesize = 0;
3335 db->init.azInit = sqlite3StdType; /* Any array of string ptrs will do */
3336 #ifdef SQLITE_ENABLE_SORTER_MMAP
3337 /* Beginning with version 3.37.0, using the VFS xFetch() API to memory-map
3338 ** the temporary files used to do external sorts (see code in vdbesort.c)
3339 ** is disabled. It can still be used either by defining
3340 ** SQLITE_ENABLE_SORTER_MMAP at compile time or by using the
3341 ** SQLITE_TESTCTRL_SORTER_MMAP test-control at runtime. */
3342 db->nMaxSorterMmap = 0x7FFFFFFF;
3343 #endif
3344 db->flags |= SQLITE_ShortColNames
3345 | SQLITE_EnableTrigger
3346 | SQLITE_EnableView
3347 | SQLITE_CacheSpill
3348 #if !defined(SQLITE_TRUSTED_SCHEMA) || SQLITE_TRUSTED_SCHEMA+0!=0
3349 | SQLITE_TrustedSchema
3350 #endif
3351 /* The SQLITE_DQS compile-time option determines the default settings
3352 ** for SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML.
3354 ** SQLITE_DQS SQLITE_DBCONFIG_DQS_DDL SQLITE_DBCONFIG_DQS_DML
3355 ** ---------- ----------------------- -----------------------
3356 ** undefined on on
3357 ** 3 on on
3358 ** 2 on off
3359 ** 1 off on
3360 ** 0 off off
3362 ** Legacy behavior is 3 (double-quoted string literals are allowed anywhere)
3363 ** and so that is the default. But developers are encouraged to use
3364 ** -DSQLITE_DQS=0 (best) or -DSQLITE_DQS=1 (second choice) if possible.
3366 #if !defined(SQLITE_DQS)
3367 # define SQLITE_DQS 3
3368 #endif
3369 #if (SQLITE_DQS&1)==1
3370 | SQLITE_DqsDML
3371 #endif
3372 #if (SQLITE_DQS&2)==2
3373 | SQLITE_DqsDDL
3374 #endif
3376 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
3377 | SQLITE_AutoIndex
3378 #endif
3379 #if SQLITE_DEFAULT_CKPTFULLFSYNC
3380 | SQLITE_CkptFullFSync
3381 #endif
3382 #if SQLITE_DEFAULT_FILE_FORMAT<4
3383 | SQLITE_LegacyFileFmt
3384 #endif
3385 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
3386 | SQLITE_LoadExtension
3387 #endif
3388 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
3389 | SQLITE_RecTriggers
3390 #endif
3391 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
3392 | SQLITE_ForeignKeys
3393 #endif
3394 #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
3395 | SQLITE_ReverseOrder
3396 #endif
3397 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
3398 | SQLITE_CellSizeCk
3399 #endif
3400 #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
3401 | SQLITE_Fts3Tokenizer
3402 #endif
3403 #if defined(SQLITE_ENABLE_QPSG)
3404 | SQLITE_EnableQPSG
3405 #endif
3406 #if defined(SQLITE_DEFAULT_DEFENSIVE)
3407 | SQLITE_Defensive
3408 #endif
3409 #if defined(SQLITE_DEFAULT_LEGACY_ALTER_TABLE)
3410 | SQLITE_LegacyAlter
3411 #endif
3412 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
3413 | SQLITE_StmtScanStatus
3414 #endif
3416 sqlite3HashInit(&db->aCollSeq);
3417 #ifndef SQLITE_OMIT_VIRTUALTABLE
3418 sqlite3HashInit(&db->aModule);
3419 #endif
3421 /* Add the default collation sequence BINARY. BINARY works for both UTF-8
3422 ** and UTF-16, so add a version for each to avoid any unnecessary
3423 ** conversions. The only error that can occur here is a malloc() failure.
3425 ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
3426 ** functions:
3428 createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
3429 createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
3430 createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
3431 createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
3432 createCollation(db, "RTRIM", SQLITE_UTF8, 0, rtrimCollFunc, 0);
3433 if( db->mallocFailed ){
3434 goto opendb_out;
3437 #if SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL)
3438 /* Process magic filenames ":localStorage:" and ":sessionStorage:" */
3439 if( zFilename && zFilename[0]==':' ){
3440 if( strcmp(zFilename, ":localStorage:")==0 ){
3441 zFilename = "file:local?vfs=kvvfs";
3442 flags |= SQLITE_OPEN_URI;
3443 }else if( strcmp(zFilename, ":sessionStorage:")==0 ){
3444 zFilename = "file:session?vfs=kvvfs";
3445 flags |= SQLITE_OPEN_URI;
3448 #endif /* SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL) */
3450 /* Parse the filename/URI argument
3452 ** Only allow sensible combinations of bits in the flags argument.
3453 ** Throw an error if any non-sense combination is used. If we
3454 ** do not block illegal combinations here, it could trigger
3455 ** assert() statements in deeper layers. Sensible combinations
3456 ** are:
3458 ** 1: SQLITE_OPEN_READONLY
3459 ** 2: SQLITE_OPEN_READWRITE
3460 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
3462 db->openFlags = flags;
3463 assert( SQLITE_OPEN_READONLY == 0x01 );
3464 assert( SQLITE_OPEN_READWRITE == 0x02 );
3465 assert( SQLITE_OPEN_CREATE == 0x04 );
3466 testcase( (1<<(flags&7))==0x02 ); /* READONLY */
3467 testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
3468 testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
3469 if( ((1<<(flags&7)) & 0x46)==0 ){
3470 rc = SQLITE_MISUSE_BKPT; /* IMP: R-18321-05872 */
3471 }else{
3472 rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
3474 if( rc!=SQLITE_OK ){
3475 if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
3476 sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
3477 sqlite3_free(zErrMsg);
3478 goto opendb_out;
3480 assert( db->pVfs!=0 );
3481 #if SQLITE_OS_KV || defined(SQLITE_OS_KV_OPTIONAL)
3482 if( sqlite3_stricmp(db->pVfs->zName, "kvvfs")==0 ){
3483 db->temp_store = 2;
3485 #endif
3487 /* Open the backend database driver */
3488 rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
3489 flags | SQLITE_OPEN_MAIN_DB);
3490 if( rc!=SQLITE_OK ){
3491 if( rc==SQLITE_IOERR_NOMEM ){
3492 rc = SQLITE_NOMEM_BKPT;
3494 sqlite3Error(db, rc);
3495 goto opendb_out;
3497 sqlite3BtreeEnter(db->aDb[0].pBt);
3498 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
3499 if( !db->mallocFailed ){
3500 sqlite3SetTextEncoding(db, SCHEMA_ENC(db));
3502 sqlite3BtreeLeave(db->aDb[0].pBt);
3503 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
3505 /* The default safety_level for the main database is FULL; for the temp
3506 ** database it is OFF. This matches the pager layer defaults.
3508 db->aDb[0].zDbSName = "main";
3509 db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
3510 db->aDb[1].zDbSName = "temp";
3511 db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
3513 db->eOpenState = SQLITE_STATE_OPEN;
3514 if( db->mallocFailed ){
3515 goto opendb_out;
3518 /* Register all built-in functions, but do not attempt to read the
3519 ** database schema yet. This is delayed until the first time the database
3520 ** is accessed.
3522 sqlite3Error(db, SQLITE_OK);
3523 sqlite3RegisterPerConnectionBuiltinFunctions(db);
3524 rc = sqlite3_errcode(db);
3527 /* Load compiled-in extensions */
3528 for(i=0; rc==SQLITE_OK && i<ArraySize(sqlite3BuiltinExtensions); i++){
3529 rc = sqlite3BuiltinExtensions[i](db);
3532 /* Load automatic extensions - extensions that have been registered
3533 ** using the sqlite3_automatic_extension() API.
3535 if( rc==SQLITE_OK ){
3536 sqlite3AutoLoadExtensions(db);
3537 rc = sqlite3_errcode(db);
3538 if( rc!=SQLITE_OK ){
3539 goto opendb_out;
3543 #ifdef SQLITE_ENABLE_INTERNAL_FUNCTIONS
3544 /* Testing use only!!! The -DSQLITE_ENABLE_INTERNAL_FUNCTIONS=1 compile-time
3545 ** option gives access to internal functions by default.
3546 ** Testing use only!!! */
3547 db->mDbFlags |= DBFLAG_InternalFunc;
3548 #endif
3550 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
3551 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
3552 ** mode. Doing nothing at all also makes NORMAL the default.
3554 #ifdef SQLITE_DEFAULT_LOCKING_MODE
3555 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
3556 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
3557 SQLITE_DEFAULT_LOCKING_MODE);
3558 #endif
3560 if( rc ) sqlite3Error(db, rc);
3562 /* Enable the lookaside-malloc subsystem */
3563 setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
3564 sqlite3GlobalConfig.nLookaside);
3566 sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
3568 opendb_out:
3569 if( db ){
3570 assert( db->mutex!=0 || isThreadsafe==0
3571 || sqlite3GlobalConfig.bFullMutex==0 );
3572 sqlite3_mutex_leave(db->mutex);
3574 rc = sqlite3_errcode(db);
3575 assert( db!=0 || (rc&0xff)==SQLITE_NOMEM );
3576 if( (rc&0xff)==SQLITE_NOMEM ){
3577 sqlite3_close(db);
3578 db = 0;
3579 }else if( rc!=SQLITE_OK ){
3580 db->eOpenState = SQLITE_STATE_SICK;
3582 *ppDb = db;
3583 #ifdef SQLITE_ENABLE_SQLLOG
3584 if( sqlite3GlobalConfig.xSqllog ){
3585 /* Opening a db handle. Fourth parameter is passed 0. */
3586 void *pArg = sqlite3GlobalConfig.pSqllogArg;
3587 sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
3589 #endif
3590 sqlite3_free_filename(zOpen);
3591 return rc;
3596 ** Open a new database handle.
3598 int sqlite3_open(
3599 const char *zFilename,
3600 sqlite3 **ppDb
3602 return openDatabase(zFilename, ppDb,
3603 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
3605 int sqlite3_open_v2(
3606 const char *filename, /* Database filename (UTF-8) */
3607 sqlite3 **ppDb, /* OUT: SQLite db handle */
3608 int flags, /* Flags */
3609 const char *zVfs /* Name of VFS module to use */
3611 return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
3614 #ifndef SQLITE_OMIT_UTF16
3616 ** Open a new database handle.
3618 int sqlite3_open16(
3619 const void *zFilename,
3620 sqlite3 **ppDb
3622 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
3623 sqlite3_value *pVal;
3624 int rc;
3626 #ifdef SQLITE_ENABLE_API_ARMOR
3627 if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
3628 #endif
3629 *ppDb = 0;
3630 #ifndef SQLITE_OMIT_AUTOINIT
3631 rc = sqlite3_initialize();
3632 if( rc ) return rc;
3633 #endif
3634 if( zFilename==0 ) zFilename = "\000\000";
3635 pVal = sqlite3ValueNew(0);
3636 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
3637 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
3638 if( zFilename8 ){
3639 rc = openDatabase(zFilename8, ppDb,
3640 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
3641 assert( *ppDb || rc==SQLITE_NOMEM );
3642 if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
3643 SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
3645 }else{
3646 rc = SQLITE_NOMEM_BKPT;
3648 sqlite3ValueFree(pVal);
3650 return rc & 0xff;
3652 #endif /* SQLITE_OMIT_UTF16 */
3655 ** Register a new collation sequence with the database handle db.
3657 int sqlite3_create_collation(
3658 sqlite3* db,
3659 const char *zName,
3660 int enc,
3661 void* pCtx,
3662 int(*xCompare)(void*,int,const void*,int,const void*)
3664 return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
3668 ** Register a new collation sequence with the database handle db.
3670 int sqlite3_create_collation_v2(
3671 sqlite3* db,
3672 const char *zName,
3673 int enc,
3674 void* pCtx,
3675 int(*xCompare)(void*,int,const void*,int,const void*),
3676 void(*xDel)(void*)
3678 int rc;
3680 #ifdef SQLITE_ENABLE_API_ARMOR
3681 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
3682 #endif
3683 sqlite3_mutex_enter(db->mutex);
3684 assert( !db->mallocFailed );
3685 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
3686 rc = sqlite3ApiExit(db, rc);
3687 sqlite3_mutex_leave(db->mutex);
3688 return rc;
3691 #ifndef SQLITE_OMIT_UTF16
3693 ** Register a new collation sequence with the database handle db.
3695 int sqlite3_create_collation16(
3696 sqlite3* db,
3697 const void *zName,
3698 int enc,
3699 void* pCtx,
3700 int(*xCompare)(void*,int,const void*,int,const void*)
3702 int rc = SQLITE_OK;
3703 char *zName8;
3705 #ifdef SQLITE_ENABLE_API_ARMOR
3706 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
3707 #endif
3708 sqlite3_mutex_enter(db->mutex);
3709 assert( !db->mallocFailed );
3710 zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
3711 if( zName8 ){
3712 rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
3713 sqlite3DbFree(db, zName8);
3715 rc = sqlite3ApiExit(db, rc);
3716 sqlite3_mutex_leave(db->mutex);
3717 return rc;
3719 #endif /* SQLITE_OMIT_UTF16 */
3722 ** Register a collation sequence factory callback with the database handle
3723 ** db. Replace any previously installed collation sequence factory.
3725 int sqlite3_collation_needed(
3726 sqlite3 *db,
3727 void *pCollNeededArg,
3728 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
3730 #ifdef SQLITE_ENABLE_API_ARMOR
3731 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3732 #endif
3733 sqlite3_mutex_enter(db->mutex);
3734 db->xCollNeeded = xCollNeeded;
3735 db->xCollNeeded16 = 0;
3736 db->pCollNeededArg = pCollNeededArg;
3737 sqlite3_mutex_leave(db->mutex);
3738 return SQLITE_OK;
3741 #ifndef SQLITE_OMIT_UTF16
3743 ** Register a collation sequence factory callback with the database handle
3744 ** db. Replace any previously installed collation sequence factory.
3746 int sqlite3_collation_needed16(
3747 sqlite3 *db,
3748 void *pCollNeededArg,
3749 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
3751 #ifdef SQLITE_ENABLE_API_ARMOR
3752 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3753 #endif
3754 sqlite3_mutex_enter(db->mutex);
3755 db->xCollNeeded = 0;
3756 db->xCollNeeded16 = xCollNeeded16;
3757 db->pCollNeededArg = pCollNeededArg;
3758 sqlite3_mutex_leave(db->mutex);
3759 return SQLITE_OK;
3761 #endif /* SQLITE_OMIT_UTF16 */
3764 ** Find existing client data.
3766 void *sqlite3_get_clientdata(sqlite3 *db, const char *zName){
3767 DbClientData *p;
3768 sqlite3_mutex_enter(db->mutex);
3769 for(p=db->pDbData; p; p=p->pNext){
3770 if( strcmp(p->zName, zName)==0 ){
3771 void *pResult = p->pData;
3772 sqlite3_mutex_leave(db->mutex);
3773 return pResult;
3776 sqlite3_mutex_leave(db->mutex);
3777 return 0;
3781 ** Add new client data to a database connection.
3783 int sqlite3_set_clientdata(
3784 sqlite3 *db, /* Attach client data to this connection */
3785 const char *zName, /* Name of the client data */
3786 void *pData, /* The client data itself */
3787 void (*xDestructor)(void*) /* Destructor */
3789 DbClientData *p, **pp;
3790 sqlite3_mutex_enter(db->mutex);
3791 pp = &db->pDbData;
3792 for(p=db->pDbData; p && strcmp(p->zName,zName); p=p->pNext){
3793 pp = &p->pNext;
3795 if( p ){
3796 assert( p->pData!=0 );
3797 if( p->xDestructor ) p->xDestructor(p->pData);
3798 if( pData==0 ){
3799 *pp = p->pNext;
3800 sqlite3_free(p);
3801 sqlite3_mutex_leave(db->mutex);
3802 return SQLITE_OK;
3804 }else if( pData==0 ){
3805 sqlite3_mutex_leave(db->mutex);
3806 return SQLITE_OK;
3807 }else{
3808 size_t n = strlen(zName);
3809 p = sqlite3_malloc64( sizeof(DbClientData)+n+1 );
3810 if( p==0 ){
3811 if( xDestructor ) xDestructor(pData);
3812 sqlite3_mutex_leave(db->mutex);
3813 return SQLITE_NOMEM;
3815 memcpy(p->zName, zName, n+1);
3816 p->pNext = db->pDbData;
3817 db->pDbData = p;
3819 p->pData = pData;
3820 p->xDestructor = xDestructor;
3821 sqlite3_mutex_leave(db->mutex);
3822 return SQLITE_OK;
3826 #ifndef SQLITE_OMIT_DEPRECATED
3828 ** This function is now an anachronism. It used to be used to recover from a
3829 ** malloc() failure, but SQLite now does this automatically.
3831 int sqlite3_global_recover(void){
3832 return SQLITE_OK;
3834 #endif
3837 ** Test to see whether or not the database connection is in autocommit
3838 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
3839 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
3840 ** by the next COMMIT or ROLLBACK.
3842 int sqlite3_get_autocommit(sqlite3 *db){
3843 #ifdef SQLITE_ENABLE_API_ARMOR
3844 if( !sqlite3SafetyCheckOk(db) ){
3845 (void)SQLITE_MISUSE_BKPT;
3846 return 0;
3848 #endif
3849 return db->autoCommit;
3853 ** The following routines are substitutes for constants SQLITE_CORRUPT,
3854 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
3855 ** constants. They serve two purposes:
3857 ** 1. Serve as a convenient place to set a breakpoint in a debugger
3858 ** to detect when version error conditions occurs.
3860 ** 2. Invoke sqlite3_log() to provide the source code location where
3861 ** a low-level error is first detected.
3863 int sqlite3ReportError(int iErr, int lineno, const char *zType){
3864 sqlite3_log(iErr, "%s at line %d of [%.10s]",
3865 zType, lineno, 20+sqlite3_sourceid());
3866 return iErr;
3868 int sqlite3CorruptError(int lineno){
3869 testcase( sqlite3GlobalConfig.xLog!=0 );
3870 return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
3872 int sqlite3MisuseError(int lineno){
3873 testcase( sqlite3GlobalConfig.xLog!=0 );
3874 return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
3876 int sqlite3CantopenError(int lineno){
3877 testcase( sqlite3GlobalConfig.xLog!=0 );
3878 return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
3880 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
3881 int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
3882 char zMsg[100];
3883 sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
3884 testcase( sqlite3GlobalConfig.xLog!=0 );
3885 return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
3887 #endif
3888 #ifdef SQLITE_DEBUG
3889 int sqlite3NomemError(int lineno){
3890 testcase( sqlite3GlobalConfig.xLog!=0 );
3891 return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
3893 int sqlite3IoerrnomemError(int lineno){
3894 testcase( sqlite3GlobalConfig.xLog!=0 );
3895 return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
3897 #endif
3899 #ifndef SQLITE_OMIT_DEPRECATED
3901 ** This is a convenience routine that makes sure that all thread-specific
3902 ** data for this thread has been deallocated.
3904 ** SQLite no longer uses thread-specific data so this routine is now a
3905 ** no-op. It is retained for historical compatibility.
3907 void sqlite3_thread_cleanup(void){
3909 #endif
3912 ** Return meta information about a specific column of a database table.
3913 ** See comment in sqlite3.h (sqlite.h.in) for details.
3915 int sqlite3_table_column_metadata(
3916 sqlite3 *db, /* Connection handle */
3917 const char *zDbName, /* Database name or NULL */
3918 const char *zTableName, /* Table name */
3919 const char *zColumnName, /* Column name */
3920 char const **pzDataType, /* OUTPUT: Declared data type */
3921 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
3922 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
3923 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
3924 int *pAutoinc /* OUTPUT: True if column is auto-increment */
3926 int rc;
3927 char *zErrMsg = 0;
3928 Table *pTab = 0;
3929 Column *pCol = 0;
3930 int iCol = 0;
3931 char const *zDataType = 0;
3932 char const *zCollSeq = 0;
3933 int notnull = 0;
3934 int primarykey = 0;
3935 int autoinc = 0;
3938 #ifdef SQLITE_ENABLE_API_ARMOR
3939 if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
3940 return SQLITE_MISUSE_BKPT;
3942 #endif
3944 /* Ensure the database schema has been loaded */
3945 sqlite3_mutex_enter(db->mutex);
3946 sqlite3BtreeEnterAll(db);
3947 rc = sqlite3Init(db, &zErrMsg);
3948 if( SQLITE_OK!=rc ){
3949 goto error_out;
3952 /* Locate the table in question */
3953 pTab = sqlite3FindTable(db, zTableName, zDbName);
3954 if( !pTab || IsView(pTab) ){
3955 pTab = 0;
3956 goto error_out;
3959 /* Find the column for which info is requested */
3960 if( zColumnName==0 ){
3961 /* Query for existence of table only */
3962 }else{
3963 for(iCol=0; iCol<pTab->nCol; iCol++){
3964 pCol = &pTab->aCol[iCol];
3965 if( 0==sqlite3StrICmp(pCol->zCnName, zColumnName) ){
3966 break;
3969 if( iCol==pTab->nCol ){
3970 if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
3971 iCol = pTab->iPKey;
3972 pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
3973 }else{
3974 pTab = 0;
3975 goto error_out;
3980 /* The following block stores the meta information that will be returned
3981 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
3982 ** and autoinc. At this point there are two possibilities:
3984 ** 1. The specified column name was rowid", "oid" or "_rowid_"
3985 ** and there is no explicitly declared IPK column.
3987 ** 2. The table is not a view and the column name identified an
3988 ** explicitly declared column. Copy meta information from *pCol.
3990 if( pCol ){
3991 zDataType = sqlite3ColumnType(pCol,0);
3992 zCollSeq = sqlite3ColumnColl(pCol);
3993 notnull = pCol->notNull!=0;
3994 primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
3995 autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
3996 }else{
3997 zDataType = "INTEGER";
3998 primarykey = 1;
4000 if( !zCollSeq ){
4001 zCollSeq = sqlite3StrBINARY;
4004 error_out:
4005 sqlite3BtreeLeaveAll(db);
4007 /* Whether the function call succeeded or failed, set the output parameters
4008 ** to whatever their local counterparts contain. If an error did occur,
4009 ** this has the effect of zeroing all output parameters.
4011 if( pzDataType ) *pzDataType = zDataType;
4012 if( pzCollSeq ) *pzCollSeq = zCollSeq;
4013 if( pNotNull ) *pNotNull = notnull;
4014 if( pPrimaryKey ) *pPrimaryKey = primarykey;
4015 if( pAutoinc ) *pAutoinc = autoinc;
4017 if( SQLITE_OK==rc && !pTab ){
4018 sqlite3DbFree(db, zErrMsg);
4019 zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
4020 zColumnName);
4021 rc = SQLITE_ERROR;
4023 sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
4024 sqlite3DbFree(db, zErrMsg);
4025 rc = sqlite3ApiExit(db, rc);
4026 sqlite3_mutex_leave(db->mutex);
4027 return rc;
4031 ** Sleep for a little while. Return the amount of time slept.
4033 int sqlite3_sleep(int ms){
4034 sqlite3_vfs *pVfs;
4035 int rc;
4036 pVfs = sqlite3_vfs_find(0);
4037 if( pVfs==0 ) return 0;
4039 /* This function works in milliseconds, but the underlying OsSleep()
4040 ** API uses microseconds. Hence the 1000's.
4042 rc = (sqlite3OsSleep(pVfs, ms<0 ? 0 : 1000*ms)/1000);
4043 return rc;
4047 ** Enable or disable the extended result codes.
4049 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
4050 #ifdef SQLITE_ENABLE_API_ARMOR
4051 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
4052 #endif
4053 sqlite3_mutex_enter(db->mutex);
4054 db->errMask = onoff ? 0xffffffff : 0xff;
4055 sqlite3_mutex_leave(db->mutex);
4056 return SQLITE_OK;
4060 ** Invoke the xFileControl method on a particular database.
4062 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
4063 int rc = SQLITE_ERROR;
4064 Btree *pBtree;
4066 #ifdef SQLITE_ENABLE_API_ARMOR
4067 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
4068 #endif
4069 sqlite3_mutex_enter(db->mutex);
4070 pBtree = sqlite3DbNameToBtree(db, zDbName);
4071 if( pBtree ){
4072 Pager *pPager;
4073 sqlite3_file *fd;
4074 sqlite3BtreeEnter(pBtree);
4075 pPager = sqlite3BtreePager(pBtree);
4076 assert( pPager!=0 );
4077 fd = sqlite3PagerFile(pPager);
4078 assert( fd!=0 );
4079 if( op==SQLITE_FCNTL_FILE_POINTER ){
4080 *(sqlite3_file**)pArg = fd;
4081 rc = SQLITE_OK;
4082 }else if( op==SQLITE_FCNTL_VFS_POINTER ){
4083 *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
4084 rc = SQLITE_OK;
4085 }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
4086 *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
4087 rc = SQLITE_OK;
4088 }else if( op==SQLITE_FCNTL_DATA_VERSION ){
4089 *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager);
4090 rc = SQLITE_OK;
4091 }else if( op==SQLITE_FCNTL_RESERVE_BYTES ){
4092 int iNew = *(int*)pArg;
4093 *(int*)pArg = sqlite3BtreeGetRequestedReserve(pBtree);
4094 if( iNew>=0 && iNew<=255 ){
4095 sqlite3BtreeSetPageSize(pBtree, 0, iNew, 0);
4097 rc = SQLITE_OK;
4098 }else if( op==SQLITE_FCNTL_RESET_CACHE ){
4099 sqlite3BtreeClearCache(pBtree);
4100 rc = SQLITE_OK;
4101 }else{
4102 int nSave = db->busyHandler.nBusy;
4103 rc = sqlite3OsFileControl(fd, op, pArg);
4104 db->busyHandler.nBusy = nSave;
4106 sqlite3BtreeLeave(pBtree);
4108 sqlite3_mutex_leave(db->mutex);
4109 return rc;
4113 ** Interface to the testing logic.
4115 int sqlite3_test_control(int op, ...){
4116 int rc = 0;
4117 #ifdef SQLITE_UNTESTABLE
4118 UNUSED_PARAMETER(op);
4119 #else
4120 va_list ap;
4121 va_start(ap, op);
4122 switch( op ){
4125 ** Save the current state of the PRNG.
4127 case SQLITE_TESTCTRL_PRNG_SAVE: {
4128 sqlite3PrngSaveState();
4129 break;
4133 ** Restore the state of the PRNG to the last state saved using
4134 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
4135 ** this verb acts like PRNG_RESET.
4137 case SQLITE_TESTCTRL_PRNG_RESTORE: {
4138 sqlite3PrngRestoreState();
4139 break;
4142 /* sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, int x, sqlite3 *db);
4144 ** Control the seed for the pseudo-random number generator (PRNG) that
4145 ** is built into SQLite. Cases:
4147 ** x!=0 && db!=0 Seed the PRNG to the current value of the
4148 ** schema cookie in the main database for db, or
4149 ** x if the schema cookie is zero. This case
4150 ** is convenient to use with database fuzzers
4151 ** as it allows the fuzzer some control over the
4152 ** the PRNG seed.
4154 ** x!=0 && db==0 Seed the PRNG to the value of x.
4156 ** x==0 && db==0 Revert to default behavior of using the
4157 ** xRandomness method on the primary VFS.
4159 ** This test-control also resets the PRNG so that the new seed will
4160 ** be used for the next call to sqlite3_randomness().
4162 #ifndef SQLITE_OMIT_WSD
4163 case SQLITE_TESTCTRL_PRNG_SEED: {
4164 int x = va_arg(ap, int);
4165 int y;
4166 sqlite3 *db = va_arg(ap, sqlite3*);
4167 assert( db==0 || db->aDb[0].pSchema!=0 );
4168 if( db && (y = db->aDb[0].pSchema->schema_cookie)!=0 ){ x = y; }
4169 sqlite3Config.iPrngSeed = x;
4170 sqlite3_randomness(0,0);
4171 break;
4173 #endif
4175 /* sqlite3_test_control(SQLITE_TESTCTRL_FK_NO_ACTION, sqlite3 *db, int b);
4177 ** If b is true, then activate the SQLITE_FkNoAction setting. If b is
4178 ** false then clearn that setting. If the SQLITE_FkNoAction setting is
4179 ** abled, all foreign key ON DELETE and ON UPDATE actions behave as if
4180 ** they were NO ACTION, regardless of how they are defined.
4182 ** NB: One must usually run "PRAGMA writable_schema=RESET" after
4183 ** using this test-control, before it will take full effect. failing
4184 ** to reset the schema can result in some unexpected behavior.
4186 case SQLITE_TESTCTRL_FK_NO_ACTION: {
4187 sqlite3 *db = va_arg(ap, sqlite3*);
4188 int b = va_arg(ap, int);
4189 if( b ){
4190 db->flags |= SQLITE_FkNoAction;
4191 }else{
4192 db->flags &= ~SQLITE_FkNoAction;
4194 break;
4198 ** sqlite3_test_control(BITVEC_TEST, size, program)
4200 ** Run a test against a Bitvec object of size. The program argument
4201 ** is an array of integers that defines the test. Return -1 on a
4202 ** memory allocation error, 0 on success, or non-zero for an error.
4203 ** See the sqlite3BitvecBuiltinTest() for additional information.
4205 case SQLITE_TESTCTRL_BITVEC_TEST: {
4206 int sz = va_arg(ap, int);
4207 int *aProg = va_arg(ap, int*);
4208 rc = sqlite3BitvecBuiltinTest(sz, aProg);
4209 break;
4213 ** sqlite3_test_control(FAULT_INSTALL, xCallback)
4215 ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
4216 ** if xCallback is not NULL.
4218 ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
4219 ** is called immediately after installing the new callback and the return
4220 ** value from sqlite3FaultSim(0) becomes the return from
4221 ** sqlite3_test_control().
4223 case SQLITE_TESTCTRL_FAULT_INSTALL: {
4224 /* A bug in MSVC prevents it from understanding pointers to functions
4225 ** types in the second argument to va_arg(). Work around the problem
4226 ** using a typedef.
4227 ** http://support.microsoft.com/kb/47961 <-- dead hyperlink
4228 ** Search at http://web.archive.org/ to find the 2015-03-16 archive
4229 ** of the link above to see the original text.
4230 ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
4232 typedef int(*sqlite3FaultFuncType)(int);
4233 sqlite3GlobalConfig.xTestCallback = va_arg(ap, sqlite3FaultFuncType);
4234 rc = sqlite3FaultSim(0);
4235 break;
4239 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
4241 ** Register hooks to call to indicate which malloc() failures
4242 ** are benign.
4244 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
4245 typedef void (*void_function)(void);
4246 void_function xBenignBegin;
4247 void_function xBenignEnd;
4248 xBenignBegin = va_arg(ap, void_function);
4249 xBenignEnd = va_arg(ap, void_function);
4250 sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
4251 break;
4255 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
4257 ** Set the PENDING byte to the value in the argument, if X>0.
4258 ** Make no changes if X==0. Return the value of the pending byte
4259 ** as it existing before this routine was called.
4261 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
4262 ** an incompatible database file format. Changing the PENDING byte
4263 ** while any database connection is open results in undefined and
4264 ** deleterious behavior.
4266 case SQLITE_TESTCTRL_PENDING_BYTE: {
4267 rc = PENDING_BYTE;
4268 #ifndef SQLITE_OMIT_WSD
4270 unsigned int newVal = va_arg(ap, unsigned int);
4271 if( newVal ) sqlite3PendingByte = newVal;
4273 #endif
4274 break;
4278 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
4280 ** This action provides a run-time test to see whether or not
4281 ** assert() was enabled at compile-time. If X is true and assert()
4282 ** is enabled, then the return value is true. If X is true and
4283 ** assert() is disabled, then the return value is zero. If X is
4284 ** false and assert() is enabled, then the assertion fires and the
4285 ** process aborts. If X is false and assert() is disabled, then the
4286 ** return value is zero.
4288 case SQLITE_TESTCTRL_ASSERT: {
4289 volatile int x = 0;
4290 assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
4291 rc = x;
4292 #if defined(SQLITE_DEBUG)
4293 /* Invoke these debugging routines so that the compiler does not
4294 ** issue "defined but not used" warnings. */
4295 if( x==9999 ){
4296 sqlite3ShowExpr(0);
4297 sqlite3ShowExpr(0);
4298 sqlite3ShowExprList(0);
4299 sqlite3ShowIdList(0);
4300 sqlite3ShowSrcList(0);
4301 sqlite3ShowWith(0);
4302 sqlite3ShowUpsert(0);
4303 #ifndef SQLITE_OMIT_TRIGGER
4304 sqlite3ShowTriggerStep(0);
4305 sqlite3ShowTriggerStepList(0);
4306 sqlite3ShowTrigger(0);
4307 sqlite3ShowTriggerList(0);
4308 #endif
4309 #ifndef SQLITE_OMIT_WINDOWFUNC
4310 sqlite3ShowWindow(0);
4311 sqlite3ShowWinFunc(0);
4312 #endif
4313 sqlite3ShowSelect(0);
4315 #endif
4316 break;
4321 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
4323 ** This action provides a run-time test to see how the ALWAYS and
4324 ** NEVER macros were defined at compile-time.
4326 ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
4328 ** The recommended test is X==2. If the return value is 2, that means
4329 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
4330 ** default setting. If the return value is 1, then ALWAYS() is either
4331 ** hard-coded to true or else it asserts if its argument is false.
4332 ** The first behavior (hard-coded to true) is the case if
4333 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
4334 ** behavior (assert if the argument to ALWAYS() is false) is the case if
4335 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
4337 ** The run-time test procedure might look something like this:
4339 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
4340 ** // ALWAYS() and NEVER() are no-op pass-through macros
4341 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
4342 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
4343 ** }else{
4344 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
4345 ** }
4347 case SQLITE_TESTCTRL_ALWAYS: {
4348 int x = va_arg(ap,int);
4349 rc = x ? ALWAYS(x) : 0;
4350 break;
4354 ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
4356 ** The integer returned reveals the byte-order of the computer on which
4357 ** SQLite is running:
4359 ** 1 big-endian, determined at run-time
4360 ** 10 little-endian, determined at run-time
4361 ** 432101 big-endian, determined at compile-time
4362 ** 123410 little-endian, determined at compile-time
4364 case SQLITE_TESTCTRL_BYTEORDER: {
4365 rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
4366 break;
4369 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
4371 ** Enable or disable various optimizations for testing purposes. The
4372 ** argument N is a bitmask of optimizations to be disabled. For normal
4373 ** operation N should be 0. The idea is that a test program (like the
4374 ** SQL Logic Test or SLT test module) can run the same SQL multiple times
4375 ** with various optimizations disabled to verify that the same answer
4376 ** is obtained in every case.
4378 case SQLITE_TESTCTRL_OPTIMIZATIONS: {
4379 sqlite3 *db = va_arg(ap, sqlite3*);
4380 db->dbOptFlags = va_arg(ap, u32);
4381 break;
4384 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, onoff, xAlt);
4386 ** If parameter onoff is 1, subsequent calls to localtime() fail.
4387 ** If 2, then invoke xAlt() instead of localtime(). If 0, normal
4388 ** processing.
4390 ** xAlt arguments are void pointers, but they really want to be:
4392 ** int xAlt(const time_t*, struct tm*);
4394 ** xAlt should write results in to struct tm object of its 2nd argument
4395 ** and return zero on success, or return non-zero on failure.
4397 case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
4398 sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
4399 if( sqlite3GlobalConfig.bLocaltimeFault==2 ){
4400 typedef int(*sqlite3LocaltimeType)(const void*,void*);
4401 sqlite3GlobalConfig.xAltLocaltime = va_arg(ap, sqlite3LocaltimeType);
4402 }else{
4403 sqlite3GlobalConfig.xAltLocaltime = 0;
4405 break;
4408 /* sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, sqlite3*);
4410 ** Toggle the ability to use internal functions on or off for
4411 ** the database connection given in the argument.
4413 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: {
4414 sqlite3 *db = va_arg(ap, sqlite3*);
4415 db->mDbFlags ^= DBFLAG_InternalFunc;
4416 break;
4419 /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
4421 ** Set or clear a flag that indicates that the database file is always well-
4422 ** formed and never corrupt. This flag is clear by default, indicating that
4423 ** database files might have arbitrary corruption. Setting the flag during
4424 ** testing causes certain assert() statements in the code to be activated
4425 ** that demonstrate invariants on well-formed database files.
4427 case SQLITE_TESTCTRL_NEVER_CORRUPT: {
4428 sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
4429 break;
4432 /* sqlite3_test_control(SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS, int);
4434 ** Set or clear a flag that causes SQLite to verify that type, name,
4435 ** and tbl_name fields of the sqlite_schema table. This is normally
4436 ** on, but it is sometimes useful to turn it off for testing.
4438 ** 2020-07-22: Disabling EXTRA_SCHEMA_CHECKS also disables the
4439 ** verification of rootpage numbers when parsing the schema. This
4440 ** is useful to make it easier to reach strange internal error states
4441 ** during testing. The EXTRA_SCHEMA_CHECKS setting is always enabled
4442 ** in production.
4444 case SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS: {
4445 sqlite3GlobalConfig.bExtraSchemaChecks = va_arg(ap, int);
4446 break;
4449 /* Set the threshold at which OP_Once counters reset back to zero.
4450 ** By default this is 0x7ffffffe (over 2 billion), but that value is
4451 ** too big to test in a reasonable amount of time, so this control is
4452 ** provided to set a small and easily reachable reset value.
4454 case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
4455 sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
4456 break;
4459 /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
4461 ** Set the VDBE coverage callback function to xCallback with context
4462 ** pointer ptr.
4464 case SQLITE_TESTCTRL_VDBE_COVERAGE: {
4465 #ifdef SQLITE_VDBE_COVERAGE
4466 typedef void (*branch_callback)(void*,unsigned int,
4467 unsigned char,unsigned char);
4468 sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
4469 sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
4470 #endif
4471 break;
4474 /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
4475 case SQLITE_TESTCTRL_SORTER_MMAP: {
4476 sqlite3 *db = va_arg(ap, sqlite3*);
4477 db->nMaxSorterMmap = va_arg(ap, int);
4478 break;
4481 /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
4483 ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
4484 ** not.
4486 case SQLITE_TESTCTRL_ISINIT: {
4487 if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
4488 break;
4491 /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
4493 ** This test control is used to create imposter tables. "db" is a pointer
4494 ** to the database connection. dbName is the database name (ex: "main" or
4495 ** "temp") which will receive the imposter. "onOff" turns imposter mode on
4496 ** or off. "tnum" is the root page of the b-tree to which the imposter
4497 ** table should connect.
4499 ** Enable imposter mode only when the schema has already been parsed. Then
4500 ** run a single CREATE TABLE statement to construct the imposter table in
4501 ** the parsed schema. Then turn imposter mode back off again.
4503 ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
4504 ** the schema to be reparsed the next time it is needed. This has the
4505 ** effect of erasing all imposter tables.
4507 case SQLITE_TESTCTRL_IMPOSTER: {
4508 sqlite3 *db = va_arg(ap, sqlite3*);
4509 int iDb;
4510 sqlite3_mutex_enter(db->mutex);
4511 iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
4512 if( iDb>=0 ){
4513 db->init.iDb = iDb;
4514 db->init.busy = db->init.imposterTable = va_arg(ap,int);
4515 db->init.newTnum = va_arg(ap,int);
4516 if( db->init.busy==0 && db->init.newTnum>0 ){
4517 sqlite3ResetAllSchemasOfConnection(db);
4520 sqlite3_mutex_leave(db->mutex);
4521 break;
4524 #if defined(YYCOVERAGE)
4525 /* sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
4527 ** This test control (only available when SQLite is compiled with
4528 ** -DYYCOVERAGE) writes a report onto "out" that shows all
4529 ** state/lookahead combinations in the parser state machine
4530 ** which are never exercised. If any state is missed, make the
4531 ** return code SQLITE_ERROR.
4533 case SQLITE_TESTCTRL_PARSER_COVERAGE: {
4534 FILE *out = va_arg(ap, FILE*);
4535 if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
4536 break;
4538 #endif /* defined(YYCOVERAGE) */
4540 /* sqlite3_test_control(SQLITE_TESTCTRL_RESULT_INTREAL, sqlite3_context*);
4542 ** This test-control causes the most recent sqlite3_result_int64() value
4543 ** to be interpreted as a MEM_IntReal instead of as an MEM_Int. Normally,
4544 ** MEM_IntReal values only arise during an INSERT operation of integer
4545 ** values into a REAL column, so they can be challenging to test. This
4546 ** test-control enables us to write an intreal() SQL function that can
4547 ** inject an intreal() value at arbitrary places in an SQL statement,
4548 ** for testing purposes.
4550 case SQLITE_TESTCTRL_RESULT_INTREAL: {
4551 sqlite3_context *pCtx = va_arg(ap, sqlite3_context*);
4552 sqlite3ResultIntReal(pCtx);
4553 break;
4556 /* sqlite3_test_control(SQLITE_TESTCTRL_SEEK_COUNT,
4557 ** sqlite3 *db, // Database connection
4558 ** u64 *pnSeek // Write seek count here
4559 ** );
4561 ** This test-control queries the seek-counter on the "main" database
4562 ** file. The seek-counter is written into *pnSeek and is then reset.
4563 ** The seek-count is only available if compiled with SQLITE_DEBUG.
4565 case SQLITE_TESTCTRL_SEEK_COUNT: {
4566 sqlite3 *db = va_arg(ap, sqlite3*);
4567 u64 *pn = va_arg(ap, sqlite3_uint64*);
4568 *pn = sqlite3BtreeSeekCount(db->aDb->pBt);
4569 (void)db; /* Silence harmless unused variable warning */
4570 break;
4573 /* sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, op, ptr)
4575 ** "ptr" is a pointer to a u32.
4577 ** op==0 Store the current sqlite3TreeTrace in *ptr
4578 ** op==1 Set sqlite3TreeTrace to the value *ptr
4579 ** op==2 Store the current sqlite3WhereTrace in *ptr
4580 ** op==3 Set sqlite3WhereTrace to the value *ptr
4582 case SQLITE_TESTCTRL_TRACEFLAGS: {
4583 int opTrace = va_arg(ap, int);
4584 u32 *ptr = va_arg(ap, u32*);
4585 switch( opTrace ){
4586 case 0: *ptr = sqlite3TreeTrace; break;
4587 case 1: sqlite3TreeTrace = *ptr; break;
4588 case 2: *ptr = sqlite3WhereTrace; break;
4589 case 3: sqlite3WhereTrace = *ptr; break;
4591 break;
4594 /* sqlite3_test_control(SQLITE_TESTCTRL_LOGEST,
4595 ** double fIn, // Input value
4596 ** int *pLogEst, // sqlite3LogEstFromDouble(fIn)
4597 ** u64 *pInt, // sqlite3LogEstToInt(*pLogEst)
4598 ** int *pLogEst2 // sqlite3LogEst(*pInt)
4599 ** );
4601 ** Test access for the LogEst conversion routines.
4603 case SQLITE_TESTCTRL_LOGEST: {
4604 double rIn = va_arg(ap, double);
4605 LogEst rLogEst = sqlite3LogEstFromDouble(rIn);
4606 int *pI1 = va_arg(ap,int*);
4607 u64 *pU64 = va_arg(ap,u64*);
4608 int *pI2 = va_arg(ap,int*);
4609 *pI1 = rLogEst;
4610 *pU64 = sqlite3LogEstToInt(rLogEst);
4611 *pI2 = sqlite3LogEst(*pU64);
4612 break;
4615 #if !defined(SQLITE_OMIT_WSD)
4616 /* sqlite3_test_control(SQLITE_TESTCTRL_USELONGDOUBLE, int X);
4618 ** X<0 Make no changes to the bUseLongDouble. Just report value.
4619 ** X==0 Disable bUseLongDouble
4620 ** X==1 Enable bUseLongDouble
4621 ** X>=2 Set bUseLongDouble to its default value for this platform
4623 case SQLITE_TESTCTRL_USELONGDOUBLE: {
4624 int b = va_arg(ap, int);
4625 if( b>=2 ) b = hasHighPrecisionDouble(b);
4626 if( b>=0 ) sqlite3Config.bUseLongDouble = b>0;
4627 rc = sqlite3Config.bUseLongDouble!=0;
4628 break;
4630 #endif
4633 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
4634 /* sqlite3_test_control(SQLITE_TESTCTRL_TUNE, id, *piValue)
4636 ** If "id" is an integer between 1 and SQLITE_NTUNE then set the value
4637 ** of the id-th tuning parameter to *piValue. If "id" is between -1
4638 ** and -SQLITE_NTUNE, then write the current value of the (-id)-th
4639 ** tuning parameter into *piValue.
4641 ** Tuning parameters are for use during transient development builds,
4642 ** to help find the best values for constants in the query planner.
4643 ** Access tuning parameters using the Tuning(ID) macro. Set the
4644 ** parameters in the CLI using ".testctrl tune ID VALUE".
4646 ** Transient use only. Tuning parameters should not be used in
4647 ** checked-in code.
4649 case SQLITE_TESTCTRL_TUNE: {
4650 int id = va_arg(ap, int);
4651 int *piValue = va_arg(ap, int*);
4652 if( id>0 && id<=SQLITE_NTUNE ){
4653 Tuning(id) = *piValue;
4654 }else if( id<0 && id>=-SQLITE_NTUNE ){
4655 *piValue = Tuning(-id);
4656 }else{
4657 rc = SQLITE_NOTFOUND;
4659 break;
4661 #endif
4663 /* sqlite3_test_control(SQLITE_TESTCTRL_JSON_SELFCHECK, &onOff);
4665 ** Activate or deactivate validation of JSONB that is generated from
4666 ** text. Off by default, as the validation is slow. Validation is
4667 ** only available if compiled using SQLITE_DEBUG.
4669 ** If onOff is initially 1, then turn it on. If onOff is initially
4670 ** off, turn it off. If onOff is initially -1, then change onOff
4671 ** to be the current setting.
4673 case SQLITE_TESTCTRL_JSON_SELFCHECK: {
4674 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
4675 int *pOnOff = va_arg(ap, int*);
4676 if( *pOnOff<0 ){
4677 *pOnOff = sqlite3Config.bJsonSelfcheck;
4678 }else{
4679 sqlite3Config.bJsonSelfcheck = (u8)((*pOnOff)&0xff);
4681 #endif
4682 break;
4685 va_end(ap);
4686 #endif /* SQLITE_UNTESTABLE */
4687 return rc;
4691 ** The Pager stores the Database filename, Journal filename, and WAL filename
4692 ** consecutively in memory, in that order. The database filename is prefixed
4693 ** by four zero bytes. Locate the start of the database filename by searching
4694 ** backwards for the first byte following four consecutive zero bytes.
4696 ** This only works if the filename passed in was obtained from the Pager.
4698 static const char *databaseName(const char *zName){
4699 while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
4700 zName--;
4702 return zName;
4706 ** Append text z[] to the end of p[]. Return a pointer to the first
4707 ** character after then zero terminator on the new text in p[].
4709 static char *appendText(char *p, const char *z){
4710 size_t n = strlen(z);
4711 memcpy(p, z, n+1);
4712 return p+n+1;
4716 ** Allocate memory to hold names for a database, journal file, WAL file,
4717 ** and query parameters. The pointer returned is valid for use by
4718 ** sqlite3_filename_database() and sqlite3_uri_parameter() and related
4719 ** functions.
4721 ** Memory layout must be compatible with that generated by the pager
4722 ** and expected by sqlite3_uri_parameter() and databaseName().
4724 const char *sqlite3_create_filename(
4725 const char *zDatabase,
4726 const char *zJournal,
4727 const char *zWal,
4728 int nParam,
4729 const char **azParam
4731 sqlite3_int64 nByte;
4732 int i;
4733 char *pResult, *p;
4734 nByte = strlen(zDatabase) + strlen(zJournal) + strlen(zWal) + 10;
4735 for(i=0; i<nParam*2; i++){
4736 nByte += strlen(azParam[i])+1;
4738 pResult = p = sqlite3_malloc64( nByte );
4739 if( p==0 ) return 0;
4740 memset(p, 0, 4);
4741 p += 4;
4742 p = appendText(p, zDatabase);
4743 for(i=0; i<nParam*2; i++){
4744 p = appendText(p, azParam[i]);
4746 *(p++) = 0;
4747 p = appendText(p, zJournal);
4748 p = appendText(p, zWal);
4749 *(p++) = 0;
4750 *(p++) = 0;
4751 assert( (sqlite3_int64)(p - pResult)==nByte );
4752 return pResult + 4;
4756 ** Free memory obtained from sqlite3_create_filename(). It is a severe
4757 ** error to call this routine with any parameter other than a pointer
4758 ** previously obtained from sqlite3_create_filename() or a NULL pointer.
4760 void sqlite3_free_filename(const char *p){
4761 if( p==0 ) return;
4762 p = databaseName(p);
4763 sqlite3_free((char*)p - 4);
4768 ** This is a utility routine, useful to VFS implementations, that checks
4769 ** to see if a database file was a URI that contained a specific query
4770 ** parameter, and if so obtains the value of the query parameter.
4772 ** The zFilename argument is the filename pointer passed into the xOpen()
4773 ** method of a VFS implementation. The zParam argument is the name of the
4774 ** query parameter we seek. This routine returns the value of the zParam
4775 ** parameter if it exists. If the parameter does not exist, this routine
4776 ** returns a NULL pointer.
4778 const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
4779 if( zFilename==0 || zParam==0 ) return 0;
4780 zFilename = databaseName(zFilename);
4781 return uriParameter(zFilename, zParam);
4785 ** Return a pointer to the name of Nth query parameter of the filename.
4787 const char *sqlite3_uri_key(const char *zFilename, int N){
4788 if( zFilename==0 || N<0 ) return 0;
4789 zFilename = databaseName(zFilename);
4790 zFilename += sqlite3Strlen30(zFilename) + 1;
4791 while( ALWAYS(zFilename) && zFilename[0] && (N--)>0 ){
4792 zFilename += sqlite3Strlen30(zFilename) + 1;
4793 zFilename += sqlite3Strlen30(zFilename) + 1;
4795 return zFilename[0] ? zFilename : 0;
4799 ** Return a boolean value for a query parameter.
4801 int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
4802 const char *z = sqlite3_uri_parameter(zFilename, zParam);
4803 bDflt = bDflt!=0;
4804 return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
4808 ** Return a 64-bit integer value for a query parameter.
4810 sqlite3_int64 sqlite3_uri_int64(
4811 const char *zFilename, /* Filename as passed to xOpen */
4812 const char *zParam, /* URI parameter sought */
4813 sqlite3_int64 bDflt /* return if parameter is missing */
4815 const char *z = sqlite3_uri_parameter(zFilename, zParam);
4816 sqlite3_int64 v;
4817 if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
4818 bDflt = v;
4820 return bDflt;
4824 ** Translate a filename that was handed to a VFS routine into the corresponding
4825 ** database, journal, or WAL file.
4827 ** It is an error to pass this routine a filename string that was not
4828 ** passed into the VFS from the SQLite core. Doing so is similar to
4829 ** passing free() a pointer that was not obtained from malloc() - it is
4830 ** an error that we cannot easily detect but that will likely cause memory
4831 ** corruption.
4833 const char *sqlite3_filename_database(const char *zFilename){
4834 if( zFilename==0 ) return 0;
4835 return databaseName(zFilename);
4837 const char *sqlite3_filename_journal(const char *zFilename){
4838 if( zFilename==0 ) return 0;
4839 zFilename = databaseName(zFilename);
4840 zFilename += sqlite3Strlen30(zFilename) + 1;
4841 while( ALWAYS(zFilename) && zFilename[0] ){
4842 zFilename += sqlite3Strlen30(zFilename) + 1;
4843 zFilename += sqlite3Strlen30(zFilename) + 1;
4845 return zFilename + 1;
4847 const char *sqlite3_filename_wal(const char *zFilename){
4848 #ifdef SQLITE_OMIT_WAL
4849 return 0;
4850 #else
4851 zFilename = sqlite3_filename_journal(zFilename);
4852 if( zFilename ) zFilename += sqlite3Strlen30(zFilename) + 1;
4853 return zFilename;
4854 #endif
4858 ** Return the Btree pointer identified by zDbName. Return NULL if not found.
4860 Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
4861 int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
4862 return iDb<0 ? 0 : db->aDb[iDb].pBt;
4866 ** Return the name of the N-th database schema. Return NULL if N is out
4867 ** of range.
4869 const char *sqlite3_db_name(sqlite3 *db, int N){
4870 #ifdef SQLITE_ENABLE_API_ARMOR
4871 if( !sqlite3SafetyCheckOk(db) ){
4872 (void)SQLITE_MISUSE_BKPT;
4873 return 0;
4875 #endif
4876 if( N<0 || N>=db->nDb ){
4877 return 0;
4878 }else{
4879 return db->aDb[N].zDbSName;
4884 ** Return the filename of the database associated with a database
4885 ** connection.
4887 const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
4888 Btree *pBt;
4889 #ifdef SQLITE_ENABLE_API_ARMOR
4890 if( !sqlite3SafetyCheckOk(db) ){
4891 (void)SQLITE_MISUSE_BKPT;
4892 return 0;
4894 #endif
4895 pBt = sqlite3DbNameToBtree(db, zDbName);
4896 return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
4900 ** Return 1 if database is read-only or 0 if read/write. Return -1 if
4901 ** no such database exists.
4903 int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
4904 Btree *pBt;
4905 #ifdef SQLITE_ENABLE_API_ARMOR
4906 if( !sqlite3SafetyCheckOk(db) ){
4907 (void)SQLITE_MISUSE_BKPT;
4908 return -1;
4910 #endif
4911 pBt = sqlite3DbNameToBtree(db, zDbName);
4912 return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
4915 #ifdef SQLITE_ENABLE_SNAPSHOT
4917 ** Obtain a snapshot handle for the snapshot of database zDb currently
4918 ** being read by handle db.
4920 int sqlite3_snapshot_get(
4921 sqlite3 *db,
4922 const char *zDb,
4923 sqlite3_snapshot **ppSnapshot
4925 int rc = SQLITE_ERROR;
4926 #ifndef SQLITE_OMIT_WAL
4928 #ifdef SQLITE_ENABLE_API_ARMOR
4929 if( !sqlite3SafetyCheckOk(db) ){
4930 return SQLITE_MISUSE_BKPT;
4932 #endif
4933 sqlite3_mutex_enter(db->mutex);
4935 if( db->autoCommit==0 ){
4936 int iDb = sqlite3FindDbName(db, zDb);
4937 if( iDb==0 || iDb>1 ){
4938 Btree *pBt = db->aDb[iDb].pBt;
4939 if( SQLITE_TXN_WRITE!=sqlite3BtreeTxnState(pBt) ){
4940 rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
4941 if( rc==SQLITE_OK ){
4942 rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
4948 sqlite3_mutex_leave(db->mutex);
4949 #endif /* SQLITE_OMIT_WAL */
4950 return rc;
4954 ** Open a read-transaction on the snapshot identified by pSnapshot.
4956 int sqlite3_snapshot_open(
4957 sqlite3 *db,
4958 const char *zDb,
4959 sqlite3_snapshot *pSnapshot
4961 int rc = SQLITE_ERROR;
4962 #ifndef SQLITE_OMIT_WAL
4964 #ifdef SQLITE_ENABLE_API_ARMOR
4965 if( !sqlite3SafetyCheckOk(db) ){
4966 return SQLITE_MISUSE_BKPT;
4968 #endif
4969 sqlite3_mutex_enter(db->mutex);
4970 if( db->autoCommit==0 ){
4971 int iDb;
4972 iDb = sqlite3FindDbName(db, zDb);
4973 if( iDb==0 || iDb>1 ){
4974 Btree *pBt = db->aDb[iDb].pBt;
4975 if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE ){
4976 Pager *pPager = sqlite3BtreePager(pBt);
4977 int bUnlock = 0;
4978 if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_NONE ){
4979 if( db->nVdbeActive==0 ){
4980 rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot);
4981 if( rc==SQLITE_OK ){
4982 bUnlock = 1;
4983 rc = sqlite3BtreeCommit(pBt);
4986 }else{
4987 rc = SQLITE_OK;
4989 if( rc==SQLITE_OK ){
4990 rc = sqlite3PagerSnapshotOpen(pPager, pSnapshot);
4992 if( rc==SQLITE_OK ){
4993 rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
4994 sqlite3PagerSnapshotOpen(pPager, 0);
4996 if( bUnlock ){
4997 sqlite3PagerSnapshotUnlock(pPager);
5003 sqlite3_mutex_leave(db->mutex);
5004 #endif /* SQLITE_OMIT_WAL */
5005 return rc;
5009 ** Recover as many snapshots as possible from the wal file associated with
5010 ** schema zDb of database db.
5012 int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
5013 int rc = SQLITE_ERROR;
5014 #ifndef SQLITE_OMIT_WAL
5015 int iDb;
5017 #ifdef SQLITE_ENABLE_API_ARMOR
5018 if( !sqlite3SafetyCheckOk(db) ){
5019 return SQLITE_MISUSE_BKPT;
5021 #endif
5023 sqlite3_mutex_enter(db->mutex);
5024 iDb = sqlite3FindDbName(db, zDb);
5025 if( iDb==0 || iDb>1 ){
5026 Btree *pBt = db->aDb[iDb].pBt;
5027 if( SQLITE_TXN_NONE==sqlite3BtreeTxnState(pBt) ){
5028 rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
5029 if( rc==SQLITE_OK ){
5030 rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
5031 sqlite3BtreeCommit(pBt);
5035 sqlite3_mutex_leave(db->mutex);
5036 #endif /* SQLITE_OMIT_WAL */
5037 return rc;
5041 ** Free a snapshot handle obtained from sqlite3_snapshot_get().
5043 void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
5044 sqlite3_free(pSnapshot);
5046 #endif /* SQLITE_ENABLE_SNAPSHOT */
5048 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
5050 ** Given the name of a compile-time option, return true if that option
5051 ** was used and false if not.
5053 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
5054 ** is not required for a match.
5056 int sqlite3_compileoption_used(const char *zOptName){
5057 int i, n;
5058 int nOpt;
5059 const char **azCompileOpt;
5061 #ifdef SQLITE_ENABLE_API_ARMOR
5062 if( zOptName==0 ){
5063 (void)SQLITE_MISUSE_BKPT;
5064 return 0;
5066 #endif
5068 azCompileOpt = sqlite3CompileOptions(&nOpt);
5070 if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
5071 n = sqlite3Strlen30(zOptName);
5073 /* Since nOpt is normally in single digits, a linear search is
5074 ** adequate. No need for a binary search. */
5075 for(i=0; i<nOpt; i++){
5076 if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
5077 && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
5079 return 1;
5082 return 0;
5086 ** Return the N-th compile-time option string. If N is out of range,
5087 ** return a NULL pointer.
5089 const char *sqlite3_compileoption_get(int N){
5090 int nOpt;
5091 const char **azCompileOpt;
5092 azCompileOpt = sqlite3CompileOptions(&nOpt);
5093 if( N>=0 && N<nOpt ){
5094 return azCompileOpt[N];
5096 return 0;
5098 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */