Fix a problem causing the recovery extension to use excessive memory and CPU time...
[sqlite.git] / src / main.c
blobbff801a87df602d85ce671f5f78a8238ea875bf1
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 case SQLITE_CONFIG_ROWID_IN_VIEW: {
769 int *pVal = va_arg(ap,int*);
770 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
771 if( 0==*pVal ) sqlite3GlobalConfig.mNoVisibleRowid = TF_NoVisibleRowid;
772 if( 1==*pVal ) sqlite3GlobalConfig.mNoVisibleRowid = 0;
773 *pVal = (sqlite3GlobalConfig.mNoVisibleRowid==0);
774 #else
775 *pVal = 0;
776 #endif
777 break;
780 default: {
781 rc = SQLITE_ERROR;
782 break;
785 va_end(ap);
786 return rc;
790 ** Set up the lookaside buffers for a database connection.
791 ** Return SQLITE_OK on success.
792 ** If lookaside is already active, return SQLITE_BUSY.
794 ** The sz parameter is the number of bytes in each lookaside slot.
795 ** The cnt parameter is the number of slots. If pStart is NULL the
796 ** space for the lookaside memory is obtained from sqlite3_malloc().
797 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
798 ** the lookaside memory.
800 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
801 #ifndef SQLITE_OMIT_LOOKASIDE
802 void *pStart;
803 sqlite3_int64 szAlloc = sz*(sqlite3_int64)cnt;
804 int nBig; /* Number of full-size slots */
805 int nSm; /* Number smaller LOOKASIDE_SMALL-byte slots */
807 if( sqlite3LookasideUsed(db,0)>0 ){
808 return SQLITE_BUSY;
810 /* Free any existing lookaside buffer for this handle before
811 ** allocating a new one so we don't have to have space for
812 ** both at the same time.
814 if( db->lookaside.bMalloced ){
815 sqlite3_free(db->lookaside.pStart);
817 /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
818 ** than a pointer to be useful.
820 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
821 if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
822 if( cnt<0 ) cnt = 0;
823 if( sz==0 || cnt==0 ){
824 sz = 0;
825 pStart = 0;
826 }else if( pBuf==0 ){
827 sqlite3BeginBenignMalloc();
828 pStart = sqlite3Malloc( szAlloc ); /* IMP: R-61949-35727 */
829 sqlite3EndBenignMalloc();
830 if( pStart ) szAlloc = sqlite3MallocSize(pStart);
831 }else{
832 pStart = pBuf;
834 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
835 if( sz>=LOOKASIDE_SMALL*3 ){
836 nBig = szAlloc/(3*LOOKASIDE_SMALL+sz);
837 nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
838 }else if( sz>=LOOKASIDE_SMALL*2 ){
839 nBig = szAlloc/(LOOKASIDE_SMALL+sz);
840 nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
841 }else
842 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
843 if( sz>0 ){
844 nBig = szAlloc/sz;
845 nSm = 0;
846 }else{
847 nBig = nSm = 0;
849 db->lookaside.pStart = pStart;
850 db->lookaside.pInit = 0;
851 db->lookaside.pFree = 0;
852 db->lookaside.sz = (u16)sz;
853 db->lookaside.szTrue = (u16)sz;
854 if( pStart ){
855 int i;
856 LookasideSlot *p;
857 assert( sz > (int)sizeof(LookasideSlot*) );
858 p = (LookasideSlot*)pStart;
859 for(i=0; i<nBig; i++){
860 p->pNext = db->lookaside.pInit;
861 db->lookaside.pInit = p;
862 p = (LookasideSlot*)&((u8*)p)[sz];
864 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
865 db->lookaside.pSmallInit = 0;
866 db->lookaside.pSmallFree = 0;
867 db->lookaside.pMiddle = p;
868 for(i=0; i<nSm; i++){
869 p->pNext = db->lookaside.pSmallInit;
870 db->lookaside.pSmallInit = p;
871 p = (LookasideSlot*)&((u8*)p)[LOOKASIDE_SMALL];
873 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
874 assert( ((uptr)p)<=szAlloc + (uptr)pStart );
875 db->lookaside.pEnd = p;
876 db->lookaside.bDisable = 0;
877 db->lookaside.bMalloced = pBuf==0 ?1:0;
878 db->lookaside.nSlot = nBig+nSm;
879 }else{
880 db->lookaside.pStart = 0;
881 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
882 db->lookaside.pSmallInit = 0;
883 db->lookaside.pSmallFree = 0;
884 db->lookaside.pMiddle = 0;
885 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
886 db->lookaside.pEnd = 0;
887 db->lookaside.bDisable = 1;
888 db->lookaside.sz = 0;
889 db->lookaside.bMalloced = 0;
890 db->lookaside.nSlot = 0;
892 db->lookaside.pTrueEnd = db->lookaside.pEnd;
893 assert( sqlite3LookasideUsed(db,0)==0 );
894 #endif /* SQLITE_OMIT_LOOKASIDE */
895 return SQLITE_OK;
899 ** Return the mutex associated with a database connection.
901 sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
902 #ifdef SQLITE_ENABLE_API_ARMOR
903 if( !sqlite3SafetyCheckOk(db) ){
904 (void)SQLITE_MISUSE_BKPT;
905 return 0;
907 #endif
908 return db->mutex;
912 ** Free up as much memory as we can from the given database
913 ** connection.
915 int sqlite3_db_release_memory(sqlite3 *db){
916 int i;
918 #ifdef SQLITE_ENABLE_API_ARMOR
919 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
920 #endif
921 sqlite3_mutex_enter(db->mutex);
922 sqlite3BtreeEnterAll(db);
923 for(i=0; i<db->nDb; i++){
924 Btree *pBt = db->aDb[i].pBt;
925 if( pBt ){
926 Pager *pPager = sqlite3BtreePager(pBt);
927 sqlite3PagerShrink(pPager);
930 sqlite3BtreeLeaveAll(db);
931 sqlite3_mutex_leave(db->mutex);
932 return SQLITE_OK;
936 ** Flush any dirty pages in the pager-cache for any attached database
937 ** to disk.
939 int sqlite3_db_cacheflush(sqlite3 *db){
940 int i;
941 int rc = SQLITE_OK;
942 int bSeenBusy = 0;
944 #ifdef SQLITE_ENABLE_API_ARMOR
945 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
946 #endif
947 sqlite3_mutex_enter(db->mutex);
948 sqlite3BtreeEnterAll(db);
949 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
950 Btree *pBt = db->aDb[i].pBt;
951 if( pBt && sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
952 Pager *pPager = sqlite3BtreePager(pBt);
953 rc = sqlite3PagerFlush(pPager);
954 if( rc==SQLITE_BUSY ){
955 bSeenBusy = 1;
956 rc = SQLITE_OK;
960 sqlite3BtreeLeaveAll(db);
961 sqlite3_mutex_leave(db->mutex);
962 return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
966 ** Configuration settings for an individual database connection
968 int sqlite3_db_config(sqlite3 *db, int op, ...){
969 va_list ap;
970 int rc;
972 #ifdef SQLITE_ENABLE_API_ARMOR
973 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
974 #endif
975 sqlite3_mutex_enter(db->mutex);
976 va_start(ap, op);
977 switch( op ){
978 case SQLITE_DBCONFIG_MAINDBNAME: {
979 /* IMP: R-06824-28531 */
980 /* IMP: R-36257-52125 */
981 db->aDb[0].zDbSName = va_arg(ap,char*);
982 rc = SQLITE_OK;
983 break;
985 case SQLITE_DBCONFIG_LOOKASIDE: {
986 void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
987 int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
988 int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
989 rc = setupLookaside(db, pBuf, sz, cnt);
990 break;
992 default: {
993 static const struct {
994 int op; /* The opcode */
995 u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
996 } aFlagOp[] = {
997 { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
998 { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
999 { SQLITE_DBCONFIG_ENABLE_VIEW, SQLITE_EnableView },
1000 { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
1001 { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension },
1002 { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose },
1003 { SQLITE_DBCONFIG_ENABLE_QPSG, SQLITE_EnableQPSG },
1004 { SQLITE_DBCONFIG_TRIGGER_EQP, SQLITE_TriggerEQP },
1005 { SQLITE_DBCONFIG_RESET_DATABASE, SQLITE_ResetDatabase },
1006 { SQLITE_DBCONFIG_DEFENSIVE, SQLITE_Defensive },
1007 { SQLITE_DBCONFIG_WRITABLE_SCHEMA, SQLITE_WriteSchema|
1008 SQLITE_NoSchemaError },
1009 { SQLITE_DBCONFIG_LEGACY_ALTER_TABLE, SQLITE_LegacyAlter },
1010 { SQLITE_DBCONFIG_DQS_DDL, SQLITE_DqsDDL },
1011 { SQLITE_DBCONFIG_DQS_DML, SQLITE_DqsDML },
1012 { SQLITE_DBCONFIG_LEGACY_FILE_FORMAT, SQLITE_LegacyFileFmt },
1013 { SQLITE_DBCONFIG_TRUSTED_SCHEMA, SQLITE_TrustedSchema },
1014 { SQLITE_DBCONFIG_STMT_SCANSTATUS, SQLITE_StmtScanStatus },
1015 { SQLITE_DBCONFIG_REVERSE_SCANORDER, SQLITE_ReverseOrder },
1017 unsigned int i;
1018 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
1019 for(i=0; i<ArraySize(aFlagOp); i++){
1020 if( aFlagOp[i].op==op ){
1021 int onoff = va_arg(ap, int);
1022 int *pRes = va_arg(ap, int*);
1023 u64 oldFlags = db->flags;
1024 if( onoff>0 ){
1025 db->flags |= aFlagOp[i].mask;
1026 }else if( onoff==0 ){
1027 db->flags &= ~(u64)aFlagOp[i].mask;
1029 if( oldFlags!=db->flags ){
1030 sqlite3ExpirePreparedStatements(db, 0);
1032 if( pRes ){
1033 *pRes = (db->flags & aFlagOp[i].mask)!=0;
1035 rc = SQLITE_OK;
1036 break;
1039 break;
1042 va_end(ap);
1043 sqlite3_mutex_leave(db->mutex);
1044 return rc;
1048 ** This is the default collating function named "BINARY" which is always
1049 ** available.
1051 static int binCollFunc(
1052 void *NotUsed,
1053 int nKey1, const void *pKey1,
1054 int nKey2, const void *pKey2
1056 int rc, n;
1057 UNUSED_PARAMETER(NotUsed);
1058 n = nKey1<nKey2 ? nKey1 : nKey2;
1059 /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
1060 ** strings byte by byte using the memcmp() function from the standard C
1061 ** library. */
1062 assert( pKey1 && pKey2 );
1063 rc = memcmp(pKey1, pKey2, n);
1064 if( rc==0 ){
1065 rc = nKey1 - nKey2;
1067 return rc;
1071 ** This is the collating function named "RTRIM" which is always
1072 ** available. Ignore trailing spaces.
1074 static int rtrimCollFunc(
1075 void *pUser,
1076 int nKey1, const void *pKey1,
1077 int nKey2, const void *pKey2
1079 const u8 *pK1 = (const u8*)pKey1;
1080 const u8 *pK2 = (const u8*)pKey2;
1081 while( nKey1 && pK1[nKey1-1]==' ' ) nKey1--;
1082 while( nKey2 && pK2[nKey2-1]==' ' ) nKey2--;
1083 return binCollFunc(pUser, nKey1, pKey1, nKey2, pKey2);
1087 ** Return true if CollSeq is the default built-in BINARY.
1089 int sqlite3IsBinary(const CollSeq *p){
1090 assert( p==0 || p->xCmp!=binCollFunc || strcmp(p->zName,"BINARY")==0 );
1091 return p==0 || p->xCmp==binCollFunc;
1095 ** Another built-in collating sequence: NOCASE.
1097 ** This collating sequence is intended to be used for "case independent
1098 ** comparison". SQLite's knowledge of upper and lower case equivalents
1099 ** extends only to the 26 characters used in the English language.
1101 ** At the moment there is only a UTF-8 implementation.
1103 static int nocaseCollatingFunc(
1104 void *NotUsed,
1105 int nKey1, const void *pKey1,
1106 int nKey2, const void *pKey2
1108 int r = sqlite3StrNICmp(
1109 (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
1110 UNUSED_PARAMETER(NotUsed);
1111 if( 0==r ){
1112 r = nKey1-nKey2;
1114 return r;
1118 ** Return the ROWID of the most recent insert
1120 sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
1121 #ifdef SQLITE_ENABLE_API_ARMOR
1122 if( !sqlite3SafetyCheckOk(db) ){
1123 (void)SQLITE_MISUSE_BKPT;
1124 return 0;
1126 #endif
1127 return db->lastRowid;
1131 ** Set the value returned by the sqlite3_last_insert_rowid() API function.
1133 void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
1134 #ifdef SQLITE_ENABLE_API_ARMOR
1135 if( !sqlite3SafetyCheckOk(db) ){
1136 (void)SQLITE_MISUSE_BKPT;
1137 return;
1139 #endif
1140 sqlite3_mutex_enter(db->mutex);
1141 db->lastRowid = iRowid;
1142 sqlite3_mutex_leave(db->mutex);
1146 ** Return the number of changes in the most recent call to sqlite3_exec().
1148 sqlite3_int64 sqlite3_changes64(sqlite3 *db){
1149 #ifdef SQLITE_ENABLE_API_ARMOR
1150 if( !sqlite3SafetyCheckOk(db) ){
1151 (void)SQLITE_MISUSE_BKPT;
1152 return 0;
1154 #endif
1155 return db->nChange;
1157 int sqlite3_changes(sqlite3 *db){
1158 return (int)sqlite3_changes64(db);
1162 ** Return the number of changes since the database handle was opened.
1164 sqlite3_int64 sqlite3_total_changes64(sqlite3 *db){
1165 #ifdef SQLITE_ENABLE_API_ARMOR
1166 if( !sqlite3SafetyCheckOk(db) ){
1167 (void)SQLITE_MISUSE_BKPT;
1168 return 0;
1170 #endif
1171 return db->nTotalChange;
1173 int sqlite3_total_changes(sqlite3 *db){
1174 return (int)sqlite3_total_changes64(db);
1178 ** Close all open savepoints. This function only manipulates fields of the
1179 ** database handle object, it does not close any savepoints that may be open
1180 ** at the b-tree/pager level.
1182 void sqlite3CloseSavepoints(sqlite3 *db){
1183 while( db->pSavepoint ){
1184 Savepoint *pTmp = db->pSavepoint;
1185 db->pSavepoint = pTmp->pNext;
1186 sqlite3DbFree(db, pTmp);
1188 db->nSavepoint = 0;
1189 db->nStatement = 0;
1190 db->isTransactionSavepoint = 0;
1194 ** Invoke the destructor function associated with FuncDef p, if any. Except,
1195 ** if this is not the last copy of the function, do not invoke it. Multiple
1196 ** copies of a single function are created when create_function() is called
1197 ** with SQLITE_ANY as the encoding.
1199 static void functionDestroy(sqlite3 *db, FuncDef *p){
1200 FuncDestructor *pDestructor;
1201 assert( (p->funcFlags & SQLITE_FUNC_BUILTIN)==0 );
1202 pDestructor = p->u.pDestructor;
1203 if( pDestructor ){
1204 pDestructor->nRef--;
1205 if( pDestructor->nRef==0 ){
1206 pDestructor->xDestroy(pDestructor->pUserData);
1207 sqlite3DbFree(db, pDestructor);
1213 ** Disconnect all sqlite3_vtab objects that belong to database connection
1214 ** db. This is called when db is being closed.
1216 static void disconnectAllVtab(sqlite3 *db){
1217 #ifndef SQLITE_OMIT_VIRTUALTABLE
1218 int i;
1219 HashElem *p;
1220 sqlite3BtreeEnterAll(db);
1221 for(i=0; i<db->nDb; i++){
1222 Schema *pSchema = db->aDb[i].pSchema;
1223 if( pSchema ){
1224 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
1225 Table *pTab = (Table *)sqliteHashData(p);
1226 if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
1230 for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
1231 Module *pMod = (Module *)sqliteHashData(p);
1232 if( pMod->pEpoTab ){
1233 sqlite3VtabDisconnect(db, pMod->pEpoTab);
1236 sqlite3VtabUnlockList(db);
1237 sqlite3BtreeLeaveAll(db);
1238 #else
1239 UNUSED_PARAMETER(db);
1240 #endif
1244 ** Return TRUE if database connection db has unfinalized prepared
1245 ** statements or unfinished sqlite3_backup objects.
1247 static int connectionIsBusy(sqlite3 *db){
1248 int j;
1249 assert( sqlite3_mutex_held(db->mutex) );
1250 if( db->pVdbe ) return 1;
1251 for(j=0; j<db->nDb; j++){
1252 Btree *pBt = db->aDb[j].pBt;
1253 if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
1255 return 0;
1259 ** Close an existing SQLite database
1261 static int sqlite3Close(sqlite3 *db, int forceZombie){
1262 if( !db ){
1263 /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
1264 ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
1265 return SQLITE_OK;
1267 if( !sqlite3SafetyCheckSickOrOk(db) ){
1268 return SQLITE_MISUSE_BKPT;
1270 sqlite3_mutex_enter(db->mutex);
1271 if( db->mTrace & SQLITE_TRACE_CLOSE ){
1272 db->trace.xV2(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
1275 /* Force xDisconnect calls on all virtual tables */
1276 disconnectAllVtab(db);
1278 /* If a transaction is open, the disconnectAllVtab() call above
1279 ** will not have called the xDisconnect() method on any virtual
1280 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
1281 ** call will do so. We need to do this before the check for active
1282 ** SQL statements below, as the v-table implementation may be storing
1283 ** some prepared statements internally.
1285 sqlite3VtabRollback(db);
1287 /* Legacy behavior (sqlite3_close() behavior) is to return
1288 ** SQLITE_BUSY if the connection can not be closed immediately.
1290 if( !forceZombie && connectionIsBusy(db) ){
1291 sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
1292 "statements or unfinished backups");
1293 sqlite3_mutex_leave(db->mutex);
1294 return SQLITE_BUSY;
1297 #ifdef SQLITE_ENABLE_SQLLOG
1298 if( sqlite3GlobalConfig.xSqllog ){
1299 /* Closing the handle. Fourth parameter is passed the value 2. */
1300 sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
1302 #endif
1304 while( db->pDbData ){
1305 DbClientData *p = db->pDbData;
1306 db->pDbData = p->pNext;
1307 assert( p->pData!=0 );
1308 if( p->xDestructor ) p->xDestructor(p->pData);
1309 sqlite3_free(p);
1312 /* Convert the connection into a zombie and then close it.
1314 db->eOpenState = SQLITE_STATE_ZOMBIE;
1315 sqlite3LeaveMutexAndCloseZombie(db);
1316 return SQLITE_OK;
1320 ** Return the transaction state for a single databse, or the maximum
1321 ** transaction state over all attached databases if zSchema is null.
1323 int sqlite3_txn_state(sqlite3 *db, const char *zSchema){
1324 int iDb, nDb;
1325 int iTxn = -1;
1326 #ifdef SQLITE_ENABLE_API_ARMOR
1327 if( !sqlite3SafetyCheckOk(db) ){
1328 (void)SQLITE_MISUSE_BKPT;
1329 return -1;
1331 #endif
1332 sqlite3_mutex_enter(db->mutex);
1333 if( zSchema ){
1334 nDb = iDb = sqlite3FindDbName(db, zSchema);
1335 if( iDb<0 ) nDb--;
1336 }else{
1337 iDb = 0;
1338 nDb = db->nDb-1;
1340 for(; iDb<=nDb; iDb++){
1341 Btree *pBt = db->aDb[iDb].pBt;
1342 int x = pBt!=0 ? sqlite3BtreeTxnState(pBt) : SQLITE_TXN_NONE;
1343 if( x>iTxn ) iTxn = x;
1345 sqlite3_mutex_leave(db->mutex);
1346 return iTxn;
1350 ** Two variations on the public interface for closing a database
1351 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
1352 ** leaves the connection open if there are unfinalized prepared
1353 ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
1354 ** version forces the connection to become a zombie if there are
1355 ** unclosed resources, and arranges for deallocation when the last
1356 ** prepare statement or sqlite3_backup closes.
1358 int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
1359 int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
1363 ** Close the mutex on database connection db.
1365 ** Furthermore, if database connection db is a zombie (meaning that there
1366 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
1367 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
1368 ** finished, then free all resources.
1370 void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
1371 HashElem *i; /* Hash table iterator */
1372 int j;
1374 /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
1375 ** or if the connection has not yet been closed by sqlite3_close_v2(),
1376 ** then just leave the mutex and return.
1378 if( db->eOpenState!=SQLITE_STATE_ZOMBIE || connectionIsBusy(db) ){
1379 sqlite3_mutex_leave(db->mutex);
1380 return;
1383 /* If we reach this point, it means that the database connection has
1384 ** closed all sqlite3_stmt and sqlite3_backup objects and has been
1385 ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
1386 ** go ahead and free all resources.
1389 /* If a transaction is open, roll it back. This also ensures that if
1390 ** any database schemas have been modified by an uncommitted transaction
1391 ** they are reset. And that the required b-tree mutex is held to make
1392 ** the pager rollback and schema reset an atomic operation. */
1393 sqlite3RollbackAll(db, SQLITE_OK);
1395 /* Free any outstanding Savepoint structures. */
1396 sqlite3CloseSavepoints(db);
1398 /* Close all database connections */
1399 for(j=0; j<db->nDb; j++){
1400 struct Db *pDb = &db->aDb[j];
1401 if( pDb->pBt ){
1402 sqlite3BtreeClose(pDb->pBt);
1403 pDb->pBt = 0;
1404 if( j!=1 ){
1405 pDb->pSchema = 0;
1409 /* Clear the TEMP schema separately and last */
1410 if( db->aDb[1].pSchema ){
1411 sqlite3SchemaClear(db->aDb[1].pSchema);
1413 sqlite3VtabUnlockList(db);
1415 /* Free up the array of auxiliary databases */
1416 sqlite3CollapseDatabaseArray(db);
1417 assert( db->nDb<=2 );
1418 assert( db->aDb==db->aDbStatic );
1420 /* Tell the code in notify.c that the connection no longer holds any
1421 ** locks and does not require any further unlock-notify callbacks.
1423 sqlite3ConnectionClosed(db);
1425 for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
1426 FuncDef *pNext, *p;
1427 p = sqliteHashData(i);
1429 functionDestroy(db, p);
1430 pNext = p->pNext;
1431 sqlite3DbFree(db, p);
1432 p = pNext;
1433 }while( p );
1435 sqlite3HashClear(&db->aFunc);
1436 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
1437 CollSeq *pColl = (CollSeq *)sqliteHashData(i);
1438 /* Invoke any destructors registered for collation sequence user data. */
1439 for(j=0; j<3; j++){
1440 if( pColl[j].xDel ){
1441 pColl[j].xDel(pColl[j].pUser);
1444 sqlite3DbFree(db, pColl);
1446 sqlite3HashClear(&db->aCollSeq);
1447 #ifndef SQLITE_OMIT_VIRTUALTABLE
1448 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
1449 Module *pMod = (Module *)sqliteHashData(i);
1450 sqlite3VtabEponymousTableClear(db, pMod);
1451 sqlite3VtabModuleUnref(db, pMod);
1453 sqlite3HashClear(&db->aModule);
1454 #endif
1456 sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
1457 sqlite3ValueFree(db->pErr);
1458 sqlite3CloseExtensions(db);
1459 #if SQLITE_USER_AUTHENTICATION
1460 sqlite3_free(db->auth.zAuthUser);
1461 sqlite3_free(db->auth.zAuthPW);
1462 #endif
1464 db->eOpenState = SQLITE_STATE_ERROR;
1466 /* The temp-database schema is allocated differently from the other schema
1467 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
1468 ** So it needs to be freed here. Todo: Why not roll the temp schema into
1469 ** the same sqliteMalloc() as the one that allocates the database
1470 ** structure?
1472 sqlite3DbFree(db, db->aDb[1].pSchema);
1473 if( db->xAutovacDestr ){
1474 db->xAutovacDestr(db->pAutovacPagesArg);
1476 sqlite3_mutex_leave(db->mutex);
1477 db->eOpenState = SQLITE_STATE_CLOSED;
1478 sqlite3_mutex_free(db->mutex);
1479 assert( sqlite3LookasideUsed(db,0)==0 );
1480 if( db->lookaside.bMalloced ){
1481 sqlite3_free(db->lookaside.pStart);
1483 sqlite3_free(db);
1487 ** Rollback all database files. If tripCode is not SQLITE_OK, then
1488 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
1489 ** breaker") and made to return tripCode if there are any further
1490 ** attempts to use that cursor. Read cursors remain open and valid
1491 ** but are "saved" in case the table pages are moved around.
1493 void sqlite3RollbackAll(sqlite3 *db, int tripCode){
1494 int i;
1495 int inTrans = 0;
1496 int schemaChange;
1497 assert( sqlite3_mutex_held(db->mutex) );
1498 sqlite3BeginBenignMalloc();
1500 /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
1501 ** This is important in case the transaction being rolled back has
1502 ** modified the database schema. If the b-tree mutexes are not taken
1503 ** here, then another shared-cache connection might sneak in between
1504 ** the database rollback and schema reset, which can cause false
1505 ** corruption reports in some cases. */
1506 sqlite3BtreeEnterAll(db);
1507 schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
1509 for(i=0; i<db->nDb; i++){
1510 Btree *p = db->aDb[i].pBt;
1511 if( p ){
1512 if( sqlite3BtreeTxnState(p)==SQLITE_TXN_WRITE ){
1513 inTrans = 1;
1515 sqlite3BtreeRollback(p, tripCode, !schemaChange);
1518 sqlite3VtabRollback(db);
1519 sqlite3EndBenignMalloc();
1521 if( schemaChange ){
1522 sqlite3ExpirePreparedStatements(db, 0);
1523 sqlite3ResetAllSchemasOfConnection(db);
1525 sqlite3BtreeLeaveAll(db);
1527 /* Any deferred constraint violations have now been resolved. */
1528 db->nDeferredCons = 0;
1529 db->nDeferredImmCons = 0;
1530 db->flags &= ~(u64)(SQLITE_DeferFKs|SQLITE_CorruptRdOnly);
1532 /* If one has been configured, invoke the rollback-hook callback */
1533 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
1534 db->xRollbackCallback(db->pRollbackArg);
1539 ** Return a static string containing the name corresponding to the error code
1540 ** specified in the argument.
1542 #if defined(SQLITE_NEED_ERR_NAME)
1543 const char *sqlite3ErrName(int rc){
1544 const char *zName = 0;
1545 int i, origRc = rc;
1546 for(i=0; i<2 && zName==0; i++, rc &= 0xff){
1547 switch( rc ){
1548 case SQLITE_OK: zName = "SQLITE_OK"; break;
1549 case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
1550 case SQLITE_ERROR_SNAPSHOT: zName = "SQLITE_ERROR_SNAPSHOT"; break;
1551 case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
1552 case SQLITE_PERM: zName = "SQLITE_PERM"; break;
1553 case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
1554 case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
1555 case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
1556 case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
1557 case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
1558 case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
1559 case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
1560 case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
1561 case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
1562 case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
1563 case SQLITE_READONLY_CANTINIT: zName = "SQLITE_READONLY_CANTINIT"; break;
1564 case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
1565 case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
1566 case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break;
1567 case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
1568 case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
1569 case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
1570 case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
1571 case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
1572 case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
1573 case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
1574 case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
1575 case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
1576 case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
1577 case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
1578 case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
1579 case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
1580 case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
1581 case SQLITE_IOERR_CHECKRESERVEDLOCK:
1582 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
1583 case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
1584 case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
1585 case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
1586 case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
1587 case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
1588 case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
1589 case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
1590 case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
1591 case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
1592 case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
1593 case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
1594 case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
1595 case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
1596 case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
1597 case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
1598 case SQLITE_FULL: zName = "SQLITE_FULL"; break;
1599 case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
1600 case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
1601 case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
1602 case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
1603 case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
1604 case SQLITE_CANTOPEN_SYMLINK: zName = "SQLITE_CANTOPEN_SYMLINK"; break;
1605 case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
1606 case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
1607 case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
1608 case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
1609 case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
1610 case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
1611 case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
1612 case SQLITE_CONSTRAINT_FOREIGNKEY:
1613 zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
1614 case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
1615 case SQLITE_CONSTRAINT_PRIMARYKEY:
1616 zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
1617 case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
1618 case SQLITE_CONSTRAINT_COMMITHOOK:
1619 zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
1620 case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
1621 case SQLITE_CONSTRAINT_FUNCTION:
1622 zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
1623 case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
1624 case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
1625 case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
1626 case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
1627 case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
1628 case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
1629 case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
1630 case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
1631 case SQLITE_ROW: zName = "SQLITE_ROW"; break;
1632 case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
1633 case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
1634 case SQLITE_NOTICE_RECOVER_ROLLBACK:
1635 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
1636 case SQLITE_NOTICE_RBU: zName = "SQLITE_NOTICE_RBU"; break;
1637 case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
1638 case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
1639 case SQLITE_DONE: zName = "SQLITE_DONE"; break;
1642 if( zName==0 ){
1643 static char zBuf[50];
1644 sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
1645 zName = zBuf;
1647 return zName;
1649 #endif
1652 ** Return a static string that describes the kind of error specified in the
1653 ** argument.
1655 const char *sqlite3ErrStr(int rc){
1656 static const char* const aMsg[] = {
1657 /* SQLITE_OK */ "not an error",
1658 /* SQLITE_ERROR */ "SQL logic error",
1659 /* SQLITE_INTERNAL */ 0,
1660 /* SQLITE_PERM */ "access permission denied",
1661 /* SQLITE_ABORT */ "query aborted",
1662 /* SQLITE_BUSY */ "database is locked",
1663 /* SQLITE_LOCKED */ "database table is locked",
1664 /* SQLITE_NOMEM */ "out of memory",
1665 /* SQLITE_READONLY */ "attempt to write a readonly database",
1666 /* SQLITE_INTERRUPT */ "interrupted",
1667 /* SQLITE_IOERR */ "disk I/O error",
1668 /* SQLITE_CORRUPT */ "database disk image is malformed",
1669 /* SQLITE_NOTFOUND */ "unknown operation",
1670 /* SQLITE_FULL */ "database or disk is full",
1671 /* SQLITE_CANTOPEN */ "unable to open database file",
1672 /* SQLITE_PROTOCOL */ "locking protocol",
1673 /* SQLITE_EMPTY */ 0,
1674 /* SQLITE_SCHEMA */ "database schema has changed",
1675 /* SQLITE_TOOBIG */ "string or blob too big",
1676 /* SQLITE_CONSTRAINT */ "constraint failed",
1677 /* SQLITE_MISMATCH */ "datatype mismatch",
1678 /* SQLITE_MISUSE */ "bad parameter or other API misuse",
1679 #ifdef SQLITE_DISABLE_LFS
1680 /* SQLITE_NOLFS */ "large file support is disabled",
1681 #else
1682 /* SQLITE_NOLFS */ 0,
1683 #endif
1684 /* SQLITE_AUTH */ "authorization denied",
1685 /* SQLITE_FORMAT */ 0,
1686 /* SQLITE_RANGE */ "column index out of range",
1687 /* SQLITE_NOTADB */ "file is not a database",
1688 /* SQLITE_NOTICE */ "notification message",
1689 /* SQLITE_WARNING */ "warning message",
1691 const char *zErr = "unknown error";
1692 switch( rc ){
1693 case SQLITE_ABORT_ROLLBACK: {
1694 zErr = "abort due to ROLLBACK";
1695 break;
1697 case SQLITE_ROW: {
1698 zErr = "another row available";
1699 break;
1701 case SQLITE_DONE: {
1702 zErr = "no more rows available";
1703 break;
1705 default: {
1706 rc &= 0xff;
1707 if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
1708 zErr = aMsg[rc];
1710 break;
1713 return zErr;
1717 ** This routine implements a busy callback that sleeps and tries
1718 ** again until a timeout value is reached. The timeout value is
1719 ** an integer number of milliseconds passed in as the first
1720 ** argument.
1722 ** Return non-zero to retry the lock. Return zero to stop trying
1723 ** and cause SQLite to return SQLITE_BUSY.
1725 static int sqliteDefaultBusyCallback(
1726 void *ptr, /* Database connection */
1727 int count /* Number of times table has been busy */
1729 #if SQLITE_OS_WIN || !defined(HAVE_NANOSLEEP) || HAVE_NANOSLEEP
1730 /* This case is for systems that have support for sleeping for fractions of
1731 ** a second. Examples: All windows systems, unix systems with nanosleep() */
1732 static const u8 delays[] =
1733 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
1734 static const u8 totals[] =
1735 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
1736 # define NDELAY ArraySize(delays)
1737 sqlite3 *db = (sqlite3 *)ptr;
1738 int tmout = db->busyTimeout;
1739 int delay, prior;
1741 assert( count>=0 );
1742 if( count < NDELAY ){
1743 delay = delays[count];
1744 prior = totals[count];
1745 }else{
1746 delay = delays[NDELAY-1];
1747 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
1749 if( prior + delay > tmout ){
1750 delay = tmout - prior;
1751 if( delay<=0 ) return 0;
1753 sqlite3OsSleep(db->pVfs, delay*1000);
1754 return 1;
1755 #else
1756 /* This case for unix systems that lack usleep() support. Sleeping
1757 ** must be done in increments of whole seconds */
1758 sqlite3 *db = (sqlite3 *)ptr;
1759 int tmout = ((sqlite3 *)ptr)->busyTimeout;
1760 if( (count+1)*1000 > tmout ){
1761 return 0;
1763 sqlite3OsSleep(db->pVfs, 1000000);
1764 return 1;
1765 #endif
1769 ** Invoke the given busy handler.
1771 ** This routine is called when an operation failed to acquire a
1772 ** lock on VFS file pFile.
1774 ** If this routine returns non-zero, the lock is retried. If it
1775 ** returns 0, the operation aborts with an SQLITE_BUSY error.
1777 int sqlite3InvokeBusyHandler(BusyHandler *p){
1778 int rc;
1779 if( p->xBusyHandler==0 || p->nBusy<0 ) return 0;
1780 rc = p->xBusyHandler(p->pBusyArg, p->nBusy);
1781 if( rc==0 ){
1782 p->nBusy = -1;
1783 }else{
1784 p->nBusy++;
1786 return rc;
1790 ** This routine sets the busy callback for an Sqlite database to the
1791 ** given callback function with the given argument.
1793 int sqlite3_busy_handler(
1794 sqlite3 *db,
1795 int (*xBusy)(void*,int),
1796 void *pArg
1798 #ifdef SQLITE_ENABLE_API_ARMOR
1799 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
1800 #endif
1801 sqlite3_mutex_enter(db->mutex);
1802 db->busyHandler.xBusyHandler = xBusy;
1803 db->busyHandler.pBusyArg = pArg;
1804 db->busyHandler.nBusy = 0;
1805 db->busyTimeout = 0;
1806 sqlite3_mutex_leave(db->mutex);
1807 return SQLITE_OK;
1810 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1812 ** This routine sets the progress callback for an Sqlite database to the
1813 ** given callback function with the given argument. The progress callback will
1814 ** be invoked every nOps opcodes.
1816 void sqlite3_progress_handler(
1817 sqlite3 *db,
1818 int nOps,
1819 int (*xProgress)(void*),
1820 void *pArg
1822 #ifdef SQLITE_ENABLE_API_ARMOR
1823 if( !sqlite3SafetyCheckOk(db) ){
1824 (void)SQLITE_MISUSE_BKPT;
1825 return;
1827 #endif
1828 sqlite3_mutex_enter(db->mutex);
1829 if( nOps>0 ){
1830 db->xProgress = xProgress;
1831 db->nProgressOps = (unsigned)nOps;
1832 db->pProgressArg = pArg;
1833 }else{
1834 db->xProgress = 0;
1835 db->nProgressOps = 0;
1836 db->pProgressArg = 0;
1838 sqlite3_mutex_leave(db->mutex);
1840 #endif
1844 ** This routine installs a default busy handler that waits for the
1845 ** specified number of milliseconds before returning 0.
1847 int sqlite3_busy_timeout(sqlite3 *db, int ms){
1848 #ifdef SQLITE_ENABLE_API_ARMOR
1849 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
1850 #endif
1851 if( ms>0 ){
1852 sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
1853 (void*)db);
1854 db->busyTimeout = ms;
1855 }else{
1856 sqlite3_busy_handler(db, 0, 0);
1858 return SQLITE_OK;
1862 ** Cause any pending operation to stop at its earliest opportunity.
1864 void sqlite3_interrupt(sqlite3 *db){
1865 #ifdef SQLITE_ENABLE_API_ARMOR
1866 if( !sqlite3SafetyCheckOk(db)
1867 && (db==0 || db->eOpenState!=SQLITE_STATE_ZOMBIE)
1869 (void)SQLITE_MISUSE_BKPT;
1870 return;
1872 #endif
1873 AtomicStore(&db->u1.isInterrupted, 1);
1877 ** Return true or false depending on whether or not an interrupt is
1878 ** pending on connection db.
1880 int sqlite3_is_interrupted(sqlite3 *db){
1881 #ifdef SQLITE_ENABLE_API_ARMOR
1882 if( !sqlite3SafetyCheckOk(db)
1883 && (db==0 || db->eOpenState!=SQLITE_STATE_ZOMBIE)
1885 (void)SQLITE_MISUSE_BKPT;
1886 return 0;
1888 #endif
1889 return AtomicLoad(&db->u1.isInterrupted)!=0;
1893 ** This function is exactly the same as sqlite3_create_function(), except
1894 ** that it is designed to be called by internal code. The difference is
1895 ** that if a malloc() fails in sqlite3_create_function(), an error code
1896 ** is returned and the mallocFailed flag cleared.
1898 int sqlite3CreateFunc(
1899 sqlite3 *db,
1900 const char *zFunctionName,
1901 int nArg,
1902 int enc,
1903 void *pUserData,
1904 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
1905 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
1906 void (*xFinal)(sqlite3_context*),
1907 void (*xValue)(sqlite3_context*),
1908 void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
1909 FuncDestructor *pDestructor
1911 FuncDef *p;
1912 int extraFlags;
1914 assert( sqlite3_mutex_held(db->mutex) );
1915 assert( xValue==0 || xSFunc==0 );
1916 if( zFunctionName==0 /* Must have a valid name */
1917 || (xSFunc!=0 && xFinal!=0) /* Not both xSFunc and xFinal */
1918 || ((xFinal==0)!=(xStep==0)) /* Both or neither of xFinal and xStep */
1919 || ((xValue==0)!=(xInverse==0)) /* Both or neither of xValue, xInverse */
1920 || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG)
1921 || (255<sqlite3Strlen30(zFunctionName))
1923 return SQLITE_MISUSE_BKPT;
1926 assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
1927 assert( SQLITE_FUNC_DIRECT==SQLITE_DIRECTONLY );
1928 extraFlags = enc & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY|
1929 SQLITE_SUBTYPE|SQLITE_INNOCUOUS|SQLITE_RESULT_SUBTYPE);
1930 enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
1932 /* The SQLITE_INNOCUOUS flag is the same bit as SQLITE_FUNC_UNSAFE. But
1933 ** the meaning is inverted. So flip the bit. */
1934 assert( SQLITE_FUNC_UNSAFE==SQLITE_INNOCUOUS );
1935 extraFlags ^= SQLITE_FUNC_UNSAFE; /* tag-20230109-1 */
1938 #ifndef SQLITE_OMIT_UTF16
1939 /* If SQLITE_UTF16 is specified as the encoding type, transform this
1940 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
1941 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
1943 ** If SQLITE_ANY is specified, add three versions of the function
1944 ** to the hash table.
1946 switch( enc ){
1947 case SQLITE_UTF16:
1948 enc = SQLITE_UTF16NATIVE;
1949 break;
1950 case SQLITE_ANY: {
1951 int rc;
1952 rc = sqlite3CreateFunc(db, zFunctionName, nArg,
1953 (SQLITE_UTF8|extraFlags)^SQLITE_FUNC_UNSAFE, /* tag-20230109-1 */
1954 pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
1955 if( rc==SQLITE_OK ){
1956 rc = sqlite3CreateFunc(db, zFunctionName, nArg,
1957 (SQLITE_UTF16LE|extraFlags)^SQLITE_FUNC_UNSAFE, /* tag-20230109-1*/
1958 pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
1960 if( rc!=SQLITE_OK ){
1961 return rc;
1963 enc = SQLITE_UTF16BE;
1964 break;
1966 case SQLITE_UTF8:
1967 case SQLITE_UTF16LE:
1968 case SQLITE_UTF16BE:
1969 break;
1970 default:
1971 enc = SQLITE_UTF8;
1972 break;
1974 #else
1975 enc = SQLITE_UTF8;
1976 #endif
1978 /* Check if an existing function is being overridden or deleted. If so,
1979 ** and there are active VMs, then return SQLITE_BUSY. If a function
1980 ** is being overridden/deleted but there are no active VMs, allow the
1981 ** operation to continue but invalidate all precompiled statements.
1983 p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
1984 if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){
1985 if( db->nVdbeActive ){
1986 sqlite3ErrorWithMsg(db, SQLITE_BUSY,
1987 "unable to delete/modify user-function due to active statements");
1988 assert( !db->mallocFailed );
1989 return SQLITE_BUSY;
1990 }else{
1991 sqlite3ExpirePreparedStatements(db, 0);
1993 }else if( xSFunc==0 && xFinal==0 ){
1994 /* Trying to delete a function that does not exist. This is a no-op.
1995 ** https://sqlite.org/forum/forumpost/726219164b */
1996 return SQLITE_OK;
1999 p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
2000 assert(p || db->mallocFailed);
2001 if( !p ){
2002 return SQLITE_NOMEM_BKPT;
2005 /* If an older version of the function with a configured destructor is
2006 ** being replaced invoke the destructor function here. */
2007 functionDestroy(db, p);
2009 if( pDestructor ){
2010 pDestructor->nRef++;
2012 p->u.pDestructor = pDestructor;
2013 p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
2014 testcase( p->funcFlags & SQLITE_DETERMINISTIC );
2015 testcase( p->funcFlags & SQLITE_DIRECTONLY );
2016 p->xSFunc = xSFunc ? xSFunc : xStep;
2017 p->xFinalize = xFinal;
2018 p->xValue = xValue;
2019 p->xInverse = xInverse;
2020 p->pUserData = pUserData;
2021 p->nArg = (u16)nArg;
2022 return SQLITE_OK;
2026 ** Worker function used by utf-8 APIs that create new functions:
2028 ** sqlite3_create_function()
2029 ** sqlite3_create_function_v2()
2030 ** sqlite3_create_window_function()
2032 static int createFunctionApi(
2033 sqlite3 *db,
2034 const char *zFunc,
2035 int nArg,
2036 int enc,
2037 void *p,
2038 void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
2039 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
2040 void (*xFinal)(sqlite3_context*),
2041 void (*xValue)(sqlite3_context*),
2042 void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
2043 void(*xDestroy)(void*)
2045 int rc = SQLITE_ERROR;
2046 FuncDestructor *pArg = 0;
2048 #ifdef SQLITE_ENABLE_API_ARMOR
2049 if( !sqlite3SafetyCheckOk(db) ){
2050 return SQLITE_MISUSE_BKPT;
2052 #endif
2053 sqlite3_mutex_enter(db->mutex);
2054 if( xDestroy ){
2055 pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor));
2056 if( !pArg ){
2057 sqlite3OomFault(db);
2058 xDestroy(p);
2059 goto out;
2061 pArg->nRef = 0;
2062 pArg->xDestroy = xDestroy;
2063 pArg->pUserData = p;
2065 rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p,
2066 xSFunc, xStep, xFinal, xValue, xInverse, pArg
2068 if( pArg && pArg->nRef==0 ){
2069 assert( rc!=SQLITE_OK || (xStep==0 && xFinal==0) );
2070 xDestroy(p);
2071 sqlite3_free(pArg);
2074 out:
2075 rc = sqlite3ApiExit(db, rc);
2076 sqlite3_mutex_leave(db->mutex);
2077 return rc;
2081 ** Create new user functions.
2083 int sqlite3_create_function(
2084 sqlite3 *db,
2085 const char *zFunc,
2086 int nArg,
2087 int enc,
2088 void *p,
2089 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
2090 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
2091 void (*xFinal)(sqlite3_context*)
2093 return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
2094 xFinal, 0, 0, 0);
2096 int sqlite3_create_function_v2(
2097 sqlite3 *db,
2098 const char *zFunc,
2099 int nArg,
2100 int enc,
2101 void *p,
2102 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
2103 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
2104 void (*xFinal)(sqlite3_context*),
2105 void (*xDestroy)(void *)
2107 return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
2108 xFinal, 0, 0, xDestroy);
2110 int sqlite3_create_window_function(
2111 sqlite3 *db,
2112 const char *zFunc,
2113 int nArg,
2114 int enc,
2115 void *p,
2116 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
2117 void (*xFinal)(sqlite3_context*),
2118 void (*xValue)(sqlite3_context*),
2119 void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
2120 void (*xDestroy)(void *)
2122 return createFunctionApi(db, zFunc, nArg, enc, p, 0, xStep,
2123 xFinal, xValue, xInverse, xDestroy);
2126 #ifndef SQLITE_OMIT_UTF16
2127 int sqlite3_create_function16(
2128 sqlite3 *db,
2129 const void *zFunctionName,
2130 int nArg,
2131 int eTextRep,
2132 void *p,
2133 void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
2134 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
2135 void (*xFinal)(sqlite3_context*)
2137 int rc;
2138 char *zFunc8;
2140 #ifdef SQLITE_ENABLE_API_ARMOR
2141 if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
2142 #endif
2143 sqlite3_mutex_enter(db->mutex);
2144 assert( !db->mallocFailed );
2145 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
2146 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0,0,0);
2147 sqlite3DbFree(db, zFunc8);
2148 rc = sqlite3ApiExit(db, rc);
2149 sqlite3_mutex_leave(db->mutex);
2150 return rc;
2152 #endif
2156 ** The following is the implementation of an SQL function that always
2157 ** fails with an error message stating that the function is used in the
2158 ** wrong context. The sqlite3_overload_function() API might construct
2159 ** SQL function that use this routine so that the functions will exist
2160 ** for name resolution but are actually overloaded by the xFindFunction
2161 ** method of virtual tables.
2163 static void sqlite3InvalidFunction(
2164 sqlite3_context *context, /* The function calling context */
2165 int NotUsed, /* Number of arguments to the function */
2166 sqlite3_value **NotUsed2 /* Value of each argument */
2168 const char *zName = (const char*)sqlite3_user_data(context);
2169 char *zErr;
2170 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2171 zErr = sqlite3_mprintf(
2172 "unable to use function %s in the requested context", zName);
2173 sqlite3_result_error(context, zErr, -1);
2174 sqlite3_free(zErr);
2178 ** Declare that a function has been overloaded by a virtual table.
2180 ** If the function already exists as a regular global function, then
2181 ** this routine is a no-op. If the function does not exist, then create
2182 ** a new one that always throws a run-time error.
2184 ** When virtual tables intend to provide an overloaded function, they
2185 ** should call this routine to make sure the global function exists.
2186 ** A global function must exist in order for name resolution to work
2187 ** properly.
2189 int sqlite3_overload_function(
2190 sqlite3 *db,
2191 const char *zName,
2192 int nArg
2194 int rc;
2195 char *zCopy;
2197 #ifdef SQLITE_ENABLE_API_ARMOR
2198 if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
2199 return SQLITE_MISUSE_BKPT;
2201 #endif
2202 sqlite3_mutex_enter(db->mutex);
2203 rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0;
2204 sqlite3_mutex_leave(db->mutex);
2205 if( rc ) return SQLITE_OK;
2206 zCopy = sqlite3_mprintf("%s", zName);
2207 if( zCopy==0 ) return SQLITE_NOMEM;
2208 return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8,
2209 zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free);
2212 #ifndef SQLITE_OMIT_TRACE
2214 ** Register a trace function. The pArg from the previously registered trace
2215 ** is returned.
2217 ** A NULL trace function means that no tracing is executes. A non-NULL
2218 ** trace is a pointer to a function that is invoked at the start of each
2219 ** SQL statement.
2221 #ifndef SQLITE_OMIT_DEPRECATED
2222 void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
2223 void *pOld;
2225 #ifdef SQLITE_ENABLE_API_ARMOR
2226 if( !sqlite3SafetyCheckOk(db) ){
2227 (void)SQLITE_MISUSE_BKPT;
2228 return 0;
2230 #endif
2231 sqlite3_mutex_enter(db->mutex);
2232 pOld = db->pTraceArg;
2233 db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
2234 db->trace.xLegacy = xTrace;
2235 db->pTraceArg = pArg;
2236 sqlite3_mutex_leave(db->mutex);
2237 return pOld;
2239 #endif /* SQLITE_OMIT_DEPRECATED */
2241 /* Register a trace callback using the version-2 interface.
2243 int sqlite3_trace_v2(
2244 sqlite3 *db, /* Trace this connection */
2245 unsigned mTrace, /* Mask of events to be traced */
2246 int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */
2247 void *pArg /* Context */
2249 #ifdef SQLITE_ENABLE_API_ARMOR
2250 if( !sqlite3SafetyCheckOk(db) ){
2251 return SQLITE_MISUSE_BKPT;
2253 #endif
2254 sqlite3_mutex_enter(db->mutex);
2255 if( mTrace==0 ) xTrace = 0;
2256 if( xTrace==0 ) mTrace = 0;
2257 db->mTrace = mTrace;
2258 db->trace.xV2 = xTrace;
2259 db->pTraceArg = pArg;
2260 sqlite3_mutex_leave(db->mutex);
2261 return SQLITE_OK;
2264 #ifndef SQLITE_OMIT_DEPRECATED
2266 ** Register a profile function. The pArg from the previously registered
2267 ** profile function is returned.
2269 ** A NULL profile function means that no profiling is executes. A non-NULL
2270 ** profile is a pointer to a function that is invoked at the conclusion of
2271 ** each SQL statement that is run.
2273 void *sqlite3_profile(
2274 sqlite3 *db,
2275 void (*xProfile)(void*,const char*,sqlite_uint64),
2276 void *pArg
2278 void *pOld;
2280 #ifdef SQLITE_ENABLE_API_ARMOR
2281 if( !sqlite3SafetyCheckOk(db) ){
2282 (void)SQLITE_MISUSE_BKPT;
2283 return 0;
2285 #endif
2286 sqlite3_mutex_enter(db->mutex);
2287 pOld = db->pProfileArg;
2288 db->xProfile = xProfile;
2289 db->pProfileArg = pArg;
2290 db->mTrace &= SQLITE_TRACE_NONLEGACY_MASK;
2291 if( db->xProfile ) db->mTrace |= SQLITE_TRACE_XPROFILE;
2292 sqlite3_mutex_leave(db->mutex);
2293 return pOld;
2295 #endif /* SQLITE_OMIT_DEPRECATED */
2296 #endif /* SQLITE_OMIT_TRACE */
2299 ** Register a function to be invoked when a transaction commits.
2300 ** If the invoked function returns non-zero, then the commit becomes a
2301 ** rollback.
2303 void *sqlite3_commit_hook(
2304 sqlite3 *db, /* Attach the hook to this database */
2305 int (*xCallback)(void*), /* Function to invoke on each commit */
2306 void *pArg /* Argument to the function */
2308 void *pOld;
2310 #ifdef SQLITE_ENABLE_API_ARMOR
2311 if( !sqlite3SafetyCheckOk(db) ){
2312 (void)SQLITE_MISUSE_BKPT;
2313 return 0;
2315 #endif
2316 sqlite3_mutex_enter(db->mutex);
2317 pOld = db->pCommitArg;
2318 db->xCommitCallback = xCallback;
2319 db->pCommitArg = pArg;
2320 sqlite3_mutex_leave(db->mutex);
2321 return pOld;
2325 ** Register a callback to be invoked each time a row is updated,
2326 ** inserted or deleted using this database connection.
2328 void *sqlite3_update_hook(
2329 sqlite3 *db, /* Attach the hook to this database */
2330 void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
2331 void *pArg /* Argument to the function */
2333 void *pRet;
2335 #ifdef SQLITE_ENABLE_API_ARMOR
2336 if( !sqlite3SafetyCheckOk(db) ){
2337 (void)SQLITE_MISUSE_BKPT;
2338 return 0;
2340 #endif
2341 sqlite3_mutex_enter(db->mutex);
2342 pRet = db->pUpdateArg;
2343 db->xUpdateCallback = xCallback;
2344 db->pUpdateArg = pArg;
2345 sqlite3_mutex_leave(db->mutex);
2346 return pRet;
2350 ** Register a callback to be invoked each time a transaction is rolled
2351 ** back by this database connection.
2353 void *sqlite3_rollback_hook(
2354 sqlite3 *db, /* Attach the hook to this database */
2355 void (*xCallback)(void*), /* Callback function */
2356 void *pArg /* Argument to the function */
2358 void *pRet;
2360 #ifdef SQLITE_ENABLE_API_ARMOR
2361 if( !sqlite3SafetyCheckOk(db) ){
2362 (void)SQLITE_MISUSE_BKPT;
2363 return 0;
2365 #endif
2366 sqlite3_mutex_enter(db->mutex);
2367 pRet = db->pRollbackArg;
2368 db->xRollbackCallback = xCallback;
2369 db->pRollbackArg = pArg;
2370 sqlite3_mutex_leave(db->mutex);
2371 return pRet;
2374 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2376 ** Register a callback to be invoked each time a row is updated,
2377 ** inserted or deleted using this database connection.
2379 void *sqlite3_preupdate_hook(
2380 sqlite3 *db, /* Attach the hook to this database */
2381 void(*xCallback)( /* Callback function */
2382 void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
2383 void *pArg /* First callback argument */
2385 void *pRet;
2387 #ifdef SQLITE_ENABLE_API_ARMOR
2388 if( db==0 ){
2389 return 0;
2391 #endif
2392 sqlite3_mutex_enter(db->mutex);
2393 pRet = db->pPreUpdateArg;
2394 db->xPreUpdateCallback = xCallback;
2395 db->pPreUpdateArg = pArg;
2396 sqlite3_mutex_leave(db->mutex);
2397 return pRet;
2399 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2402 ** Register a function to be invoked prior to each autovacuum that
2403 ** determines the number of pages to vacuum.
2405 int sqlite3_autovacuum_pages(
2406 sqlite3 *db, /* Attach the hook to this database */
2407 unsigned int (*xCallback)(void*,const char*,u32,u32,u32),
2408 void *pArg, /* Argument to the function */
2409 void (*xDestructor)(void*) /* Destructor for pArg */
2411 #ifdef SQLITE_ENABLE_API_ARMOR
2412 if( !sqlite3SafetyCheckOk(db) ){
2413 if( xDestructor ) xDestructor(pArg);
2414 return SQLITE_MISUSE_BKPT;
2416 #endif
2417 sqlite3_mutex_enter(db->mutex);
2418 if( db->xAutovacDestr ){
2419 db->xAutovacDestr(db->pAutovacPagesArg);
2421 db->xAutovacPages = xCallback;
2422 db->pAutovacPagesArg = pArg;
2423 db->xAutovacDestr = xDestructor;
2424 sqlite3_mutex_leave(db->mutex);
2425 return SQLITE_OK;
2429 #ifndef SQLITE_OMIT_WAL
2431 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
2432 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
2433 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
2434 ** wal_autocheckpoint()).
2436 int sqlite3WalDefaultHook(
2437 void *pClientData, /* Argument */
2438 sqlite3 *db, /* Connection */
2439 const char *zDb, /* Database */
2440 int nFrame /* Size of WAL */
2442 if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
2443 sqlite3BeginBenignMalloc();
2444 sqlite3_wal_checkpoint(db, zDb);
2445 sqlite3EndBenignMalloc();
2447 return SQLITE_OK;
2449 #endif /* SQLITE_OMIT_WAL */
2452 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
2453 ** a database after committing a transaction if there are nFrame or
2454 ** more frames in the log file. Passing zero or a negative value as the
2455 ** nFrame parameter disables automatic checkpoints entirely.
2457 ** The callback registered by this function replaces any existing callback
2458 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
2459 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
2460 ** configured by this function.
2462 int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
2463 #ifdef SQLITE_OMIT_WAL
2464 UNUSED_PARAMETER(db);
2465 UNUSED_PARAMETER(nFrame);
2466 #else
2467 #ifdef SQLITE_ENABLE_API_ARMOR
2468 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
2469 #endif
2470 if( nFrame>0 ){
2471 sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
2472 }else{
2473 sqlite3_wal_hook(db, 0, 0);
2475 #endif
2476 return SQLITE_OK;
2480 ** Register a callback to be invoked each time a transaction is written
2481 ** into the write-ahead-log by this database connection.
2483 void *sqlite3_wal_hook(
2484 sqlite3 *db, /* Attach the hook to this db handle */
2485 int(*xCallback)(void *, sqlite3*, const char*, int),
2486 void *pArg /* First argument passed to xCallback() */
2488 #ifndef SQLITE_OMIT_WAL
2489 void *pRet;
2490 #ifdef SQLITE_ENABLE_API_ARMOR
2491 if( !sqlite3SafetyCheckOk(db) ){
2492 (void)SQLITE_MISUSE_BKPT;
2493 return 0;
2495 #endif
2496 sqlite3_mutex_enter(db->mutex);
2497 pRet = db->pWalArg;
2498 db->xWalCallback = xCallback;
2499 db->pWalArg = pArg;
2500 sqlite3_mutex_leave(db->mutex);
2501 return pRet;
2502 #else
2503 return 0;
2504 #endif
2508 ** Checkpoint database zDb.
2510 int sqlite3_wal_checkpoint_v2(
2511 sqlite3 *db, /* Database handle */
2512 const char *zDb, /* Name of attached database (or NULL) */
2513 int eMode, /* SQLITE_CHECKPOINT_* value */
2514 int *pnLog, /* OUT: Size of WAL log in frames */
2515 int *pnCkpt /* OUT: Total number of frames checkpointed */
2517 #ifdef SQLITE_OMIT_WAL
2518 return SQLITE_OK;
2519 #else
2520 int rc; /* Return code */
2521 int iDb; /* Schema to checkpoint */
2523 #ifdef SQLITE_ENABLE_API_ARMOR
2524 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
2525 #endif
2527 /* Initialize the output variables to -1 in case an error occurs. */
2528 if( pnLog ) *pnLog = -1;
2529 if( pnCkpt ) *pnCkpt = -1;
2531 assert( SQLITE_CHECKPOINT_PASSIVE==0 );
2532 assert( SQLITE_CHECKPOINT_FULL==1 );
2533 assert( SQLITE_CHECKPOINT_RESTART==2 );
2534 assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
2535 if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
2536 /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
2537 ** mode: */
2538 return SQLITE_MISUSE_BKPT;
2541 sqlite3_mutex_enter(db->mutex);
2542 if( zDb && zDb[0] ){
2543 iDb = sqlite3FindDbName(db, zDb);
2544 }else{
2545 iDb = SQLITE_MAX_DB; /* This means process all schemas */
2547 if( iDb<0 ){
2548 rc = SQLITE_ERROR;
2549 sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
2550 }else{
2551 db->busyHandler.nBusy = 0;
2552 rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
2553 sqlite3Error(db, rc);
2555 rc = sqlite3ApiExit(db, rc);
2557 /* If there are no active statements, clear the interrupt flag at this
2558 ** point. */
2559 if( db->nVdbeActive==0 ){
2560 AtomicStore(&db->u1.isInterrupted, 0);
2563 sqlite3_mutex_leave(db->mutex);
2564 return rc;
2565 #endif
2570 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
2571 ** to contains a zero-length string, all attached databases are
2572 ** checkpointed.
2574 int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
2575 /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
2576 ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
2577 return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
2580 #ifndef SQLITE_OMIT_WAL
2582 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
2583 ** not currently open in WAL mode.
2585 ** If a transaction is open on the database being checkpointed, this
2586 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
2587 ** an error occurs while running the checkpoint, an SQLite error code is
2588 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
2590 ** The mutex on database handle db should be held by the caller. The mutex
2591 ** associated with the specific b-tree being checkpointed is taken by
2592 ** this function while the checkpoint is running.
2594 ** If iDb is passed SQLITE_MAX_DB then all attached databases are
2595 ** checkpointed. If an error is encountered it is returned immediately -
2596 ** no attempt is made to checkpoint any remaining databases.
2598 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
2599 ** or TRUNCATE.
2601 int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
2602 int rc = SQLITE_OK; /* Return code */
2603 int i; /* Used to iterate through attached dbs */
2604 int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
2606 assert( sqlite3_mutex_held(db->mutex) );
2607 assert( !pnLog || *pnLog==-1 );
2608 assert( !pnCkpt || *pnCkpt==-1 );
2609 testcase( iDb==SQLITE_MAX_ATTACHED ); /* See forum post a006d86f72 */
2610 testcase( iDb==SQLITE_MAX_DB );
2612 for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
2613 if( i==iDb || iDb==SQLITE_MAX_DB ){
2614 rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
2615 pnLog = 0;
2616 pnCkpt = 0;
2617 if( rc==SQLITE_BUSY ){
2618 bBusy = 1;
2619 rc = SQLITE_OK;
2624 return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
2626 #endif /* SQLITE_OMIT_WAL */
2629 ** This function returns true if main-memory should be used instead of
2630 ** a temporary file for transient pager files and statement journals.
2631 ** The value returned depends on the value of db->temp_store (runtime
2632 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
2633 ** following table describes the relationship between these two values
2634 ** and this functions return value.
2636 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
2637 ** ----------------- -------------- ------------------------------
2638 ** 0 any file (return 0)
2639 ** 1 1 file (return 0)
2640 ** 1 2 memory (return 1)
2641 ** 1 0 file (return 0)
2642 ** 2 1 file (return 0)
2643 ** 2 2 memory (return 1)
2644 ** 2 0 memory (return 1)
2645 ** 3 any memory (return 1)
2647 int sqlite3TempInMemory(const sqlite3 *db){
2648 #if SQLITE_TEMP_STORE==1
2649 return ( db->temp_store==2 );
2650 #endif
2651 #if SQLITE_TEMP_STORE==2
2652 return ( db->temp_store!=1 );
2653 #endif
2654 #if SQLITE_TEMP_STORE==3
2655 UNUSED_PARAMETER(db);
2656 return 1;
2657 #endif
2658 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
2659 UNUSED_PARAMETER(db);
2660 return 0;
2661 #endif
2665 ** Return UTF-8 encoded English language explanation of the most recent
2666 ** error.
2668 const char *sqlite3_errmsg(sqlite3 *db){
2669 const char *z;
2670 if( !db ){
2671 return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
2673 if( !sqlite3SafetyCheckSickOrOk(db) ){
2674 return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
2676 sqlite3_mutex_enter(db->mutex);
2677 if( db->mallocFailed ){
2678 z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
2679 }else{
2680 testcase( db->pErr==0 );
2681 z = db->errCode ? (char*)sqlite3_value_text(db->pErr) : 0;
2682 assert( !db->mallocFailed );
2683 if( z==0 ){
2684 z = sqlite3ErrStr(db->errCode);
2687 sqlite3_mutex_leave(db->mutex);
2688 return z;
2692 ** Return the byte offset of the most recent error
2694 int sqlite3_error_offset(sqlite3 *db){
2695 int iOffset = -1;
2696 if( db && sqlite3SafetyCheckSickOrOk(db) && db->errCode ){
2697 sqlite3_mutex_enter(db->mutex);
2698 iOffset = db->errByteOffset;
2699 sqlite3_mutex_leave(db->mutex);
2701 return iOffset;
2704 #ifndef SQLITE_OMIT_UTF16
2706 ** Return UTF-16 encoded English language explanation of the most recent
2707 ** error.
2709 const void *sqlite3_errmsg16(sqlite3 *db){
2710 static const u16 outOfMem[] = {
2711 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
2713 static const u16 misuse[] = {
2714 'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
2715 'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
2716 'm', 'i', 's', 'u', 's', 'e', 0
2719 const void *z;
2720 if( !db ){
2721 return (void *)outOfMem;
2723 if( !sqlite3SafetyCheckSickOrOk(db) ){
2724 return (void *)misuse;
2726 sqlite3_mutex_enter(db->mutex);
2727 if( db->mallocFailed ){
2728 z = (void *)outOfMem;
2729 }else{
2730 z = sqlite3_value_text16(db->pErr);
2731 if( z==0 ){
2732 sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
2733 z = sqlite3_value_text16(db->pErr);
2735 /* A malloc() may have failed within the call to sqlite3_value_text16()
2736 ** above. If this is the case, then the db->mallocFailed flag needs to
2737 ** be cleared before returning. Do this directly, instead of via
2738 ** sqlite3ApiExit(), to avoid setting the database handle error message.
2740 sqlite3OomClear(db);
2742 sqlite3_mutex_leave(db->mutex);
2743 return z;
2745 #endif /* SQLITE_OMIT_UTF16 */
2748 ** Return the most recent error code generated by an SQLite routine. If NULL is
2749 ** passed to this function, we assume a malloc() failed during sqlite3_open().
2751 int sqlite3_errcode(sqlite3 *db){
2752 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
2753 return SQLITE_MISUSE_BKPT;
2755 if( !db || db->mallocFailed ){
2756 return SQLITE_NOMEM_BKPT;
2758 return db->errCode & db->errMask;
2760 int sqlite3_extended_errcode(sqlite3 *db){
2761 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
2762 return SQLITE_MISUSE_BKPT;
2764 if( !db || db->mallocFailed ){
2765 return SQLITE_NOMEM_BKPT;
2767 return db->errCode;
2769 int sqlite3_system_errno(sqlite3 *db){
2770 return db ? db->iSysErrno : 0;
2774 ** Return a string that describes the kind of error specified in the
2775 ** argument. For now, this simply calls the internal sqlite3ErrStr()
2776 ** function.
2778 const char *sqlite3_errstr(int rc){
2779 return sqlite3ErrStr(rc);
2783 ** Create a new collating function for database "db". The name is zName
2784 ** and the encoding is enc.
2786 static int createCollation(
2787 sqlite3* db,
2788 const char *zName,
2789 u8 enc,
2790 void* pCtx,
2791 int(*xCompare)(void*,int,const void*,int,const void*),
2792 void(*xDel)(void*)
2794 CollSeq *pColl;
2795 int enc2;
2797 assert( sqlite3_mutex_held(db->mutex) );
2799 /* If SQLITE_UTF16 is specified as the encoding type, transform this
2800 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
2801 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
2803 enc2 = enc;
2804 testcase( enc2==SQLITE_UTF16 );
2805 testcase( enc2==SQLITE_UTF16_ALIGNED );
2806 if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
2807 enc2 = SQLITE_UTF16NATIVE;
2809 if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
2810 return SQLITE_MISUSE_BKPT;
2813 /* Check if this call is removing or replacing an existing collation
2814 ** sequence. If so, and there are active VMs, return busy. If there
2815 ** are no active VMs, invalidate any pre-compiled statements.
2817 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
2818 if( pColl && pColl->xCmp ){
2819 if( db->nVdbeActive ){
2820 sqlite3ErrorWithMsg(db, SQLITE_BUSY,
2821 "unable to delete/modify collation sequence due to active statements");
2822 return SQLITE_BUSY;
2824 sqlite3ExpirePreparedStatements(db, 0);
2826 /* If collation sequence pColl was created directly by a call to
2827 ** sqlite3_create_collation, and not generated by synthCollSeq(),
2828 ** then any copies made by synthCollSeq() need to be invalidated.
2829 ** Also, collation destructor - CollSeq.xDel() - function may need
2830 ** to be called.
2832 if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
2833 CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
2834 int j;
2835 for(j=0; j<3; j++){
2836 CollSeq *p = &aColl[j];
2837 if( p->enc==pColl->enc ){
2838 if( p->xDel ){
2839 p->xDel(p->pUser);
2841 p->xCmp = 0;
2847 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
2848 if( pColl==0 ) return SQLITE_NOMEM_BKPT;
2849 pColl->xCmp = xCompare;
2850 pColl->pUser = pCtx;
2851 pColl->xDel = xDel;
2852 pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
2853 sqlite3Error(db, SQLITE_OK);
2854 return SQLITE_OK;
2859 ** This array defines hard upper bounds on limit values. The
2860 ** initializer must be kept in sync with the SQLITE_LIMIT_*
2861 ** #defines in sqlite3.h.
2863 static const int aHardLimit[] = {
2864 SQLITE_MAX_LENGTH,
2865 SQLITE_MAX_SQL_LENGTH,
2866 SQLITE_MAX_COLUMN,
2867 SQLITE_MAX_EXPR_DEPTH,
2868 SQLITE_MAX_COMPOUND_SELECT,
2869 SQLITE_MAX_VDBE_OP,
2870 SQLITE_MAX_FUNCTION_ARG,
2871 SQLITE_MAX_ATTACHED,
2872 SQLITE_MAX_LIKE_PATTERN_LENGTH,
2873 SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
2874 SQLITE_MAX_TRIGGER_DEPTH,
2875 SQLITE_MAX_WORKER_THREADS,
2879 ** Make sure the hard limits are set to reasonable values
2881 #if SQLITE_MAX_LENGTH<100
2882 # error SQLITE_MAX_LENGTH must be at least 100
2883 #endif
2884 #if SQLITE_MAX_SQL_LENGTH<100
2885 # error SQLITE_MAX_SQL_LENGTH must be at least 100
2886 #endif
2887 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
2888 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
2889 #endif
2890 #if SQLITE_MAX_COMPOUND_SELECT<2
2891 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
2892 #endif
2893 #if SQLITE_MAX_VDBE_OP<40
2894 # error SQLITE_MAX_VDBE_OP must be at least 40
2895 #endif
2896 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
2897 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
2898 #endif
2899 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
2900 # error SQLITE_MAX_ATTACHED must be between 0 and 125
2901 #endif
2902 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
2903 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
2904 #endif
2905 #if SQLITE_MAX_COLUMN>32767
2906 # error SQLITE_MAX_COLUMN must not exceed 32767
2907 #endif
2908 #if SQLITE_MAX_TRIGGER_DEPTH<1
2909 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
2910 #endif
2911 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
2912 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
2913 #endif
2917 ** Change the value of a limit. Report the old value.
2918 ** If an invalid limit index is supplied, report -1.
2919 ** Make no changes but still report the old value if the
2920 ** new limit is negative.
2922 ** A new lower limit does not shrink existing constructs.
2923 ** It merely prevents new constructs that exceed the limit
2924 ** from forming.
2926 int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
2927 int oldLimit;
2929 #ifdef SQLITE_ENABLE_API_ARMOR
2930 if( !sqlite3SafetyCheckOk(db) ){
2931 (void)SQLITE_MISUSE_BKPT;
2932 return -1;
2934 #endif
2936 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
2937 ** there is a hard upper bound set at compile-time by a C preprocessor
2938 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
2939 ** "_MAX_".)
2941 assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
2942 assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
2943 assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
2944 assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
2945 assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
2946 assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
2947 assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
2948 assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
2949 assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
2950 SQLITE_MAX_LIKE_PATTERN_LENGTH );
2951 assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
2952 assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
2953 assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
2954 assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
2957 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
2958 return -1;
2960 oldLimit = db->aLimit[limitId];
2961 if( newLimit>=0 ){ /* IMP: R-52476-28732 */
2962 if( newLimit>aHardLimit[limitId] ){
2963 newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
2964 }else if( newLimit<1 && limitId==SQLITE_LIMIT_LENGTH ){
2965 newLimit = 1;
2967 db->aLimit[limitId] = newLimit;
2969 return oldLimit; /* IMP: R-53341-35419 */
2973 ** This function is used to parse both URIs and non-URI filenames passed by the
2974 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
2975 ** URIs specified as part of ATTACH statements.
2977 ** The first argument to this function is the name of the VFS to use (or
2978 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
2979 ** query parameter. The second argument contains the URI (or non-URI filename)
2980 ** itself. When this function is called the *pFlags variable should contain
2981 ** the default flags to open the database handle with. The value stored in
2982 ** *pFlags may be updated before returning if the URI filename contains
2983 ** "cache=xxx" or "mode=xxx" query parameters.
2985 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
2986 ** the VFS that should be used to open the database file. *pzFile is set to
2987 ** point to a buffer containing the name of the file to open. The value
2988 ** stored in *pzFile is a database name acceptable to sqlite3_uri_parameter()
2989 ** and is in the same format as names created using sqlite3_create_filename().
2990 ** The caller must invoke sqlite3_free_filename() (not sqlite3_free()!) on
2991 ** the value returned in *pzFile to avoid a memory leak.
2993 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
2994 ** may be set to point to a buffer containing an English language error
2995 ** message. It is the responsibility of the caller to eventually release
2996 ** this buffer by calling sqlite3_free().
2998 int sqlite3ParseUri(
2999 const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
3000 const char *zUri, /* Nul-terminated URI to parse */
3001 unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
3002 sqlite3_vfs **ppVfs, /* OUT: VFS to use */
3003 char **pzFile, /* OUT: Filename component of URI */
3004 char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
3006 int rc = SQLITE_OK;
3007 unsigned int flags = *pFlags;
3008 const char *zVfs = zDefaultVfs;
3009 char *zFile;
3010 char c;
3011 int nUri = sqlite3Strlen30(zUri);
3013 assert( *pzErrMsg==0 );
3015 if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
3016 || AtomicLoad(&sqlite3GlobalConfig.bOpenUri)) /* IMP: R-51689-46548 */
3017 && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
3019 char *zOpt;
3020 int eState; /* Parser state when parsing URI */
3021 int iIn; /* Input character index */
3022 int iOut = 0; /* Output character index */
3023 u64 nByte = nUri+8; /* Bytes of space to allocate */
3025 /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
3026 ** method that there may be extra parameters following the file-name. */
3027 flags |= SQLITE_OPEN_URI;
3029 for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
3030 zFile = sqlite3_malloc64(nByte);
3031 if( !zFile ) return SQLITE_NOMEM_BKPT;
3033 memset(zFile, 0, 4); /* 4-byte of 0x00 is the start of DB name marker */
3034 zFile += 4;
3036 iIn = 5;
3037 #ifdef SQLITE_ALLOW_URI_AUTHORITY
3038 if( strncmp(zUri+5, "///", 3)==0 ){
3039 iIn = 7;
3040 /* The following condition causes URIs with five leading / characters
3041 ** like file://///host/path to be converted into UNCs like //host/path.
3042 ** The correct URI for that UNC has only two or four leading / characters
3043 ** file://host/path or file:////host/path. But 5 leading slashes is a
3044 ** common error, we are told, so we handle it as a special case. */
3045 if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
3046 }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
3047 iIn = 16;
3049 #else
3050 /* Discard the scheme and authority segments of the URI. */
3051 if( zUri[5]=='/' && zUri[6]=='/' ){
3052 iIn = 7;
3053 while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
3054 if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
3055 *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
3056 iIn-7, &zUri[7]);
3057 rc = SQLITE_ERROR;
3058 goto parse_uri_out;
3061 #endif
3063 /* Copy the filename and any query parameters into the zFile buffer.
3064 ** Decode %HH escape codes along the way.
3066 ** Within this loop, variable eState may be set to 0, 1 or 2, depending
3067 ** on the parsing context. As follows:
3069 ** 0: Parsing file-name.
3070 ** 1: Parsing name section of a name=value query parameter.
3071 ** 2: Parsing value section of a name=value query parameter.
3073 eState = 0;
3074 while( (c = zUri[iIn])!=0 && c!='#' ){
3075 iIn++;
3076 if( c=='%'
3077 && sqlite3Isxdigit(zUri[iIn])
3078 && sqlite3Isxdigit(zUri[iIn+1])
3080 int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
3081 octet += sqlite3HexToInt(zUri[iIn++]);
3083 assert( octet>=0 && octet<256 );
3084 if( octet==0 ){
3085 #ifndef SQLITE_ENABLE_URI_00_ERROR
3086 /* This branch is taken when "%00" appears within the URI. In this
3087 ** case we ignore all text in the remainder of the path, name or
3088 ** value currently being parsed. So ignore the current character
3089 ** and skip to the next "?", "=" or "&", as appropriate. */
3090 while( (c = zUri[iIn])!=0 && c!='#'
3091 && (eState!=0 || c!='?')
3092 && (eState!=1 || (c!='=' && c!='&'))
3093 && (eState!=2 || c!='&')
3095 iIn++;
3097 continue;
3098 #else
3099 /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
3100 *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
3101 rc = SQLITE_ERROR;
3102 goto parse_uri_out;
3103 #endif
3105 c = octet;
3106 }else if( eState==1 && (c=='&' || c=='=') ){
3107 if( zFile[iOut-1]==0 ){
3108 /* An empty option name. Ignore this option altogether. */
3109 while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
3110 continue;
3112 if( c=='&' ){
3113 zFile[iOut++] = '\0';
3114 }else{
3115 eState = 2;
3117 c = 0;
3118 }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
3119 c = 0;
3120 eState = 1;
3122 zFile[iOut++] = c;
3124 if( eState==1 ) zFile[iOut++] = '\0';
3125 memset(zFile+iOut, 0, 4); /* end-of-options + empty journal filenames */
3127 /* Check if there were any options specified that should be interpreted
3128 ** here. Options that are interpreted here include "vfs" and those that
3129 ** correspond to flags that may be passed to the sqlite3_open_v2()
3130 ** method. */
3131 zOpt = &zFile[sqlite3Strlen30(zFile)+1];
3132 while( zOpt[0] ){
3133 int nOpt = sqlite3Strlen30(zOpt);
3134 char *zVal = &zOpt[nOpt+1];
3135 int nVal = sqlite3Strlen30(zVal);
3137 if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
3138 zVfs = zVal;
3139 }else{
3140 struct OpenMode {
3141 const char *z;
3142 int mode;
3143 } *aMode = 0;
3144 char *zModeType = 0;
3145 int mask = 0;
3146 int limit = 0;
3148 if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
3149 static struct OpenMode aCacheMode[] = {
3150 { "shared", SQLITE_OPEN_SHAREDCACHE },
3151 { "private", SQLITE_OPEN_PRIVATECACHE },
3152 { 0, 0 }
3155 mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
3156 aMode = aCacheMode;
3157 limit = mask;
3158 zModeType = "cache";
3160 if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
3161 static struct OpenMode aOpenMode[] = {
3162 { "ro", SQLITE_OPEN_READONLY },
3163 { "rw", SQLITE_OPEN_READWRITE },
3164 { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
3165 { "memory", SQLITE_OPEN_MEMORY },
3166 { 0, 0 }
3169 mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
3170 | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
3171 aMode = aOpenMode;
3172 limit = mask & flags;
3173 zModeType = "access";
3176 if( aMode ){
3177 int i;
3178 int mode = 0;
3179 for(i=0; aMode[i].z; i++){
3180 const char *z = aMode[i].z;
3181 if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
3182 mode = aMode[i].mode;
3183 break;
3186 if( mode==0 ){
3187 *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
3188 rc = SQLITE_ERROR;
3189 goto parse_uri_out;
3191 if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
3192 *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
3193 zModeType, zVal);
3194 rc = SQLITE_PERM;
3195 goto parse_uri_out;
3197 flags = (flags & ~mask) | mode;
3201 zOpt = &zVal[nVal+1];
3204 }else{
3205 zFile = sqlite3_malloc64(nUri+8);
3206 if( !zFile ) return SQLITE_NOMEM_BKPT;
3207 memset(zFile, 0, 4);
3208 zFile += 4;
3209 if( nUri ){
3210 memcpy(zFile, zUri, nUri);
3212 memset(zFile+nUri, 0, 4);
3213 flags &= ~SQLITE_OPEN_URI;
3216 *ppVfs = sqlite3_vfs_find(zVfs);
3217 if( *ppVfs==0 ){
3218 *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
3219 rc = SQLITE_ERROR;
3221 parse_uri_out:
3222 if( rc!=SQLITE_OK ){
3223 sqlite3_free_filename(zFile);
3224 zFile = 0;
3226 *pFlags = flags;
3227 *pzFile = zFile;
3228 return rc;
3232 ** This routine does the core work of extracting URI parameters from a
3233 ** database filename for the sqlite3_uri_parameter() interface.
3235 static const char *uriParameter(const char *zFilename, const char *zParam){
3236 zFilename += sqlite3Strlen30(zFilename) + 1;
3237 while( ALWAYS(zFilename!=0) && zFilename[0] ){
3238 int x = strcmp(zFilename, zParam);
3239 zFilename += sqlite3Strlen30(zFilename) + 1;
3240 if( x==0 ) return zFilename;
3241 zFilename += sqlite3Strlen30(zFilename) + 1;
3243 return 0;
3249 ** This routine does the work of opening a database on behalf of
3250 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
3251 ** is UTF-8 encoded.
3253 static int openDatabase(
3254 const char *zFilename, /* Database filename UTF-8 encoded */
3255 sqlite3 **ppDb, /* OUT: Returned database handle */
3256 unsigned int flags, /* Operational flags */
3257 const char *zVfs /* Name of the VFS to use */
3259 sqlite3 *db; /* Store allocated handle here */
3260 int rc; /* Return code */
3261 int isThreadsafe; /* True for threadsafe connections */
3262 char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
3263 char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
3264 int i; /* Loop counter */
3266 #ifdef SQLITE_ENABLE_API_ARMOR
3267 if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
3268 #endif
3269 *ppDb = 0;
3270 #ifndef SQLITE_OMIT_AUTOINIT
3271 rc = sqlite3_initialize();
3272 if( rc ) return rc;
3273 #endif
3275 if( sqlite3GlobalConfig.bCoreMutex==0 ){
3276 isThreadsafe = 0;
3277 }else if( flags & SQLITE_OPEN_NOMUTEX ){
3278 isThreadsafe = 0;
3279 }else if( flags & SQLITE_OPEN_FULLMUTEX ){
3280 isThreadsafe = 1;
3281 }else{
3282 isThreadsafe = sqlite3GlobalConfig.bFullMutex;
3285 if( flags & SQLITE_OPEN_PRIVATECACHE ){
3286 flags &= ~SQLITE_OPEN_SHAREDCACHE;
3287 }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
3288 flags |= SQLITE_OPEN_SHAREDCACHE;
3291 /* Remove harmful bits from the flags parameter
3293 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
3294 ** dealt with in the previous code block. Besides these, the only
3295 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
3296 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
3297 ** SQLITE_OPEN_PRIVATECACHE, SQLITE_OPEN_EXRESCODE, and some reserved
3298 ** bits. Silently mask off all other flags.
3300 flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
3301 SQLITE_OPEN_EXCLUSIVE |
3302 SQLITE_OPEN_MAIN_DB |
3303 SQLITE_OPEN_TEMP_DB |
3304 SQLITE_OPEN_TRANSIENT_DB |
3305 SQLITE_OPEN_MAIN_JOURNAL |
3306 SQLITE_OPEN_TEMP_JOURNAL |
3307 SQLITE_OPEN_SUBJOURNAL |
3308 SQLITE_OPEN_SUPER_JOURNAL |
3309 SQLITE_OPEN_NOMUTEX |
3310 SQLITE_OPEN_FULLMUTEX |
3311 SQLITE_OPEN_WAL
3314 /* Allocate the sqlite data structure */
3315 db = sqlite3MallocZero( sizeof(sqlite3) );
3316 if( db==0 ) goto opendb_out;
3317 if( isThreadsafe
3318 #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
3319 || sqlite3GlobalConfig.bCoreMutex
3320 #endif
3322 db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
3323 if( db->mutex==0 ){
3324 sqlite3_free(db);
3325 db = 0;
3326 goto opendb_out;
3328 if( isThreadsafe==0 ){
3329 sqlite3MutexWarnOnContention(db->mutex);
3332 sqlite3_mutex_enter(db->mutex);
3333 db->errMask = (flags & SQLITE_OPEN_EXRESCODE)!=0 ? 0xffffffff : 0xff;
3334 db->nDb = 2;
3335 db->eOpenState = SQLITE_STATE_BUSY;
3336 db->aDb = db->aDbStatic;
3337 db->lookaside.bDisable = 1;
3338 db->lookaside.sz = 0;
3340 assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
3341 memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
3342 db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
3343 db->autoCommit = 1;
3344 db->nextAutovac = -1;
3345 db->szMmap = sqlite3GlobalConfig.szMmap;
3346 db->nextPagesize = 0;
3347 db->init.azInit = sqlite3StdType; /* Any array of string ptrs will do */
3348 #ifdef SQLITE_ENABLE_SORTER_MMAP
3349 /* Beginning with version 3.37.0, using the VFS xFetch() API to memory-map
3350 ** the temporary files used to do external sorts (see code in vdbesort.c)
3351 ** is disabled. It can still be used either by defining
3352 ** SQLITE_ENABLE_SORTER_MMAP at compile time or by using the
3353 ** SQLITE_TESTCTRL_SORTER_MMAP test-control at runtime. */
3354 db->nMaxSorterMmap = 0x7FFFFFFF;
3355 #endif
3356 db->flags |= SQLITE_ShortColNames
3357 | SQLITE_EnableTrigger
3358 | SQLITE_EnableView
3359 | SQLITE_CacheSpill
3360 #if !defined(SQLITE_TRUSTED_SCHEMA) || SQLITE_TRUSTED_SCHEMA+0!=0
3361 | SQLITE_TrustedSchema
3362 #endif
3363 /* The SQLITE_DQS compile-time option determines the default settings
3364 ** for SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML.
3366 ** SQLITE_DQS SQLITE_DBCONFIG_DQS_DDL SQLITE_DBCONFIG_DQS_DML
3367 ** ---------- ----------------------- -----------------------
3368 ** undefined on on
3369 ** 3 on on
3370 ** 2 on off
3371 ** 1 off on
3372 ** 0 off off
3374 ** Legacy behavior is 3 (double-quoted string literals are allowed anywhere)
3375 ** and so that is the default. But developers are encouraged to use
3376 ** -DSQLITE_DQS=0 (best) or -DSQLITE_DQS=1 (second choice) if possible.
3378 #if !defined(SQLITE_DQS)
3379 # define SQLITE_DQS 3
3380 #endif
3381 #if (SQLITE_DQS&1)==1
3382 | SQLITE_DqsDML
3383 #endif
3384 #if (SQLITE_DQS&2)==2
3385 | SQLITE_DqsDDL
3386 #endif
3388 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
3389 | SQLITE_AutoIndex
3390 #endif
3391 #if SQLITE_DEFAULT_CKPTFULLFSYNC
3392 | SQLITE_CkptFullFSync
3393 #endif
3394 #if SQLITE_DEFAULT_FILE_FORMAT<4
3395 | SQLITE_LegacyFileFmt
3396 #endif
3397 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
3398 | SQLITE_LoadExtension
3399 #endif
3400 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
3401 | SQLITE_RecTriggers
3402 #endif
3403 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
3404 | SQLITE_ForeignKeys
3405 #endif
3406 #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
3407 | SQLITE_ReverseOrder
3408 #endif
3409 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
3410 | SQLITE_CellSizeCk
3411 #endif
3412 #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
3413 | SQLITE_Fts3Tokenizer
3414 #endif
3415 #if defined(SQLITE_ENABLE_QPSG)
3416 | SQLITE_EnableQPSG
3417 #endif
3418 #if defined(SQLITE_DEFAULT_DEFENSIVE)
3419 | SQLITE_Defensive
3420 #endif
3421 #if defined(SQLITE_DEFAULT_LEGACY_ALTER_TABLE)
3422 | SQLITE_LegacyAlter
3423 #endif
3424 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
3425 | SQLITE_StmtScanStatus
3426 #endif
3428 sqlite3HashInit(&db->aCollSeq);
3429 #ifndef SQLITE_OMIT_VIRTUALTABLE
3430 sqlite3HashInit(&db->aModule);
3431 #endif
3433 /* Add the default collation sequence BINARY. BINARY works for both UTF-8
3434 ** and UTF-16, so add a version for each to avoid any unnecessary
3435 ** conversions. The only error that can occur here is a malloc() failure.
3437 ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
3438 ** functions:
3440 createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
3441 createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
3442 createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
3443 createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
3444 createCollation(db, "RTRIM", SQLITE_UTF8, 0, rtrimCollFunc, 0);
3445 if( db->mallocFailed ){
3446 goto opendb_out;
3449 #if SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL)
3450 /* Process magic filenames ":localStorage:" and ":sessionStorage:" */
3451 if( zFilename && zFilename[0]==':' ){
3452 if( strcmp(zFilename, ":localStorage:")==0 ){
3453 zFilename = "file:local?vfs=kvvfs";
3454 flags |= SQLITE_OPEN_URI;
3455 }else if( strcmp(zFilename, ":sessionStorage:")==0 ){
3456 zFilename = "file:session?vfs=kvvfs";
3457 flags |= SQLITE_OPEN_URI;
3460 #endif /* SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL) */
3462 /* Parse the filename/URI argument
3464 ** Only allow sensible combinations of bits in the flags argument.
3465 ** Throw an error if any non-sense combination is used. If we
3466 ** do not block illegal combinations here, it could trigger
3467 ** assert() statements in deeper layers. Sensible combinations
3468 ** are:
3470 ** 1: SQLITE_OPEN_READONLY
3471 ** 2: SQLITE_OPEN_READWRITE
3472 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
3474 db->openFlags = flags;
3475 assert( SQLITE_OPEN_READONLY == 0x01 );
3476 assert( SQLITE_OPEN_READWRITE == 0x02 );
3477 assert( SQLITE_OPEN_CREATE == 0x04 );
3478 testcase( (1<<(flags&7))==0x02 ); /* READONLY */
3479 testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
3480 testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
3481 if( ((1<<(flags&7)) & 0x46)==0 ){
3482 rc = SQLITE_MISUSE_BKPT; /* IMP: R-18321-05872 */
3483 }else{
3484 rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
3486 if( rc!=SQLITE_OK ){
3487 if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
3488 sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
3489 sqlite3_free(zErrMsg);
3490 goto opendb_out;
3492 assert( db->pVfs!=0 );
3493 #if SQLITE_OS_KV || defined(SQLITE_OS_KV_OPTIONAL)
3494 if( sqlite3_stricmp(db->pVfs->zName, "kvvfs")==0 ){
3495 db->temp_store = 2;
3497 #endif
3499 /* Open the backend database driver */
3500 rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
3501 flags | SQLITE_OPEN_MAIN_DB);
3502 if( rc!=SQLITE_OK ){
3503 if( rc==SQLITE_IOERR_NOMEM ){
3504 rc = SQLITE_NOMEM_BKPT;
3506 sqlite3Error(db, rc);
3507 goto opendb_out;
3509 sqlite3BtreeEnter(db->aDb[0].pBt);
3510 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
3511 if( !db->mallocFailed ){
3512 sqlite3SetTextEncoding(db, SCHEMA_ENC(db));
3514 sqlite3BtreeLeave(db->aDb[0].pBt);
3515 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
3517 /* The default safety_level for the main database is FULL; for the temp
3518 ** database it is OFF. This matches the pager layer defaults.
3520 db->aDb[0].zDbSName = "main";
3521 db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
3522 db->aDb[1].zDbSName = "temp";
3523 db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
3525 db->eOpenState = SQLITE_STATE_OPEN;
3526 if( db->mallocFailed ){
3527 goto opendb_out;
3530 /* Register all built-in functions, but do not attempt to read the
3531 ** database schema yet. This is delayed until the first time the database
3532 ** is accessed.
3534 sqlite3Error(db, SQLITE_OK);
3535 sqlite3RegisterPerConnectionBuiltinFunctions(db);
3536 rc = sqlite3_errcode(db);
3539 /* Load compiled-in extensions */
3540 for(i=0; rc==SQLITE_OK && i<ArraySize(sqlite3BuiltinExtensions); i++){
3541 rc = sqlite3BuiltinExtensions[i](db);
3544 /* Load automatic extensions - extensions that have been registered
3545 ** using the sqlite3_automatic_extension() API.
3547 if( rc==SQLITE_OK ){
3548 sqlite3AutoLoadExtensions(db);
3549 rc = sqlite3_errcode(db);
3550 if( rc!=SQLITE_OK ){
3551 goto opendb_out;
3555 #ifdef SQLITE_ENABLE_INTERNAL_FUNCTIONS
3556 /* Testing use only!!! The -DSQLITE_ENABLE_INTERNAL_FUNCTIONS=1 compile-time
3557 ** option gives access to internal functions by default.
3558 ** Testing use only!!! */
3559 db->mDbFlags |= DBFLAG_InternalFunc;
3560 #endif
3562 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
3563 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
3564 ** mode. Doing nothing at all also makes NORMAL the default.
3566 #ifdef SQLITE_DEFAULT_LOCKING_MODE
3567 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
3568 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
3569 SQLITE_DEFAULT_LOCKING_MODE);
3570 #endif
3572 if( rc ) sqlite3Error(db, rc);
3574 /* Enable the lookaside-malloc subsystem */
3575 setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
3576 sqlite3GlobalConfig.nLookaside);
3578 sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
3580 opendb_out:
3581 if( db ){
3582 assert( db->mutex!=0 || isThreadsafe==0
3583 || sqlite3GlobalConfig.bFullMutex==0 );
3584 sqlite3_mutex_leave(db->mutex);
3586 rc = sqlite3_errcode(db);
3587 assert( db!=0 || (rc&0xff)==SQLITE_NOMEM );
3588 if( (rc&0xff)==SQLITE_NOMEM ){
3589 sqlite3_close(db);
3590 db = 0;
3591 }else if( rc!=SQLITE_OK ){
3592 db->eOpenState = SQLITE_STATE_SICK;
3594 *ppDb = db;
3595 #ifdef SQLITE_ENABLE_SQLLOG
3596 if( sqlite3GlobalConfig.xSqllog ){
3597 /* Opening a db handle. Fourth parameter is passed 0. */
3598 void *pArg = sqlite3GlobalConfig.pSqllogArg;
3599 sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
3601 #endif
3602 sqlite3_free_filename(zOpen);
3603 return rc;
3608 ** Open a new database handle.
3610 int sqlite3_open(
3611 const char *zFilename,
3612 sqlite3 **ppDb
3614 return openDatabase(zFilename, ppDb,
3615 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
3617 int sqlite3_open_v2(
3618 const char *filename, /* Database filename (UTF-8) */
3619 sqlite3 **ppDb, /* OUT: SQLite db handle */
3620 int flags, /* Flags */
3621 const char *zVfs /* Name of VFS module to use */
3623 return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
3626 #ifndef SQLITE_OMIT_UTF16
3628 ** Open a new database handle.
3630 int sqlite3_open16(
3631 const void *zFilename,
3632 sqlite3 **ppDb
3634 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
3635 sqlite3_value *pVal;
3636 int rc;
3638 #ifdef SQLITE_ENABLE_API_ARMOR
3639 if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
3640 #endif
3641 *ppDb = 0;
3642 #ifndef SQLITE_OMIT_AUTOINIT
3643 rc = sqlite3_initialize();
3644 if( rc ) return rc;
3645 #endif
3646 if( zFilename==0 ) zFilename = "\000\000";
3647 pVal = sqlite3ValueNew(0);
3648 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
3649 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
3650 if( zFilename8 ){
3651 rc = openDatabase(zFilename8, ppDb,
3652 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
3653 assert( *ppDb || rc==SQLITE_NOMEM );
3654 if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
3655 SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
3657 }else{
3658 rc = SQLITE_NOMEM_BKPT;
3660 sqlite3ValueFree(pVal);
3662 return rc & 0xff;
3664 #endif /* SQLITE_OMIT_UTF16 */
3667 ** Register a new collation sequence with the database handle db.
3669 int sqlite3_create_collation(
3670 sqlite3* db,
3671 const char *zName,
3672 int enc,
3673 void* pCtx,
3674 int(*xCompare)(void*,int,const void*,int,const void*)
3676 return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
3680 ** Register a new collation sequence with the database handle db.
3682 int sqlite3_create_collation_v2(
3683 sqlite3* db,
3684 const char *zName,
3685 int enc,
3686 void* pCtx,
3687 int(*xCompare)(void*,int,const void*,int,const void*),
3688 void(*xDel)(void*)
3690 int rc;
3692 #ifdef SQLITE_ENABLE_API_ARMOR
3693 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
3694 #endif
3695 sqlite3_mutex_enter(db->mutex);
3696 assert( !db->mallocFailed );
3697 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
3698 rc = sqlite3ApiExit(db, rc);
3699 sqlite3_mutex_leave(db->mutex);
3700 return rc;
3703 #ifndef SQLITE_OMIT_UTF16
3705 ** Register a new collation sequence with the database handle db.
3707 int sqlite3_create_collation16(
3708 sqlite3* db,
3709 const void *zName,
3710 int enc,
3711 void* pCtx,
3712 int(*xCompare)(void*,int,const void*,int,const void*)
3714 int rc = SQLITE_OK;
3715 char *zName8;
3717 #ifdef SQLITE_ENABLE_API_ARMOR
3718 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
3719 #endif
3720 sqlite3_mutex_enter(db->mutex);
3721 assert( !db->mallocFailed );
3722 zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
3723 if( zName8 ){
3724 rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
3725 sqlite3DbFree(db, zName8);
3727 rc = sqlite3ApiExit(db, rc);
3728 sqlite3_mutex_leave(db->mutex);
3729 return rc;
3731 #endif /* SQLITE_OMIT_UTF16 */
3734 ** Register a collation sequence factory callback with the database handle
3735 ** db. Replace any previously installed collation sequence factory.
3737 int sqlite3_collation_needed(
3738 sqlite3 *db,
3739 void *pCollNeededArg,
3740 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
3742 #ifdef SQLITE_ENABLE_API_ARMOR
3743 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3744 #endif
3745 sqlite3_mutex_enter(db->mutex);
3746 db->xCollNeeded = xCollNeeded;
3747 db->xCollNeeded16 = 0;
3748 db->pCollNeededArg = pCollNeededArg;
3749 sqlite3_mutex_leave(db->mutex);
3750 return SQLITE_OK;
3753 #ifndef SQLITE_OMIT_UTF16
3755 ** Register a collation sequence factory callback with the database handle
3756 ** db. Replace any previously installed collation sequence factory.
3758 int sqlite3_collation_needed16(
3759 sqlite3 *db,
3760 void *pCollNeededArg,
3761 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
3763 #ifdef SQLITE_ENABLE_API_ARMOR
3764 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3765 #endif
3766 sqlite3_mutex_enter(db->mutex);
3767 db->xCollNeeded = 0;
3768 db->xCollNeeded16 = xCollNeeded16;
3769 db->pCollNeededArg = pCollNeededArg;
3770 sqlite3_mutex_leave(db->mutex);
3771 return SQLITE_OK;
3773 #endif /* SQLITE_OMIT_UTF16 */
3776 ** Find existing client data.
3778 void *sqlite3_get_clientdata(sqlite3 *db, const char *zName){
3779 DbClientData *p;
3780 sqlite3_mutex_enter(db->mutex);
3781 for(p=db->pDbData; p; p=p->pNext){
3782 if( strcmp(p->zName, zName)==0 ){
3783 void *pResult = p->pData;
3784 sqlite3_mutex_leave(db->mutex);
3785 return pResult;
3788 sqlite3_mutex_leave(db->mutex);
3789 return 0;
3793 ** Add new client data to a database connection.
3795 int sqlite3_set_clientdata(
3796 sqlite3 *db, /* Attach client data to this connection */
3797 const char *zName, /* Name of the client data */
3798 void *pData, /* The client data itself */
3799 void (*xDestructor)(void*) /* Destructor */
3801 DbClientData *p, **pp;
3802 sqlite3_mutex_enter(db->mutex);
3803 pp = &db->pDbData;
3804 for(p=db->pDbData; p && strcmp(p->zName,zName); p=p->pNext){
3805 pp = &p->pNext;
3807 if( p ){
3808 assert( p->pData!=0 );
3809 if( p->xDestructor ) p->xDestructor(p->pData);
3810 if( pData==0 ){
3811 *pp = p->pNext;
3812 sqlite3_free(p);
3813 sqlite3_mutex_leave(db->mutex);
3814 return SQLITE_OK;
3816 }else if( pData==0 ){
3817 sqlite3_mutex_leave(db->mutex);
3818 return SQLITE_OK;
3819 }else{
3820 size_t n = strlen(zName);
3821 p = sqlite3_malloc64( sizeof(DbClientData)+n+1 );
3822 if( p==0 ){
3823 if( xDestructor ) xDestructor(pData);
3824 sqlite3_mutex_leave(db->mutex);
3825 return SQLITE_NOMEM;
3827 memcpy(p->zName, zName, n+1);
3828 p->pNext = db->pDbData;
3829 db->pDbData = p;
3831 p->pData = pData;
3832 p->xDestructor = xDestructor;
3833 sqlite3_mutex_leave(db->mutex);
3834 return SQLITE_OK;
3838 #ifndef SQLITE_OMIT_DEPRECATED
3840 ** This function is now an anachronism. It used to be used to recover from a
3841 ** malloc() failure, but SQLite now does this automatically.
3843 int sqlite3_global_recover(void){
3844 return SQLITE_OK;
3846 #endif
3849 ** Test to see whether or not the database connection is in autocommit
3850 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
3851 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
3852 ** by the next COMMIT or ROLLBACK.
3854 int sqlite3_get_autocommit(sqlite3 *db){
3855 #ifdef SQLITE_ENABLE_API_ARMOR
3856 if( !sqlite3SafetyCheckOk(db) ){
3857 (void)SQLITE_MISUSE_BKPT;
3858 return 0;
3860 #endif
3861 return db->autoCommit;
3865 ** The following routines are substitutes for constants SQLITE_CORRUPT,
3866 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
3867 ** constants. They serve two purposes:
3869 ** 1. Serve as a convenient place to set a breakpoint in a debugger
3870 ** to detect when version error conditions occurs.
3872 ** 2. Invoke sqlite3_log() to provide the source code location where
3873 ** a low-level error is first detected.
3875 int sqlite3ReportError(int iErr, int lineno, const char *zType){
3876 sqlite3_log(iErr, "%s at line %d of [%.10s]",
3877 zType, lineno, 20+sqlite3_sourceid());
3878 return iErr;
3880 int sqlite3CorruptError(int lineno){
3881 testcase( sqlite3GlobalConfig.xLog!=0 );
3882 return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
3884 int sqlite3MisuseError(int lineno){
3885 testcase( sqlite3GlobalConfig.xLog!=0 );
3886 return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
3888 int sqlite3CantopenError(int lineno){
3889 testcase( sqlite3GlobalConfig.xLog!=0 );
3890 return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
3892 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
3893 int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
3894 char zMsg[100];
3895 sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
3896 testcase( sqlite3GlobalConfig.xLog!=0 );
3897 return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
3899 #endif
3900 #ifdef SQLITE_DEBUG
3901 int sqlite3NomemError(int lineno){
3902 testcase( sqlite3GlobalConfig.xLog!=0 );
3903 return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
3905 int sqlite3IoerrnomemError(int lineno){
3906 testcase( sqlite3GlobalConfig.xLog!=0 );
3907 return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
3909 #endif
3911 #ifndef SQLITE_OMIT_DEPRECATED
3913 ** This is a convenience routine that makes sure that all thread-specific
3914 ** data for this thread has been deallocated.
3916 ** SQLite no longer uses thread-specific data so this routine is now a
3917 ** no-op. It is retained for historical compatibility.
3919 void sqlite3_thread_cleanup(void){
3921 #endif
3924 ** Return meta information about a specific column of a database table.
3925 ** See comment in sqlite3.h (sqlite.h.in) for details.
3927 int sqlite3_table_column_metadata(
3928 sqlite3 *db, /* Connection handle */
3929 const char *zDbName, /* Database name or NULL */
3930 const char *zTableName, /* Table name */
3931 const char *zColumnName, /* Column name */
3932 char const **pzDataType, /* OUTPUT: Declared data type */
3933 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
3934 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
3935 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
3936 int *pAutoinc /* OUTPUT: True if column is auto-increment */
3938 int rc;
3939 char *zErrMsg = 0;
3940 Table *pTab = 0;
3941 Column *pCol = 0;
3942 int iCol = 0;
3943 char const *zDataType = 0;
3944 char const *zCollSeq = 0;
3945 int notnull = 0;
3946 int primarykey = 0;
3947 int autoinc = 0;
3950 #ifdef SQLITE_ENABLE_API_ARMOR
3951 if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
3952 return SQLITE_MISUSE_BKPT;
3954 #endif
3956 /* Ensure the database schema has been loaded */
3957 sqlite3_mutex_enter(db->mutex);
3958 sqlite3BtreeEnterAll(db);
3959 rc = sqlite3Init(db, &zErrMsg);
3960 if( SQLITE_OK!=rc ){
3961 goto error_out;
3964 /* Locate the table in question */
3965 pTab = sqlite3FindTable(db, zTableName, zDbName);
3966 if( !pTab || IsView(pTab) ){
3967 pTab = 0;
3968 goto error_out;
3971 /* Find the column for which info is requested */
3972 if( zColumnName==0 ){
3973 /* Query for existence of table only */
3974 }else{
3975 for(iCol=0; iCol<pTab->nCol; iCol++){
3976 pCol = &pTab->aCol[iCol];
3977 if( 0==sqlite3StrICmp(pCol->zCnName, zColumnName) ){
3978 break;
3981 if( iCol==pTab->nCol ){
3982 if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
3983 iCol = pTab->iPKey;
3984 pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
3985 }else{
3986 pTab = 0;
3987 goto error_out;
3992 /* The following block stores the meta information that will be returned
3993 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
3994 ** and autoinc. At this point there are two possibilities:
3996 ** 1. The specified column name was rowid", "oid" or "_rowid_"
3997 ** and there is no explicitly declared IPK column.
3999 ** 2. The table is not a view and the column name identified an
4000 ** explicitly declared column. Copy meta information from *pCol.
4002 if( pCol ){
4003 zDataType = sqlite3ColumnType(pCol,0);
4004 zCollSeq = sqlite3ColumnColl(pCol);
4005 notnull = pCol->notNull!=0;
4006 primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
4007 autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
4008 }else{
4009 zDataType = "INTEGER";
4010 primarykey = 1;
4012 if( !zCollSeq ){
4013 zCollSeq = sqlite3StrBINARY;
4016 error_out:
4017 sqlite3BtreeLeaveAll(db);
4019 /* Whether the function call succeeded or failed, set the output parameters
4020 ** to whatever their local counterparts contain. If an error did occur,
4021 ** this has the effect of zeroing all output parameters.
4023 if( pzDataType ) *pzDataType = zDataType;
4024 if( pzCollSeq ) *pzCollSeq = zCollSeq;
4025 if( pNotNull ) *pNotNull = notnull;
4026 if( pPrimaryKey ) *pPrimaryKey = primarykey;
4027 if( pAutoinc ) *pAutoinc = autoinc;
4029 if( SQLITE_OK==rc && !pTab ){
4030 sqlite3DbFree(db, zErrMsg);
4031 zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
4032 zColumnName);
4033 rc = SQLITE_ERROR;
4035 sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
4036 sqlite3DbFree(db, zErrMsg);
4037 rc = sqlite3ApiExit(db, rc);
4038 sqlite3_mutex_leave(db->mutex);
4039 return rc;
4043 ** Sleep for a little while. Return the amount of time slept.
4045 int sqlite3_sleep(int ms){
4046 sqlite3_vfs *pVfs;
4047 int rc;
4048 pVfs = sqlite3_vfs_find(0);
4049 if( pVfs==0 ) return 0;
4051 /* This function works in milliseconds, but the underlying OsSleep()
4052 ** API uses microseconds. Hence the 1000's.
4054 rc = (sqlite3OsSleep(pVfs, ms<0 ? 0 : 1000*ms)/1000);
4055 return rc;
4059 ** Enable or disable the extended result codes.
4061 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
4062 #ifdef SQLITE_ENABLE_API_ARMOR
4063 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
4064 #endif
4065 sqlite3_mutex_enter(db->mutex);
4066 db->errMask = onoff ? 0xffffffff : 0xff;
4067 sqlite3_mutex_leave(db->mutex);
4068 return SQLITE_OK;
4072 ** Invoke the xFileControl method on a particular database.
4074 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
4075 int rc = SQLITE_ERROR;
4076 Btree *pBtree;
4078 #ifdef SQLITE_ENABLE_API_ARMOR
4079 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
4080 #endif
4081 sqlite3_mutex_enter(db->mutex);
4082 pBtree = sqlite3DbNameToBtree(db, zDbName);
4083 if( pBtree ){
4084 Pager *pPager;
4085 sqlite3_file *fd;
4086 sqlite3BtreeEnter(pBtree);
4087 pPager = sqlite3BtreePager(pBtree);
4088 assert( pPager!=0 );
4089 fd = sqlite3PagerFile(pPager);
4090 assert( fd!=0 );
4091 if( op==SQLITE_FCNTL_FILE_POINTER ){
4092 *(sqlite3_file**)pArg = fd;
4093 rc = SQLITE_OK;
4094 }else if( op==SQLITE_FCNTL_VFS_POINTER ){
4095 *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
4096 rc = SQLITE_OK;
4097 }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
4098 *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
4099 rc = SQLITE_OK;
4100 }else if( op==SQLITE_FCNTL_DATA_VERSION ){
4101 *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager);
4102 rc = SQLITE_OK;
4103 }else if( op==SQLITE_FCNTL_RESERVE_BYTES ){
4104 int iNew = *(int*)pArg;
4105 *(int*)pArg = sqlite3BtreeGetRequestedReserve(pBtree);
4106 if( iNew>=0 && iNew<=255 ){
4107 sqlite3BtreeSetPageSize(pBtree, 0, iNew, 0);
4109 rc = SQLITE_OK;
4110 }else if( op==SQLITE_FCNTL_RESET_CACHE ){
4111 sqlite3BtreeClearCache(pBtree);
4112 rc = SQLITE_OK;
4113 }else{
4114 int nSave = db->busyHandler.nBusy;
4115 rc = sqlite3OsFileControl(fd, op, pArg);
4116 db->busyHandler.nBusy = nSave;
4118 sqlite3BtreeLeave(pBtree);
4120 sqlite3_mutex_leave(db->mutex);
4121 return rc;
4125 ** Interface to the testing logic.
4127 int sqlite3_test_control(int op, ...){
4128 int rc = 0;
4129 #ifdef SQLITE_UNTESTABLE
4130 UNUSED_PARAMETER(op);
4131 #else
4132 va_list ap;
4133 va_start(ap, op);
4134 switch( op ){
4137 ** Save the current state of the PRNG.
4139 case SQLITE_TESTCTRL_PRNG_SAVE: {
4140 sqlite3PrngSaveState();
4141 break;
4145 ** Restore the state of the PRNG to the last state saved using
4146 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
4147 ** this verb acts like PRNG_RESET.
4149 case SQLITE_TESTCTRL_PRNG_RESTORE: {
4150 sqlite3PrngRestoreState();
4151 break;
4154 /* sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, int x, sqlite3 *db);
4156 ** Control the seed for the pseudo-random number generator (PRNG) that
4157 ** is built into SQLite. Cases:
4159 ** x!=0 && db!=0 Seed the PRNG to the current value of the
4160 ** schema cookie in the main database for db, or
4161 ** x if the schema cookie is zero. This case
4162 ** is convenient to use with database fuzzers
4163 ** as it allows the fuzzer some control over the
4164 ** the PRNG seed.
4166 ** x!=0 && db==0 Seed the PRNG to the value of x.
4168 ** x==0 && db==0 Revert to default behavior of using the
4169 ** xRandomness method on the primary VFS.
4171 ** This test-control also resets the PRNG so that the new seed will
4172 ** be used for the next call to sqlite3_randomness().
4174 #ifndef SQLITE_OMIT_WSD
4175 case SQLITE_TESTCTRL_PRNG_SEED: {
4176 int x = va_arg(ap, int);
4177 int y;
4178 sqlite3 *db = va_arg(ap, sqlite3*);
4179 assert( db==0 || db->aDb[0].pSchema!=0 );
4180 if( db && (y = db->aDb[0].pSchema->schema_cookie)!=0 ){ x = y; }
4181 sqlite3Config.iPrngSeed = x;
4182 sqlite3_randomness(0,0);
4183 break;
4185 #endif
4187 /* sqlite3_test_control(SQLITE_TESTCTRL_FK_NO_ACTION, sqlite3 *db, int b);
4189 ** If b is true, then activate the SQLITE_FkNoAction setting. If b is
4190 ** false then clearn that setting. If the SQLITE_FkNoAction setting is
4191 ** abled, all foreign key ON DELETE and ON UPDATE actions behave as if
4192 ** they were NO ACTION, regardless of how they are defined.
4194 ** NB: One must usually run "PRAGMA writable_schema=RESET" after
4195 ** using this test-control, before it will take full effect. failing
4196 ** to reset the schema can result in some unexpected behavior.
4198 case SQLITE_TESTCTRL_FK_NO_ACTION: {
4199 sqlite3 *db = va_arg(ap, sqlite3*);
4200 int b = va_arg(ap, int);
4201 if( b ){
4202 db->flags |= SQLITE_FkNoAction;
4203 }else{
4204 db->flags &= ~SQLITE_FkNoAction;
4206 break;
4210 ** sqlite3_test_control(BITVEC_TEST, size, program)
4212 ** Run a test against a Bitvec object of size. The program argument
4213 ** is an array of integers that defines the test. Return -1 on a
4214 ** memory allocation error, 0 on success, or non-zero for an error.
4215 ** See the sqlite3BitvecBuiltinTest() for additional information.
4217 case SQLITE_TESTCTRL_BITVEC_TEST: {
4218 int sz = va_arg(ap, int);
4219 int *aProg = va_arg(ap, int*);
4220 rc = sqlite3BitvecBuiltinTest(sz, aProg);
4221 break;
4225 ** sqlite3_test_control(FAULT_INSTALL, xCallback)
4227 ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
4228 ** if xCallback is not NULL.
4230 ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
4231 ** is called immediately after installing the new callback and the return
4232 ** value from sqlite3FaultSim(0) becomes the return from
4233 ** sqlite3_test_control().
4235 case SQLITE_TESTCTRL_FAULT_INSTALL: {
4236 /* A bug in MSVC prevents it from understanding pointers to functions
4237 ** types in the second argument to va_arg(). Work around the problem
4238 ** using a typedef.
4239 ** http://support.microsoft.com/kb/47961 <-- dead hyperlink
4240 ** Search at http://web.archive.org/ to find the 2015-03-16 archive
4241 ** of the link above to see the original text.
4242 ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
4244 typedef int(*sqlite3FaultFuncType)(int);
4245 sqlite3GlobalConfig.xTestCallback = va_arg(ap, sqlite3FaultFuncType);
4246 rc = sqlite3FaultSim(0);
4247 break;
4251 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
4253 ** Register hooks to call to indicate which malloc() failures
4254 ** are benign.
4256 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
4257 typedef void (*void_function)(void);
4258 void_function xBenignBegin;
4259 void_function xBenignEnd;
4260 xBenignBegin = va_arg(ap, void_function);
4261 xBenignEnd = va_arg(ap, void_function);
4262 sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
4263 break;
4267 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
4269 ** Set the PENDING byte to the value in the argument, if X>0.
4270 ** Make no changes if X==0. Return the value of the pending byte
4271 ** as it existing before this routine was called.
4273 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
4274 ** an incompatible database file format. Changing the PENDING byte
4275 ** while any database connection is open results in undefined and
4276 ** deleterious behavior.
4278 case SQLITE_TESTCTRL_PENDING_BYTE: {
4279 rc = PENDING_BYTE;
4280 #ifndef SQLITE_OMIT_WSD
4282 unsigned int newVal = va_arg(ap, unsigned int);
4283 if( newVal ) sqlite3PendingByte = newVal;
4285 #endif
4286 break;
4290 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
4292 ** This action provides a run-time test to see whether or not
4293 ** assert() was enabled at compile-time. If X is true and assert()
4294 ** is enabled, then the return value is true. If X is true and
4295 ** assert() is disabled, then the return value is zero. If X is
4296 ** false and assert() is enabled, then the assertion fires and the
4297 ** process aborts. If X is false and assert() is disabled, then the
4298 ** return value is zero.
4300 case SQLITE_TESTCTRL_ASSERT: {
4301 volatile int x = 0;
4302 assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
4303 rc = x;
4304 #if defined(SQLITE_DEBUG)
4305 /* Invoke these debugging routines so that the compiler does not
4306 ** issue "defined but not used" warnings. */
4307 if( x==9999 ){
4308 sqlite3ShowExpr(0);
4309 sqlite3ShowExpr(0);
4310 sqlite3ShowExprList(0);
4311 sqlite3ShowIdList(0);
4312 sqlite3ShowSrcList(0);
4313 sqlite3ShowWith(0);
4314 sqlite3ShowUpsert(0);
4315 #ifndef SQLITE_OMIT_TRIGGER
4316 sqlite3ShowTriggerStep(0);
4317 sqlite3ShowTriggerStepList(0);
4318 sqlite3ShowTrigger(0);
4319 sqlite3ShowTriggerList(0);
4320 #endif
4321 #ifndef SQLITE_OMIT_WINDOWFUNC
4322 sqlite3ShowWindow(0);
4323 sqlite3ShowWinFunc(0);
4324 #endif
4325 sqlite3ShowSelect(0);
4327 #endif
4328 break;
4333 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
4335 ** This action provides a run-time test to see how the ALWAYS and
4336 ** NEVER macros were defined at compile-time.
4338 ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
4340 ** The recommended test is X==2. If the return value is 2, that means
4341 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
4342 ** default setting. If the return value is 1, then ALWAYS() is either
4343 ** hard-coded to true or else it asserts if its argument is false.
4344 ** The first behavior (hard-coded to true) is the case if
4345 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
4346 ** behavior (assert if the argument to ALWAYS() is false) is the case if
4347 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
4349 ** The run-time test procedure might look something like this:
4351 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
4352 ** // ALWAYS() and NEVER() are no-op pass-through macros
4353 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
4354 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
4355 ** }else{
4356 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
4357 ** }
4359 case SQLITE_TESTCTRL_ALWAYS: {
4360 int x = va_arg(ap,int);
4361 rc = x ? ALWAYS(x) : 0;
4362 break;
4366 ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
4368 ** The integer returned reveals the byte-order of the computer on which
4369 ** SQLite is running:
4371 ** 1 big-endian, determined at run-time
4372 ** 10 little-endian, determined at run-time
4373 ** 432101 big-endian, determined at compile-time
4374 ** 123410 little-endian, determined at compile-time
4376 case SQLITE_TESTCTRL_BYTEORDER: {
4377 rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
4378 break;
4381 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
4383 ** Enable or disable various optimizations for testing purposes. The
4384 ** argument N is a bitmask of optimizations to be disabled. For normal
4385 ** operation N should be 0. The idea is that a test program (like the
4386 ** SQL Logic Test or SLT test module) can run the same SQL multiple times
4387 ** with various optimizations disabled to verify that the same answer
4388 ** is obtained in every case.
4390 case SQLITE_TESTCTRL_OPTIMIZATIONS: {
4391 sqlite3 *db = va_arg(ap, sqlite3*);
4392 db->dbOptFlags = va_arg(ap, u32);
4393 break;
4396 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, onoff, xAlt);
4398 ** If parameter onoff is 1, subsequent calls to localtime() fail.
4399 ** If 2, then invoke xAlt() instead of localtime(). If 0, normal
4400 ** processing.
4402 ** xAlt arguments are void pointers, but they really want to be:
4404 ** int xAlt(const time_t*, struct tm*);
4406 ** xAlt should write results in to struct tm object of its 2nd argument
4407 ** and return zero on success, or return non-zero on failure.
4409 case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
4410 sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
4411 if( sqlite3GlobalConfig.bLocaltimeFault==2 ){
4412 typedef int(*sqlite3LocaltimeType)(const void*,void*);
4413 sqlite3GlobalConfig.xAltLocaltime = va_arg(ap, sqlite3LocaltimeType);
4414 }else{
4415 sqlite3GlobalConfig.xAltLocaltime = 0;
4417 break;
4420 /* sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, sqlite3*);
4422 ** Toggle the ability to use internal functions on or off for
4423 ** the database connection given in the argument.
4425 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: {
4426 sqlite3 *db = va_arg(ap, sqlite3*);
4427 db->mDbFlags ^= DBFLAG_InternalFunc;
4428 break;
4431 /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
4433 ** Set or clear a flag that indicates that the database file is always well-
4434 ** formed and never corrupt. This flag is clear by default, indicating that
4435 ** database files might have arbitrary corruption. Setting the flag during
4436 ** testing causes certain assert() statements in the code to be activated
4437 ** that demonstrate invariants on well-formed database files.
4439 case SQLITE_TESTCTRL_NEVER_CORRUPT: {
4440 sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
4441 break;
4444 /* sqlite3_test_control(SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS, int);
4446 ** Set or clear a flag that causes SQLite to verify that type, name,
4447 ** and tbl_name fields of the sqlite_schema table. This is normally
4448 ** on, but it is sometimes useful to turn it off for testing.
4450 ** 2020-07-22: Disabling EXTRA_SCHEMA_CHECKS also disables the
4451 ** verification of rootpage numbers when parsing the schema. This
4452 ** is useful to make it easier to reach strange internal error states
4453 ** during testing. The EXTRA_SCHEMA_CHECKS setting is always enabled
4454 ** in production.
4456 case SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS: {
4457 sqlite3GlobalConfig.bExtraSchemaChecks = va_arg(ap, int);
4458 break;
4461 /* Set the threshold at which OP_Once counters reset back to zero.
4462 ** By default this is 0x7ffffffe (over 2 billion), but that value is
4463 ** too big to test in a reasonable amount of time, so this control is
4464 ** provided to set a small and easily reachable reset value.
4466 case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
4467 sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
4468 break;
4471 /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
4473 ** Set the VDBE coverage callback function to xCallback with context
4474 ** pointer ptr.
4476 case SQLITE_TESTCTRL_VDBE_COVERAGE: {
4477 #ifdef SQLITE_VDBE_COVERAGE
4478 typedef void (*branch_callback)(void*,unsigned int,
4479 unsigned char,unsigned char);
4480 sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
4481 sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
4482 #endif
4483 break;
4486 /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
4487 case SQLITE_TESTCTRL_SORTER_MMAP: {
4488 sqlite3 *db = va_arg(ap, sqlite3*);
4489 db->nMaxSorterMmap = va_arg(ap, int);
4490 break;
4493 /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
4495 ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
4496 ** not.
4498 case SQLITE_TESTCTRL_ISINIT: {
4499 if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
4500 break;
4503 /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
4505 ** This test control is used to create imposter tables. "db" is a pointer
4506 ** to the database connection. dbName is the database name (ex: "main" or
4507 ** "temp") which will receive the imposter. "onOff" turns imposter mode on
4508 ** or off. "tnum" is the root page of the b-tree to which the imposter
4509 ** table should connect.
4511 ** Enable imposter mode only when the schema has already been parsed. Then
4512 ** run a single CREATE TABLE statement to construct the imposter table in
4513 ** the parsed schema. Then turn imposter mode back off again.
4515 ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
4516 ** the schema to be reparsed the next time it is needed. This has the
4517 ** effect of erasing all imposter tables.
4519 case SQLITE_TESTCTRL_IMPOSTER: {
4520 sqlite3 *db = va_arg(ap, sqlite3*);
4521 int iDb;
4522 sqlite3_mutex_enter(db->mutex);
4523 iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
4524 if( iDb>=0 ){
4525 db->init.iDb = iDb;
4526 db->init.busy = db->init.imposterTable = va_arg(ap,int);
4527 db->init.newTnum = va_arg(ap,int);
4528 if( db->init.busy==0 && db->init.newTnum>0 ){
4529 sqlite3ResetAllSchemasOfConnection(db);
4532 sqlite3_mutex_leave(db->mutex);
4533 break;
4536 #if defined(YYCOVERAGE)
4537 /* sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
4539 ** This test control (only available when SQLite is compiled with
4540 ** -DYYCOVERAGE) writes a report onto "out" that shows all
4541 ** state/lookahead combinations in the parser state machine
4542 ** which are never exercised. If any state is missed, make the
4543 ** return code SQLITE_ERROR.
4545 case SQLITE_TESTCTRL_PARSER_COVERAGE: {
4546 FILE *out = va_arg(ap, FILE*);
4547 if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
4548 break;
4550 #endif /* defined(YYCOVERAGE) */
4552 /* sqlite3_test_control(SQLITE_TESTCTRL_RESULT_INTREAL, sqlite3_context*);
4554 ** This test-control causes the most recent sqlite3_result_int64() value
4555 ** to be interpreted as a MEM_IntReal instead of as an MEM_Int. Normally,
4556 ** MEM_IntReal values only arise during an INSERT operation of integer
4557 ** values into a REAL column, so they can be challenging to test. This
4558 ** test-control enables us to write an intreal() SQL function that can
4559 ** inject an intreal() value at arbitrary places in an SQL statement,
4560 ** for testing purposes.
4562 case SQLITE_TESTCTRL_RESULT_INTREAL: {
4563 sqlite3_context *pCtx = va_arg(ap, sqlite3_context*);
4564 sqlite3ResultIntReal(pCtx);
4565 break;
4568 /* sqlite3_test_control(SQLITE_TESTCTRL_SEEK_COUNT,
4569 ** sqlite3 *db, // Database connection
4570 ** u64 *pnSeek // Write seek count here
4571 ** );
4573 ** This test-control queries the seek-counter on the "main" database
4574 ** file. The seek-counter is written into *pnSeek and is then reset.
4575 ** The seek-count is only available if compiled with SQLITE_DEBUG.
4577 case SQLITE_TESTCTRL_SEEK_COUNT: {
4578 sqlite3 *db = va_arg(ap, sqlite3*);
4579 u64 *pn = va_arg(ap, sqlite3_uint64*);
4580 *pn = sqlite3BtreeSeekCount(db->aDb->pBt);
4581 (void)db; /* Silence harmless unused variable warning */
4582 break;
4585 /* sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, op, ptr)
4587 ** "ptr" is a pointer to a u32.
4589 ** op==0 Store the current sqlite3TreeTrace in *ptr
4590 ** op==1 Set sqlite3TreeTrace to the value *ptr
4591 ** op==2 Store the current sqlite3WhereTrace in *ptr
4592 ** op==3 Set sqlite3WhereTrace to the value *ptr
4594 case SQLITE_TESTCTRL_TRACEFLAGS: {
4595 int opTrace = va_arg(ap, int);
4596 u32 *ptr = va_arg(ap, u32*);
4597 switch( opTrace ){
4598 case 0: *ptr = sqlite3TreeTrace; break;
4599 case 1: sqlite3TreeTrace = *ptr; break;
4600 case 2: *ptr = sqlite3WhereTrace; break;
4601 case 3: sqlite3WhereTrace = *ptr; break;
4603 break;
4606 /* sqlite3_test_control(SQLITE_TESTCTRL_LOGEST,
4607 ** double fIn, // Input value
4608 ** int *pLogEst, // sqlite3LogEstFromDouble(fIn)
4609 ** u64 *pInt, // sqlite3LogEstToInt(*pLogEst)
4610 ** int *pLogEst2 // sqlite3LogEst(*pInt)
4611 ** );
4613 ** Test access for the LogEst conversion routines.
4615 case SQLITE_TESTCTRL_LOGEST: {
4616 double rIn = va_arg(ap, double);
4617 LogEst rLogEst = sqlite3LogEstFromDouble(rIn);
4618 int *pI1 = va_arg(ap,int*);
4619 u64 *pU64 = va_arg(ap,u64*);
4620 int *pI2 = va_arg(ap,int*);
4621 *pI1 = rLogEst;
4622 *pU64 = sqlite3LogEstToInt(rLogEst);
4623 *pI2 = sqlite3LogEst(*pU64);
4624 break;
4627 #if !defined(SQLITE_OMIT_WSD)
4628 /* sqlite3_test_control(SQLITE_TESTCTRL_USELONGDOUBLE, int X);
4630 ** X<0 Make no changes to the bUseLongDouble. Just report value.
4631 ** X==0 Disable bUseLongDouble
4632 ** X==1 Enable bUseLongDouble
4633 ** X>=2 Set bUseLongDouble to its default value for this platform
4635 case SQLITE_TESTCTRL_USELONGDOUBLE: {
4636 int b = va_arg(ap, int);
4637 if( b>=2 ) b = hasHighPrecisionDouble(b);
4638 if( b>=0 ) sqlite3Config.bUseLongDouble = b>0;
4639 rc = sqlite3Config.bUseLongDouble!=0;
4640 break;
4642 #endif
4645 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
4646 /* sqlite3_test_control(SQLITE_TESTCTRL_TUNE, id, *piValue)
4648 ** If "id" is an integer between 1 and SQLITE_NTUNE then set the value
4649 ** of the id-th tuning parameter to *piValue. If "id" is between -1
4650 ** and -SQLITE_NTUNE, then write the current value of the (-id)-th
4651 ** tuning parameter into *piValue.
4653 ** Tuning parameters are for use during transient development builds,
4654 ** to help find the best values for constants in the query planner.
4655 ** Access tuning parameters using the Tuning(ID) macro. Set the
4656 ** parameters in the CLI using ".testctrl tune ID VALUE".
4658 ** Transient use only. Tuning parameters should not be used in
4659 ** checked-in code.
4661 case SQLITE_TESTCTRL_TUNE: {
4662 int id = va_arg(ap, int);
4663 int *piValue = va_arg(ap, int*);
4664 if( id>0 && id<=SQLITE_NTUNE ){
4665 Tuning(id) = *piValue;
4666 }else if( id<0 && id>=-SQLITE_NTUNE ){
4667 *piValue = Tuning(-id);
4668 }else{
4669 rc = SQLITE_NOTFOUND;
4671 break;
4673 #endif
4675 /* sqlite3_test_control(SQLITE_TESTCTRL_JSON_SELFCHECK, &onOff);
4677 ** Activate or deactivate validation of JSONB that is generated from
4678 ** text. Off by default, as the validation is slow. Validation is
4679 ** only available if compiled using SQLITE_DEBUG.
4681 ** If onOff is initially 1, then turn it on. If onOff is initially
4682 ** off, turn it off. If onOff is initially -1, then change onOff
4683 ** to be the current setting.
4685 case SQLITE_TESTCTRL_JSON_SELFCHECK: {
4686 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
4687 int *pOnOff = va_arg(ap, int*);
4688 if( *pOnOff<0 ){
4689 *pOnOff = sqlite3Config.bJsonSelfcheck;
4690 }else{
4691 sqlite3Config.bJsonSelfcheck = (u8)((*pOnOff)&0xff);
4693 #endif
4694 break;
4697 va_end(ap);
4698 #endif /* SQLITE_UNTESTABLE */
4699 return rc;
4703 ** The Pager stores the Database filename, Journal filename, and WAL filename
4704 ** consecutively in memory, in that order. The database filename is prefixed
4705 ** by four zero bytes. Locate the start of the database filename by searching
4706 ** backwards for the first byte following four consecutive zero bytes.
4708 ** This only works if the filename passed in was obtained from the Pager.
4710 static const char *databaseName(const char *zName){
4711 while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
4712 zName--;
4714 return zName;
4718 ** Append text z[] to the end of p[]. Return a pointer to the first
4719 ** character after then zero terminator on the new text in p[].
4721 static char *appendText(char *p, const char *z){
4722 size_t n = strlen(z);
4723 memcpy(p, z, n+1);
4724 return p+n+1;
4728 ** Allocate memory to hold names for a database, journal file, WAL file,
4729 ** and query parameters. The pointer returned is valid for use by
4730 ** sqlite3_filename_database() and sqlite3_uri_parameter() and related
4731 ** functions.
4733 ** Memory layout must be compatible with that generated by the pager
4734 ** and expected by sqlite3_uri_parameter() and databaseName().
4736 const char *sqlite3_create_filename(
4737 const char *zDatabase,
4738 const char *zJournal,
4739 const char *zWal,
4740 int nParam,
4741 const char **azParam
4743 sqlite3_int64 nByte;
4744 int i;
4745 char *pResult, *p;
4746 nByte = strlen(zDatabase) + strlen(zJournal) + strlen(zWal) + 10;
4747 for(i=0; i<nParam*2; i++){
4748 nByte += strlen(azParam[i])+1;
4750 pResult = p = sqlite3_malloc64( nByte );
4751 if( p==0 ) return 0;
4752 memset(p, 0, 4);
4753 p += 4;
4754 p = appendText(p, zDatabase);
4755 for(i=0; i<nParam*2; i++){
4756 p = appendText(p, azParam[i]);
4758 *(p++) = 0;
4759 p = appendText(p, zJournal);
4760 p = appendText(p, zWal);
4761 *(p++) = 0;
4762 *(p++) = 0;
4763 assert( (sqlite3_int64)(p - pResult)==nByte );
4764 return pResult + 4;
4768 ** Free memory obtained from sqlite3_create_filename(). It is a severe
4769 ** error to call this routine with any parameter other than a pointer
4770 ** previously obtained from sqlite3_create_filename() or a NULL pointer.
4772 void sqlite3_free_filename(const char *p){
4773 if( p==0 ) return;
4774 p = databaseName(p);
4775 sqlite3_free((char*)p - 4);
4780 ** This is a utility routine, useful to VFS implementations, that checks
4781 ** to see if a database file was a URI that contained a specific query
4782 ** parameter, and if so obtains the value of the query parameter.
4784 ** The zFilename argument is the filename pointer passed into the xOpen()
4785 ** method of a VFS implementation. The zParam argument is the name of the
4786 ** query parameter we seek. This routine returns the value of the zParam
4787 ** parameter if it exists. If the parameter does not exist, this routine
4788 ** returns a NULL pointer.
4790 const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
4791 if( zFilename==0 || zParam==0 ) return 0;
4792 zFilename = databaseName(zFilename);
4793 return uriParameter(zFilename, zParam);
4797 ** Return a pointer to the name of Nth query parameter of the filename.
4799 const char *sqlite3_uri_key(const char *zFilename, int N){
4800 if( zFilename==0 || N<0 ) return 0;
4801 zFilename = databaseName(zFilename);
4802 zFilename += sqlite3Strlen30(zFilename) + 1;
4803 while( ALWAYS(zFilename) && zFilename[0] && (N--)>0 ){
4804 zFilename += sqlite3Strlen30(zFilename) + 1;
4805 zFilename += sqlite3Strlen30(zFilename) + 1;
4807 return zFilename[0] ? zFilename : 0;
4811 ** Return a boolean value for a query parameter.
4813 int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
4814 const char *z = sqlite3_uri_parameter(zFilename, zParam);
4815 bDflt = bDflt!=0;
4816 return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
4820 ** Return a 64-bit integer value for a query parameter.
4822 sqlite3_int64 sqlite3_uri_int64(
4823 const char *zFilename, /* Filename as passed to xOpen */
4824 const char *zParam, /* URI parameter sought */
4825 sqlite3_int64 bDflt /* return if parameter is missing */
4827 const char *z = sqlite3_uri_parameter(zFilename, zParam);
4828 sqlite3_int64 v;
4829 if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
4830 bDflt = v;
4832 return bDflt;
4836 ** Translate a filename that was handed to a VFS routine into the corresponding
4837 ** database, journal, or WAL file.
4839 ** It is an error to pass this routine a filename string that was not
4840 ** passed into the VFS from the SQLite core. Doing so is similar to
4841 ** passing free() a pointer that was not obtained from malloc() - it is
4842 ** an error that we cannot easily detect but that will likely cause memory
4843 ** corruption.
4845 const char *sqlite3_filename_database(const char *zFilename){
4846 if( zFilename==0 ) return 0;
4847 return databaseName(zFilename);
4849 const char *sqlite3_filename_journal(const char *zFilename){
4850 if( zFilename==0 ) return 0;
4851 zFilename = databaseName(zFilename);
4852 zFilename += sqlite3Strlen30(zFilename) + 1;
4853 while( ALWAYS(zFilename) && zFilename[0] ){
4854 zFilename += sqlite3Strlen30(zFilename) + 1;
4855 zFilename += sqlite3Strlen30(zFilename) + 1;
4857 return zFilename + 1;
4859 const char *sqlite3_filename_wal(const char *zFilename){
4860 #ifdef SQLITE_OMIT_WAL
4861 return 0;
4862 #else
4863 zFilename = sqlite3_filename_journal(zFilename);
4864 if( zFilename ) zFilename += sqlite3Strlen30(zFilename) + 1;
4865 return zFilename;
4866 #endif
4870 ** Return the Btree pointer identified by zDbName. Return NULL if not found.
4872 Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
4873 int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
4874 return iDb<0 ? 0 : db->aDb[iDb].pBt;
4878 ** Return the name of the N-th database schema. Return NULL if N is out
4879 ** of range.
4881 const char *sqlite3_db_name(sqlite3 *db, int N){
4882 #ifdef SQLITE_ENABLE_API_ARMOR
4883 if( !sqlite3SafetyCheckOk(db) ){
4884 (void)SQLITE_MISUSE_BKPT;
4885 return 0;
4887 #endif
4888 if( N<0 || N>=db->nDb ){
4889 return 0;
4890 }else{
4891 return db->aDb[N].zDbSName;
4896 ** Return the filename of the database associated with a database
4897 ** connection.
4899 const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
4900 Btree *pBt;
4901 #ifdef SQLITE_ENABLE_API_ARMOR
4902 if( !sqlite3SafetyCheckOk(db) ){
4903 (void)SQLITE_MISUSE_BKPT;
4904 return 0;
4906 #endif
4907 pBt = sqlite3DbNameToBtree(db, zDbName);
4908 return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
4912 ** Return 1 if database is read-only or 0 if read/write. Return -1 if
4913 ** no such database exists.
4915 int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
4916 Btree *pBt;
4917 #ifdef SQLITE_ENABLE_API_ARMOR
4918 if( !sqlite3SafetyCheckOk(db) ){
4919 (void)SQLITE_MISUSE_BKPT;
4920 return -1;
4922 #endif
4923 pBt = sqlite3DbNameToBtree(db, zDbName);
4924 return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
4927 #ifdef SQLITE_ENABLE_SNAPSHOT
4929 ** Obtain a snapshot handle for the snapshot of database zDb currently
4930 ** being read by handle db.
4932 int sqlite3_snapshot_get(
4933 sqlite3 *db,
4934 const char *zDb,
4935 sqlite3_snapshot **ppSnapshot
4937 int rc = SQLITE_ERROR;
4938 #ifndef SQLITE_OMIT_WAL
4940 #ifdef SQLITE_ENABLE_API_ARMOR
4941 if( !sqlite3SafetyCheckOk(db) ){
4942 return SQLITE_MISUSE_BKPT;
4944 #endif
4945 sqlite3_mutex_enter(db->mutex);
4947 if( db->autoCommit==0 ){
4948 int iDb = sqlite3FindDbName(db, zDb);
4949 if( iDb==0 || iDb>1 ){
4950 Btree *pBt = db->aDb[iDb].pBt;
4951 if( SQLITE_TXN_WRITE!=sqlite3BtreeTxnState(pBt) ){
4952 rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
4953 if( rc==SQLITE_OK ){
4954 rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
4960 sqlite3_mutex_leave(db->mutex);
4961 #endif /* SQLITE_OMIT_WAL */
4962 return rc;
4966 ** Open a read-transaction on the snapshot identified by pSnapshot.
4968 int sqlite3_snapshot_open(
4969 sqlite3 *db,
4970 const char *zDb,
4971 sqlite3_snapshot *pSnapshot
4973 int rc = SQLITE_ERROR;
4974 #ifndef SQLITE_OMIT_WAL
4976 #ifdef SQLITE_ENABLE_API_ARMOR
4977 if( !sqlite3SafetyCheckOk(db) ){
4978 return SQLITE_MISUSE_BKPT;
4980 #endif
4981 sqlite3_mutex_enter(db->mutex);
4982 if( db->autoCommit==0 ){
4983 int iDb;
4984 iDb = sqlite3FindDbName(db, zDb);
4985 if( iDb==0 || iDb>1 ){
4986 Btree *pBt = db->aDb[iDb].pBt;
4987 if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE ){
4988 Pager *pPager = sqlite3BtreePager(pBt);
4989 int bUnlock = 0;
4990 if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_NONE ){
4991 if( db->nVdbeActive==0 ){
4992 rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot);
4993 if( rc==SQLITE_OK ){
4994 bUnlock = 1;
4995 rc = sqlite3BtreeCommit(pBt);
4998 }else{
4999 rc = SQLITE_OK;
5001 if( rc==SQLITE_OK ){
5002 rc = sqlite3PagerSnapshotOpen(pPager, pSnapshot);
5004 if( rc==SQLITE_OK ){
5005 rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
5006 sqlite3PagerSnapshotOpen(pPager, 0);
5008 if( bUnlock ){
5009 sqlite3PagerSnapshotUnlock(pPager);
5015 sqlite3_mutex_leave(db->mutex);
5016 #endif /* SQLITE_OMIT_WAL */
5017 return rc;
5021 ** Recover as many snapshots as possible from the wal file associated with
5022 ** schema zDb of database db.
5024 int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
5025 int rc = SQLITE_ERROR;
5026 #ifndef SQLITE_OMIT_WAL
5027 int iDb;
5029 #ifdef SQLITE_ENABLE_API_ARMOR
5030 if( !sqlite3SafetyCheckOk(db) ){
5031 return SQLITE_MISUSE_BKPT;
5033 #endif
5035 sqlite3_mutex_enter(db->mutex);
5036 iDb = sqlite3FindDbName(db, zDb);
5037 if( iDb==0 || iDb>1 ){
5038 Btree *pBt = db->aDb[iDb].pBt;
5039 if( SQLITE_TXN_NONE==sqlite3BtreeTxnState(pBt) ){
5040 rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
5041 if( rc==SQLITE_OK ){
5042 rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
5043 sqlite3BtreeCommit(pBt);
5047 sqlite3_mutex_leave(db->mutex);
5048 #endif /* SQLITE_OMIT_WAL */
5049 return rc;
5053 ** Free a snapshot handle obtained from sqlite3_snapshot_get().
5055 void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
5056 sqlite3_free(pSnapshot);
5058 #endif /* SQLITE_ENABLE_SNAPSHOT */
5060 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
5062 ** Given the name of a compile-time option, return true if that option
5063 ** was used and false if not.
5065 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
5066 ** is not required for a match.
5068 int sqlite3_compileoption_used(const char *zOptName){
5069 int i, n;
5070 int nOpt;
5071 const char **azCompileOpt;
5073 #ifdef SQLITE_ENABLE_API_ARMOR
5074 if( zOptName==0 ){
5075 (void)SQLITE_MISUSE_BKPT;
5076 return 0;
5078 #endif
5080 azCompileOpt = sqlite3CompileOptions(&nOpt);
5082 if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
5083 n = sqlite3Strlen30(zOptName);
5085 /* Since nOpt is normally in single digits, a linear search is
5086 ** adequate. No need for a binary search. */
5087 for(i=0; i<nOpt; i++){
5088 if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
5089 && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
5091 return 1;
5094 return 0;
5098 ** Return the N-th compile-time option string. If N is out of range,
5099 ** return a NULL pointer.
5101 const char *sqlite3_compileoption_get(int N){
5102 int nOpt;
5103 const char **azCompileOpt;
5104 azCompileOpt = sqlite3CompileOptions(&nOpt);
5105 if( N>=0 && N<nOpt ){
5106 return azCompileOpt[N];
5108 return 0;
5110 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */