Fix code indentation. No logic changes.
[sqlite.git] / src / main.c
blob3c8035c120ce960c8139a22f0270d1583cad3a0f
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
28 #ifdef SQLITE_ENABLE_JSON1
29 int sqlite3Json1Init(sqlite3*);
30 #endif
31 #ifdef SQLITE_ENABLE_STMTVTAB
32 int sqlite3StmtVtabInit(sqlite3*);
33 #endif
34 #ifdef SQLITE_ENABLE_FTS5
35 int sqlite3Fts5Init(sqlite3*);
36 #endif
38 #ifndef SQLITE_AMALGAMATION
39 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
40 ** contains the text of SQLITE_VERSION macro.
42 const char sqlite3_version[] = SQLITE_VERSION;
43 #endif
45 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
46 ** a pointer to the to the sqlite3_version[] string constant.
48 const char *sqlite3_libversion(void){ return sqlite3_version; }
50 /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
51 ** pointer to a string constant whose value is the same as the
52 ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
53 ** an edited copy of the amalgamation, then the last four characters of
54 ** the hash might be different from SQLITE_SOURCE_ID.
56 const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
58 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
59 ** returns an integer equal to SQLITE_VERSION_NUMBER.
61 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
63 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
64 ** zero if and only if SQLite was compiled with mutexing code omitted due to
65 ** the SQLITE_THREADSAFE compile-time option being set to 0.
67 int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
70 ** When compiling the test fixture or with debugging enabled (on Win32),
71 ** this variable being set to non-zero will cause OSTRACE macros to emit
72 ** extra diagnostic information.
74 #ifdef SQLITE_HAVE_OS_TRACE
75 # ifndef SQLITE_DEBUG_OS_TRACE
76 # define SQLITE_DEBUG_OS_TRACE 0
77 # endif
78 int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
79 #endif
81 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
83 ** If the following function pointer is not NULL and if
84 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
85 ** I/O active are written using this function. These messages
86 ** are intended for debugging activity only.
88 SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
89 #endif
92 ** If the following global variable points to a string which is the
93 ** name of a directory, then that directory will be used to store
94 ** temporary files.
96 ** See also the "PRAGMA temp_store_directory" SQL command.
98 char *sqlite3_temp_directory = 0;
101 ** If the following global variable points to a string which is the
102 ** name of a directory, then that directory will be used to store
103 ** all database files specified with a relative pathname.
105 ** See also the "PRAGMA data_store_directory" SQL command.
107 char *sqlite3_data_directory = 0;
110 ** Initialize SQLite.
112 ** This routine must be called to initialize the memory allocation,
113 ** VFS, and mutex subsystems prior to doing any serious work with
114 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
115 ** this routine will be called automatically by key routines such as
116 ** sqlite3_open().
118 ** This routine is a no-op except on its very first call for the process,
119 ** or for the first call after a call to sqlite3_shutdown.
121 ** The first thread to call this routine runs the initialization to
122 ** completion. If subsequent threads call this routine before the first
123 ** thread has finished the initialization process, then the subsequent
124 ** threads must block until the first thread finishes with the initialization.
126 ** The first thread might call this routine recursively. Recursive
127 ** calls to this routine should not block, of course. Otherwise the
128 ** initialization process would never complete.
130 ** Let X be the first thread to enter this routine. Let Y be some other
131 ** thread. Then while the initial invocation of this routine by X is
132 ** incomplete, it is required that:
134 ** * Calls to this routine from Y must block until the outer-most
135 ** call by X completes.
137 ** * Recursive calls to this routine from thread X return immediately
138 ** without blocking.
140 int sqlite3_initialize(void){
141 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
142 int rc; /* Result code */
143 #ifdef SQLITE_EXTRA_INIT
144 int bRunExtraInit = 0; /* Extra initialization needed */
145 #endif
147 #ifdef SQLITE_OMIT_WSD
148 rc = sqlite3_wsd_init(4096, 24);
149 if( rc!=SQLITE_OK ){
150 return rc;
152 #endif
154 /* If the following assert() fails on some obscure processor/compiler
155 ** combination, the work-around is to set the correct pointer
156 ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
157 assert( SQLITE_PTRSIZE==sizeof(char*) );
159 /* If SQLite is already completely initialized, then this call
160 ** to sqlite3_initialize() should be a no-op. But the initialization
161 ** must be complete. So isInit must not be set until the very end
162 ** of this routine.
164 if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
166 /* Make sure the mutex subsystem is initialized. If unable to
167 ** initialize the mutex subsystem, return early with the error.
168 ** If the system is so sick that we are unable to allocate a mutex,
169 ** there is not much SQLite is going to be able to do.
171 ** The mutex subsystem must take care of serializing its own
172 ** initialization.
174 rc = sqlite3MutexInit();
175 if( rc ) return rc;
177 /* Initialize the malloc() system and the recursive pInitMutex mutex.
178 ** This operation is protected by the STATIC_MASTER mutex. Note that
179 ** MutexAlloc() is called for a static mutex prior to initializing the
180 ** malloc subsystem - this implies that the allocation of a static
181 ** mutex must not require support from the malloc subsystem.
183 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
184 sqlite3_mutex_enter(pMaster);
185 sqlite3GlobalConfig.isMutexInit = 1;
186 if( !sqlite3GlobalConfig.isMallocInit ){
187 rc = sqlite3MallocInit();
189 if( rc==SQLITE_OK ){
190 sqlite3GlobalConfig.isMallocInit = 1;
191 if( !sqlite3GlobalConfig.pInitMutex ){
192 sqlite3GlobalConfig.pInitMutex =
193 sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
194 if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
195 rc = SQLITE_NOMEM_BKPT;
199 if( rc==SQLITE_OK ){
200 sqlite3GlobalConfig.nRefInitMutex++;
202 sqlite3_mutex_leave(pMaster);
204 /* If rc is not SQLITE_OK at this point, then either the malloc
205 ** subsystem could not be initialized or the system failed to allocate
206 ** the pInitMutex mutex. Return an error in either case. */
207 if( rc!=SQLITE_OK ){
208 return rc;
211 /* Do the rest of the initialization under the recursive mutex so
212 ** that we will be able to handle recursive calls into
213 ** sqlite3_initialize(). The recursive calls normally come through
214 ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
215 ** recursive calls might also be possible.
217 ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
218 ** to the xInit method, so the xInit method need not be threadsafe.
220 ** The following mutex is what serializes access to the appdef pcache xInit
221 ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
222 ** call to sqlite3PcacheInitialize().
224 sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
225 if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
226 sqlite3GlobalConfig.inProgress = 1;
227 #ifdef SQLITE_ENABLE_SQLLOG
229 extern void sqlite3_init_sqllog(void);
230 sqlite3_init_sqllog();
232 #endif
233 memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
234 sqlite3RegisterBuiltinFunctions();
235 if( sqlite3GlobalConfig.isPCacheInit==0 ){
236 rc = sqlite3PcacheInitialize();
238 if( rc==SQLITE_OK ){
239 sqlite3GlobalConfig.isPCacheInit = 1;
240 rc = sqlite3OsInit();
242 if( rc==SQLITE_OK ){
243 sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
244 sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
245 sqlite3GlobalConfig.isInit = 1;
246 #ifdef SQLITE_EXTRA_INIT
247 bRunExtraInit = 1;
248 #endif
250 sqlite3GlobalConfig.inProgress = 0;
252 sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
254 /* Go back under the static mutex and clean up the recursive
255 ** mutex to prevent a resource leak.
257 sqlite3_mutex_enter(pMaster);
258 sqlite3GlobalConfig.nRefInitMutex--;
259 if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
260 assert( sqlite3GlobalConfig.nRefInitMutex==0 );
261 sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
262 sqlite3GlobalConfig.pInitMutex = 0;
264 sqlite3_mutex_leave(pMaster);
266 /* The following is just a sanity check to make sure SQLite has
267 ** been compiled correctly. It is important to run this code, but
268 ** we don't want to run it too often and soak up CPU cycles for no
269 ** reason. So we run it once during initialization.
271 #ifndef NDEBUG
272 #ifndef SQLITE_OMIT_FLOATING_POINT
273 /* This section of code's only "output" is via assert() statements. */
274 if ( rc==SQLITE_OK ){
275 u64 x = (((u64)1)<<63)-1;
276 double y;
277 assert(sizeof(x)==8);
278 assert(sizeof(x)==sizeof(y));
279 memcpy(&y, &x, 8);
280 assert( sqlite3IsNaN(y) );
282 #endif
283 #endif
285 /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
286 ** compile-time option.
288 #ifdef SQLITE_EXTRA_INIT
289 if( bRunExtraInit ){
290 int SQLITE_EXTRA_INIT(const char*);
291 rc = SQLITE_EXTRA_INIT(0);
293 #endif
295 return rc;
299 ** Undo the effects of sqlite3_initialize(). Must not be called while
300 ** there are outstanding database connections or memory allocations or
301 ** while any part of SQLite is otherwise in use in any thread. This
302 ** routine is not threadsafe. But it is safe to invoke this routine
303 ** on when SQLite is already shut down. If SQLite is already shut down
304 ** when this routine is invoked, then this routine is a harmless no-op.
306 int sqlite3_shutdown(void){
307 #ifdef SQLITE_OMIT_WSD
308 int rc = sqlite3_wsd_init(4096, 24);
309 if( rc!=SQLITE_OK ){
310 return rc;
312 #endif
314 if( sqlite3GlobalConfig.isInit ){
315 #ifdef SQLITE_EXTRA_SHUTDOWN
316 void SQLITE_EXTRA_SHUTDOWN(void);
317 SQLITE_EXTRA_SHUTDOWN();
318 #endif
319 sqlite3_os_end();
320 sqlite3_reset_auto_extension();
321 sqlite3GlobalConfig.isInit = 0;
323 if( sqlite3GlobalConfig.isPCacheInit ){
324 sqlite3PcacheShutdown();
325 sqlite3GlobalConfig.isPCacheInit = 0;
327 if( sqlite3GlobalConfig.isMallocInit ){
328 sqlite3MallocEnd();
329 sqlite3GlobalConfig.isMallocInit = 0;
331 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
332 /* The heap subsystem has now been shutdown and these values are supposed
333 ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
334 ** which would rely on that heap subsystem; therefore, make sure these
335 ** values cannot refer to heap memory that was just invalidated when the
336 ** heap subsystem was shutdown. This is only done if the current call to
337 ** this function resulted in the heap subsystem actually being shutdown.
339 sqlite3_data_directory = 0;
340 sqlite3_temp_directory = 0;
341 #endif
343 if( sqlite3GlobalConfig.isMutexInit ){
344 sqlite3MutexEnd();
345 sqlite3GlobalConfig.isMutexInit = 0;
348 return SQLITE_OK;
352 ** This API allows applications to modify the global configuration of
353 ** the SQLite library at run-time.
355 ** This routine should only be called when there are no outstanding
356 ** database connections or memory allocations. This routine is not
357 ** threadsafe. Failure to heed these warnings can lead to unpredictable
358 ** behavior.
360 int sqlite3_config(int op, ...){
361 va_list ap;
362 int rc = SQLITE_OK;
364 /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
365 ** the SQLite library is in use. */
366 if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
368 va_start(ap, op);
369 switch( op ){
371 /* Mutex configuration options are only available in a threadsafe
372 ** compile.
374 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
375 case SQLITE_CONFIG_SINGLETHREAD: {
376 /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
377 ** Single-thread. */
378 sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
379 sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
380 break;
382 #endif
383 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
384 case SQLITE_CONFIG_MULTITHREAD: {
385 /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
386 ** Multi-thread. */
387 sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
388 sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
389 break;
391 #endif
392 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
393 case SQLITE_CONFIG_SERIALIZED: {
394 /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
395 ** Serialized. */
396 sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
397 sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
398 break;
400 #endif
401 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
402 case SQLITE_CONFIG_MUTEX: {
403 /* Specify an alternative mutex implementation */
404 sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
405 break;
407 #endif
408 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
409 case SQLITE_CONFIG_GETMUTEX: {
410 /* Retrieve the current mutex implementation */
411 *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
412 break;
414 #endif
416 case SQLITE_CONFIG_MALLOC: {
417 /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
418 ** single argument which is a pointer to an instance of the
419 ** sqlite3_mem_methods structure. The argument specifies alternative
420 ** low-level memory allocation routines to be used in place of the memory
421 ** allocation routines built into SQLite. */
422 sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
423 break;
425 case SQLITE_CONFIG_GETMALLOC: {
426 /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
427 ** single argument which is a pointer to an instance of the
428 ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
429 ** filled with the currently defined memory allocation routines. */
430 if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
431 *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
432 break;
434 case SQLITE_CONFIG_MEMSTATUS: {
435 /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
436 ** single argument of type int, interpreted as a boolean, which enables
437 ** or disables the collection of memory allocation statistics. */
438 sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
439 break;
441 case SQLITE_CONFIG_SMALL_MALLOC: {
442 sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
443 break;
445 case SQLITE_CONFIG_PAGECACHE: {
446 /* EVIDENCE-OF: R-18761-36601 There are three arguments to
447 ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
448 ** the size of each page cache line (sz), and the number of cache lines
449 ** (N). */
450 sqlite3GlobalConfig.pPage = va_arg(ap, void*);
451 sqlite3GlobalConfig.szPage = va_arg(ap, int);
452 sqlite3GlobalConfig.nPage = va_arg(ap, int);
453 break;
455 case SQLITE_CONFIG_PCACHE_HDRSZ: {
456 /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
457 ** a single parameter which is a pointer to an integer and writes into
458 ** that integer the number of extra bytes per page required for each page
459 ** in SQLITE_CONFIG_PAGECACHE. */
460 *va_arg(ap, int*) =
461 sqlite3HeaderSizeBtree() +
462 sqlite3HeaderSizePcache() +
463 sqlite3HeaderSizePcache1();
464 break;
467 case SQLITE_CONFIG_PCACHE: {
468 /* no-op */
469 break;
471 case SQLITE_CONFIG_GETPCACHE: {
472 /* now an error */
473 rc = SQLITE_ERROR;
474 break;
477 case SQLITE_CONFIG_PCACHE2: {
478 /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
479 ** single argument which is a pointer to an sqlite3_pcache_methods2
480 ** object. This object specifies the interface to a custom page cache
481 ** implementation. */
482 sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
483 break;
485 case SQLITE_CONFIG_GETPCACHE2: {
486 /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
487 ** single argument which is a pointer to an sqlite3_pcache_methods2
488 ** object. SQLite copies of the current page cache implementation into
489 ** that object. */
490 if( sqlite3GlobalConfig.pcache2.xInit==0 ){
491 sqlite3PCacheSetDefault();
493 *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
494 break;
497 /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
498 ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
499 ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
500 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
501 case SQLITE_CONFIG_HEAP: {
502 /* EVIDENCE-OF: R-19854-42126 There are three arguments to
503 ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
504 ** number of bytes in the memory buffer, and the minimum allocation size.
506 sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
507 sqlite3GlobalConfig.nHeap = va_arg(ap, int);
508 sqlite3GlobalConfig.mnReq = va_arg(ap, int);
510 if( sqlite3GlobalConfig.mnReq<1 ){
511 sqlite3GlobalConfig.mnReq = 1;
512 }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
513 /* cap min request size at 2^12 */
514 sqlite3GlobalConfig.mnReq = (1<<12);
517 if( sqlite3GlobalConfig.pHeap==0 ){
518 /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
519 ** is NULL, then SQLite reverts to using its default memory allocator
520 ** (the system malloc() implementation), undoing any prior invocation of
521 ** SQLITE_CONFIG_MALLOC.
523 ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
524 ** revert to its default implementation when sqlite3_initialize() is run
526 memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
527 }else{
528 /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
529 ** alternative memory allocator is engaged to handle all of SQLites
530 ** memory allocation needs. */
531 #ifdef SQLITE_ENABLE_MEMSYS3
532 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
533 #endif
534 #ifdef SQLITE_ENABLE_MEMSYS5
535 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
536 #endif
538 break;
540 #endif
542 case SQLITE_CONFIG_LOOKASIDE: {
543 sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
544 sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
545 break;
548 /* Record a pointer to the logger function and its first argument.
549 ** The default is NULL. Logging is disabled if the function pointer is
550 ** NULL.
552 case SQLITE_CONFIG_LOG: {
553 /* MSVC is picky about pulling func ptrs from va lists.
554 ** http://support.microsoft.com/kb/47961
555 ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
557 typedef void(*LOGFUNC_t)(void*,int,const char*);
558 sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
559 sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
560 break;
563 /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
564 ** can be changed at start-time using the
565 ** sqlite3_config(SQLITE_CONFIG_URI,1) or
566 ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
568 case SQLITE_CONFIG_URI: {
569 /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
570 ** argument of type int. If non-zero, then URI handling is globally
571 ** enabled. If the parameter is zero, then URI handling is globally
572 ** disabled. */
573 sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
574 break;
577 case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
578 /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
579 ** option takes a single integer argument which is interpreted as a
580 ** boolean in order to enable or disable the use of covering indices for
581 ** full table scans in the query optimizer. */
582 sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
583 break;
586 #ifdef SQLITE_ENABLE_SQLLOG
587 case SQLITE_CONFIG_SQLLOG: {
588 typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
589 sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
590 sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
591 break;
593 #endif
595 case SQLITE_CONFIG_MMAP_SIZE: {
596 /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
597 ** integer (sqlite3_int64) values that are the default mmap size limit
598 ** (the default setting for PRAGMA mmap_size) and the maximum allowed
599 ** mmap size limit. */
600 sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
601 sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
602 /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
603 ** negative, then that argument is changed to its compile-time default.
605 ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
606 ** silently truncated if necessary so that it does not exceed the
607 ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
608 ** compile-time option.
610 if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
611 mxMmap = SQLITE_MAX_MMAP_SIZE;
613 if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
614 if( szMmap>mxMmap) szMmap = mxMmap;
615 sqlite3GlobalConfig.mxMmap = mxMmap;
616 sqlite3GlobalConfig.szMmap = szMmap;
617 break;
620 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
621 case SQLITE_CONFIG_WIN32_HEAPSIZE: {
622 /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
623 ** unsigned integer value that specifies the maximum size of the created
624 ** heap. */
625 sqlite3GlobalConfig.nHeap = va_arg(ap, int);
626 break;
628 #endif
630 case SQLITE_CONFIG_PMASZ: {
631 sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
632 break;
635 case SQLITE_CONFIG_STMTJRNL_SPILL: {
636 sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
637 break;
640 default: {
641 rc = SQLITE_ERROR;
642 break;
645 va_end(ap);
646 return rc;
650 ** Set up the lookaside buffers for a database connection.
651 ** Return SQLITE_OK on success.
652 ** If lookaside is already active, return SQLITE_BUSY.
654 ** The sz parameter is the number of bytes in each lookaside slot.
655 ** The cnt parameter is the number of slots. If pStart is NULL the
656 ** space for the lookaside memory is obtained from sqlite3_malloc().
657 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
658 ** the lookaside memory.
660 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
661 #ifndef SQLITE_OMIT_LOOKASIDE
662 void *pStart;
664 if( sqlite3LookasideUsed(db,0)>0 ){
665 return SQLITE_BUSY;
667 /* Free any existing lookaside buffer for this handle before
668 ** allocating a new one so we don't have to have space for
669 ** both at the same time.
671 if( db->lookaside.bMalloced ){
672 sqlite3_free(db->lookaside.pStart);
674 /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
675 ** than a pointer to be useful.
677 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
678 if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
679 if( cnt<0 ) cnt = 0;
680 if( sz==0 || cnt==0 ){
681 sz = 0;
682 pStart = 0;
683 }else if( pBuf==0 ){
684 sqlite3BeginBenignMalloc();
685 pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
686 sqlite3EndBenignMalloc();
687 if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
688 }else{
689 pStart = pBuf;
691 db->lookaside.pStart = pStart;
692 db->lookaside.pInit = 0;
693 db->lookaside.pFree = 0;
694 db->lookaside.sz = (u16)sz;
695 if( pStart ){
696 int i;
697 LookasideSlot *p;
698 assert( sz > (int)sizeof(LookasideSlot*) );
699 db->lookaside.nSlot = cnt;
700 p = (LookasideSlot*)pStart;
701 for(i=cnt-1; i>=0; i--){
702 p->pNext = db->lookaside.pInit;
703 db->lookaside.pInit = p;
704 p = (LookasideSlot*)&((u8*)p)[sz];
706 db->lookaside.pEnd = p;
707 db->lookaside.bDisable = 0;
708 db->lookaside.bMalloced = pBuf==0 ?1:0;
709 }else{
710 db->lookaside.pStart = db;
711 db->lookaside.pEnd = db;
712 db->lookaside.bDisable = 1;
713 db->lookaside.bMalloced = 0;
714 db->lookaside.nSlot = 0;
716 #endif /* SQLITE_OMIT_LOOKASIDE */
717 return SQLITE_OK;
721 ** Return the mutex associated with a database connection.
723 sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
724 #ifdef SQLITE_ENABLE_API_ARMOR
725 if( !sqlite3SafetyCheckOk(db) ){
726 (void)SQLITE_MISUSE_BKPT;
727 return 0;
729 #endif
730 return db->mutex;
734 ** Free up as much memory as we can from the given database
735 ** connection.
737 int sqlite3_db_release_memory(sqlite3 *db){
738 int i;
740 #ifdef SQLITE_ENABLE_API_ARMOR
741 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
742 #endif
743 sqlite3_mutex_enter(db->mutex);
744 sqlite3BtreeEnterAll(db);
745 for(i=0; i<db->nDb; i++){
746 Btree *pBt = db->aDb[i].pBt;
747 if( pBt ){
748 Pager *pPager = sqlite3BtreePager(pBt);
749 sqlite3PagerShrink(pPager);
752 sqlite3BtreeLeaveAll(db);
753 sqlite3_mutex_leave(db->mutex);
754 return SQLITE_OK;
758 ** Flush any dirty pages in the pager-cache for any attached database
759 ** to disk.
761 int sqlite3_db_cacheflush(sqlite3 *db){
762 int i;
763 int rc = SQLITE_OK;
764 int bSeenBusy = 0;
766 #ifdef SQLITE_ENABLE_API_ARMOR
767 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
768 #endif
769 sqlite3_mutex_enter(db->mutex);
770 sqlite3BtreeEnterAll(db);
771 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
772 Btree *pBt = db->aDb[i].pBt;
773 if( pBt && sqlite3BtreeIsInTrans(pBt) ){
774 Pager *pPager = sqlite3BtreePager(pBt);
775 rc = sqlite3PagerFlush(pPager);
776 if( rc==SQLITE_BUSY ){
777 bSeenBusy = 1;
778 rc = SQLITE_OK;
782 sqlite3BtreeLeaveAll(db);
783 sqlite3_mutex_leave(db->mutex);
784 return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
788 ** Configuration settings for an individual database connection
790 int sqlite3_db_config(sqlite3 *db, int op, ...){
791 va_list ap;
792 int rc;
793 va_start(ap, op);
794 switch( op ){
795 case SQLITE_DBCONFIG_MAINDBNAME: {
796 /* IMP: R-06824-28531 */
797 /* IMP: R-36257-52125 */
798 db->aDb[0].zDbSName = va_arg(ap,char*);
799 rc = SQLITE_OK;
800 break;
802 case SQLITE_DBCONFIG_LOOKASIDE: {
803 void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
804 int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
805 int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
806 rc = setupLookaside(db, pBuf, sz, cnt);
807 break;
809 default: {
810 static const struct {
811 int op; /* The opcode */
812 u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
813 } aFlagOp[] = {
814 { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
815 { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
816 { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
817 { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension },
818 { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose },
819 { SQLITE_DBCONFIG_ENABLE_QPSG, SQLITE_EnableQPSG },
820 { SQLITE_DBCONFIG_TRIGGER_EQP, SQLITE_TriggerEQP },
822 unsigned int i;
823 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
824 for(i=0; i<ArraySize(aFlagOp); i++){
825 if( aFlagOp[i].op==op ){
826 int onoff = va_arg(ap, int);
827 int *pRes = va_arg(ap, int*);
828 u32 oldFlags = db->flags;
829 if( onoff>0 ){
830 db->flags |= aFlagOp[i].mask;
831 }else if( onoff==0 ){
832 db->flags &= ~aFlagOp[i].mask;
834 if( oldFlags!=db->flags ){
835 sqlite3ExpirePreparedStatements(db);
837 if( pRes ){
838 *pRes = (db->flags & aFlagOp[i].mask)!=0;
840 rc = SQLITE_OK;
841 break;
844 break;
847 va_end(ap);
848 return rc;
853 ** Return true if the buffer z[0..n-1] contains all spaces.
855 static int allSpaces(const char *z, int n){
856 while( n>0 && z[n-1]==' ' ){ n--; }
857 return n==0;
861 ** This is the default collating function named "BINARY" which is always
862 ** available.
864 ** If the padFlag argument is not NULL then space padding at the end
865 ** of strings is ignored. This implements the RTRIM collation.
867 static int binCollFunc(
868 void *padFlag,
869 int nKey1, const void *pKey1,
870 int nKey2, const void *pKey2
872 int rc, n;
873 n = nKey1<nKey2 ? nKey1 : nKey2;
874 /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
875 ** strings byte by byte using the memcmp() function from the standard C
876 ** library. */
877 assert( pKey1 && pKey2 );
878 rc = memcmp(pKey1, pKey2, n);
879 if( rc==0 ){
880 if( padFlag
881 && allSpaces(((char*)pKey1)+n, nKey1-n)
882 && allSpaces(((char*)pKey2)+n, nKey2-n)
884 /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
885 ** spaces at the end of either string do not change the result. In other
886 ** words, strings will compare equal to one another as long as they
887 ** differ only in the number of spaces at the end.
889 }else{
890 rc = nKey1 - nKey2;
893 return rc;
897 ** Another built-in collating sequence: NOCASE.
899 ** This collating sequence is intended to be used for "case independent
900 ** comparison". SQLite's knowledge of upper and lower case equivalents
901 ** extends only to the 26 characters used in the English language.
903 ** At the moment there is only a UTF-8 implementation.
905 static int nocaseCollatingFunc(
906 void *NotUsed,
907 int nKey1, const void *pKey1,
908 int nKey2, const void *pKey2
910 int r = sqlite3StrNICmp(
911 (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
912 UNUSED_PARAMETER(NotUsed);
913 if( 0==r ){
914 r = nKey1-nKey2;
916 return r;
920 ** Return the ROWID of the most recent insert
922 sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
923 #ifdef SQLITE_ENABLE_API_ARMOR
924 if( !sqlite3SafetyCheckOk(db) ){
925 (void)SQLITE_MISUSE_BKPT;
926 return 0;
928 #endif
929 return db->lastRowid;
933 ** Set the value returned by the sqlite3_last_insert_rowid() API function.
935 void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
936 #ifdef SQLITE_ENABLE_API_ARMOR
937 if( !sqlite3SafetyCheckOk(db) ){
938 (void)SQLITE_MISUSE_BKPT;
939 return;
941 #endif
942 sqlite3_mutex_enter(db->mutex);
943 db->lastRowid = iRowid;
944 sqlite3_mutex_leave(db->mutex);
948 ** Return the number of changes in the most recent call to sqlite3_exec().
950 int sqlite3_changes(sqlite3 *db){
951 #ifdef SQLITE_ENABLE_API_ARMOR
952 if( !sqlite3SafetyCheckOk(db) ){
953 (void)SQLITE_MISUSE_BKPT;
954 return 0;
956 #endif
957 return db->nChange;
961 ** Return the number of changes since the database handle was opened.
963 int sqlite3_total_changes(sqlite3 *db){
964 #ifdef SQLITE_ENABLE_API_ARMOR
965 if( !sqlite3SafetyCheckOk(db) ){
966 (void)SQLITE_MISUSE_BKPT;
967 return 0;
969 #endif
970 return db->nTotalChange;
974 ** Close all open savepoints. This function only manipulates fields of the
975 ** database handle object, it does not close any savepoints that may be open
976 ** at the b-tree/pager level.
978 void sqlite3CloseSavepoints(sqlite3 *db){
979 while( db->pSavepoint ){
980 Savepoint *pTmp = db->pSavepoint;
981 db->pSavepoint = pTmp->pNext;
982 sqlite3DbFree(db, pTmp);
984 db->nSavepoint = 0;
985 db->nStatement = 0;
986 db->isTransactionSavepoint = 0;
990 ** Invoke the destructor function associated with FuncDef p, if any. Except,
991 ** if this is not the last copy of the function, do not invoke it. Multiple
992 ** copies of a single function are created when create_function() is called
993 ** with SQLITE_ANY as the encoding.
995 static void functionDestroy(sqlite3 *db, FuncDef *p){
996 FuncDestructor *pDestructor = p->u.pDestructor;
997 if( pDestructor ){
998 pDestructor->nRef--;
999 if( pDestructor->nRef==0 ){
1000 pDestructor->xDestroy(pDestructor->pUserData);
1001 sqlite3DbFree(db, pDestructor);
1007 ** Disconnect all sqlite3_vtab objects that belong to database connection
1008 ** db. This is called when db is being closed.
1010 static void disconnectAllVtab(sqlite3 *db){
1011 #ifndef SQLITE_OMIT_VIRTUALTABLE
1012 int i;
1013 HashElem *p;
1014 sqlite3BtreeEnterAll(db);
1015 for(i=0; i<db->nDb; i++){
1016 Schema *pSchema = db->aDb[i].pSchema;
1017 if( db->aDb[i].pSchema ){
1018 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
1019 Table *pTab = (Table *)sqliteHashData(p);
1020 if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
1024 for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
1025 Module *pMod = (Module *)sqliteHashData(p);
1026 if( pMod->pEpoTab ){
1027 sqlite3VtabDisconnect(db, pMod->pEpoTab);
1030 sqlite3VtabUnlockList(db);
1031 sqlite3BtreeLeaveAll(db);
1032 #else
1033 UNUSED_PARAMETER(db);
1034 #endif
1038 ** Return TRUE if database connection db has unfinalized prepared
1039 ** statements or unfinished sqlite3_backup objects.
1041 static int connectionIsBusy(sqlite3 *db){
1042 int j;
1043 assert( sqlite3_mutex_held(db->mutex) );
1044 if( db->pVdbe ) return 1;
1045 for(j=0; j<db->nDb; j++){
1046 Btree *pBt = db->aDb[j].pBt;
1047 if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
1049 return 0;
1053 ** Close an existing SQLite database
1055 static int sqlite3Close(sqlite3 *db, int forceZombie){
1056 if( !db ){
1057 /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
1058 ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
1059 return SQLITE_OK;
1061 if( !sqlite3SafetyCheckSickOrOk(db) ){
1062 return SQLITE_MISUSE_BKPT;
1064 sqlite3_mutex_enter(db->mutex);
1065 if( db->mTrace & SQLITE_TRACE_CLOSE ){
1066 db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
1069 /* Force xDisconnect calls on all virtual tables */
1070 disconnectAllVtab(db);
1072 /* If a transaction is open, the disconnectAllVtab() call above
1073 ** will not have called the xDisconnect() method on any virtual
1074 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
1075 ** call will do so. We need to do this before the check for active
1076 ** SQL statements below, as the v-table implementation may be storing
1077 ** some prepared statements internally.
1079 sqlite3VtabRollback(db);
1081 /* Legacy behavior (sqlite3_close() behavior) is to return
1082 ** SQLITE_BUSY if the connection can not be closed immediately.
1084 if( !forceZombie && connectionIsBusy(db) ){
1085 sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
1086 "statements or unfinished backups");
1087 sqlite3_mutex_leave(db->mutex);
1088 return SQLITE_BUSY;
1091 #ifdef SQLITE_ENABLE_SQLLOG
1092 if( sqlite3GlobalConfig.xSqllog ){
1093 /* Closing the handle. Fourth parameter is passed the value 2. */
1094 sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
1096 #endif
1098 /* Convert the connection into a zombie and then close it.
1100 db->magic = SQLITE_MAGIC_ZOMBIE;
1101 sqlite3LeaveMutexAndCloseZombie(db);
1102 return SQLITE_OK;
1106 ** Two variations on the public interface for closing a database
1107 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
1108 ** leaves the connection option if there are unfinalized prepared
1109 ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
1110 ** version forces the connection to become a zombie if there are
1111 ** unclosed resources, and arranges for deallocation when the last
1112 ** prepare statement or sqlite3_backup closes.
1114 int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
1115 int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
1119 ** Close the mutex on database connection db.
1121 ** Furthermore, if database connection db is a zombie (meaning that there
1122 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
1123 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
1124 ** finished, then free all resources.
1126 void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
1127 HashElem *i; /* Hash table iterator */
1128 int j;
1130 /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
1131 ** or if the connection has not yet been closed by sqlite3_close_v2(),
1132 ** then just leave the mutex and return.
1134 if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
1135 sqlite3_mutex_leave(db->mutex);
1136 return;
1139 /* If we reach this point, it means that the database connection has
1140 ** closed all sqlite3_stmt and sqlite3_backup objects and has been
1141 ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
1142 ** go ahead and free all resources.
1145 /* If a transaction is open, roll it back. This also ensures that if
1146 ** any database schemas have been modified by an uncommitted transaction
1147 ** they are reset. And that the required b-tree mutex is held to make
1148 ** the pager rollback and schema reset an atomic operation. */
1149 sqlite3RollbackAll(db, SQLITE_OK);
1151 /* Free any outstanding Savepoint structures. */
1152 sqlite3CloseSavepoints(db);
1154 /* Close all database connections */
1155 for(j=0; j<db->nDb; j++){
1156 struct Db *pDb = &db->aDb[j];
1157 if( pDb->pBt ){
1158 sqlite3BtreeClose(pDb->pBt);
1159 pDb->pBt = 0;
1160 if( j!=1 ){
1161 pDb->pSchema = 0;
1165 /* Clear the TEMP schema separately and last */
1166 if( db->aDb[1].pSchema ){
1167 sqlite3SchemaClear(db->aDb[1].pSchema);
1169 sqlite3VtabUnlockList(db);
1171 /* Free up the array of auxiliary databases */
1172 sqlite3CollapseDatabaseArray(db);
1173 assert( db->nDb<=2 );
1174 assert( db->aDb==db->aDbStatic );
1176 /* Tell the code in notify.c that the connection no longer holds any
1177 ** locks and does not require any further unlock-notify callbacks.
1179 sqlite3ConnectionClosed(db);
1181 for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
1182 FuncDef *pNext, *p;
1183 p = sqliteHashData(i);
1185 functionDestroy(db, p);
1186 pNext = p->pNext;
1187 sqlite3DbFree(db, p);
1188 p = pNext;
1189 }while( p );
1191 sqlite3HashClear(&db->aFunc);
1192 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
1193 CollSeq *pColl = (CollSeq *)sqliteHashData(i);
1194 /* Invoke any destructors registered for collation sequence user data. */
1195 for(j=0; j<3; j++){
1196 if( pColl[j].xDel ){
1197 pColl[j].xDel(pColl[j].pUser);
1200 sqlite3DbFree(db, pColl);
1202 sqlite3HashClear(&db->aCollSeq);
1203 #ifndef SQLITE_OMIT_VIRTUALTABLE
1204 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
1205 Module *pMod = (Module *)sqliteHashData(i);
1206 if( pMod->xDestroy ){
1207 pMod->xDestroy(pMod->pAux);
1209 sqlite3VtabEponymousTableClear(db, pMod);
1210 sqlite3DbFree(db, pMod);
1212 sqlite3HashClear(&db->aModule);
1213 #endif
1215 sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
1216 sqlite3ValueFree(db->pErr);
1217 sqlite3CloseExtensions(db);
1218 #if SQLITE_USER_AUTHENTICATION
1219 sqlite3_free(db->auth.zAuthUser);
1220 sqlite3_free(db->auth.zAuthPW);
1221 #endif
1223 db->magic = SQLITE_MAGIC_ERROR;
1225 /* The temp-database schema is allocated differently from the other schema
1226 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
1227 ** So it needs to be freed here. Todo: Why not roll the temp schema into
1228 ** the same sqliteMalloc() as the one that allocates the database
1229 ** structure?
1231 sqlite3DbFree(db, db->aDb[1].pSchema);
1232 sqlite3_mutex_leave(db->mutex);
1233 db->magic = SQLITE_MAGIC_CLOSED;
1234 sqlite3_mutex_free(db->mutex);
1235 assert( sqlite3LookasideUsed(db,0)==0 );
1236 if( db->lookaside.bMalloced ){
1237 sqlite3_free(db->lookaside.pStart);
1239 sqlite3_free(db);
1243 ** Rollback all database files. If tripCode is not SQLITE_OK, then
1244 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
1245 ** breaker") and made to return tripCode if there are any further
1246 ** attempts to use that cursor. Read cursors remain open and valid
1247 ** but are "saved" in case the table pages are moved around.
1249 void sqlite3RollbackAll(sqlite3 *db, int tripCode){
1250 int i;
1251 int inTrans = 0;
1252 int schemaChange;
1253 assert( sqlite3_mutex_held(db->mutex) );
1254 sqlite3BeginBenignMalloc();
1256 /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
1257 ** This is important in case the transaction being rolled back has
1258 ** modified the database schema. If the b-tree mutexes are not taken
1259 ** here, then another shared-cache connection might sneak in between
1260 ** the database rollback and schema reset, which can cause false
1261 ** corruption reports in some cases. */
1262 sqlite3BtreeEnterAll(db);
1263 schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
1265 for(i=0; i<db->nDb; i++){
1266 Btree *p = db->aDb[i].pBt;
1267 if( p ){
1268 if( sqlite3BtreeIsInTrans(p) ){
1269 inTrans = 1;
1271 sqlite3BtreeRollback(p, tripCode, !schemaChange);
1274 sqlite3VtabRollback(db);
1275 sqlite3EndBenignMalloc();
1277 if( (db->mDbFlags&DBFLAG_SchemaChange)!=0 && db->init.busy==0 ){
1278 sqlite3ExpirePreparedStatements(db);
1279 sqlite3ResetAllSchemasOfConnection(db);
1281 sqlite3BtreeLeaveAll(db);
1283 /* Any deferred constraint violations have now been resolved. */
1284 db->nDeferredCons = 0;
1285 db->nDeferredImmCons = 0;
1286 db->flags &= ~SQLITE_DeferFKs;
1288 /* If one has been configured, invoke the rollback-hook callback */
1289 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
1290 db->xRollbackCallback(db->pRollbackArg);
1295 ** Return a static string containing the name corresponding to the error code
1296 ** specified in the argument.
1298 #if defined(SQLITE_NEED_ERR_NAME)
1299 const char *sqlite3ErrName(int rc){
1300 const char *zName = 0;
1301 int i, origRc = rc;
1302 for(i=0; i<2 && zName==0; i++, rc &= 0xff){
1303 switch( rc ){
1304 case SQLITE_OK: zName = "SQLITE_OK"; break;
1305 case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
1306 case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
1307 case SQLITE_PERM: zName = "SQLITE_PERM"; break;
1308 case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
1309 case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
1310 case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
1311 case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
1312 case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
1313 case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
1314 case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
1315 case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
1316 case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
1317 case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
1318 case SQLITE_READONLY_CANTINIT: zName = "SQLITE_READONLY_CANTINIT"; break;
1319 case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
1320 case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
1321 case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
1322 case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
1323 case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
1324 case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
1325 case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
1326 case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
1327 case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
1328 case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
1329 case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
1330 case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
1331 case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
1332 case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
1333 case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
1334 case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
1335 case SQLITE_IOERR_CHECKRESERVEDLOCK:
1336 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
1337 case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
1338 case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
1339 case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
1340 case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
1341 case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
1342 case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
1343 case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
1344 case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
1345 case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
1346 case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
1347 case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
1348 case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
1349 case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
1350 case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
1351 case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
1352 case SQLITE_FULL: zName = "SQLITE_FULL"; break;
1353 case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
1354 case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
1355 case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
1356 case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
1357 case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
1358 case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
1359 case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
1360 case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
1361 case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
1362 case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
1363 case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
1364 case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
1365 case SQLITE_CONSTRAINT_FOREIGNKEY:
1366 zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
1367 case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
1368 case SQLITE_CONSTRAINT_PRIMARYKEY:
1369 zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
1370 case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
1371 case SQLITE_CONSTRAINT_COMMITHOOK:
1372 zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
1373 case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
1374 case SQLITE_CONSTRAINT_FUNCTION:
1375 zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
1376 case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
1377 case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
1378 case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
1379 case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
1380 case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
1381 case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
1382 case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
1383 case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
1384 case SQLITE_ROW: zName = "SQLITE_ROW"; break;
1385 case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
1386 case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
1387 case SQLITE_NOTICE_RECOVER_ROLLBACK:
1388 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
1389 case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
1390 case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
1391 case SQLITE_DONE: zName = "SQLITE_DONE"; break;
1394 if( zName==0 ){
1395 static char zBuf[50];
1396 sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
1397 zName = zBuf;
1399 return zName;
1401 #endif
1404 ** Return a static string that describes the kind of error specified in the
1405 ** argument.
1407 const char *sqlite3ErrStr(int rc){
1408 static const char* const aMsg[] = {
1409 /* SQLITE_OK */ "not an error",
1410 /* SQLITE_ERROR */ "SQL logic error",
1411 /* SQLITE_INTERNAL */ 0,
1412 /* SQLITE_PERM */ "access permission denied",
1413 /* SQLITE_ABORT */ "query aborted",
1414 /* SQLITE_BUSY */ "database is locked",
1415 /* SQLITE_LOCKED */ "database table is locked",
1416 /* SQLITE_NOMEM */ "out of memory",
1417 /* SQLITE_READONLY */ "attempt to write a readonly database",
1418 /* SQLITE_INTERRUPT */ "interrupted",
1419 /* SQLITE_IOERR */ "disk I/O error",
1420 /* SQLITE_CORRUPT */ "database disk image is malformed",
1421 /* SQLITE_NOTFOUND */ "unknown operation",
1422 /* SQLITE_FULL */ "database or disk is full",
1423 /* SQLITE_CANTOPEN */ "unable to open database file",
1424 /* SQLITE_PROTOCOL */ "locking protocol",
1425 /* SQLITE_EMPTY */ 0,
1426 /* SQLITE_SCHEMA */ "database schema has changed",
1427 /* SQLITE_TOOBIG */ "string or blob too big",
1428 /* SQLITE_CONSTRAINT */ "constraint failed",
1429 /* SQLITE_MISMATCH */ "datatype mismatch",
1430 /* SQLITE_MISUSE */ "bad parameter or other API misuse",
1431 #ifdef SQLITE_DISABLE_LFS
1432 /* SQLITE_NOLFS */ "large file support is disabled",
1433 #else
1434 /* SQLITE_NOLFS */ 0,
1435 #endif
1436 /* SQLITE_AUTH */ "authorization denied",
1437 /* SQLITE_FORMAT */ 0,
1438 /* SQLITE_RANGE */ "column index out of range",
1439 /* SQLITE_NOTADB */ "file is not a database",
1441 const char *zErr = "unknown error";
1442 switch( rc ){
1443 case SQLITE_ABORT_ROLLBACK: {
1444 zErr = "abort due to ROLLBACK";
1445 break;
1447 default: {
1448 rc &= 0xff;
1449 if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
1450 zErr = aMsg[rc];
1452 break;
1455 return zErr;
1459 ** This routine implements a busy callback that sleeps and tries
1460 ** again until a timeout value is reached. The timeout value is
1461 ** an integer number of milliseconds passed in as the first
1462 ** argument.
1464 static int sqliteDefaultBusyCallback(
1465 void *ptr, /* Database connection */
1466 int count /* Number of times table has been busy */
1468 #if SQLITE_OS_WIN || HAVE_USLEEP
1469 static const u8 delays[] =
1470 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
1471 static const u8 totals[] =
1472 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
1473 # define NDELAY ArraySize(delays)
1474 sqlite3 *db = (sqlite3 *)ptr;
1475 int timeout = db->busyTimeout;
1476 int delay, prior;
1478 assert( count>=0 );
1479 if( count < NDELAY ){
1480 delay = delays[count];
1481 prior = totals[count];
1482 }else{
1483 delay = delays[NDELAY-1];
1484 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
1486 if( prior + delay > timeout ){
1487 delay = timeout - prior;
1488 if( delay<=0 ) return 0;
1490 sqlite3OsSleep(db->pVfs, delay*1000);
1491 return 1;
1492 #else
1493 sqlite3 *db = (sqlite3 *)ptr;
1494 int timeout = ((sqlite3 *)ptr)->busyTimeout;
1495 if( (count+1)*1000 > timeout ){
1496 return 0;
1498 sqlite3OsSleep(db->pVfs, 1000000);
1499 return 1;
1500 #endif
1504 ** Invoke the given busy handler.
1506 ** This routine is called when an operation failed with a lock.
1507 ** If this routine returns non-zero, the lock is retried. If it
1508 ** returns 0, the operation aborts with an SQLITE_BUSY error.
1510 int sqlite3InvokeBusyHandler(BusyHandler *p){
1511 int rc;
1512 if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
1513 rc = p->xFunc(p->pArg, p->nBusy);
1514 if( rc==0 ){
1515 p->nBusy = -1;
1516 }else{
1517 p->nBusy++;
1519 return rc;
1523 ** This routine sets the busy callback for an Sqlite database to the
1524 ** given callback function with the given argument.
1526 int sqlite3_busy_handler(
1527 sqlite3 *db,
1528 int (*xBusy)(void*,int),
1529 void *pArg
1531 #ifdef SQLITE_ENABLE_API_ARMOR
1532 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
1533 #endif
1534 sqlite3_mutex_enter(db->mutex);
1535 db->busyHandler.xFunc = xBusy;
1536 db->busyHandler.pArg = pArg;
1537 db->busyHandler.nBusy = 0;
1538 db->busyTimeout = 0;
1539 sqlite3_mutex_leave(db->mutex);
1540 return SQLITE_OK;
1543 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1545 ** This routine sets the progress callback for an Sqlite database to the
1546 ** given callback function with the given argument. The progress callback will
1547 ** be invoked every nOps opcodes.
1549 void sqlite3_progress_handler(
1550 sqlite3 *db,
1551 int nOps,
1552 int (*xProgress)(void*),
1553 void *pArg
1555 #ifdef SQLITE_ENABLE_API_ARMOR
1556 if( !sqlite3SafetyCheckOk(db) ){
1557 (void)SQLITE_MISUSE_BKPT;
1558 return;
1560 #endif
1561 sqlite3_mutex_enter(db->mutex);
1562 if( nOps>0 ){
1563 db->xProgress = xProgress;
1564 db->nProgressOps = (unsigned)nOps;
1565 db->pProgressArg = pArg;
1566 }else{
1567 db->xProgress = 0;
1568 db->nProgressOps = 0;
1569 db->pProgressArg = 0;
1571 sqlite3_mutex_leave(db->mutex);
1573 #endif
1577 ** This routine installs a default busy handler that waits for the
1578 ** specified number of milliseconds before returning 0.
1580 int sqlite3_busy_timeout(sqlite3 *db, int ms){
1581 #ifdef SQLITE_ENABLE_API_ARMOR
1582 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
1583 #endif
1584 if( ms>0 ){
1585 sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
1586 db->busyTimeout = ms;
1587 }else{
1588 sqlite3_busy_handler(db, 0, 0);
1590 return SQLITE_OK;
1594 ** Cause any pending operation to stop at its earliest opportunity.
1596 void sqlite3_interrupt(sqlite3 *db){
1597 #ifdef SQLITE_ENABLE_API_ARMOR
1598 if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){
1599 (void)SQLITE_MISUSE_BKPT;
1600 return;
1602 #endif
1603 db->u1.isInterrupted = 1;
1608 ** This function is exactly the same as sqlite3_create_function(), except
1609 ** that it is designed to be called by internal code. The difference is
1610 ** that if a malloc() fails in sqlite3_create_function(), an error code
1611 ** is returned and the mallocFailed flag cleared.
1613 int sqlite3CreateFunc(
1614 sqlite3 *db,
1615 const char *zFunctionName,
1616 int nArg,
1617 int enc,
1618 void *pUserData,
1619 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
1620 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
1621 void (*xFinal)(sqlite3_context*),
1622 FuncDestructor *pDestructor
1624 FuncDef *p;
1625 int nName;
1626 int extraFlags;
1628 assert( sqlite3_mutex_held(db->mutex) );
1629 if( zFunctionName==0 ||
1630 (xSFunc && (xFinal || xStep)) ||
1631 (!xSFunc && (xFinal && !xStep)) ||
1632 (!xSFunc && (!xFinal && xStep)) ||
1633 (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
1634 (255<(nName = sqlite3Strlen30( zFunctionName))) ){
1635 return SQLITE_MISUSE_BKPT;
1638 assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
1639 extraFlags = enc & SQLITE_DETERMINISTIC;
1640 enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
1642 #ifndef SQLITE_OMIT_UTF16
1643 /* If SQLITE_UTF16 is specified as the encoding type, transform this
1644 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
1645 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
1647 ** If SQLITE_ANY is specified, add three versions of the function
1648 ** to the hash table.
1650 if( enc==SQLITE_UTF16 ){
1651 enc = SQLITE_UTF16NATIVE;
1652 }else if( enc==SQLITE_ANY ){
1653 int rc;
1654 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
1655 pUserData, xSFunc, xStep, xFinal, pDestructor);
1656 if( rc==SQLITE_OK ){
1657 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
1658 pUserData, xSFunc, xStep, xFinal, pDestructor);
1660 if( rc!=SQLITE_OK ){
1661 return rc;
1663 enc = SQLITE_UTF16BE;
1665 #else
1666 enc = SQLITE_UTF8;
1667 #endif
1669 /* Check if an existing function is being overridden or deleted. If so,
1670 ** and there are active VMs, then return SQLITE_BUSY. If a function
1671 ** is being overridden/deleted but there are no active VMs, allow the
1672 ** operation to continue but invalidate all precompiled statements.
1674 p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
1675 if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
1676 if( db->nVdbeActive ){
1677 sqlite3ErrorWithMsg(db, SQLITE_BUSY,
1678 "unable to delete/modify user-function due to active statements");
1679 assert( !db->mallocFailed );
1680 return SQLITE_BUSY;
1681 }else{
1682 sqlite3ExpirePreparedStatements(db);
1686 p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
1687 assert(p || db->mallocFailed);
1688 if( !p ){
1689 return SQLITE_NOMEM_BKPT;
1692 /* If an older version of the function with a configured destructor is
1693 ** being replaced invoke the destructor function here. */
1694 functionDestroy(db, p);
1696 if( pDestructor ){
1697 pDestructor->nRef++;
1699 p->u.pDestructor = pDestructor;
1700 p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
1701 testcase( p->funcFlags & SQLITE_DETERMINISTIC );
1702 p->xSFunc = xSFunc ? xSFunc : xStep;
1703 p->xFinalize = xFinal;
1704 p->pUserData = pUserData;
1705 p->nArg = (u16)nArg;
1706 return SQLITE_OK;
1710 ** Create new user functions.
1712 int sqlite3_create_function(
1713 sqlite3 *db,
1714 const char *zFunc,
1715 int nArg,
1716 int enc,
1717 void *p,
1718 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
1719 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
1720 void (*xFinal)(sqlite3_context*)
1722 return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep,
1723 xFinal, 0);
1726 int sqlite3_create_function_v2(
1727 sqlite3 *db,
1728 const char *zFunc,
1729 int nArg,
1730 int enc,
1731 void *p,
1732 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
1733 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
1734 void (*xFinal)(sqlite3_context*),
1735 void (*xDestroy)(void *)
1737 int rc = SQLITE_ERROR;
1738 FuncDestructor *pArg = 0;
1740 #ifdef SQLITE_ENABLE_API_ARMOR
1741 if( !sqlite3SafetyCheckOk(db) ){
1742 return SQLITE_MISUSE_BKPT;
1744 #endif
1745 sqlite3_mutex_enter(db->mutex);
1746 if( xDestroy ){
1747 pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
1748 if( !pArg ){
1749 xDestroy(p);
1750 goto out;
1752 pArg->xDestroy = xDestroy;
1753 pArg->pUserData = p;
1755 rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
1756 if( pArg && pArg->nRef==0 ){
1757 assert( rc!=SQLITE_OK );
1758 xDestroy(p);
1759 sqlite3DbFree(db, pArg);
1762 out:
1763 rc = sqlite3ApiExit(db, rc);
1764 sqlite3_mutex_leave(db->mutex);
1765 return rc;
1768 #ifndef SQLITE_OMIT_UTF16
1769 int sqlite3_create_function16(
1770 sqlite3 *db,
1771 const void *zFunctionName,
1772 int nArg,
1773 int eTextRep,
1774 void *p,
1775 void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
1776 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
1777 void (*xFinal)(sqlite3_context*)
1779 int rc;
1780 char *zFunc8;
1782 #ifdef SQLITE_ENABLE_API_ARMOR
1783 if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
1784 #endif
1785 sqlite3_mutex_enter(db->mutex);
1786 assert( !db->mallocFailed );
1787 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
1788 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0);
1789 sqlite3DbFree(db, zFunc8);
1790 rc = sqlite3ApiExit(db, rc);
1791 sqlite3_mutex_leave(db->mutex);
1792 return rc;
1794 #endif
1798 ** Declare that a function has been overloaded by a virtual table.
1800 ** If the function already exists as a regular global function, then
1801 ** this routine is a no-op. If the function does not exist, then create
1802 ** a new one that always throws a run-time error.
1804 ** When virtual tables intend to provide an overloaded function, they
1805 ** should call this routine to make sure the global function exists.
1806 ** A global function must exist in order for name resolution to work
1807 ** properly.
1809 int sqlite3_overload_function(
1810 sqlite3 *db,
1811 const char *zName,
1812 int nArg
1814 int rc = SQLITE_OK;
1816 #ifdef SQLITE_ENABLE_API_ARMOR
1817 if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
1818 return SQLITE_MISUSE_BKPT;
1820 #endif
1821 sqlite3_mutex_enter(db->mutex);
1822 if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){
1823 rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
1824 0, sqlite3InvalidFunction, 0, 0, 0);
1826 rc = sqlite3ApiExit(db, rc);
1827 sqlite3_mutex_leave(db->mutex);
1828 return rc;
1831 #ifndef SQLITE_OMIT_TRACE
1833 ** Register a trace function. The pArg from the previously registered trace
1834 ** is returned.
1836 ** A NULL trace function means that no tracing is executes. A non-NULL
1837 ** trace is a pointer to a function that is invoked at the start of each
1838 ** SQL statement.
1840 #ifndef SQLITE_OMIT_DEPRECATED
1841 void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
1842 void *pOld;
1844 #ifdef SQLITE_ENABLE_API_ARMOR
1845 if( !sqlite3SafetyCheckOk(db) ){
1846 (void)SQLITE_MISUSE_BKPT;
1847 return 0;
1849 #endif
1850 sqlite3_mutex_enter(db->mutex);
1851 pOld = db->pTraceArg;
1852 db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
1853 db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
1854 db->pTraceArg = pArg;
1855 sqlite3_mutex_leave(db->mutex);
1856 return pOld;
1858 #endif /* SQLITE_OMIT_DEPRECATED */
1860 /* Register a trace callback using the version-2 interface.
1862 int sqlite3_trace_v2(
1863 sqlite3 *db, /* Trace this connection */
1864 unsigned mTrace, /* Mask of events to be traced */
1865 int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */
1866 void *pArg /* Context */
1868 #ifdef SQLITE_ENABLE_API_ARMOR
1869 if( !sqlite3SafetyCheckOk(db) ){
1870 return SQLITE_MISUSE_BKPT;
1872 #endif
1873 sqlite3_mutex_enter(db->mutex);
1874 if( mTrace==0 ) xTrace = 0;
1875 if( xTrace==0 ) mTrace = 0;
1876 db->mTrace = mTrace;
1877 db->xTrace = xTrace;
1878 db->pTraceArg = pArg;
1879 sqlite3_mutex_leave(db->mutex);
1880 return SQLITE_OK;
1883 #ifndef SQLITE_OMIT_DEPRECATED
1885 ** Register a profile function. The pArg from the previously registered
1886 ** profile function is returned.
1888 ** A NULL profile function means that no profiling is executes. A non-NULL
1889 ** profile is a pointer to a function that is invoked at the conclusion of
1890 ** each SQL statement that is run.
1892 void *sqlite3_profile(
1893 sqlite3 *db,
1894 void (*xProfile)(void*,const char*,sqlite_uint64),
1895 void *pArg
1897 void *pOld;
1899 #ifdef SQLITE_ENABLE_API_ARMOR
1900 if( !sqlite3SafetyCheckOk(db) ){
1901 (void)SQLITE_MISUSE_BKPT;
1902 return 0;
1904 #endif
1905 sqlite3_mutex_enter(db->mutex);
1906 pOld = db->pProfileArg;
1907 db->xProfile = xProfile;
1908 db->pProfileArg = pArg;
1909 sqlite3_mutex_leave(db->mutex);
1910 return pOld;
1912 #endif /* SQLITE_OMIT_DEPRECATED */
1913 #endif /* SQLITE_OMIT_TRACE */
1916 ** Register a function to be invoked when a transaction commits.
1917 ** If the invoked function returns non-zero, then the commit becomes a
1918 ** rollback.
1920 void *sqlite3_commit_hook(
1921 sqlite3 *db, /* Attach the hook to this database */
1922 int (*xCallback)(void*), /* Function to invoke on each commit */
1923 void *pArg /* Argument to the function */
1925 void *pOld;
1927 #ifdef SQLITE_ENABLE_API_ARMOR
1928 if( !sqlite3SafetyCheckOk(db) ){
1929 (void)SQLITE_MISUSE_BKPT;
1930 return 0;
1932 #endif
1933 sqlite3_mutex_enter(db->mutex);
1934 pOld = db->pCommitArg;
1935 db->xCommitCallback = xCallback;
1936 db->pCommitArg = pArg;
1937 sqlite3_mutex_leave(db->mutex);
1938 return pOld;
1942 ** Register a callback to be invoked each time a row is updated,
1943 ** inserted or deleted using this database connection.
1945 void *sqlite3_update_hook(
1946 sqlite3 *db, /* Attach the hook to this database */
1947 void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
1948 void *pArg /* Argument to the function */
1950 void *pRet;
1952 #ifdef SQLITE_ENABLE_API_ARMOR
1953 if( !sqlite3SafetyCheckOk(db) ){
1954 (void)SQLITE_MISUSE_BKPT;
1955 return 0;
1957 #endif
1958 sqlite3_mutex_enter(db->mutex);
1959 pRet = db->pUpdateArg;
1960 db->xUpdateCallback = xCallback;
1961 db->pUpdateArg = pArg;
1962 sqlite3_mutex_leave(db->mutex);
1963 return pRet;
1967 ** Register a callback to be invoked each time a transaction is rolled
1968 ** back by this database connection.
1970 void *sqlite3_rollback_hook(
1971 sqlite3 *db, /* Attach the hook to this database */
1972 void (*xCallback)(void*), /* Callback function */
1973 void *pArg /* Argument to the function */
1975 void *pRet;
1977 #ifdef SQLITE_ENABLE_API_ARMOR
1978 if( !sqlite3SafetyCheckOk(db) ){
1979 (void)SQLITE_MISUSE_BKPT;
1980 return 0;
1982 #endif
1983 sqlite3_mutex_enter(db->mutex);
1984 pRet = db->pRollbackArg;
1985 db->xRollbackCallback = xCallback;
1986 db->pRollbackArg = pArg;
1987 sqlite3_mutex_leave(db->mutex);
1988 return pRet;
1991 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1993 ** Register a callback to be invoked each time a row is updated,
1994 ** inserted or deleted using this database connection.
1996 void *sqlite3_preupdate_hook(
1997 sqlite3 *db, /* Attach the hook to this database */
1998 void(*xCallback)( /* Callback function */
1999 void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
2000 void *pArg /* First callback argument */
2002 void *pRet;
2003 sqlite3_mutex_enter(db->mutex);
2004 pRet = db->pPreUpdateArg;
2005 db->xPreUpdateCallback = xCallback;
2006 db->pPreUpdateArg = pArg;
2007 sqlite3_mutex_leave(db->mutex);
2008 return pRet;
2010 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2012 #ifndef SQLITE_OMIT_WAL
2014 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
2015 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
2016 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
2017 ** wal_autocheckpoint()).
2019 int sqlite3WalDefaultHook(
2020 void *pClientData, /* Argument */
2021 sqlite3 *db, /* Connection */
2022 const char *zDb, /* Database */
2023 int nFrame /* Size of WAL */
2025 if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
2026 sqlite3BeginBenignMalloc();
2027 sqlite3_wal_checkpoint(db, zDb);
2028 sqlite3EndBenignMalloc();
2030 return SQLITE_OK;
2032 #endif /* SQLITE_OMIT_WAL */
2035 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
2036 ** a database after committing a transaction if there are nFrame or
2037 ** more frames in the log file. Passing zero or a negative value as the
2038 ** nFrame parameter disables automatic checkpoints entirely.
2040 ** The callback registered by this function replaces any existing callback
2041 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
2042 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
2043 ** configured by this function.
2045 int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
2046 #ifdef SQLITE_OMIT_WAL
2047 UNUSED_PARAMETER(db);
2048 UNUSED_PARAMETER(nFrame);
2049 #else
2050 #ifdef SQLITE_ENABLE_API_ARMOR
2051 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
2052 #endif
2053 if( nFrame>0 ){
2054 sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
2055 }else{
2056 sqlite3_wal_hook(db, 0, 0);
2058 #endif
2059 return SQLITE_OK;
2063 ** Register a callback to be invoked each time a transaction is written
2064 ** into the write-ahead-log by this database connection.
2066 void *sqlite3_wal_hook(
2067 sqlite3 *db, /* Attach the hook to this db handle */
2068 int(*xCallback)(void *, sqlite3*, const char*, int),
2069 void *pArg /* First argument passed to xCallback() */
2071 #ifndef SQLITE_OMIT_WAL
2072 void *pRet;
2073 #ifdef SQLITE_ENABLE_API_ARMOR
2074 if( !sqlite3SafetyCheckOk(db) ){
2075 (void)SQLITE_MISUSE_BKPT;
2076 return 0;
2078 #endif
2079 sqlite3_mutex_enter(db->mutex);
2080 pRet = db->pWalArg;
2081 db->xWalCallback = xCallback;
2082 db->pWalArg = pArg;
2083 sqlite3_mutex_leave(db->mutex);
2084 return pRet;
2085 #else
2086 return 0;
2087 #endif
2091 ** Checkpoint database zDb.
2093 int sqlite3_wal_checkpoint_v2(
2094 sqlite3 *db, /* Database handle */
2095 const char *zDb, /* Name of attached database (or NULL) */
2096 int eMode, /* SQLITE_CHECKPOINT_* value */
2097 int *pnLog, /* OUT: Size of WAL log in frames */
2098 int *pnCkpt /* OUT: Total number of frames checkpointed */
2100 #ifdef SQLITE_OMIT_WAL
2101 return SQLITE_OK;
2102 #else
2103 int rc; /* Return code */
2104 int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
2106 #ifdef SQLITE_ENABLE_API_ARMOR
2107 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
2108 #endif
2110 /* Initialize the output variables to -1 in case an error occurs. */
2111 if( pnLog ) *pnLog = -1;
2112 if( pnCkpt ) *pnCkpt = -1;
2114 assert( SQLITE_CHECKPOINT_PASSIVE==0 );
2115 assert( SQLITE_CHECKPOINT_FULL==1 );
2116 assert( SQLITE_CHECKPOINT_RESTART==2 );
2117 assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
2118 if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
2119 /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
2120 ** mode: */
2121 return SQLITE_MISUSE;
2124 sqlite3_mutex_enter(db->mutex);
2125 if( zDb && zDb[0] ){
2126 iDb = sqlite3FindDbName(db, zDb);
2128 if( iDb<0 ){
2129 rc = SQLITE_ERROR;
2130 sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
2131 }else{
2132 db->busyHandler.nBusy = 0;
2133 rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
2134 sqlite3Error(db, rc);
2136 rc = sqlite3ApiExit(db, rc);
2138 /* If there are no active statements, clear the interrupt flag at this
2139 ** point. */
2140 if( db->nVdbeActive==0 ){
2141 db->u1.isInterrupted = 0;
2144 sqlite3_mutex_leave(db->mutex);
2145 return rc;
2146 #endif
2151 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
2152 ** to contains a zero-length string, all attached databases are
2153 ** checkpointed.
2155 int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
2156 /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
2157 ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
2158 return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
2161 #ifndef SQLITE_OMIT_WAL
2163 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
2164 ** not currently open in WAL mode.
2166 ** If a transaction is open on the database being checkpointed, this
2167 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
2168 ** an error occurs while running the checkpoint, an SQLite error code is
2169 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
2171 ** The mutex on database handle db should be held by the caller. The mutex
2172 ** associated with the specific b-tree being checkpointed is taken by
2173 ** this function while the checkpoint is running.
2175 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
2176 ** checkpointed. If an error is encountered it is returned immediately -
2177 ** no attempt is made to checkpoint any remaining databases.
2179 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
2180 ** or TRUNCATE.
2182 int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
2183 int rc = SQLITE_OK; /* Return code */
2184 int i; /* Used to iterate through attached dbs */
2185 int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
2187 assert( sqlite3_mutex_held(db->mutex) );
2188 assert( !pnLog || *pnLog==-1 );
2189 assert( !pnCkpt || *pnCkpt==-1 );
2191 for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
2192 if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
2193 rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
2194 pnLog = 0;
2195 pnCkpt = 0;
2196 if( rc==SQLITE_BUSY ){
2197 bBusy = 1;
2198 rc = SQLITE_OK;
2203 return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
2205 #endif /* SQLITE_OMIT_WAL */
2208 ** This function returns true if main-memory should be used instead of
2209 ** a temporary file for transient pager files and statement journals.
2210 ** The value returned depends on the value of db->temp_store (runtime
2211 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
2212 ** following table describes the relationship between these two values
2213 ** and this functions return value.
2215 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
2216 ** ----------------- -------------- ------------------------------
2217 ** 0 any file (return 0)
2218 ** 1 1 file (return 0)
2219 ** 1 2 memory (return 1)
2220 ** 1 0 file (return 0)
2221 ** 2 1 file (return 0)
2222 ** 2 2 memory (return 1)
2223 ** 2 0 memory (return 1)
2224 ** 3 any memory (return 1)
2226 int sqlite3TempInMemory(const sqlite3 *db){
2227 #if SQLITE_TEMP_STORE==1
2228 return ( db->temp_store==2 );
2229 #endif
2230 #if SQLITE_TEMP_STORE==2
2231 return ( db->temp_store!=1 );
2232 #endif
2233 #if SQLITE_TEMP_STORE==3
2234 UNUSED_PARAMETER(db);
2235 return 1;
2236 #endif
2237 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
2238 UNUSED_PARAMETER(db);
2239 return 0;
2240 #endif
2244 ** Return UTF-8 encoded English language explanation of the most recent
2245 ** error.
2247 const char *sqlite3_errmsg(sqlite3 *db){
2248 const char *z;
2249 if( !db ){
2250 return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
2252 if( !sqlite3SafetyCheckSickOrOk(db) ){
2253 return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
2255 sqlite3_mutex_enter(db->mutex);
2256 if( db->mallocFailed ){
2257 z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
2258 }else{
2259 testcase( db->pErr==0 );
2260 z = (char*)sqlite3_value_text(db->pErr);
2261 assert( !db->mallocFailed );
2262 if( z==0 ){
2263 z = sqlite3ErrStr(db->errCode);
2266 sqlite3_mutex_leave(db->mutex);
2267 return z;
2270 #ifndef SQLITE_OMIT_UTF16
2272 ** Return UTF-16 encoded English language explanation of the most recent
2273 ** error.
2275 const void *sqlite3_errmsg16(sqlite3 *db){
2276 static const u16 outOfMem[] = {
2277 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
2279 static const u16 misuse[] = {
2280 'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
2281 'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
2282 'm', 'i', 's', 'u', 's', 'e', 0
2285 const void *z;
2286 if( !db ){
2287 return (void *)outOfMem;
2289 if( !sqlite3SafetyCheckSickOrOk(db) ){
2290 return (void *)misuse;
2292 sqlite3_mutex_enter(db->mutex);
2293 if( db->mallocFailed ){
2294 z = (void *)outOfMem;
2295 }else{
2296 z = sqlite3_value_text16(db->pErr);
2297 if( z==0 ){
2298 sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
2299 z = sqlite3_value_text16(db->pErr);
2301 /* A malloc() may have failed within the call to sqlite3_value_text16()
2302 ** above. If this is the case, then the db->mallocFailed flag needs to
2303 ** be cleared before returning. Do this directly, instead of via
2304 ** sqlite3ApiExit(), to avoid setting the database handle error message.
2306 sqlite3OomClear(db);
2308 sqlite3_mutex_leave(db->mutex);
2309 return z;
2311 #endif /* SQLITE_OMIT_UTF16 */
2314 ** Return the most recent error code generated by an SQLite routine. If NULL is
2315 ** passed to this function, we assume a malloc() failed during sqlite3_open().
2317 int sqlite3_errcode(sqlite3 *db){
2318 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
2319 return SQLITE_MISUSE_BKPT;
2321 if( !db || db->mallocFailed ){
2322 return SQLITE_NOMEM_BKPT;
2324 return db->errCode & db->errMask;
2326 int sqlite3_extended_errcode(sqlite3 *db){
2327 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
2328 return SQLITE_MISUSE_BKPT;
2330 if( !db || db->mallocFailed ){
2331 return SQLITE_NOMEM_BKPT;
2333 return db->errCode;
2335 int sqlite3_system_errno(sqlite3 *db){
2336 return db ? db->iSysErrno : 0;
2340 ** Return a string that describes the kind of error specified in the
2341 ** argument. For now, this simply calls the internal sqlite3ErrStr()
2342 ** function.
2344 const char *sqlite3_errstr(int rc){
2345 return sqlite3ErrStr(rc);
2349 ** Create a new collating function for database "db". The name is zName
2350 ** and the encoding is enc.
2352 static int createCollation(
2353 sqlite3* db,
2354 const char *zName,
2355 u8 enc,
2356 void* pCtx,
2357 int(*xCompare)(void*,int,const void*,int,const void*),
2358 void(*xDel)(void*)
2360 CollSeq *pColl;
2361 int enc2;
2363 assert( sqlite3_mutex_held(db->mutex) );
2365 /* If SQLITE_UTF16 is specified as the encoding type, transform this
2366 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
2367 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
2369 enc2 = enc;
2370 testcase( enc2==SQLITE_UTF16 );
2371 testcase( enc2==SQLITE_UTF16_ALIGNED );
2372 if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
2373 enc2 = SQLITE_UTF16NATIVE;
2375 if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
2376 return SQLITE_MISUSE_BKPT;
2379 /* Check if this call is removing or replacing an existing collation
2380 ** sequence. If so, and there are active VMs, return busy. If there
2381 ** are no active VMs, invalidate any pre-compiled statements.
2383 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
2384 if( pColl && pColl->xCmp ){
2385 if( db->nVdbeActive ){
2386 sqlite3ErrorWithMsg(db, SQLITE_BUSY,
2387 "unable to delete/modify collation sequence due to active statements");
2388 return SQLITE_BUSY;
2390 sqlite3ExpirePreparedStatements(db);
2392 /* If collation sequence pColl was created directly by a call to
2393 ** sqlite3_create_collation, and not generated by synthCollSeq(),
2394 ** then any copies made by synthCollSeq() need to be invalidated.
2395 ** Also, collation destructor - CollSeq.xDel() - function may need
2396 ** to be called.
2398 if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
2399 CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
2400 int j;
2401 for(j=0; j<3; j++){
2402 CollSeq *p = &aColl[j];
2403 if( p->enc==pColl->enc ){
2404 if( p->xDel ){
2405 p->xDel(p->pUser);
2407 p->xCmp = 0;
2413 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
2414 if( pColl==0 ) return SQLITE_NOMEM_BKPT;
2415 pColl->xCmp = xCompare;
2416 pColl->pUser = pCtx;
2417 pColl->xDel = xDel;
2418 pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
2419 sqlite3Error(db, SQLITE_OK);
2420 return SQLITE_OK;
2425 ** This array defines hard upper bounds on limit values. The
2426 ** initializer must be kept in sync with the SQLITE_LIMIT_*
2427 ** #defines in sqlite3.h.
2429 static const int aHardLimit[] = {
2430 SQLITE_MAX_LENGTH,
2431 SQLITE_MAX_SQL_LENGTH,
2432 SQLITE_MAX_COLUMN,
2433 SQLITE_MAX_EXPR_DEPTH,
2434 SQLITE_MAX_COMPOUND_SELECT,
2435 SQLITE_MAX_VDBE_OP,
2436 SQLITE_MAX_FUNCTION_ARG,
2437 SQLITE_MAX_ATTACHED,
2438 SQLITE_MAX_LIKE_PATTERN_LENGTH,
2439 SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
2440 SQLITE_MAX_TRIGGER_DEPTH,
2441 SQLITE_MAX_WORKER_THREADS,
2445 ** Make sure the hard limits are set to reasonable values
2447 #if SQLITE_MAX_LENGTH<100
2448 # error SQLITE_MAX_LENGTH must be at least 100
2449 #endif
2450 #if SQLITE_MAX_SQL_LENGTH<100
2451 # error SQLITE_MAX_SQL_LENGTH must be at least 100
2452 #endif
2453 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
2454 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
2455 #endif
2456 #if SQLITE_MAX_COMPOUND_SELECT<2
2457 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
2458 #endif
2459 #if SQLITE_MAX_VDBE_OP<40
2460 # error SQLITE_MAX_VDBE_OP must be at least 40
2461 #endif
2462 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
2463 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
2464 #endif
2465 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
2466 # error SQLITE_MAX_ATTACHED must be between 0 and 125
2467 #endif
2468 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
2469 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
2470 #endif
2471 #if SQLITE_MAX_COLUMN>32767
2472 # error SQLITE_MAX_COLUMN must not exceed 32767
2473 #endif
2474 #if SQLITE_MAX_TRIGGER_DEPTH<1
2475 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
2476 #endif
2477 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
2478 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
2479 #endif
2483 ** Change the value of a limit. Report the old value.
2484 ** If an invalid limit index is supplied, report -1.
2485 ** Make no changes but still report the old value if the
2486 ** new limit is negative.
2488 ** A new lower limit does not shrink existing constructs.
2489 ** It merely prevents new constructs that exceed the limit
2490 ** from forming.
2492 int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
2493 int oldLimit;
2495 #ifdef SQLITE_ENABLE_API_ARMOR
2496 if( !sqlite3SafetyCheckOk(db) ){
2497 (void)SQLITE_MISUSE_BKPT;
2498 return -1;
2500 #endif
2502 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
2503 ** there is a hard upper bound set at compile-time by a C preprocessor
2504 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
2505 ** "_MAX_".)
2507 assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
2508 assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
2509 assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
2510 assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
2511 assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
2512 assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
2513 assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
2514 assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
2515 assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
2516 SQLITE_MAX_LIKE_PATTERN_LENGTH );
2517 assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
2518 assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
2519 assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
2520 assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
2523 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
2524 return -1;
2526 oldLimit = db->aLimit[limitId];
2527 if( newLimit>=0 ){ /* IMP: R-52476-28732 */
2528 if( newLimit>aHardLimit[limitId] ){
2529 newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
2531 db->aLimit[limitId] = newLimit;
2533 return oldLimit; /* IMP: R-53341-35419 */
2537 ** This function is used to parse both URIs and non-URI filenames passed by the
2538 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
2539 ** URIs specified as part of ATTACH statements.
2541 ** The first argument to this function is the name of the VFS to use (or
2542 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
2543 ** query parameter. The second argument contains the URI (or non-URI filename)
2544 ** itself. When this function is called the *pFlags variable should contain
2545 ** the default flags to open the database handle with. The value stored in
2546 ** *pFlags may be updated before returning if the URI filename contains
2547 ** "cache=xxx" or "mode=xxx" query parameters.
2549 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
2550 ** the VFS that should be used to open the database file. *pzFile is set to
2551 ** point to a buffer containing the name of the file to open. It is the
2552 ** responsibility of the caller to eventually call sqlite3_free() to release
2553 ** this buffer.
2555 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
2556 ** may be set to point to a buffer containing an English language error
2557 ** message. It is the responsibility of the caller to eventually release
2558 ** this buffer by calling sqlite3_free().
2560 int sqlite3ParseUri(
2561 const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
2562 const char *zUri, /* Nul-terminated URI to parse */
2563 unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
2564 sqlite3_vfs **ppVfs, /* OUT: VFS to use */
2565 char **pzFile, /* OUT: Filename component of URI */
2566 char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
2568 int rc = SQLITE_OK;
2569 unsigned int flags = *pFlags;
2570 const char *zVfs = zDefaultVfs;
2571 char *zFile;
2572 char c;
2573 int nUri = sqlite3Strlen30(zUri);
2575 assert( *pzErrMsg==0 );
2577 if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
2578 || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
2579 && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
2581 char *zOpt;
2582 int eState; /* Parser state when parsing URI */
2583 int iIn; /* Input character index */
2584 int iOut = 0; /* Output character index */
2585 u64 nByte = nUri+2; /* Bytes of space to allocate */
2587 /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
2588 ** method that there may be extra parameters following the file-name. */
2589 flags |= SQLITE_OPEN_URI;
2591 for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
2592 zFile = sqlite3_malloc64(nByte);
2593 if( !zFile ) return SQLITE_NOMEM_BKPT;
2595 iIn = 5;
2596 #ifdef SQLITE_ALLOW_URI_AUTHORITY
2597 if( strncmp(zUri+5, "///", 3)==0 ){
2598 iIn = 7;
2599 /* The following condition causes URIs with five leading / characters
2600 ** like file://///host/path to be converted into UNCs like //host/path.
2601 ** The correct URI for that UNC has only two or four leading / characters
2602 ** file://host/path or file:////host/path. But 5 leading slashes is a
2603 ** common error, we are told, so we handle it as a special case. */
2604 if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
2605 }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
2606 iIn = 16;
2608 #else
2609 /* Discard the scheme and authority segments of the URI. */
2610 if( zUri[5]=='/' && zUri[6]=='/' ){
2611 iIn = 7;
2612 while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
2613 if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
2614 *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
2615 iIn-7, &zUri[7]);
2616 rc = SQLITE_ERROR;
2617 goto parse_uri_out;
2620 #endif
2622 /* Copy the filename and any query parameters into the zFile buffer.
2623 ** Decode %HH escape codes along the way.
2625 ** Within this loop, variable eState may be set to 0, 1 or 2, depending
2626 ** on the parsing context. As follows:
2628 ** 0: Parsing file-name.
2629 ** 1: Parsing name section of a name=value query parameter.
2630 ** 2: Parsing value section of a name=value query parameter.
2632 eState = 0;
2633 while( (c = zUri[iIn])!=0 && c!='#' ){
2634 iIn++;
2635 if( c=='%'
2636 && sqlite3Isxdigit(zUri[iIn])
2637 && sqlite3Isxdigit(zUri[iIn+1])
2639 int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
2640 octet += sqlite3HexToInt(zUri[iIn++]);
2642 assert( octet>=0 && octet<256 );
2643 if( octet==0 ){
2644 #ifndef SQLITE_ENABLE_URI_00_ERROR
2645 /* This branch is taken when "%00" appears within the URI. In this
2646 ** case we ignore all text in the remainder of the path, name or
2647 ** value currently being parsed. So ignore the current character
2648 ** and skip to the next "?", "=" or "&", as appropriate. */
2649 while( (c = zUri[iIn])!=0 && c!='#'
2650 && (eState!=0 || c!='?')
2651 && (eState!=1 || (c!='=' && c!='&'))
2652 && (eState!=2 || c!='&')
2654 iIn++;
2656 continue;
2657 #else
2658 /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
2659 *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
2660 rc = SQLITE_ERROR;
2661 goto parse_uri_out;
2662 #endif
2664 c = octet;
2665 }else if( eState==1 && (c=='&' || c=='=') ){
2666 if( zFile[iOut-1]==0 ){
2667 /* An empty option name. Ignore this option altogether. */
2668 while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
2669 continue;
2671 if( c=='&' ){
2672 zFile[iOut++] = '\0';
2673 }else{
2674 eState = 2;
2676 c = 0;
2677 }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
2678 c = 0;
2679 eState = 1;
2681 zFile[iOut++] = c;
2683 if( eState==1 ) zFile[iOut++] = '\0';
2684 zFile[iOut++] = '\0';
2685 zFile[iOut++] = '\0';
2687 /* Check if there were any options specified that should be interpreted
2688 ** here. Options that are interpreted here include "vfs" and those that
2689 ** correspond to flags that may be passed to the sqlite3_open_v2()
2690 ** method. */
2691 zOpt = &zFile[sqlite3Strlen30(zFile)+1];
2692 while( zOpt[0] ){
2693 int nOpt = sqlite3Strlen30(zOpt);
2694 char *zVal = &zOpt[nOpt+1];
2695 int nVal = sqlite3Strlen30(zVal);
2697 if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
2698 zVfs = zVal;
2699 }else{
2700 struct OpenMode {
2701 const char *z;
2702 int mode;
2703 } *aMode = 0;
2704 char *zModeType = 0;
2705 int mask = 0;
2706 int limit = 0;
2708 if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
2709 static struct OpenMode aCacheMode[] = {
2710 { "shared", SQLITE_OPEN_SHAREDCACHE },
2711 { "private", SQLITE_OPEN_PRIVATECACHE },
2712 { 0, 0 }
2715 mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
2716 aMode = aCacheMode;
2717 limit = mask;
2718 zModeType = "cache";
2720 if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
2721 static struct OpenMode aOpenMode[] = {
2722 { "ro", SQLITE_OPEN_READONLY },
2723 { "rw", SQLITE_OPEN_READWRITE },
2724 { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
2725 { "memory", SQLITE_OPEN_MEMORY },
2726 { 0, 0 }
2729 mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
2730 | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
2731 aMode = aOpenMode;
2732 limit = mask & flags;
2733 zModeType = "access";
2736 if( aMode ){
2737 int i;
2738 int mode = 0;
2739 for(i=0; aMode[i].z; i++){
2740 const char *z = aMode[i].z;
2741 if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
2742 mode = aMode[i].mode;
2743 break;
2746 if( mode==0 ){
2747 *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
2748 rc = SQLITE_ERROR;
2749 goto parse_uri_out;
2751 if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
2752 *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
2753 zModeType, zVal);
2754 rc = SQLITE_PERM;
2755 goto parse_uri_out;
2757 flags = (flags & ~mask) | mode;
2761 zOpt = &zVal[nVal+1];
2764 }else{
2765 zFile = sqlite3_malloc64(nUri+2);
2766 if( !zFile ) return SQLITE_NOMEM_BKPT;
2767 if( nUri ){
2768 memcpy(zFile, zUri, nUri);
2770 zFile[nUri] = '\0';
2771 zFile[nUri+1] = '\0';
2772 flags &= ~SQLITE_OPEN_URI;
2775 *ppVfs = sqlite3_vfs_find(zVfs);
2776 if( *ppVfs==0 ){
2777 *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
2778 rc = SQLITE_ERROR;
2780 parse_uri_out:
2781 if( rc!=SQLITE_OK ){
2782 sqlite3_free(zFile);
2783 zFile = 0;
2785 *pFlags = flags;
2786 *pzFile = zFile;
2787 return rc;
2792 ** This routine does the work of opening a database on behalf of
2793 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
2794 ** is UTF-8 encoded.
2796 static int openDatabase(
2797 const char *zFilename, /* Database filename UTF-8 encoded */
2798 sqlite3 **ppDb, /* OUT: Returned database handle */
2799 unsigned int flags, /* Operational flags */
2800 const char *zVfs /* Name of the VFS to use */
2802 sqlite3 *db; /* Store allocated handle here */
2803 int rc; /* Return code */
2804 int isThreadsafe; /* True for threadsafe connections */
2805 char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
2806 char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
2808 #ifdef SQLITE_ENABLE_API_ARMOR
2809 if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
2810 #endif
2811 *ppDb = 0;
2812 #ifndef SQLITE_OMIT_AUTOINIT
2813 rc = sqlite3_initialize();
2814 if( rc ) return rc;
2815 #endif
2817 if( sqlite3GlobalConfig.bCoreMutex==0 ){
2818 isThreadsafe = 0;
2819 }else if( flags & SQLITE_OPEN_NOMUTEX ){
2820 isThreadsafe = 0;
2821 }else if( flags & SQLITE_OPEN_FULLMUTEX ){
2822 isThreadsafe = 1;
2823 }else{
2824 isThreadsafe = sqlite3GlobalConfig.bFullMutex;
2827 if( flags & SQLITE_OPEN_PRIVATECACHE ){
2828 flags &= ~SQLITE_OPEN_SHAREDCACHE;
2829 }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
2830 flags |= SQLITE_OPEN_SHAREDCACHE;
2833 /* Remove harmful bits from the flags parameter
2835 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
2836 ** dealt with in the previous code block. Besides these, the only
2837 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
2838 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
2839 ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
2840 ** off all other flags.
2842 flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
2843 SQLITE_OPEN_EXCLUSIVE |
2844 SQLITE_OPEN_MAIN_DB |
2845 SQLITE_OPEN_TEMP_DB |
2846 SQLITE_OPEN_TRANSIENT_DB |
2847 SQLITE_OPEN_MAIN_JOURNAL |
2848 SQLITE_OPEN_TEMP_JOURNAL |
2849 SQLITE_OPEN_SUBJOURNAL |
2850 SQLITE_OPEN_MASTER_JOURNAL |
2851 SQLITE_OPEN_NOMUTEX |
2852 SQLITE_OPEN_FULLMUTEX |
2853 SQLITE_OPEN_WAL
2856 /* Allocate the sqlite data structure */
2857 db = sqlite3MallocZero( sizeof(sqlite3) );
2858 if( db==0 ) goto opendb_out;
2859 if( isThreadsafe
2860 #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
2861 || sqlite3GlobalConfig.bCoreMutex
2862 #endif
2864 db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
2865 if( db->mutex==0 ){
2866 sqlite3_free(db);
2867 db = 0;
2868 goto opendb_out;
2870 if( isThreadsafe==0 ){
2871 sqlite3MutexWarnOnContention(db->mutex);
2874 sqlite3_mutex_enter(db->mutex);
2875 db->errMask = 0xff;
2876 db->nDb = 2;
2877 db->magic = SQLITE_MAGIC_BUSY;
2878 db->aDb = db->aDbStatic;
2880 assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
2881 memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
2882 db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
2883 db->autoCommit = 1;
2884 db->nextAutovac = -1;
2885 db->szMmap = sqlite3GlobalConfig.szMmap;
2886 db->nextPagesize = 0;
2887 db->nMaxSorterMmap = 0x7FFFFFFF;
2888 db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
2889 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
2890 | SQLITE_AutoIndex
2891 #endif
2892 #if SQLITE_DEFAULT_CKPTFULLFSYNC
2893 | SQLITE_CkptFullFSync
2894 #endif
2895 #if SQLITE_DEFAULT_FILE_FORMAT<4
2896 | SQLITE_LegacyFileFmt
2897 #endif
2898 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
2899 | SQLITE_LoadExtension
2900 #endif
2901 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
2902 | SQLITE_RecTriggers
2903 #endif
2904 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
2905 | SQLITE_ForeignKeys
2906 #endif
2907 #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
2908 | SQLITE_ReverseOrder
2909 #endif
2910 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
2911 | SQLITE_CellSizeCk
2912 #endif
2913 #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
2914 | SQLITE_Fts3Tokenizer
2915 #endif
2916 #if defined(SQLITE_ENABLE_QPSG)
2917 | SQLITE_EnableQPSG
2918 #endif
2920 sqlite3HashInit(&db->aCollSeq);
2921 #ifndef SQLITE_OMIT_VIRTUALTABLE
2922 sqlite3HashInit(&db->aModule);
2923 #endif
2925 /* Add the default collation sequence BINARY. BINARY works for both UTF-8
2926 ** and UTF-16, so add a version for each to avoid any unnecessary
2927 ** conversions. The only error that can occur here is a malloc() failure.
2929 ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
2930 ** functions:
2932 createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
2933 createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
2934 createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
2935 createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
2936 createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
2937 if( db->mallocFailed ){
2938 goto opendb_out;
2940 /* EVIDENCE-OF: R-08308-17224 The default collating function for all
2941 ** strings is BINARY.
2943 db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
2944 assert( db->pDfltColl!=0 );
2946 /* Parse the filename/URI argument
2948 ** Only allow sensible combinations of bits in the flags argument.
2949 ** Throw an error if any non-sense combination is used. If we
2950 ** do not block illegal combinations here, it could trigger
2951 ** assert() statements in deeper layers. Sensible combinations
2952 ** are:
2954 ** 1: SQLITE_OPEN_READONLY
2955 ** 2: SQLITE_OPEN_READWRITE
2956 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
2958 db->openFlags = flags;
2959 assert( SQLITE_OPEN_READONLY == 0x01 );
2960 assert( SQLITE_OPEN_READWRITE == 0x02 );
2961 assert( SQLITE_OPEN_CREATE == 0x04 );
2962 testcase( (1<<(flags&7))==0x02 ); /* READONLY */
2963 testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
2964 testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
2965 if( ((1<<(flags&7)) & 0x46)==0 ){
2966 rc = SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
2967 }else{
2968 rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
2970 if( rc!=SQLITE_OK ){
2971 if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
2972 sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
2973 sqlite3_free(zErrMsg);
2974 goto opendb_out;
2977 /* Open the backend database driver */
2978 rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
2979 flags | SQLITE_OPEN_MAIN_DB);
2980 if( rc!=SQLITE_OK ){
2981 if( rc==SQLITE_IOERR_NOMEM ){
2982 rc = SQLITE_NOMEM_BKPT;
2984 sqlite3Error(db, rc);
2985 goto opendb_out;
2987 sqlite3BtreeEnter(db->aDb[0].pBt);
2988 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
2989 if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
2990 sqlite3BtreeLeave(db->aDb[0].pBt);
2991 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
2993 /* The default safety_level for the main database is FULL; for the temp
2994 ** database it is OFF. This matches the pager layer defaults.
2996 db->aDb[0].zDbSName = "main";
2997 db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
2998 db->aDb[1].zDbSName = "temp";
2999 db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
3001 db->magic = SQLITE_MAGIC_OPEN;
3002 if( db->mallocFailed ){
3003 goto opendb_out;
3006 /* Register all built-in functions, but do not attempt to read the
3007 ** database schema yet. This is delayed until the first time the database
3008 ** is accessed.
3010 sqlite3Error(db, SQLITE_OK);
3011 sqlite3RegisterPerConnectionBuiltinFunctions(db);
3012 rc = sqlite3_errcode(db);
3014 #ifdef SQLITE_ENABLE_FTS5
3015 /* Register any built-in FTS5 module before loading the automatic
3016 ** extensions. This allows automatic extensions to register FTS5
3017 ** tokenizers and auxiliary functions. */
3018 if( !db->mallocFailed && rc==SQLITE_OK ){
3019 rc = sqlite3Fts5Init(db);
3021 #endif
3023 /* Load automatic extensions - extensions that have been registered
3024 ** using the sqlite3_automatic_extension() API.
3026 if( rc==SQLITE_OK ){
3027 sqlite3AutoLoadExtensions(db);
3028 rc = sqlite3_errcode(db);
3029 if( rc!=SQLITE_OK ){
3030 goto opendb_out;
3034 #ifdef SQLITE_ENABLE_FTS1
3035 if( !db->mallocFailed ){
3036 extern int sqlite3Fts1Init(sqlite3*);
3037 rc = sqlite3Fts1Init(db);
3039 #endif
3041 #ifdef SQLITE_ENABLE_FTS2
3042 if( !db->mallocFailed && rc==SQLITE_OK ){
3043 extern int sqlite3Fts2Init(sqlite3*);
3044 rc = sqlite3Fts2Init(db);
3046 #endif
3048 #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
3049 if( !db->mallocFailed && rc==SQLITE_OK ){
3050 rc = sqlite3Fts3Init(db);
3052 #endif
3054 #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
3055 if( !db->mallocFailed && rc==SQLITE_OK ){
3056 rc = sqlite3IcuInit(db);
3058 #endif
3060 #ifdef SQLITE_ENABLE_RTREE
3061 if( !db->mallocFailed && rc==SQLITE_OK){
3062 rc = sqlite3RtreeInit(db);
3064 #endif
3066 #ifdef SQLITE_ENABLE_DBPAGE_VTAB
3067 if( !db->mallocFailed && rc==SQLITE_OK){
3068 rc = sqlite3DbpageRegister(db);
3070 #endif
3072 #ifdef SQLITE_ENABLE_DBSTAT_VTAB
3073 if( !db->mallocFailed && rc==SQLITE_OK){
3074 rc = sqlite3DbstatRegister(db);
3076 #endif
3078 #ifdef SQLITE_ENABLE_JSON1
3079 if( !db->mallocFailed && rc==SQLITE_OK){
3080 rc = sqlite3Json1Init(db);
3082 #endif
3084 #ifdef SQLITE_ENABLE_STMTVTAB
3085 if( !db->mallocFailed && rc==SQLITE_OK){
3086 rc = sqlite3StmtVtabInit(db);
3088 #endif
3090 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
3091 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
3092 ** mode. Doing nothing at all also makes NORMAL the default.
3094 #ifdef SQLITE_DEFAULT_LOCKING_MODE
3095 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
3096 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
3097 SQLITE_DEFAULT_LOCKING_MODE);
3098 #endif
3100 if( rc ) sqlite3Error(db, rc);
3102 /* Enable the lookaside-malloc subsystem */
3103 setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
3104 sqlite3GlobalConfig.nLookaside);
3106 sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
3108 opendb_out:
3109 if( db ){
3110 assert( db->mutex!=0 || isThreadsafe==0
3111 || sqlite3GlobalConfig.bFullMutex==0 );
3112 sqlite3_mutex_leave(db->mutex);
3114 rc = sqlite3_errcode(db);
3115 assert( db!=0 || rc==SQLITE_NOMEM );
3116 if( rc==SQLITE_NOMEM ){
3117 sqlite3_close(db);
3118 db = 0;
3119 }else if( rc!=SQLITE_OK ){
3120 db->magic = SQLITE_MAGIC_SICK;
3122 *ppDb = db;
3123 #ifdef SQLITE_ENABLE_SQLLOG
3124 if( sqlite3GlobalConfig.xSqllog ){
3125 /* Opening a db handle. Fourth parameter is passed 0. */
3126 void *pArg = sqlite3GlobalConfig.pSqllogArg;
3127 sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
3129 #endif
3130 #if defined(SQLITE_HAS_CODEC)
3131 if( rc==SQLITE_OK ){
3132 const char *zKey;
3133 if( (zKey = sqlite3_uri_parameter(zOpen, "hexkey"))!=0 && zKey[0] ){
3134 u8 iByte;
3135 int i;
3136 char zDecoded[40];
3137 for(i=0, iByte=0; i<sizeof(zDecoded)*2 && sqlite3Isxdigit(zKey[i]); i++){
3138 iByte = (iByte<<4) + sqlite3HexToInt(zKey[i]);
3139 if( (i&1)!=0 ) zDecoded[i/2] = iByte;
3141 sqlite3_key_v2(db, 0, zDecoded, i/2);
3142 }else if( (zKey = sqlite3_uri_parameter(zOpen, "key"))!=0 ){
3143 sqlite3_key_v2(db, 0, zKey, sqlite3Strlen30(zKey));
3146 #endif
3147 sqlite3_free(zOpen);
3148 return rc & 0xff;
3152 ** Open a new database handle.
3154 int sqlite3_open(
3155 const char *zFilename,
3156 sqlite3 **ppDb
3158 return openDatabase(zFilename, ppDb,
3159 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
3161 int sqlite3_open_v2(
3162 const char *filename, /* Database filename (UTF-8) */
3163 sqlite3 **ppDb, /* OUT: SQLite db handle */
3164 int flags, /* Flags */
3165 const char *zVfs /* Name of VFS module to use */
3167 return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
3170 #ifndef SQLITE_OMIT_UTF16
3172 ** Open a new database handle.
3174 int sqlite3_open16(
3175 const void *zFilename,
3176 sqlite3 **ppDb
3178 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
3179 sqlite3_value *pVal;
3180 int rc;
3182 #ifdef SQLITE_ENABLE_API_ARMOR
3183 if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
3184 #endif
3185 *ppDb = 0;
3186 #ifndef SQLITE_OMIT_AUTOINIT
3187 rc = sqlite3_initialize();
3188 if( rc ) return rc;
3189 #endif
3190 if( zFilename==0 ) zFilename = "\000\000";
3191 pVal = sqlite3ValueNew(0);
3192 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
3193 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
3194 if( zFilename8 ){
3195 rc = openDatabase(zFilename8, ppDb,
3196 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
3197 assert( *ppDb || rc==SQLITE_NOMEM );
3198 if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
3199 SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
3201 }else{
3202 rc = SQLITE_NOMEM_BKPT;
3204 sqlite3ValueFree(pVal);
3206 return rc & 0xff;
3208 #endif /* SQLITE_OMIT_UTF16 */
3211 ** Register a new collation sequence with the database handle db.
3213 int sqlite3_create_collation(
3214 sqlite3* db,
3215 const char *zName,
3216 int enc,
3217 void* pCtx,
3218 int(*xCompare)(void*,int,const void*,int,const void*)
3220 return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
3224 ** Register a new collation sequence with the database handle db.
3226 int sqlite3_create_collation_v2(
3227 sqlite3* db,
3228 const char *zName,
3229 int enc,
3230 void* pCtx,
3231 int(*xCompare)(void*,int,const void*,int,const void*),
3232 void(*xDel)(void*)
3234 int rc;
3236 #ifdef SQLITE_ENABLE_API_ARMOR
3237 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
3238 #endif
3239 sqlite3_mutex_enter(db->mutex);
3240 assert( !db->mallocFailed );
3241 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
3242 rc = sqlite3ApiExit(db, rc);
3243 sqlite3_mutex_leave(db->mutex);
3244 return rc;
3247 #ifndef SQLITE_OMIT_UTF16
3249 ** Register a new collation sequence with the database handle db.
3251 int sqlite3_create_collation16(
3252 sqlite3* db,
3253 const void *zName,
3254 int enc,
3255 void* pCtx,
3256 int(*xCompare)(void*,int,const void*,int,const void*)
3258 int rc = SQLITE_OK;
3259 char *zName8;
3261 #ifdef SQLITE_ENABLE_API_ARMOR
3262 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
3263 #endif
3264 sqlite3_mutex_enter(db->mutex);
3265 assert( !db->mallocFailed );
3266 zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
3267 if( zName8 ){
3268 rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
3269 sqlite3DbFree(db, zName8);
3271 rc = sqlite3ApiExit(db, rc);
3272 sqlite3_mutex_leave(db->mutex);
3273 return rc;
3275 #endif /* SQLITE_OMIT_UTF16 */
3278 ** Register a collation sequence factory callback with the database handle
3279 ** db. Replace any previously installed collation sequence factory.
3281 int sqlite3_collation_needed(
3282 sqlite3 *db,
3283 void *pCollNeededArg,
3284 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
3286 #ifdef SQLITE_ENABLE_API_ARMOR
3287 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3288 #endif
3289 sqlite3_mutex_enter(db->mutex);
3290 db->xCollNeeded = xCollNeeded;
3291 db->xCollNeeded16 = 0;
3292 db->pCollNeededArg = pCollNeededArg;
3293 sqlite3_mutex_leave(db->mutex);
3294 return SQLITE_OK;
3297 #ifndef SQLITE_OMIT_UTF16
3299 ** Register a collation sequence factory callback with the database handle
3300 ** db. Replace any previously installed collation sequence factory.
3302 int sqlite3_collation_needed16(
3303 sqlite3 *db,
3304 void *pCollNeededArg,
3305 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
3307 #ifdef SQLITE_ENABLE_API_ARMOR
3308 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3309 #endif
3310 sqlite3_mutex_enter(db->mutex);
3311 db->xCollNeeded = 0;
3312 db->xCollNeeded16 = xCollNeeded16;
3313 db->pCollNeededArg = pCollNeededArg;
3314 sqlite3_mutex_leave(db->mutex);
3315 return SQLITE_OK;
3317 #endif /* SQLITE_OMIT_UTF16 */
3319 #ifndef SQLITE_OMIT_DEPRECATED
3321 ** This function is now an anachronism. It used to be used to recover from a
3322 ** malloc() failure, but SQLite now does this automatically.
3324 int sqlite3_global_recover(void){
3325 return SQLITE_OK;
3327 #endif
3330 ** Test to see whether or not the database connection is in autocommit
3331 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
3332 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
3333 ** by the next COMMIT or ROLLBACK.
3335 int sqlite3_get_autocommit(sqlite3 *db){
3336 #ifdef SQLITE_ENABLE_API_ARMOR
3337 if( !sqlite3SafetyCheckOk(db) ){
3338 (void)SQLITE_MISUSE_BKPT;
3339 return 0;
3341 #endif
3342 return db->autoCommit;
3346 ** The following routines are substitutes for constants SQLITE_CORRUPT,
3347 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
3348 ** constants. They serve two purposes:
3350 ** 1. Serve as a convenient place to set a breakpoint in a debugger
3351 ** to detect when version error conditions occurs.
3353 ** 2. Invoke sqlite3_log() to provide the source code location where
3354 ** a low-level error is first detected.
3356 int sqlite3ReportError(int iErr, int lineno, const char *zType){
3357 sqlite3_log(iErr, "%s at line %d of [%.10s]",
3358 zType, lineno, 20+sqlite3_sourceid());
3359 return iErr;
3361 int sqlite3CorruptError(int lineno){
3362 testcase( sqlite3GlobalConfig.xLog!=0 );
3363 return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
3365 int sqlite3MisuseError(int lineno){
3366 testcase( sqlite3GlobalConfig.xLog!=0 );
3367 return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
3369 int sqlite3CantopenError(int lineno){
3370 testcase( sqlite3GlobalConfig.xLog!=0 );
3371 return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
3373 #ifdef SQLITE_DEBUG
3374 int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
3375 char zMsg[100];
3376 sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
3377 testcase( sqlite3GlobalConfig.xLog!=0 );
3378 return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
3380 int sqlite3NomemError(int lineno){
3381 testcase( sqlite3GlobalConfig.xLog!=0 );
3382 return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
3384 int sqlite3IoerrnomemError(int lineno){
3385 testcase( sqlite3GlobalConfig.xLog!=0 );
3386 return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
3388 #endif
3390 #ifndef SQLITE_OMIT_DEPRECATED
3392 ** This is a convenience routine that makes sure that all thread-specific
3393 ** data for this thread has been deallocated.
3395 ** SQLite no longer uses thread-specific data so this routine is now a
3396 ** no-op. It is retained for historical compatibility.
3398 void sqlite3_thread_cleanup(void){
3400 #endif
3403 ** Return meta information about a specific column of a database table.
3404 ** See comment in sqlite3.h (sqlite.h.in) for details.
3406 int sqlite3_table_column_metadata(
3407 sqlite3 *db, /* Connection handle */
3408 const char *zDbName, /* Database name or NULL */
3409 const char *zTableName, /* Table name */
3410 const char *zColumnName, /* Column name */
3411 char const **pzDataType, /* OUTPUT: Declared data type */
3412 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
3413 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
3414 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
3415 int *pAutoinc /* OUTPUT: True if column is auto-increment */
3417 int rc;
3418 char *zErrMsg = 0;
3419 Table *pTab = 0;
3420 Column *pCol = 0;
3421 int iCol = 0;
3422 char const *zDataType = 0;
3423 char const *zCollSeq = 0;
3424 int notnull = 0;
3425 int primarykey = 0;
3426 int autoinc = 0;
3429 #ifdef SQLITE_ENABLE_API_ARMOR
3430 if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
3431 return SQLITE_MISUSE_BKPT;
3433 #endif
3435 /* Ensure the database schema has been loaded */
3436 sqlite3_mutex_enter(db->mutex);
3437 sqlite3BtreeEnterAll(db);
3438 rc = sqlite3Init(db, &zErrMsg);
3439 if( SQLITE_OK!=rc ){
3440 goto error_out;
3443 /* Locate the table in question */
3444 pTab = sqlite3FindTable(db, zTableName, zDbName);
3445 if( !pTab || pTab->pSelect ){
3446 pTab = 0;
3447 goto error_out;
3450 /* Find the column for which info is requested */
3451 if( zColumnName==0 ){
3452 /* Query for existance of table only */
3453 }else{
3454 for(iCol=0; iCol<pTab->nCol; iCol++){
3455 pCol = &pTab->aCol[iCol];
3456 if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
3457 break;
3460 if( iCol==pTab->nCol ){
3461 if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
3462 iCol = pTab->iPKey;
3463 pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
3464 }else{
3465 pTab = 0;
3466 goto error_out;
3471 /* The following block stores the meta information that will be returned
3472 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
3473 ** and autoinc. At this point there are two possibilities:
3475 ** 1. The specified column name was rowid", "oid" or "_rowid_"
3476 ** and there is no explicitly declared IPK column.
3478 ** 2. The table is not a view and the column name identified an
3479 ** explicitly declared column. Copy meta information from *pCol.
3481 if( pCol ){
3482 zDataType = sqlite3ColumnType(pCol,0);
3483 zCollSeq = pCol->zColl;
3484 notnull = pCol->notNull!=0;
3485 primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
3486 autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
3487 }else{
3488 zDataType = "INTEGER";
3489 primarykey = 1;
3491 if( !zCollSeq ){
3492 zCollSeq = sqlite3StrBINARY;
3495 error_out:
3496 sqlite3BtreeLeaveAll(db);
3498 /* Whether the function call succeeded or failed, set the output parameters
3499 ** to whatever their local counterparts contain. If an error did occur,
3500 ** this has the effect of zeroing all output parameters.
3502 if( pzDataType ) *pzDataType = zDataType;
3503 if( pzCollSeq ) *pzCollSeq = zCollSeq;
3504 if( pNotNull ) *pNotNull = notnull;
3505 if( pPrimaryKey ) *pPrimaryKey = primarykey;
3506 if( pAutoinc ) *pAutoinc = autoinc;
3508 if( SQLITE_OK==rc && !pTab ){
3509 sqlite3DbFree(db, zErrMsg);
3510 zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
3511 zColumnName);
3512 rc = SQLITE_ERROR;
3514 sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
3515 sqlite3DbFree(db, zErrMsg);
3516 rc = sqlite3ApiExit(db, rc);
3517 sqlite3_mutex_leave(db->mutex);
3518 return rc;
3522 ** Sleep for a little while. Return the amount of time slept.
3524 int sqlite3_sleep(int ms){
3525 sqlite3_vfs *pVfs;
3526 int rc;
3527 pVfs = sqlite3_vfs_find(0);
3528 if( pVfs==0 ) return 0;
3530 /* This function works in milliseconds, but the underlying OsSleep()
3531 ** API uses microseconds. Hence the 1000's.
3533 rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
3534 return rc;
3538 ** Enable or disable the extended result codes.
3540 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
3541 #ifdef SQLITE_ENABLE_API_ARMOR
3542 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3543 #endif
3544 sqlite3_mutex_enter(db->mutex);
3545 db->errMask = onoff ? 0xffffffff : 0xff;
3546 sqlite3_mutex_leave(db->mutex);
3547 return SQLITE_OK;
3551 ** Invoke the xFileControl method on a particular database.
3553 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
3554 int rc = SQLITE_ERROR;
3555 Btree *pBtree;
3557 #ifdef SQLITE_ENABLE_API_ARMOR
3558 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3559 #endif
3560 sqlite3_mutex_enter(db->mutex);
3561 pBtree = sqlite3DbNameToBtree(db, zDbName);
3562 if( pBtree ){
3563 Pager *pPager;
3564 sqlite3_file *fd;
3565 sqlite3BtreeEnter(pBtree);
3566 pPager = sqlite3BtreePager(pBtree);
3567 assert( pPager!=0 );
3568 fd = sqlite3PagerFile(pPager);
3569 assert( fd!=0 );
3570 if( op==SQLITE_FCNTL_FILE_POINTER ){
3571 *(sqlite3_file**)pArg = fd;
3572 rc = SQLITE_OK;
3573 }else if( op==SQLITE_FCNTL_VFS_POINTER ){
3574 *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
3575 rc = SQLITE_OK;
3576 }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
3577 *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
3578 rc = SQLITE_OK;
3579 }else if( fd->pMethods ){
3580 rc = sqlite3OsFileControl(fd, op, pArg);
3581 }else{
3582 rc = SQLITE_NOTFOUND;
3584 sqlite3BtreeLeave(pBtree);
3586 sqlite3_mutex_leave(db->mutex);
3587 return rc;
3591 ** Interface to the testing logic.
3593 int sqlite3_test_control(int op, ...){
3594 int rc = 0;
3595 #ifdef SQLITE_UNTESTABLE
3596 UNUSED_PARAMETER(op);
3597 #else
3598 va_list ap;
3599 va_start(ap, op);
3600 switch( op ){
3603 ** Save the current state of the PRNG.
3605 case SQLITE_TESTCTRL_PRNG_SAVE: {
3606 sqlite3PrngSaveState();
3607 break;
3611 ** Restore the state of the PRNG to the last state saved using
3612 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
3613 ** this verb acts like PRNG_RESET.
3615 case SQLITE_TESTCTRL_PRNG_RESTORE: {
3616 sqlite3PrngRestoreState();
3617 break;
3621 ** Reset the PRNG back to its uninitialized state. The next call
3622 ** to sqlite3_randomness() will reseed the PRNG using a single call
3623 ** to the xRandomness method of the default VFS.
3625 case SQLITE_TESTCTRL_PRNG_RESET: {
3626 sqlite3_randomness(0,0);
3627 break;
3631 ** sqlite3_test_control(BITVEC_TEST, size, program)
3633 ** Run a test against a Bitvec object of size. The program argument
3634 ** is an array of integers that defines the test. Return -1 on a
3635 ** memory allocation error, 0 on success, or non-zero for an error.
3636 ** See the sqlite3BitvecBuiltinTest() for additional information.
3638 case SQLITE_TESTCTRL_BITVEC_TEST: {
3639 int sz = va_arg(ap, int);
3640 int *aProg = va_arg(ap, int*);
3641 rc = sqlite3BitvecBuiltinTest(sz, aProg);
3642 break;
3646 ** sqlite3_test_control(FAULT_INSTALL, xCallback)
3648 ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
3649 ** if xCallback is not NULL.
3651 ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
3652 ** is called immediately after installing the new callback and the return
3653 ** value from sqlite3FaultSim(0) becomes the return from
3654 ** sqlite3_test_control().
3656 case SQLITE_TESTCTRL_FAULT_INSTALL: {
3657 /* MSVC is picky about pulling func ptrs from va lists.
3658 ** http://support.microsoft.com/kb/47961
3659 ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
3661 typedef int(*TESTCALLBACKFUNC_t)(int);
3662 sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
3663 rc = sqlite3FaultSim(0);
3664 break;
3668 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
3670 ** Register hooks to call to indicate which malloc() failures
3671 ** are benign.
3673 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
3674 typedef void (*void_function)(void);
3675 void_function xBenignBegin;
3676 void_function xBenignEnd;
3677 xBenignBegin = va_arg(ap, void_function);
3678 xBenignEnd = va_arg(ap, void_function);
3679 sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
3680 break;
3684 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
3686 ** Set the PENDING byte to the value in the argument, if X>0.
3687 ** Make no changes if X==0. Return the value of the pending byte
3688 ** as it existing before this routine was called.
3690 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
3691 ** an incompatible database file format. Changing the PENDING byte
3692 ** while any database connection is open results in undefined and
3693 ** deleterious behavior.
3695 case SQLITE_TESTCTRL_PENDING_BYTE: {
3696 rc = PENDING_BYTE;
3697 #ifndef SQLITE_OMIT_WSD
3699 unsigned int newVal = va_arg(ap, unsigned int);
3700 if( newVal ) sqlite3PendingByte = newVal;
3702 #endif
3703 break;
3707 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
3709 ** This action provides a run-time test to see whether or not
3710 ** assert() was enabled at compile-time. If X is true and assert()
3711 ** is enabled, then the return value is true. If X is true and
3712 ** assert() is disabled, then the return value is zero. If X is
3713 ** false and assert() is enabled, then the assertion fires and the
3714 ** process aborts. If X is false and assert() is disabled, then the
3715 ** return value is zero.
3717 case SQLITE_TESTCTRL_ASSERT: {
3718 volatile int x = 0;
3719 assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
3720 rc = x;
3721 break;
3726 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
3728 ** This action provides a run-time test to see how the ALWAYS and
3729 ** NEVER macros were defined at compile-time.
3731 ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
3733 ** The recommended test is X==2. If the return value is 2, that means
3734 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
3735 ** default setting. If the return value is 1, then ALWAYS() is either
3736 ** hard-coded to true or else it asserts if its argument is false.
3737 ** The first behavior (hard-coded to true) is the case if
3738 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
3739 ** behavior (assert if the argument to ALWAYS() is false) is the case if
3740 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
3742 ** The run-time test procedure might look something like this:
3744 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
3745 ** // ALWAYS() and NEVER() are no-op pass-through macros
3746 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
3747 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
3748 ** }else{
3749 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
3750 ** }
3752 case SQLITE_TESTCTRL_ALWAYS: {
3753 int x = va_arg(ap,int);
3754 rc = x ? ALWAYS(x) : 0;
3755 break;
3759 ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
3761 ** The integer returned reveals the byte-order of the computer on which
3762 ** SQLite is running:
3764 ** 1 big-endian, determined at run-time
3765 ** 10 little-endian, determined at run-time
3766 ** 432101 big-endian, determined at compile-time
3767 ** 123410 little-endian, determined at compile-time
3769 case SQLITE_TESTCTRL_BYTEORDER: {
3770 rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
3771 break;
3774 /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
3776 ** Set the nReserve size to N for the main database on the database
3777 ** connection db.
3779 case SQLITE_TESTCTRL_RESERVE: {
3780 sqlite3 *db = va_arg(ap, sqlite3*);
3781 int x = va_arg(ap,int);
3782 sqlite3_mutex_enter(db->mutex);
3783 sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
3784 sqlite3_mutex_leave(db->mutex);
3785 break;
3788 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
3790 ** Enable or disable various optimizations for testing purposes. The
3791 ** argument N is a bitmask of optimizations to be disabled. For normal
3792 ** operation N should be 0. The idea is that a test program (like the
3793 ** SQL Logic Test or SLT test module) can run the same SQL multiple times
3794 ** with various optimizations disabled to verify that the same answer
3795 ** is obtained in every case.
3797 case SQLITE_TESTCTRL_OPTIMIZATIONS: {
3798 sqlite3 *db = va_arg(ap, sqlite3*);
3799 db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
3800 break;
3803 #ifdef SQLITE_N_KEYWORD
3804 /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
3806 ** If zWord is a keyword recognized by the parser, then return the
3807 ** number of keywords. Or if zWord is not a keyword, return 0.
3809 ** This test feature is only available in the amalgamation since
3810 ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
3811 ** is built using separate source files.
3813 case SQLITE_TESTCTRL_ISKEYWORD: {
3814 const char *zWord = va_arg(ap, const char*);
3815 int n = sqlite3Strlen30(zWord);
3816 rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
3817 break;
3819 #endif
3821 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
3823 ** If parameter onoff is non-zero, configure the wrappers so that all
3824 ** subsequent calls to localtime() and variants fail. If onoff is zero,
3825 ** undo this setting.
3827 case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
3828 sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
3829 break;
3832 /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
3834 ** Set or clear a flag that indicates that the database file is always well-
3835 ** formed and never corrupt. This flag is clear by default, indicating that
3836 ** database files might have arbitrary corruption. Setting the flag during
3837 ** testing causes certain assert() statements in the code to be activated
3838 ** that demonstrat invariants on well-formed database files.
3840 case SQLITE_TESTCTRL_NEVER_CORRUPT: {
3841 sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
3842 break;
3845 /* Set the threshold at which OP_Once counters reset back to zero.
3846 ** By default this is 0x7ffffffe (over 2 billion), but that value is
3847 ** too big to test in a reasonable amount of time, so this control is
3848 ** provided to set a small and easily reachable reset value.
3850 case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
3851 sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
3852 break;
3855 /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
3857 ** Set the VDBE coverage callback function to xCallback with context
3858 ** pointer ptr.
3860 case SQLITE_TESTCTRL_VDBE_COVERAGE: {
3861 #ifdef SQLITE_VDBE_COVERAGE
3862 typedef void (*branch_callback)(void*,int,u8,u8);
3863 sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
3864 sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
3865 #endif
3866 break;
3869 /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
3870 case SQLITE_TESTCTRL_SORTER_MMAP: {
3871 sqlite3 *db = va_arg(ap, sqlite3*);
3872 db->nMaxSorterMmap = va_arg(ap, int);
3873 break;
3876 /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
3878 ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
3879 ** not.
3881 case SQLITE_TESTCTRL_ISINIT: {
3882 if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
3883 break;
3886 /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
3888 ** This test control is used to create imposter tables. "db" is a pointer
3889 ** to the database connection. dbName is the database name (ex: "main" or
3890 ** "temp") which will receive the imposter. "onOff" turns imposter mode on
3891 ** or off. "tnum" is the root page of the b-tree to which the imposter
3892 ** table should connect.
3894 ** Enable imposter mode only when the schema has already been parsed. Then
3895 ** run a single CREATE TABLE statement to construct the imposter table in
3896 ** the parsed schema. Then turn imposter mode back off again.
3898 ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
3899 ** the schema to be reparsed the next time it is needed. This has the
3900 ** effect of erasing all imposter tables.
3902 case SQLITE_TESTCTRL_IMPOSTER: {
3903 sqlite3 *db = va_arg(ap, sqlite3*);
3904 sqlite3_mutex_enter(db->mutex);
3905 db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
3906 db->init.busy = db->init.imposterTable = va_arg(ap,int);
3907 db->init.newTnum = va_arg(ap,int);
3908 if( db->init.busy==0 && db->init.newTnum>0 ){
3909 sqlite3ResetAllSchemasOfConnection(db);
3911 sqlite3_mutex_leave(db->mutex);
3912 break;
3915 #if defined(YYCOVERAGE)
3916 /* sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
3918 ** This test control (only available when SQLite is compiled with
3919 ** -DYYCOVERAGE) writes a report onto "out" that shows all
3920 ** state/lookahead combinations in the parser state machine
3921 ** which are never exercised. If any state is missed, make the
3922 ** return code SQLITE_ERROR.
3924 case SQLITE_TESTCTRL_PARSER_COVERAGE: {
3925 FILE *out = va_arg(ap, FILE*);
3926 if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
3927 break;
3929 #endif /* defined(YYCOVERAGE) */
3931 va_end(ap);
3932 #endif /* SQLITE_UNTESTABLE */
3933 return rc;
3937 ** This is a utility routine, useful to VFS implementations, that checks
3938 ** to see if a database file was a URI that contained a specific query
3939 ** parameter, and if so obtains the value of the query parameter.
3941 ** The zFilename argument is the filename pointer passed into the xOpen()
3942 ** method of a VFS implementation. The zParam argument is the name of the
3943 ** query parameter we seek. This routine returns the value of the zParam
3944 ** parameter if it exists. If the parameter does not exist, this routine
3945 ** returns a NULL pointer.
3947 const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
3948 if( zFilename==0 || zParam==0 ) return 0;
3949 zFilename += sqlite3Strlen30(zFilename) + 1;
3950 while( zFilename[0] ){
3951 int x = strcmp(zFilename, zParam);
3952 zFilename += sqlite3Strlen30(zFilename) + 1;
3953 if( x==0 ) return zFilename;
3954 zFilename += sqlite3Strlen30(zFilename) + 1;
3956 return 0;
3960 ** Return a boolean value for a query parameter.
3962 int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
3963 const char *z = sqlite3_uri_parameter(zFilename, zParam);
3964 bDflt = bDflt!=0;
3965 return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
3969 ** Return a 64-bit integer value for a query parameter.
3971 sqlite3_int64 sqlite3_uri_int64(
3972 const char *zFilename, /* Filename as passed to xOpen */
3973 const char *zParam, /* URI parameter sought */
3974 sqlite3_int64 bDflt /* return if parameter is missing */
3976 const char *z = sqlite3_uri_parameter(zFilename, zParam);
3977 sqlite3_int64 v;
3978 if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
3979 bDflt = v;
3981 return bDflt;
3985 ** Return the Btree pointer identified by zDbName. Return NULL if not found.
3987 Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
3988 int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
3989 return iDb<0 ? 0 : db->aDb[iDb].pBt;
3993 ** Return the filename of the database associated with a database
3994 ** connection.
3996 const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
3997 Btree *pBt;
3998 #ifdef SQLITE_ENABLE_API_ARMOR
3999 if( !sqlite3SafetyCheckOk(db) ){
4000 (void)SQLITE_MISUSE_BKPT;
4001 return 0;
4003 #endif
4004 pBt = sqlite3DbNameToBtree(db, zDbName);
4005 return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
4009 ** Return 1 if database is read-only or 0 if read/write. Return -1 if
4010 ** no such database exists.
4012 int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
4013 Btree *pBt;
4014 #ifdef SQLITE_ENABLE_API_ARMOR
4015 if( !sqlite3SafetyCheckOk(db) ){
4016 (void)SQLITE_MISUSE_BKPT;
4017 return -1;
4019 #endif
4020 pBt = sqlite3DbNameToBtree(db, zDbName);
4021 return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
4024 #ifdef SQLITE_ENABLE_SNAPSHOT
4026 ** Obtain a snapshot handle for the snapshot of database zDb currently
4027 ** being read by handle db.
4029 int sqlite3_snapshot_get(
4030 sqlite3 *db,
4031 const char *zDb,
4032 sqlite3_snapshot **ppSnapshot
4034 int rc = SQLITE_ERROR;
4035 #ifndef SQLITE_OMIT_WAL
4037 #ifdef SQLITE_ENABLE_API_ARMOR
4038 if( !sqlite3SafetyCheckOk(db) ){
4039 return SQLITE_MISUSE_BKPT;
4041 #endif
4042 sqlite3_mutex_enter(db->mutex);
4044 if( db->autoCommit==0 ){
4045 int iDb = sqlite3FindDbName(db, zDb);
4046 if( iDb==0 || iDb>1 ){
4047 Btree *pBt = db->aDb[iDb].pBt;
4048 if( 0==sqlite3BtreeIsInTrans(pBt) ){
4049 rc = sqlite3BtreeBeginTrans(pBt, 0);
4050 if( rc==SQLITE_OK ){
4051 rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
4057 sqlite3_mutex_leave(db->mutex);
4058 #endif /* SQLITE_OMIT_WAL */
4059 return rc;
4063 ** Open a read-transaction on the snapshot idendified by pSnapshot.
4065 int sqlite3_snapshot_open(
4066 sqlite3 *db,
4067 const char *zDb,
4068 sqlite3_snapshot *pSnapshot
4070 int rc = SQLITE_ERROR;
4071 #ifndef SQLITE_OMIT_WAL
4073 #ifdef SQLITE_ENABLE_API_ARMOR
4074 if( !sqlite3SafetyCheckOk(db) ){
4075 return SQLITE_MISUSE_BKPT;
4077 #endif
4078 sqlite3_mutex_enter(db->mutex);
4079 if( db->autoCommit==0 ){
4080 int iDb;
4081 iDb = sqlite3FindDbName(db, zDb);
4082 if( iDb==0 || iDb>1 ){
4083 Btree *pBt = db->aDb[iDb].pBt;
4084 if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
4085 rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
4086 if( rc==SQLITE_OK ){
4087 rc = sqlite3BtreeBeginTrans(pBt, 0);
4088 sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
4094 sqlite3_mutex_leave(db->mutex);
4095 #endif /* SQLITE_OMIT_WAL */
4096 return rc;
4100 ** Recover as many snapshots as possible from the wal file associated with
4101 ** schema zDb of database db.
4103 int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
4104 int rc = SQLITE_ERROR;
4105 int iDb;
4106 #ifndef SQLITE_OMIT_WAL
4108 #ifdef SQLITE_ENABLE_API_ARMOR
4109 if( !sqlite3SafetyCheckOk(db) ){
4110 return SQLITE_MISUSE_BKPT;
4112 #endif
4114 sqlite3_mutex_enter(db->mutex);
4115 iDb = sqlite3FindDbName(db, zDb);
4116 if( iDb==0 || iDb>1 ){
4117 Btree *pBt = db->aDb[iDb].pBt;
4118 if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
4119 rc = sqlite3BtreeBeginTrans(pBt, 0);
4120 if( rc==SQLITE_OK ){
4121 rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
4122 sqlite3BtreeCommit(pBt);
4126 sqlite3_mutex_leave(db->mutex);
4127 #endif /* SQLITE_OMIT_WAL */
4128 return rc;
4132 ** Free a snapshot handle obtained from sqlite3_snapshot_get().
4134 void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
4135 sqlite3_free(pSnapshot);
4137 #endif /* SQLITE_ENABLE_SNAPSHOT */
4139 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
4141 ** Given the name of a compile-time option, return true if that option
4142 ** was used and false if not.
4144 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
4145 ** is not required for a match.
4147 int sqlite3_compileoption_used(const char *zOptName){
4148 int i, n;
4149 int nOpt;
4150 const char **azCompileOpt;
4152 #if SQLITE_ENABLE_API_ARMOR
4153 if( zOptName==0 ){
4154 (void)SQLITE_MISUSE_BKPT;
4155 return 0;
4157 #endif
4159 azCompileOpt = sqlite3CompileOptions(&nOpt);
4161 if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
4162 n = sqlite3Strlen30(zOptName);
4164 /* Since nOpt is normally in single digits, a linear search is
4165 ** adequate. No need for a binary search. */
4166 for(i=0; i<nOpt; i++){
4167 if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
4168 && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
4170 return 1;
4173 return 0;
4177 ** Return the N-th compile-time option string. If N is out of range,
4178 ** return a NULL pointer.
4180 const char *sqlite3_compileoption_get(int N){
4181 int nOpt;
4182 const char **azCompileOpt;
4183 azCompileOpt = sqlite3CompileOptions(&nOpt);
4184 if( N>=0 && N<nOpt ){
4185 return azCompileOpt[N];
4187 return 0;
4189 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */