4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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
22 #ifdef SQLITE_ENABLE_RTREE
25 #ifdef SQLITE_ENABLE_ICU
26 # include "sqliteicu.h"
29 #ifndef SQLITE_AMALGAMATION
30 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
31 ** contains the text of SQLITE_VERSION macro.
33 const char sqlite3_version
[] = SQLITE_VERSION
;
36 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
37 ** a pointer to the to the sqlite3_version[] string constant.
39 const char *sqlite3_libversion(void){ return sqlite3_version
; }
41 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
42 ** pointer to a string constant whose value is the same as the
43 ** SQLITE_SOURCE_ID C preprocessor macro.
45 const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID
; }
47 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
48 ** returns an integer equal to SQLITE_VERSION_NUMBER.
50 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER
; }
52 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
53 ** zero if and only if SQLite was compiled with mutexing code omitted due to
54 ** the SQLITE_THREADSAFE compile-time option being set to 0.
56 int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE
; }
58 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
60 ** If the following function pointer is not NULL and if
61 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
62 ** I/O active are written using this function. These messages
63 ** are intended for debugging activity only.
65 void (*sqlite3IoTrace
)(const char*, ...) = 0;
69 ** If the following global variable points to a string which is the
70 ** name of a directory, then that directory will be used to store
73 ** See also the "PRAGMA temp_store_directory" SQL command.
75 char *sqlite3_temp_directory
= 0;
78 ** If the following global variable points to a string which is the
79 ** name of a directory, then that directory will be used to store
80 ** all database files specified with a relative pathname.
82 ** See also the "PRAGMA data_store_directory" SQL command.
84 char *sqlite3_data_directory
= 0;
89 ** This routine must be called to initialize the memory allocation,
90 ** VFS, and mutex subsystems prior to doing any serious work with
91 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
92 ** this routine will be called automatically by key routines such as
95 ** This routine is a no-op except on its very first call for the process,
96 ** or for the first call after a call to sqlite3_shutdown.
98 ** The first thread to call this routine runs the initialization to
99 ** completion. If subsequent threads call this routine before the first
100 ** thread has finished the initialization process, then the subsequent
101 ** threads must block until the first thread finishes with the initialization.
103 ** The first thread might call this routine recursively. Recursive
104 ** calls to this routine should not block, of course. Otherwise the
105 ** initialization process would never complete.
107 ** Let X be the first thread to enter this routine. Let Y be some other
108 ** thread. Then while the initial invocation of this routine by X is
109 ** incomplete, it is required that:
111 ** * Calls to this routine from Y must block until the outer-most
112 ** call by X completes.
114 ** * Recursive calls to this routine from thread X return immediately
117 int sqlite3_initialize(void){
118 MUTEX_LOGIC( sqlite3_mutex
*pMaster
; ) /* The main static mutex */
119 int rc
; /* Result code */
120 #ifdef SQLITE_EXTRA_INIT
121 int bRunExtraInit
= 0; /* Extra initialization needed */
124 #ifdef SQLITE_OMIT_WSD
125 rc
= sqlite3_wsd_init(4096, 24);
131 /* If SQLite is already completely initialized, then this call
132 ** to sqlite3_initialize() should be a no-op. But the initialization
133 ** must be complete. So isInit must not be set until the very end
136 if( sqlite3GlobalConfig
.isInit
) return SQLITE_OK
;
138 /* Make sure the mutex subsystem is initialized. If unable to
139 ** initialize the mutex subsystem, return early with the error.
140 ** If the system is so sick that we are unable to allocate a mutex,
141 ** there is not much SQLite is going to be able to do.
143 ** The mutex subsystem must take care of serializing its own
146 rc
= sqlite3MutexInit();
149 /* Initialize the malloc() system and the recursive pInitMutex mutex.
150 ** This operation is protected by the STATIC_MASTER mutex. Note that
151 ** MutexAlloc() is called for a static mutex prior to initializing the
152 ** malloc subsystem - this implies that the allocation of a static
153 ** mutex must not require support from the malloc subsystem.
155 MUTEX_LOGIC( pMaster
= sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER
); )
156 sqlite3_mutex_enter(pMaster
);
157 sqlite3GlobalConfig
.isMutexInit
= 1;
158 if( !sqlite3GlobalConfig
.isMallocInit
){
159 rc
= sqlite3MallocInit();
162 sqlite3GlobalConfig
.isMallocInit
= 1;
163 if( !sqlite3GlobalConfig
.pInitMutex
){
164 sqlite3GlobalConfig
.pInitMutex
=
165 sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE
);
166 if( sqlite3GlobalConfig
.bCoreMutex
&& !sqlite3GlobalConfig
.pInitMutex
){
172 sqlite3GlobalConfig
.nRefInitMutex
++;
174 sqlite3_mutex_leave(pMaster
);
176 /* If rc is not SQLITE_OK at this point, then either the malloc
177 ** subsystem could not be initialized or the system failed to allocate
178 ** the pInitMutex mutex. Return an error in either case. */
183 /* Do the rest of the initialization under the recursive mutex so
184 ** that we will be able to handle recursive calls into
185 ** sqlite3_initialize(). The recursive calls normally come through
186 ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
187 ** recursive calls might also be possible.
189 ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
190 ** to the xInit method, so the xInit method need not be threadsafe.
192 ** The following mutex is what serializes access to the appdef pcache xInit
193 ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
194 ** call to sqlite3PcacheInitialize().
196 sqlite3_mutex_enter(sqlite3GlobalConfig
.pInitMutex
);
197 if( sqlite3GlobalConfig
.isInit
==0 && sqlite3GlobalConfig
.inProgress
==0 ){
198 FuncDefHash
*pHash
= &GLOBAL(FuncDefHash
, sqlite3GlobalFunctions
);
199 sqlite3GlobalConfig
.inProgress
= 1;
200 memset(pHash
, 0, sizeof(sqlite3GlobalFunctions
));
201 sqlite3RegisterGlobalFunctions();
202 if( sqlite3GlobalConfig
.isPCacheInit
==0 ){
203 rc
= sqlite3PcacheInitialize();
206 sqlite3GlobalConfig
.isPCacheInit
= 1;
207 rc
= sqlite3OsInit();
210 sqlite3PCacheBufferSetup( sqlite3GlobalConfig
.pPage
,
211 sqlite3GlobalConfig
.szPage
, sqlite3GlobalConfig
.nPage
);
212 sqlite3GlobalConfig
.isInit
= 1;
213 #ifdef SQLITE_EXTRA_INIT
217 sqlite3GlobalConfig
.inProgress
= 0;
219 sqlite3_mutex_leave(sqlite3GlobalConfig
.pInitMutex
);
221 /* Go back under the static mutex and clean up the recursive
222 ** mutex to prevent a resource leak.
224 sqlite3_mutex_enter(pMaster
);
225 sqlite3GlobalConfig
.nRefInitMutex
--;
226 if( sqlite3GlobalConfig
.nRefInitMutex
<=0 ){
227 assert( sqlite3GlobalConfig
.nRefInitMutex
==0 );
228 sqlite3_mutex_free(sqlite3GlobalConfig
.pInitMutex
);
229 sqlite3GlobalConfig
.pInitMutex
= 0;
231 sqlite3_mutex_leave(pMaster
);
233 /* The following is just a sanity check to make sure SQLite has
234 ** been compiled correctly. It is important to run this code, but
235 ** we don't want to run it too often and soak up CPU cycles for no
236 ** reason. So we run it once during initialization.
239 #ifndef SQLITE_OMIT_FLOATING_POINT
240 /* This section of code's only "output" is via assert() statements. */
241 if ( rc
==SQLITE_OK
){
242 u64 x
= (((u64
)1)<<63)-1;
244 assert(sizeof(x
)==8);
245 assert(sizeof(x
)==sizeof(y
));
247 assert( sqlite3IsNaN(y
) );
252 /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
253 ** compile-time option.
255 #ifdef SQLITE_EXTRA_INIT
257 int SQLITE_EXTRA_INIT(const char*);
258 rc
= SQLITE_EXTRA_INIT(0);
266 ** Undo the effects of sqlite3_initialize(). Must not be called while
267 ** there are outstanding database connections or memory allocations or
268 ** while any part of SQLite is otherwise in use in any thread. This
269 ** routine is not threadsafe. But it is safe to invoke this routine
270 ** on when SQLite is already shut down. If SQLite is already shut down
271 ** when this routine is invoked, then this routine is a harmless no-op.
273 int sqlite3_shutdown(void){
274 if( sqlite3GlobalConfig
.isInit
){
275 #ifdef SQLITE_EXTRA_SHUTDOWN
276 void SQLITE_EXTRA_SHUTDOWN(void);
277 SQLITE_EXTRA_SHUTDOWN();
280 sqlite3_reset_auto_extension();
281 sqlite3GlobalConfig
.isInit
= 0;
283 if( sqlite3GlobalConfig
.isPCacheInit
){
284 sqlite3PcacheShutdown();
285 sqlite3GlobalConfig
.isPCacheInit
= 0;
287 if( sqlite3GlobalConfig
.isMallocInit
){
289 sqlite3GlobalConfig
.isMallocInit
= 0;
291 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
292 /* The heap subsystem has now been shutdown and these values are supposed
293 ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
294 ** which would rely on that heap subsystem; therefore, make sure these
295 ** values cannot refer to heap memory that was just invalidated when the
296 ** heap subsystem was shutdown. This is only done if the current call to
297 ** this function resulted in the heap subsystem actually being shutdown.
299 sqlite3_data_directory
= 0;
300 sqlite3_temp_directory
= 0;
303 if( sqlite3GlobalConfig
.isMutexInit
){
305 sqlite3GlobalConfig
.isMutexInit
= 0;
312 ** This API allows applications to modify the global configuration of
313 ** the SQLite library at run-time.
315 ** This routine should only be called when there are no outstanding
316 ** database connections or memory allocations. This routine is not
317 ** threadsafe. Failure to heed these warnings can lead to unpredictable
320 int sqlite3_config(int op
, ...){
324 /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
325 ** the SQLite library is in use. */
326 if( sqlite3GlobalConfig
.isInit
) return SQLITE_MISUSE_BKPT
;
331 /* Mutex configuration options are only available in a threadsafe
334 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
335 case SQLITE_CONFIG_SINGLETHREAD
: {
336 /* Disable all mutexing */
337 sqlite3GlobalConfig
.bCoreMutex
= 0;
338 sqlite3GlobalConfig
.bFullMutex
= 0;
341 case SQLITE_CONFIG_MULTITHREAD
: {
342 /* Disable mutexing of database connections */
343 /* Enable mutexing of core data structures */
344 sqlite3GlobalConfig
.bCoreMutex
= 1;
345 sqlite3GlobalConfig
.bFullMutex
= 0;
348 case SQLITE_CONFIG_SERIALIZED
: {
349 /* Enable all mutexing */
350 sqlite3GlobalConfig
.bCoreMutex
= 1;
351 sqlite3GlobalConfig
.bFullMutex
= 1;
354 case SQLITE_CONFIG_MUTEX
: {
355 /* Specify an alternative mutex implementation */
356 sqlite3GlobalConfig
.mutex
= *va_arg(ap
, sqlite3_mutex_methods
*);
359 case SQLITE_CONFIG_GETMUTEX
: {
360 /* Retrieve the current mutex implementation */
361 *va_arg(ap
, sqlite3_mutex_methods
*) = sqlite3GlobalConfig
.mutex
;
367 case SQLITE_CONFIG_MALLOC
: {
368 /* Specify an alternative malloc implementation */
369 sqlite3GlobalConfig
.m
= *va_arg(ap
, sqlite3_mem_methods
*);
372 case SQLITE_CONFIG_GETMALLOC
: {
373 /* Retrieve the current malloc() implementation */
374 if( sqlite3GlobalConfig
.m
.xMalloc
==0 ) sqlite3MemSetDefault();
375 *va_arg(ap
, sqlite3_mem_methods
*) = sqlite3GlobalConfig
.m
;
378 case SQLITE_CONFIG_MEMSTATUS
: {
379 /* Enable or disable the malloc status collection */
380 sqlite3GlobalConfig
.bMemstat
= va_arg(ap
, int);
383 case SQLITE_CONFIG_SCRATCH
: {
384 /* Designate a buffer for scratch memory space */
385 sqlite3GlobalConfig
.pScratch
= va_arg(ap
, void*);
386 sqlite3GlobalConfig
.szScratch
= va_arg(ap
, int);
387 sqlite3GlobalConfig
.nScratch
= va_arg(ap
, int);
390 case SQLITE_CONFIG_PAGECACHE
: {
391 /* Designate a buffer for page cache memory space */
392 sqlite3GlobalConfig
.pPage
= va_arg(ap
, void*);
393 sqlite3GlobalConfig
.szPage
= va_arg(ap
, int);
394 sqlite3GlobalConfig
.nPage
= va_arg(ap
, int);
398 case SQLITE_CONFIG_PCACHE
: {
402 case SQLITE_CONFIG_GETPCACHE
: {
408 case SQLITE_CONFIG_PCACHE2
: {
409 /* Specify an alternative page cache implementation */
410 sqlite3GlobalConfig
.pcache2
= *va_arg(ap
, sqlite3_pcache_methods2
*);
413 case SQLITE_CONFIG_GETPCACHE2
: {
414 if( sqlite3GlobalConfig
.pcache2
.xInit
==0 ){
415 sqlite3PCacheSetDefault();
417 *va_arg(ap
, sqlite3_pcache_methods2
*) = sqlite3GlobalConfig
.pcache2
;
421 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
422 case SQLITE_CONFIG_HEAP
: {
423 /* Designate a buffer for heap memory space */
424 sqlite3GlobalConfig
.pHeap
= va_arg(ap
, void*);
425 sqlite3GlobalConfig
.nHeap
= va_arg(ap
, int);
426 sqlite3GlobalConfig
.mnReq
= va_arg(ap
, int);
428 if( sqlite3GlobalConfig
.mnReq
<1 ){
429 sqlite3GlobalConfig
.mnReq
= 1;
430 }else if( sqlite3GlobalConfig
.mnReq
>(1<<12) ){
431 /* cap min request size at 2^12 */
432 sqlite3GlobalConfig
.mnReq
= (1<<12);
435 if( sqlite3GlobalConfig
.pHeap
==0 ){
436 /* If the heap pointer is NULL, then restore the malloc implementation
437 ** back to NULL pointers too. This will cause the malloc to go
438 ** back to its default implementation when sqlite3_initialize() is
441 memset(&sqlite3GlobalConfig
.m
, 0, sizeof(sqlite3GlobalConfig
.m
));
443 /* The heap pointer is not NULL, then install one of the
444 ** mem5.c/mem3.c methods. The enclosing #if guarantees at
445 ** least one of these methods is currently enabled.
447 #ifdef SQLITE_ENABLE_MEMSYS3
448 sqlite3GlobalConfig
.m
= *sqlite3MemGetMemsys3();
450 #ifdef SQLITE_ENABLE_MEMSYS5
451 sqlite3GlobalConfig
.m
= *sqlite3MemGetMemsys5();
458 case SQLITE_CONFIG_LOOKASIDE
: {
459 sqlite3GlobalConfig
.szLookaside
= va_arg(ap
, int);
460 sqlite3GlobalConfig
.nLookaside
= va_arg(ap
, int);
464 /* Record a pointer to the logger function and its first argument.
465 ** The default is NULL. Logging is disabled if the function pointer is
468 case SQLITE_CONFIG_LOG
: {
469 /* MSVC is picky about pulling func ptrs from va lists.
470 ** http://support.microsoft.com/kb/47961
471 ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
473 typedef void(*LOGFUNC_t
)(void*,int,const char*);
474 sqlite3GlobalConfig
.xLog
= va_arg(ap
, LOGFUNC_t
);
475 sqlite3GlobalConfig
.pLogArg
= va_arg(ap
, void*);
479 /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
480 ** can be changed at start-time using the
481 ** sqlite3_config(SQLITE_CONFIG_URI,1) or
482 ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
484 case SQLITE_CONFIG_URI
: {
485 sqlite3GlobalConfig
.bOpenUri
= va_arg(ap
, int);
489 case SQLITE_CONFIG_COVERING_INDEX_SCAN
: {
490 sqlite3GlobalConfig
.bUseCis
= va_arg(ap
, int);
494 #ifdef SQLITE_ENABLE_SQLLOG
495 case SQLITE_CONFIG_SQLLOG
: {
496 typedef void(*SQLLOGFUNC_t
)(void*, sqlite3
*, const char*, int);
497 sqlite3GlobalConfig
.xSqllog
= va_arg(ap
, SQLLOGFUNC_t
);
498 sqlite3GlobalConfig
.pSqllogArg
= va_arg(ap
, void *);
503 case SQLITE_CONFIG_MMAP_SIZE
: {
504 sqlite3_int64 szMmap
= va_arg(ap
, sqlite3_int64
);
505 sqlite3_int64 mxMmap
= va_arg(ap
, sqlite3_int64
);
506 if( mxMmap
<0 || mxMmap
>SQLITE_MAX_MMAP_SIZE
){
507 mxMmap
= SQLITE_MAX_MMAP_SIZE
;
509 sqlite3GlobalConfig
.mxMmap
= mxMmap
;
510 if( szMmap
<0 ) szMmap
= SQLITE_DEFAULT_MMAP_SIZE
;
511 if( szMmap
>mxMmap
) szMmap
= mxMmap
;
512 sqlite3GlobalConfig
.szMmap
= szMmap
;
516 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC)
517 case SQLITE_CONFIG_WIN32_HEAPSIZE
: {
518 sqlite3GlobalConfig
.nHeap
= va_arg(ap
, int);
533 ** Set up the lookaside buffers for a database connection.
534 ** Return SQLITE_OK on success.
535 ** If lookaside is already active, return SQLITE_BUSY.
537 ** The sz parameter is the number of bytes in each lookaside slot.
538 ** The cnt parameter is the number of slots. If pStart is NULL the
539 ** space for the lookaside memory is obtained from sqlite3_malloc().
540 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
541 ** the lookaside memory.
543 static int setupLookaside(sqlite3
*db
, void *pBuf
, int sz
, int cnt
){
545 if( db
->lookaside
.nOut
){
548 /* Free any existing lookaside buffer for this handle before
549 ** allocating a new one so we don't have to have space for
550 ** both at the same time.
552 if( db
->lookaside
.bMalloced
){
553 sqlite3_free(db
->lookaside
.pStart
);
555 /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
556 ** than a pointer to be useful.
558 sz
= ROUNDDOWN8(sz
); /* IMP: R-33038-09382 */
559 if( sz
<=(int)sizeof(LookasideSlot
*) ) sz
= 0;
561 if( sz
==0 || cnt
==0 ){
565 sqlite3BeginBenignMalloc();
566 pStart
= sqlite3Malloc( sz
*cnt
); /* IMP: R-61949-35727 */
567 sqlite3EndBenignMalloc();
568 if( pStart
) cnt
= sqlite3MallocSize(pStart
)/sz
;
572 db
->lookaside
.pStart
= pStart
;
573 db
->lookaside
.pFree
= 0;
574 db
->lookaside
.sz
= (u16
)sz
;
578 assert( sz
> (int)sizeof(LookasideSlot
*) );
579 p
= (LookasideSlot
*)pStart
;
580 for(i
=cnt
-1; i
>=0; i
--){
581 p
->pNext
= db
->lookaside
.pFree
;
582 db
->lookaside
.pFree
= p
;
583 p
= (LookasideSlot
*)&((u8
*)p
)[sz
];
585 db
->lookaside
.pEnd
= p
;
586 db
->lookaside
.bEnabled
= 1;
587 db
->lookaside
.bMalloced
= pBuf
==0 ?1:0;
589 db
->lookaside
.pStart
= db
;
590 db
->lookaside
.pEnd
= db
;
591 db
->lookaside
.bEnabled
= 0;
592 db
->lookaside
.bMalloced
= 0;
598 ** Return the mutex associated with a database connection.
600 sqlite3_mutex
*sqlite3_db_mutex(sqlite3
*db
){
605 ** Free up as much memory as we can from the given database
608 int sqlite3_db_release_memory(sqlite3
*db
){
610 sqlite3_mutex_enter(db
->mutex
);
611 sqlite3BtreeEnterAll(db
);
612 for(i
=0; i
<db
->nDb
; i
++){
613 Btree
*pBt
= db
->aDb
[i
].pBt
;
615 Pager
*pPager
= sqlite3BtreePager(pBt
);
616 sqlite3PagerShrink(pPager
);
619 sqlite3BtreeLeaveAll(db
);
620 sqlite3_mutex_leave(db
->mutex
);
625 ** Configuration settings for an individual database connection
627 int sqlite3_db_config(sqlite3
*db
, int op
, ...){
632 case SQLITE_DBCONFIG_LOOKASIDE
: {
633 void *pBuf
= va_arg(ap
, void*); /* IMP: R-26835-10964 */
634 int sz
= va_arg(ap
, int); /* IMP: R-47871-25994 */
635 int cnt
= va_arg(ap
, int); /* IMP: R-04460-53386 */
636 rc
= setupLookaside(db
, pBuf
, sz
, cnt
);
640 static const struct {
641 int op
; /* The opcode */
642 u32 mask
; /* Mask of the bit in sqlite3.flags to set/clear */
644 { SQLITE_DBCONFIG_ENABLE_FKEY
, SQLITE_ForeignKeys
},
645 { SQLITE_DBCONFIG_ENABLE_TRIGGER
, SQLITE_EnableTrigger
},
648 rc
= SQLITE_ERROR
; /* IMP: R-42790-23372 */
649 for(i
=0; i
<ArraySize(aFlagOp
); i
++){
650 if( aFlagOp
[i
].op
==op
){
651 int onoff
= va_arg(ap
, int);
652 int *pRes
= va_arg(ap
, int*);
653 int oldFlags
= db
->flags
;
655 db
->flags
|= aFlagOp
[i
].mask
;
656 }else if( onoff
==0 ){
657 db
->flags
&= ~aFlagOp
[i
].mask
;
659 if( oldFlags
!=db
->flags
){
660 sqlite3ExpirePreparedStatements(db
);
663 *pRes
= (db
->flags
& aFlagOp
[i
].mask
)!=0;
678 ** Return true if the buffer z[0..n-1] contains all spaces.
680 static int allSpaces(const char *z
, int n
){
681 while( n
>0 && z
[n
-1]==' ' ){ n
--; }
686 ** This is the default collating function named "BINARY" which is always
689 ** If the padFlag argument is not NULL then space padding at the end
690 ** of strings is ignored. This implements the RTRIM collation.
692 static int binCollFunc(
694 int nKey1
, const void *pKey1
,
695 int nKey2
, const void *pKey2
698 n
= nKey1
<nKey2
? nKey1
: nKey2
;
699 rc
= memcmp(pKey1
, pKey2
, n
);
702 && allSpaces(((char*)pKey1
)+n
, nKey1
-n
)
703 && allSpaces(((char*)pKey2
)+n
, nKey2
-n
)
705 /* Leave rc unchanged at 0 */
714 ** Another built-in collating sequence: NOCASE.
716 ** This collating sequence is intended to be used for "case independent
717 ** comparison". SQLite's knowledge of upper and lower case equivalents
718 ** extends only to the 26 characters used in the English language.
720 ** At the moment there is only a UTF-8 implementation.
722 static int nocaseCollatingFunc(
724 int nKey1
, const void *pKey1
,
725 int nKey2
, const void *pKey2
727 int r
= sqlite3StrNICmp(
728 (const char *)pKey1
, (const char *)pKey2
, (nKey1
<nKey2
)?nKey1
:nKey2
);
729 UNUSED_PARAMETER(NotUsed
);
737 ** Return the ROWID of the most recent insert
739 sqlite_int64
sqlite3_last_insert_rowid(sqlite3
*db
){
740 return db
->lastRowid
;
744 ** Return the number of changes in the most recent call to sqlite3_exec().
746 int sqlite3_changes(sqlite3
*db
){
751 ** Return the number of changes since the database handle was opened.
753 int sqlite3_total_changes(sqlite3
*db
){
754 return db
->nTotalChange
;
758 ** Close all open savepoints. This function only manipulates fields of the
759 ** database handle object, it does not close any savepoints that may be open
760 ** at the b-tree/pager level.
762 void sqlite3CloseSavepoints(sqlite3
*db
){
763 while( db
->pSavepoint
){
764 Savepoint
*pTmp
= db
->pSavepoint
;
765 db
->pSavepoint
= pTmp
->pNext
;
766 sqlite3DbFree(db
, pTmp
);
770 db
->isTransactionSavepoint
= 0;
774 ** Invoke the destructor function associated with FuncDef p, if any. Except,
775 ** if this is not the last copy of the function, do not invoke it. Multiple
776 ** copies of a single function are created when create_function() is called
777 ** with SQLITE_ANY as the encoding.
779 static void functionDestroy(sqlite3
*db
, FuncDef
*p
){
780 FuncDestructor
*pDestructor
= p
->pDestructor
;
783 if( pDestructor
->nRef
==0 ){
784 pDestructor
->xDestroy(pDestructor
->pUserData
);
785 sqlite3DbFree(db
, pDestructor
);
791 ** Disconnect all sqlite3_vtab objects that belong to database connection
792 ** db. This is called when db is being closed.
794 static void disconnectAllVtab(sqlite3
*db
){
795 #ifndef SQLITE_OMIT_VIRTUALTABLE
797 sqlite3BtreeEnterAll(db
);
798 for(i
=0; i
<db
->nDb
; i
++){
799 Schema
*pSchema
= db
->aDb
[i
].pSchema
;
800 if( db
->aDb
[i
].pSchema
){
802 for(p
=sqliteHashFirst(&pSchema
->tblHash
); p
; p
=sqliteHashNext(p
)){
803 Table
*pTab
= (Table
*)sqliteHashData(p
);
804 if( IsVirtual(pTab
) ) sqlite3VtabDisconnect(db
, pTab
);
808 sqlite3VtabUnlockList(db
);
809 sqlite3BtreeLeaveAll(db
);
811 UNUSED_PARAMETER(db
);
816 ** Return TRUE if database connection db has unfinalized prepared
817 ** statements or unfinished sqlite3_backup objects.
819 static int connectionIsBusy(sqlite3
*db
){
821 assert( sqlite3_mutex_held(db
->mutex
) );
822 if( db
->pVdbe
) return 1;
823 for(j
=0; j
<db
->nDb
; j
++){
824 Btree
*pBt
= db
->aDb
[j
].pBt
;
825 if( pBt
&& sqlite3BtreeIsInBackup(pBt
) ) return 1;
831 ** Close an existing SQLite database
833 static int sqlite3Close(sqlite3
*db
, int forceZombie
){
835 /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
836 ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
839 if( !sqlite3SafetyCheckSickOrOk(db
) ){
840 return SQLITE_MISUSE_BKPT
;
842 sqlite3_mutex_enter(db
->mutex
);
844 /* Force xDisconnect calls on all virtual tables */
845 disconnectAllVtab(db
);
847 /* If a transaction is open, the disconnectAllVtab() call above
848 ** will not have called the xDisconnect() method on any virtual
849 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
850 ** call will do so. We need to do this before the check for active
851 ** SQL statements below, as the v-table implementation may be storing
852 ** some prepared statements internally.
854 sqlite3VtabRollback(db
);
856 /* Legacy behavior (sqlite3_close() behavior) is to return
857 ** SQLITE_BUSY if the connection can not be closed immediately.
859 if( !forceZombie
&& connectionIsBusy(db
) ){
860 sqlite3ErrorWithMsg(db
, SQLITE_BUSY
, "unable to close due to unfinalized "
861 "statements or unfinished backups");
862 sqlite3_mutex_leave(db
->mutex
);
866 #ifdef SQLITE_ENABLE_SQLLOG
867 if( sqlite3GlobalConfig
.xSqllog
){
868 /* Closing the handle. Fourth parameter is passed the value 2. */
869 sqlite3GlobalConfig
.xSqllog(sqlite3GlobalConfig
.pSqllogArg
, db
, 0, 2);
873 /* Convert the connection into a zombie and then close it.
875 db
->magic
= SQLITE_MAGIC_ZOMBIE
;
876 sqlite3LeaveMutexAndCloseZombie(db
);
881 ** Two variations on the public interface for closing a database
882 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
883 ** leaves the connection option if there are unfinalized prepared
884 ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
885 ** version forces the connection to become a zombie if there are
886 ** unclosed resources, and arranges for deallocation when the last
887 ** prepare statement or sqlite3_backup closes.
889 int sqlite3_close(sqlite3
*db
){ return sqlite3Close(db
,0); }
890 int sqlite3_close_v2(sqlite3
*db
){ return sqlite3Close(db
,1); }
894 ** Close the mutex on database connection db.
896 ** Furthermore, if database connection db is a zombie (meaning that there
897 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
898 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
899 ** finished, then free all resources.
901 void sqlite3LeaveMutexAndCloseZombie(sqlite3
*db
){
902 HashElem
*i
; /* Hash table iterator */
905 /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
906 ** or if the connection has not yet been closed by sqlite3_close_v2(),
907 ** then just leave the mutex and return.
909 if( db
->magic
!=SQLITE_MAGIC_ZOMBIE
|| connectionIsBusy(db
) ){
910 sqlite3_mutex_leave(db
->mutex
);
914 /* If we reach this point, it means that the database connection has
915 ** closed all sqlite3_stmt and sqlite3_backup objects and has been
916 ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
917 ** go ahead and free all resources.
920 /* If a transaction is open, roll it back. This also ensures that if
921 ** any database schemas have been modified by an uncommitted transaction
922 ** they are reset. And that the required b-tree mutex is held to make
923 ** the pager rollback and schema reset an atomic operation. */
924 sqlite3RollbackAll(db
, SQLITE_OK
);
926 /* Free any outstanding Savepoint structures. */
927 sqlite3CloseSavepoints(db
);
929 /* Close all database connections */
930 for(j
=0; j
<db
->nDb
; j
++){
931 struct Db
*pDb
= &db
->aDb
[j
];
934 /* Must clear the KeyInfo cache. See ticket [e4a18565a36884b00edf] */
935 sqlite3BtreeEnter(pDb
->pBt
);
936 for(i
=sqliteHashFirst(&pDb
->pSchema
->idxHash
); i
; i
=sqliteHashNext(i
)){
937 Index
*pIdx
= sqliteHashData(i
);
938 sqlite3KeyInfoUnref(pIdx
->pKeyInfo
);
941 sqlite3BtreeLeave(pDb
->pBt
);
943 sqlite3BtreeClose(pDb
->pBt
);
950 /* Clear the TEMP schema separately and last */
951 if( db
->aDb
[1].pSchema
){
952 sqlite3SchemaClear(db
->aDb
[1].pSchema
);
954 sqlite3VtabUnlockList(db
);
956 /* Free up the array of auxiliary databases */
957 sqlite3CollapseDatabaseArray(db
);
958 assert( db
->nDb
<=2 );
959 assert( db
->aDb
==db
->aDbStatic
);
961 /* Tell the code in notify.c that the connection no longer holds any
962 ** locks and does not require any further unlock-notify callbacks.
964 sqlite3ConnectionClosed(db
);
966 for(j
=0; j
<ArraySize(db
->aFunc
.a
); j
++){
967 FuncDef
*pNext
, *pHash
, *p
;
968 for(p
=db
->aFunc
.a
[j
]; p
; p
=pHash
){
971 functionDestroy(db
, p
);
973 sqlite3DbFree(db
, p
);
978 for(i
=sqliteHashFirst(&db
->aCollSeq
); i
; i
=sqliteHashNext(i
)){
979 CollSeq
*pColl
= (CollSeq
*)sqliteHashData(i
);
980 /* Invoke any destructors registered for collation sequence user data. */
983 pColl
[j
].xDel(pColl
[j
].pUser
);
986 sqlite3DbFree(db
, pColl
);
988 sqlite3HashClear(&db
->aCollSeq
);
989 #ifndef SQLITE_OMIT_VIRTUALTABLE
990 for(i
=sqliteHashFirst(&db
->aModule
); i
; i
=sqliteHashNext(i
)){
991 Module
*pMod
= (Module
*)sqliteHashData(i
);
992 if( pMod
->xDestroy
){
993 pMod
->xDestroy(pMod
->pAux
);
995 sqlite3DbFree(db
, pMod
);
997 sqlite3HashClear(&db
->aModule
);
1000 sqlite3Error(db
, SQLITE_OK
); /* Deallocates any cached error strings. */
1001 sqlite3ValueFree(db
->pErr
);
1002 sqlite3CloseExtensions(db
);
1003 #if SQLITE_USER_AUTHENTICATION
1004 sqlite3_free(db
->auth
.zAuthUser
);
1005 sqlite3_free(db
->auth
.zAuthPW
);
1008 db
->magic
= SQLITE_MAGIC_ERROR
;
1010 /* The temp-database schema is allocated differently from the other schema
1011 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
1012 ** So it needs to be freed here. Todo: Why not roll the temp schema into
1013 ** the same sqliteMalloc() as the one that allocates the database
1016 sqlite3DbFree(db
, db
->aDb
[1].pSchema
);
1017 sqlite3_mutex_leave(db
->mutex
);
1018 db
->magic
= SQLITE_MAGIC_CLOSED
;
1019 sqlite3_mutex_free(db
->mutex
);
1020 assert( db
->lookaside
.nOut
==0 ); /* Fails on a lookaside memory leak */
1021 if( db
->lookaside
.bMalloced
){
1022 sqlite3_free(db
->lookaside
.pStart
);
1028 ** Rollback all database files. If tripCode is not SQLITE_OK, then
1029 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
1030 ** breaker") and made to return tripCode if there are any further
1031 ** attempts to use that cursor. Read cursors remain open and valid
1032 ** but are "saved" in case the table pages are moved around.
1034 void sqlite3RollbackAll(sqlite3
*db
, int tripCode
){
1038 assert( sqlite3_mutex_held(db
->mutex
) );
1039 sqlite3BeginBenignMalloc();
1041 /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
1042 ** This is important in case the transaction being rolled back has
1043 ** modified the database schema. If the b-tree mutexes are not taken
1044 ** here, then another shared-cache connection might sneak in between
1045 ** the database rollback and schema reset, which can cause false
1046 ** corruption reports in some cases. */
1047 sqlite3BtreeEnterAll(db
);
1048 schemaChange
= (db
->flags
& SQLITE_InternChanges
)!=0 && db
->init
.busy
==0;
1050 for(i
=0; i
<db
->nDb
; i
++){
1051 Btree
*p
= db
->aDb
[i
].pBt
;
1053 if( sqlite3BtreeIsInTrans(p
) ){
1056 sqlite3BtreeRollback(p
, tripCode
, !schemaChange
);
1059 sqlite3VtabRollback(db
);
1060 sqlite3EndBenignMalloc();
1062 if( (db
->flags
&SQLITE_InternChanges
)!=0 && db
->init
.busy
==0 ){
1063 sqlite3ExpirePreparedStatements(db
);
1064 sqlite3ResetAllSchemasOfConnection(db
);
1066 sqlite3BtreeLeaveAll(db
);
1068 /* Any deferred constraint violations have now been resolved. */
1069 db
->nDeferredCons
= 0;
1070 db
->nDeferredImmCons
= 0;
1071 db
->flags
&= ~SQLITE_DeferFKs
;
1073 /* If one has been configured, invoke the rollback-hook callback */
1074 if( db
->xRollbackCallback
&& (inTrans
|| !db
->autoCommit
) ){
1075 db
->xRollbackCallback(db
->pRollbackArg
);
1080 ** Return a static string containing the name corresponding to the error code
1081 ** specified in the argument.
1083 #if (defined(SQLITE_DEBUG) && SQLITE_OS_WIN) || defined(SQLITE_TEST)
1084 const char *sqlite3ErrName(int rc
){
1085 const char *zName
= 0;
1087 for(i
=0; i
<2 && zName
==0; i
++, rc
&= 0xff){
1089 case SQLITE_OK
: zName
= "SQLITE_OK"; break;
1090 case SQLITE_ERROR
: zName
= "SQLITE_ERROR"; break;
1091 case SQLITE_INTERNAL
: zName
= "SQLITE_INTERNAL"; break;
1092 case SQLITE_PERM
: zName
= "SQLITE_PERM"; break;
1093 case SQLITE_ABORT
: zName
= "SQLITE_ABORT"; break;
1094 case SQLITE_ABORT_ROLLBACK
: zName
= "SQLITE_ABORT_ROLLBACK"; break;
1095 case SQLITE_BUSY
: zName
= "SQLITE_BUSY"; break;
1096 case SQLITE_BUSY_RECOVERY
: zName
= "SQLITE_BUSY_RECOVERY"; break;
1097 case SQLITE_BUSY_SNAPSHOT
: zName
= "SQLITE_BUSY_SNAPSHOT"; break;
1098 case SQLITE_LOCKED
: zName
= "SQLITE_LOCKED"; break;
1099 case SQLITE_LOCKED_SHAREDCACHE
: zName
= "SQLITE_LOCKED_SHAREDCACHE";break;
1100 case SQLITE_NOMEM
: zName
= "SQLITE_NOMEM"; break;
1101 case SQLITE_READONLY
: zName
= "SQLITE_READONLY"; break;
1102 case SQLITE_READONLY_RECOVERY
: zName
= "SQLITE_READONLY_RECOVERY"; break;
1103 case SQLITE_READONLY_CANTLOCK
: zName
= "SQLITE_READONLY_CANTLOCK"; break;
1104 case SQLITE_READONLY_ROLLBACK
: zName
= "SQLITE_READONLY_ROLLBACK"; break;
1105 case SQLITE_READONLY_DBMOVED
: zName
= "SQLITE_READONLY_DBMOVED"; break;
1106 case SQLITE_INTERRUPT
: zName
= "SQLITE_INTERRUPT"; break;
1107 case SQLITE_IOERR
: zName
= "SQLITE_IOERR"; break;
1108 case SQLITE_IOERR_READ
: zName
= "SQLITE_IOERR_READ"; break;
1109 case SQLITE_IOERR_SHORT_READ
: zName
= "SQLITE_IOERR_SHORT_READ"; break;
1110 case SQLITE_IOERR_WRITE
: zName
= "SQLITE_IOERR_WRITE"; break;
1111 case SQLITE_IOERR_FSYNC
: zName
= "SQLITE_IOERR_FSYNC"; break;
1112 case SQLITE_IOERR_DIR_FSYNC
: zName
= "SQLITE_IOERR_DIR_FSYNC"; break;
1113 case SQLITE_IOERR_TRUNCATE
: zName
= "SQLITE_IOERR_TRUNCATE"; break;
1114 case SQLITE_IOERR_FSTAT
: zName
= "SQLITE_IOERR_FSTAT"; break;
1115 case SQLITE_IOERR_UNLOCK
: zName
= "SQLITE_IOERR_UNLOCK"; break;
1116 case SQLITE_IOERR_RDLOCK
: zName
= "SQLITE_IOERR_RDLOCK"; break;
1117 case SQLITE_IOERR_DELETE
: zName
= "SQLITE_IOERR_DELETE"; break;
1118 case SQLITE_IOERR_NOMEM
: zName
= "SQLITE_IOERR_NOMEM"; break;
1119 case SQLITE_IOERR_ACCESS
: zName
= "SQLITE_IOERR_ACCESS"; break;
1120 case SQLITE_IOERR_CHECKRESERVEDLOCK
:
1121 zName
= "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
1122 case SQLITE_IOERR_LOCK
: zName
= "SQLITE_IOERR_LOCK"; break;
1123 case SQLITE_IOERR_CLOSE
: zName
= "SQLITE_IOERR_CLOSE"; break;
1124 case SQLITE_IOERR_DIR_CLOSE
: zName
= "SQLITE_IOERR_DIR_CLOSE"; break;
1125 case SQLITE_IOERR_SHMOPEN
: zName
= "SQLITE_IOERR_SHMOPEN"; break;
1126 case SQLITE_IOERR_SHMSIZE
: zName
= "SQLITE_IOERR_SHMSIZE"; break;
1127 case SQLITE_IOERR_SHMLOCK
: zName
= "SQLITE_IOERR_SHMLOCK"; break;
1128 case SQLITE_IOERR_SHMMAP
: zName
= "SQLITE_IOERR_SHMMAP"; break;
1129 case SQLITE_IOERR_SEEK
: zName
= "SQLITE_IOERR_SEEK"; break;
1130 case SQLITE_IOERR_DELETE_NOENT
: zName
= "SQLITE_IOERR_DELETE_NOENT";break;
1131 case SQLITE_IOERR_MMAP
: zName
= "SQLITE_IOERR_MMAP"; break;
1132 case SQLITE_IOERR_GETTEMPPATH
: zName
= "SQLITE_IOERR_GETTEMPPATH"; break;
1133 case SQLITE_IOERR_CONVPATH
: zName
= "SQLITE_IOERR_CONVPATH"; break;
1134 case SQLITE_CORRUPT
: zName
= "SQLITE_CORRUPT"; break;
1135 case SQLITE_CORRUPT_VTAB
: zName
= "SQLITE_CORRUPT_VTAB"; break;
1136 case SQLITE_NOTFOUND
: zName
= "SQLITE_NOTFOUND"; break;
1137 case SQLITE_FULL
: zName
= "SQLITE_FULL"; break;
1138 case SQLITE_CANTOPEN
: zName
= "SQLITE_CANTOPEN"; break;
1139 case SQLITE_CANTOPEN_NOTEMPDIR
: zName
= "SQLITE_CANTOPEN_NOTEMPDIR";break;
1140 case SQLITE_CANTOPEN_ISDIR
: zName
= "SQLITE_CANTOPEN_ISDIR"; break;
1141 case SQLITE_CANTOPEN_FULLPATH
: zName
= "SQLITE_CANTOPEN_FULLPATH"; break;
1142 case SQLITE_CANTOPEN_CONVPATH
: zName
= "SQLITE_CANTOPEN_CONVPATH"; break;
1143 case SQLITE_PROTOCOL
: zName
= "SQLITE_PROTOCOL"; break;
1144 case SQLITE_EMPTY
: zName
= "SQLITE_EMPTY"; break;
1145 case SQLITE_SCHEMA
: zName
= "SQLITE_SCHEMA"; break;
1146 case SQLITE_TOOBIG
: zName
= "SQLITE_TOOBIG"; break;
1147 case SQLITE_CONSTRAINT
: zName
= "SQLITE_CONSTRAINT"; break;
1148 case SQLITE_CONSTRAINT_UNIQUE
: zName
= "SQLITE_CONSTRAINT_UNIQUE"; break;
1149 case SQLITE_CONSTRAINT_TRIGGER
: zName
= "SQLITE_CONSTRAINT_TRIGGER";break;
1150 case SQLITE_CONSTRAINT_FOREIGNKEY
:
1151 zName
= "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
1152 case SQLITE_CONSTRAINT_CHECK
: zName
= "SQLITE_CONSTRAINT_CHECK"; break;
1153 case SQLITE_CONSTRAINT_PRIMARYKEY
:
1154 zName
= "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
1155 case SQLITE_CONSTRAINT_NOTNULL
: zName
= "SQLITE_CONSTRAINT_NOTNULL";break;
1156 case SQLITE_CONSTRAINT_COMMITHOOK
:
1157 zName
= "SQLITE_CONSTRAINT_COMMITHOOK"; break;
1158 case SQLITE_CONSTRAINT_VTAB
: zName
= "SQLITE_CONSTRAINT_VTAB"; break;
1159 case SQLITE_CONSTRAINT_FUNCTION
:
1160 zName
= "SQLITE_CONSTRAINT_FUNCTION"; break;
1161 case SQLITE_CONSTRAINT_ROWID
: zName
= "SQLITE_CONSTRAINT_ROWID"; break;
1162 case SQLITE_MISMATCH
: zName
= "SQLITE_MISMATCH"; break;
1163 case SQLITE_MISUSE
: zName
= "SQLITE_MISUSE"; break;
1164 case SQLITE_NOLFS
: zName
= "SQLITE_NOLFS"; break;
1165 case SQLITE_AUTH
: zName
= "SQLITE_AUTH"; break;
1166 case SQLITE_FORMAT
: zName
= "SQLITE_FORMAT"; break;
1167 case SQLITE_RANGE
: zName
= "SQLITE_RANGE"; break;
1168 case SQLITE_NOTADB
: zName
= "SQLITE_NOTADB"; break;
1169 case SQLITE_ROW
: zName
= "SQLITE_ROW"; break;
1170 case SQLITE_NOTICE
: zName
= "SQLITE_NOTICE"; break;
1171 case SQLITE_NOTICE_RECOVER_WAL
: zName
= "SQLITE_NOTICE_RECOVER_WAL";break;
1172 case SQLITE_NOTICE_RECOVER_ROLLBACK
:
1173 zName
= "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
1174 case SQLITE_WARNING
: zName
= "SQLITE_WARNING"; break;
1175 case SQLITE_WARNING_AUTOINDEX
: zName
= "SQLITE_WARNING_AUTOINDEX"; break;
1176 case SQLITE_DONE
: zName
= "SQLITE_DONE"; break;
1180 static char zBuf
[50];
1181 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "SQLITE_UNKNOWN(%d)", origRc
);
1189 ** Return a static string that describes the kind of error specified in the
1192 const char *sqlite3ErrStr(int rc
){
1193 static const char* const aMsg
[] = {
1194 /* SQLITE_OK */ "not an error",
1195 /* SQLITE_ERROR */ "SQL logic error or missing database",
1196 /* SQLITE_INTERNAL */ 0,
1197 /* SQLITE_PERM */ "access permission denied",
1198 /* SQLITE_ABORT */ "callback requested query abort",
1199 /* SQLITE_BUSY */ "database is locked",
1200 /* SQLITE_LOCKED */ "database table is locked",
1201 /* SQLITE_NOMEM */ "out of memory",
1202 /* SQLITE_READONLY */ "attempt to write a readonly database",
1203 /* SQLITE_INTERRUPT */ "interrupted",
1204 /* SQLITE_IOERR */ "disk I/O error",
1205 /* SQLITE_CORRUPT */ "database disk image is malformed",
1206 /* SQLITE_NOTFOUND */ "unknown operation",
1207 /* SQLITE_FULL */ "database or disk is full",
1208 /* SQLITE_CANTOPEN */ "unable to open database file",
1209 /* SQLITE_PROTOCOL */ "locking protocol",
1210 /* SQLITE_EMPTY */ "table contains no data",
1211 /* SQLITE_SCHEMA */ "database schema has changed",
1212 /* SQLITE_TOOBIG */ "string or blob too big",
1213 /* SQLITE_CONSTRAINT */ "constraint failed",
1214 /* SQLITE_MISMATCH */ "datatype mismatch",
1215 /* SQLITE_MISUSE */ "library routine called out of sequence",
1216 /* SQLITE_NOLFS */ "large file support is disabled",
1217 /* SQLITE_AUTH */ "authorization denied",
1218 /* SQLITE_FORMAT */ "auxiliary database format error",
1219 /* SQLITE_RANGE */ "bind or column index out of range",
1220 /* SQLITE_NOTADB */ "file is encrypted or is not a database",
1222 const char *zErr
= "unknown error";
1224 case SQLITE_ABORT_ROLLBACK
: {
1225 zErr
= "abort due to ROLLBACK";
1230 if( ALWAYS(rc
>=0) && rc
<ArraySize(aMsg
) && aMsg
[rc
]!=0 ){
1240 ** This routine implements a busy callback that sleeps and tries
1241 ** again until a timeout value is reached. The timeout value is
1242 ** an integer number of milliseconds passed in as the first
1245 static int sqliteDefaultBusyCallback(
1246 void *ptr
, /* Database connection */
1247 int count
/* Number of times table has been busy */
1249 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
1250 static const u8 delays
[] =
1251 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
1252 static const u8 totals
[] =
1253 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
1254 # define NDELAY ArraySize(delays)
1255 sqlite3
*db
= (sqlite3
*)ptr
;
1256 int timeout
= db
->busyTimeout
;
1260 if( count
< NDELAY
){
1261 delay
= delays
[count
];
1262 prior
= totals
[count
];
1264 delay
= delays
[NDELAY
-1];
1265 prior
= totals
[NDELAY
-1] + delay
*(count
-(NDELAY
-1));
1267 if( prior
+ delay
> timeout
){
1268 delay
= timeout
- prior
;
1269 if( delay
<=0 ) return 0;
1271 sqlite3OsSleep(db
->pVfs
, delay
*1000);
1274 sqlite3
*db
= (sqlite3
*)ptr
;
1275 int timeout
= ((sqlite3
*)ptr
)->busyTimeout
;
1276 if( (count
+1)*1000 > timeout
){
1279 sqlite3OsSleep(db
->pVfs
, 1000000);
1285 ** Invoke the given busy handler.
1287 ** This routine is called when an operation failed with a lock.
1288 ** If this routine returns non-zero, the lock is retried. If it
1289 ** returns 0, the operation aborts with an SQLITE_BUSY error.
1291 int sqlite3InvokeBusyHandler(BusyHandler
*p
){
1293 if( NEVER(p
==0) || p
->xFunc
==0 || p
->nBusy
<0 ) return 0;
1294 rc
= p
->xFunc(p
->pArg
, p
->nBusy
);
1304 ** This routine sets the busy callback for an Sqlite database to the
1305 ** given callback function with the given argument.
1307 int sqlite3_busy_handler(
1309 int (*xBusy
)(void*,int),
1312 sqlite3_mutex_enter(db
->mutex
);
1313 db
->busyHandler
.xFunc
= xBusy
;
1314 db
->busyHandler
.pArg
= pArg
;
1315 db
->busyHandler
.nBusy
= 0;
1316 db
->busyTimeout
= 0;
1317 sqlite3_mutex_leave(db
->mutex
);
1321 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1323 ** This routine sets the progress callback for an Sqlite database to the
1324 ** given callback function with the given argument. The progress callback will
1325 ** be invoked every nOps opcodes.
1327 void sqlite3_progress_handler(
1330 int (*xProgress
)(void*),
1333 sqlite3_mutex_enter(db
->mutex
);
1335 db
->xProgress
= xProgress
;
1336 db
->nProgressOps
= (unsigned)nOps
;
1337 db
->pProgressArg
= pArg
;
1340 db
->nProgressOps
= 0;
1341 db
->pProgressArg
= 0;
1343 sqlite3_mutex_leave(db
->mutex
);
1349 ** This routine installs a default busy handler that waits for the
1350 ** specified number of milliseconds before returning 0.
1352 int sqlite3_busy_timeout(sqlite3
*db
, int ms
){
1354 sqlite3_busy_handler(db
, sqliteDefaultBusyCallback
, (void*)db
);
1355 db
->busyTimeout
= ms
;
1357 sqlite3_busy_handler(db
, 0, 0);
1363 ** Cause any pending operation to stop at its earliest opportunity.
1365 void sqlite3_interrupt(sqlite3
*db
){
1366 db
->u1
.isInterrupted
= 1;
1371 ** This function is exactly the same as sqlite3_create_function(), except
1372 ** that it is designed to be called by internal code. The difference is
1373 ** that if a malloc() fails in sqlite3_create_function(), an error code
1374 ** is returned and the mallocFailed flag cleared.
1376 int sqlite3CreateFunc(
1378 const char *zFunctionName
,
1382 void (*xFunc
)(sqlite3_context
*,int,sqlite3_value
**),
1383 void (*xStep
)(sqlite3_context
*,int,sqlite3_value
**),
1384 void (*xFinal
)(sqlite3_context
*),
1385 FuncDestructor
*pDestructor
1391 assert( sqlite3_mutex_held(db
->mutex
) );
1392 if( zFunctionName
==0 ||
1393 (xFunc
&& (xFinal
|| xStep
)) ||
1394 (!xFunc
&& (xFinal
&& !xStep
)) ||
1395 (!xFunc
&& (!xFinal
&& xStep
)) ||
1396 (nArg
<-1 || nArg
>SQLITE_MAX_FUNCTION_ARG
) ||
1397 (255<(nName
= sqlite3Strlen30( zFunctionName
))) ){
1398 return SQLITE_MISUSE_BKPT
;
1401 assert( SQLITE_FUNC_CONSTANT
==SQLITE_DETERMINISTIC
);
1402 extraFlags
= enc
& SQLITE_DETERMINISTIC
;
1403 enc
&= (SQLITE_FUNC_ENCMASK
|SQLITE_ANY
);
1405 #ifndef SQLITE_OMIT_UTF16
1406 /* If SQLITE_UTF16 is specified as the encoding type, transform this
1407 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
1408 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
1410 ** If SQLITE_ANY is specified, add three versions of the function
1411 ** to the hash table.
1413 if( enc
==SQLITE_UTF16
){
1414 enc
= SQLITE_UTF16NATIVE
;
1415 }else if( enc
==SQLITE_ANY
){
1417 rc
= sqlite3CreateFunc(db
, zFunctionName
, nArg
, SQLITE_UTF8
|extraFlags
,
1418 pUserData
, xFunc
, xStep
, xFinal
, pDestructor
);
1419 if( rc
==SQLITE_OK
){
1420 rc
= sqlite3CreateFunc(db
, zFunctionName
, nArg
, SQLITE_UTF16LE
|extraFlags
,
1421 pUserData
, xFunc
, xStep
, xFinal
, pDestructor
);
1423 if( rc
!=SQLITE_OK
){
1426 enc
= SQLITE_UTF16BE
;
1432 /* Check if an existing function is being overridden or deleted. If so,
1433 ** and there are active VMs, then return SQLITE_BUSY. If a function
1434 ** is being overridden/deleted but there are no active VMs, allow the
1435 ** operation to continue but invalidate all precompiled statements.
1437 p
= sqlite3FindFunction(db
, zFunctionName
, nName
, nArg
, (u8
)enc
, 0);
1438 if( p
&& (p
->funcFlags
& SQLITE_FUNC_ENCMASK
)==enc
&& p
->nArg
==nArg
){
1439 if( db
->nVdbeActive
){
1440 sqlite3ErrorWithMsg(db
, SQLITE_BUSY
,
1441 "unable to delete/modify user-function due to active statements");
1442 assert( !db
->mallocFailed
);
1445 sqlite3ExpirePreparedStatements(db
);
1449 p
= sqlite3FindFunction(db
, zFunctionName
, nName
, nArg
, (u8
)enc
, 1);
1450 assert(p
|| db
->mallocFailed
);
1452 return SQLITE_NOMEM
;
1455 /* If an older version of the function with a configured destructor is
1456 ** being replaced invoke the destructor function here. */
1457 functionDestroy(db
, p
);
1460 pDestructor
->nRef
++;
1462 p
->pDestructor
= pDestructor
;
1463 p
->funcFlags
= (p
->funcFlags
& SQLITE_FUNC_ENCMASK
) | extraFlags
;
1464 testcase( p
->funcFlags
& SQLITE_DETERMINISTIC
);
1467 p
->xFinalize
= xFinal
;
1468 p
->pUserData
= pUserData
;
1469 p
->nArg
= (u16
)nArg
;
1474 ** Create new user functions.
1476 int sqlite3_create_function(
1482 void (*xFunc
)(sqlite3_context
*,int,sqlite3_value
**),
1483 void (*xStep
)(sqlite3_context
*,int,sqlite3_value
**),
1484 void (*xFinal
)(sqlite3_context
*)
1486 return sqlite3_create_function_v2(db
, zFunc
, nArg
, enc
, p
, xFunc
, xStep
,
1490 int sqlite3_create_function_v2(
1496 void (*xFunc
)(sqlite3_context
*,int,sqlite3_value
**),
1497 void (*xStep
)(sqlite3_context
*,int,sqlite3_value
**),
1498 void (*xFinal
)(sqlite3_context
*),
1499 void (*xDestroy
)(void *)
1501 int rc
= SQLITE_ERROR
;
1502 FuncDestructor
*pArg
= 0;
1503 sqlite3_mutex_enter(db
->mutex
);
1505 pArg
= (FuncDestructor
*)sqlite3DbMallocZero(db
, sizeof(FuncDestructor
));
1510 pArg
->xDestroy
= xDestroy
;
1511 pArg
->pUserData
= p
;
1513 rc
= sqlite3CreateFunc(db
, zFunc
, nArg
, enc
, p
, xFunc
, xStep
, xFinal
, pArg
);
1514 if( pArg
&& pArg
->nRef
==0 ){
1515 assert( rc
!=SQLITE_OK
);
1517 sqlite3DbFree(db
, pArg
);
1521 rc
= sqlite3ApiExit(db
, rc
);
1522 sqlite3_mutex_leave(db
->mutex
);
1526 #ifndef SQLITE_OMIT_UTF16
1527 int sqlite3_create_function16(
1529 const void *zFunctionName
,
1533 void (*xFunc
)(sqlite3_context
*,int,sqlite3_value
**),
1534 void (*xStep
)(sqlite3_context
*,int,sqlite3_value
**),
1535 void (*xFinal
)(sqlite3_context
*)
1539 sqlite3_mutex_enter(db
->mutex
);
1540 assert( !db
->mallocFailed
);
1541 zFunc8
= sqlite3Utf16to8(db
, zFunctionName
, -1, SQLITE_UTF16NATIVE
);
1542 rc
= sqlite3CreateFunc(db
, zFunc8
, nArg
, eTextRep
, p
, xFunc
, xStep
, xFinal
,0);
1543 sqlite3DbFree(db
, zFunc8
);
1544 rc
= sqlite3ApiExit(db
, rc
);
1545 sqlite3_mutex_leave(db
->mutex
);
1552 ** Declare that a function has been overloaded by a virtual table.
1554 ** If the function already exists as a regular global function, then
1555 ** this routine is a no-op. If the function does not exist, then create
1556 ** a new one that always throws a run-time error.
1558 ** When virtual tables intend to provide an overloaded function, they
1559 ** should call this routine to make sure the global function exists.
1560 ** A global function must exist in order for name resolution to work
1563 int sqlite3_overload_function(
1568 int nName
= sqlite3Strlen30(zName
);
1570 sqlite3_mutex_enter(db
->mutex
);
1571 if( sqlite3FindFunction(db
, zName
, nName
, nArg
, SQLITE_UTF8
, 0)==0 ){
1572 rc
= sqlite3CreateFunc(db
, zName
, nArg
, SQLITE_UTF8
,
1573 0, sqlite3InvalidFunction
, 0, 0, 0);
1575 rc
= sqlite3ApiExit(db
, rc
);
1576 sqlite3_mutex_leave(db
->mutex
);
1580 #ifndef SQLITE_OMIT_TRACE
1582 ** Register a trace function. The pArg from the previously registered trace
1585 ** A NULL trace function means that no tracing is executes. A non-NULL
1586 ** trace is a pointer to a function that is invoked at the start of each
1589 void *sqlite3_trace(sqlite3
*db
, void (*xTrace
)(void*,const char*), void *pArg
){
1591 sqlite3_mutex_enter(db
->mutex
);
1592 pOld
= db
->pTraceArg
;
1593 db
->xTrace
= xTrace
;
1594 db
->pTraceArg
= pArg
;
1595 sqlite3_mutex_leave(db
->mutex
);
1599 ** Register a profile function. The pArg from the previously registered
1600 ** profile function is returned.
1602 ** A NULL profile function means that no profiling is executes. A non-NULL
1603 ** profile is a pointer to a function that is invoked at the conclusion of
1604 ** each SQL statement that is run.
1606 void *sqlite3_profile(
1608 void (*xProfile
)(void*,const char*,sqlite_uint64
),
1612 sqlite3_mutex_enter(db
->mutex
);
1613 pOld
= db
->pProfileArg
;
1614 db
->xProfile
= xProfile
;
1615 db
->pProfileArg
= pArg
;
1616 sqlite3_mutex_leave(db
->mutex
);
1619 #endif /* SQLITE_OMIT_TRACE */
1622 ** Register a function to be invoked when a transaction commits.
1623 ** If the invoked function returns non-zero, then the commit becomes a
1626 void *sqlite3_commit_hook(
1627 sqlite3
*db
, /* Attach the hook to this database */
1628 int (*xCallback
)(void*), /* Function to invoke on each commit */
1629 void *pArg
/* Argument to the function */
1632 sqlite3_mutex_enter(db
->mutex
);
1633 pOld
= db
->pCommitArg
;
1634 db
->xCommitCallback
= xCallback
;
1635 db
->pCommitArg
= pArg
;
1636 sqlite3_mutex_leave(db
->mutex
);
1641 ** Register a callback to be invoked each time a row is updated,
1642 ** inserted or deleted using this database connection.
1644 void *sqlite3_update_hook(
1645 sqlite3
*db
, /* Attach the hook to this database */
1646 void (*xCallback
)(void*,int,char const *,char const *,sqlite_int64
),
1647 void *pArg
/* Argument to the function */
1650 sqlite3_mutex_enter(db
->mutex
);
1651 pRet
= db
->pUpdateArg
;
1652 db
->xUpdateCallback
= xCallback
;
1653 db
->pUpdateArg
= pArg
;
1654 sqlite3_mutex_leave(db
->mutex
);
1659 ** Register a callback to be invoked each time a transaction is rolled
1660 ** back by this database connection.
1662 void *sqlite3_rollback_hook(
1663 sqlite3
*db
, /* Attach the hook to this database */
1664 void (*xCallback
)(void*), /* Callback function */
1665 void *pArg
/* Argument to the function */
1668 sqlite3_mutex_enter(db
->mutex
);
1669 pRet
= db
->pRollbackArg
;
1670 db
->xRollbackCallback
= xCallback
;
1671 db
->pRollbackArg
= pArg
;
1672 sqlite3_mutex_leave(db
->mutex
);
1676 #ifndef SQLITE_OMIT_WAL
1678 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
1679 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
1680 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
1681 ** wal_autocheckpoint()).
1683 int sqlite3WalDefaultHook(
1684 void *pClientData
, /* Argument */
1685 sqlite3
*db
, /* Connection */
1686 const char *zDb
, /* Database */
1687 int nFrame
/* Size of WAL */
1689 if( nFrame
>=SQLITE_PTR_TO_INT(pClientData
) ){
1690 sqlite3BeginBenignMalloc();
1691 sqlite3_wal_checkpoint(db
, zDb
);
1692 sqlite3EndBenignMalloc();
1696 #endif /* SQLITE_OMIT_WAL */
1699 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
1700 ** a database after committing a transaction if there are nFrame or
1701 ** more frames in the log file. Passing zero or a negative value as the
1702 ** nFrame parameter disables automatic checkpoints entirely.
1704 ** The callback registered by this function replaces any existing callback
1705 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
1706 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
1707 ** configured by this function.
1709 int sqlite3_wal_autocheckpoint(sqlite3
*db
, int nFrame
){
1710 #ifdef SQLITE_OMIT_WAL
1711 UNUSED_PARAMETER(db
);
1712 UNUSED_PARAMETER(nFrame
);
1715 sqlite3_wal_hook(db
, sqlite3WalDefaultHook
, SQLITE_INT_TO_PTR(nFrame
));
1717 sqlite3_wal_hook(db
, 0, 0);
1724 ** Register a callback to be invoked each time a transaction is written
1725 ** into the write-ahead-log by this database connection.
1727 void *sqlite3_wal_hook(
1728 sqlite3
*db
, /* Attach the hook to this db handle */
1729 int(*xCallback
)(void *, sqlite3
*, const char*, int),
1730 void *pArg
/* First argument passed to xCallback() */
1732 #ifndef SQLITE_OMIT_WAL
1734 sqlite3_mutex_enter(db
->mutex
);
1736 db
->xWalCallback
= xCallback
;
1738 sqlite3_mutex_leave(db
->mutex
);
1746 ** Checkpoint database zDb.
1748 int sqlite3_wal_checkpoint_v2(
1749 sqlite3
*db
, /* Database handle */
1750 const char *zDb
, /* Name of attached database (or NULL) */
1751 int eMode
, /* SQLITE_CHECKPOINT_* value */
1752 int *pnLog
, /* OUT: Size of WAL log in frames */
1753 int *pnCkpt
/* OUT: Total number of frames checkpointed */
1755 #ifdef SQLITE_OMIT_WAL
1758 int rc
; /* Return code */
1759 int iDb
= SQLITE_MAX_ATTACHED
; /* sqlite3.aDb[] index of db to checkpoint */
1761 /* Initialize the output variables to -1 in case an error occurs. */
1762 if( pnLog
) *pnLog
= -1;
1763 if( pnCkpt
) *pnCkpt
= -1;
1765 assert( SQLITE_CHECKPOINT_FULL
>SQLITE_CHECKPOINT_PASSIVE
);
1766 assert( SQLITE_CHECKPOINT_FULL
<SQLITE_CHECKPOINT_RESTART
);
1767 assert( SQLITE_CHECKPOINT_PASSIVE
+2==SQLITE_CHECKPOINT_RESTART
);
1768 if( eMode
<SQLITE_CHECKPOINT_PASSIVE
|| eMode
>SQLITE_CHECKPOINT_RESTART
){
1769 return SQLITE_MISUSE
;
1772 sqlite3_mutex_enter(db
->mutex
);
1773 if( zDb
&& zDb
[0] ){
1774 iDb
= sqlite3FindDbName(db
, zDb
);
1778 sqlite3ErrorWithMsg(db
, SQLITE_ERROR
, "unknown database: %s", zDb
);
1780 rc
= sqlite3Checkpoint(db
, iDb
, eMode
, pnLog
, pnCkpt
);
1781 sqlite3Error(db
, rc
);
1783 rc
= sqlite3ApiExit(db
, rc
);
1784 sqlite3_mutex_leave(db
->mutex
);
1791 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
1792 ** to contains a zero-length string, all attached databases are
1795 int sqlite3_wal_checkpoint(sqlite3
*db
, const char *zDb
){
1796 return sqlite3_wal_checkpoint_v2(db
, zDb
, SQLITE_CHECKPOINT_PASSIVE
, 0, 0);
1799 #ifndef SQLITE_OMIT_WAL
1801 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
1802 ** not currently open in WAL mode.
1804 ** If a transaction is open on the database being checkpointed, this
1805 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
1806 ** an error occurs while running the checkpoint, an SQLite error code is
1807 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
1809 ** The mutex on database handle db should be held by the caller. The mutex
1810 ** associated with the specific b-tree being checkpointed is taken by
1811 ** this function while the checkpoint is running.
1813 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
1814 ** checkpointed. If an error is encountered it is returned immediately -
1815 ** no attempt is made to checkpoint any remaining databases.
1817 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
1819 int sqlite3Checkpoint(sqlite3
*db
, int iDb
, int eMode
, int *pnLog
, int *pnCkpt
){
1820 int rc
= SQLITE_OK
; /* Return code */
1821 int i
; /* Used to iterate through attached dbs */
1822 int bBusy
= 0; /* True if SQLITE_BUSY has been encountered */
1824 assert( sqlite3_mutex_held(db
->mutex
) );
1825 assert( !pnLog
|| *pnLog
==-1 );
1826 assert( !pnCkpt
|| *pnCkpt
==-1 );
1828 for(i
=0; i
<db
->nDb
&& rc
==SQLITE_OK
; i
++){
1829 if( i
==iDb
|| iDb
==SQLITE_MAX_ATTACHED
){
1830 rc
= sqlite3BtreeCheckpoint(db
->aDb
[i
].pBt
, eMode
, pnLog
, pnCkpt
);
1833 if( rc
==SQLITE_BUSY
){
1840 return (rc
==SQLITE_OK
&& bBusy
) ? SQLITE_BUSY
: rc
;
1842 #endif /* SQLITE_OMIT_WAL */
1845 ** This function returns true if main-memory should be used instead of
1846 ** a temporary file for transient pager files and statement journals.
1847 ** The value returned depends on the value of db->temp_store (runtime
1848 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
1849 ** following table describes the relationship between these two values
1850 ** and this functions return value.
1852 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
1853 ** ----------------- -------------- ------------------------------
1854 ** 0 any file (return 0)
1855 ** 1 1 file (return 0)
1856 ** 1 2 memory (return 1)
1857 ** 1 0 file (return 0)
1858 ** 2 1 file (return 0)
1859 ** 2 2 memory (return 1)
1860 ** 2 0 memory (return 1)
1861 ** 3 any memory (return 1)
1863 int sqlite3TempInMemory(const sqlite3
*db
){
1864 #if SQLITE_TEMP_STORE==1
1865 return ( db
->temp_store
==2 );
1867 #if SQLITE_TEMP_STORE==2
1868 return ( db
->temp_store
!=1 );
1870 #if SQLITE_TEMP_STORE==3
1873 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
1879 ** Return UTF-8 encoded English language explanation of the most recent
1882 const char *sqlite3_errmsg(sqlite3
*db
){
1885 return sqlite3ErrStr(SQLITE_NOMEM
);
1887 if( !sqlite3SafetyCheckSickOrOk(db
) ){
1888 return sqlite3ErrStr(SQLITE_MISUSE_BKPT
);
1890 sqlite3_mutex_enter(db
->mutex
);
1891 if( db
->mallocFailed
){
1892 z
= sqlite3ErrStr(SQLITE_NOMEM
);
1894 testcase( db
->pErr
==0 );
1895 z
= (char*)sqlite3_value_text(db
->pErr
);
1896 assert( !db
->mallocFailed
);
1898 z
= sqlite3ErrStr(db
->errCode
);
1901 sqlite3_mutex_leave(db
->mutex
);
1905 #ifndef SQLITE_OMIT_UTF16
1907 ** Return UTF-16 encoded English language explanation of the most recent
1910 const void *sqlite3_errmsg16(sqlite3
*db
){
1911 static const u16 outOfMem
[] = {
1912 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
1914 static const u16 misuse
[] = {
1915 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
1916 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
1917 'c', 'a', 'l', 'l', 'e', 'd', ' ',
1920 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
1925 return (void *)outOfMem
;
1927 if( !sqlite3SafetyCheckSickOrOk(db
) ){
1928 return (void *)misuse
;
1930 sqlite3_mutex_enter(db
->mutex
);
1931 if( db
->mallocFailed
){
1932 z
= (void *)outOfMem
;
1934 z
= sqlite3_value_text16(db
->pErr
);
1936 sqlite3ErrorWithMsg(db
, db
->errCode
, sqlite3ErrStr(db
->errCode
));
1937 z
= sqlite3_value_text16(db
->pErr
);
1939 /* A malloc() may have failed within the call to sqlite3_value_text16()
1940 ** above. If this is the case, then the db->mallocFailed flag needs to
1941 ** be cleared before returning. Do this directly, instead of via
1942 ** sqlite3ApiExit(), to avoid setting the database handle error message.
1944 db
->mallocFailed
= 0;
1946 sqlite3_mutex_leave(db
->mutex
);
1949 #endif /* SQLITE_OMIT_UTF16 */
1952 ** Return the most recent error code generated by an SQLite routine. If NULL is
1953 ** passed to this function, we assume a malloc() failed during sqlite3_open().
1955 int sqlite3_errcode(sqlite3
*db
){
1956 if( db
&& !sqlite3SafetyCheckSickOrOk(db
) ){
1957 return SQLITE_MISUSE_BKPT
;
1959 if( !db
|| db
->mallocFailed
){
1960 return SQLITE_NOMEM
;
1962 return db
->errCode
& db
->errMask
;
1964 int sqlite3_extended_errcode(sqlite3
*db
){
1965 if( db
&& !sqlite3SafetyCheckSickOrOk(db
) ){
1966 return SQLITE_MISUSE_BKPT
;
1968 if( !db
|| db
->mallocFailed
){
1969 return SQLITE_NOMEM
;
1975 ** Return a string that describes the kind of error specified in the
1976 ** argument. For now, this simply calls the internal sqlite3ErrStr()
1979 const char *sqlite3_errstr(int rc
){
1980 return sqlite3ErrStr(rc
);
1984 ** Invalidate all cached KeyInfo objects for database connection "db"
1986 static void invalidateCachedKeyInfo(sqlite3
*db
){
1987 Db
*pDb
; /* A single database */
1988 int iDb
; /* The database index number */
1989 HashElem
*k
; /* For looping over tables in pDb */
1990 Table
*pTab
; /* A table in the database */
1991 Index
*pIdx
; /* Each index */
1993 for(iDb
=0, pDb
=db
->aDb
; iDb
<db
->nDb
; iDb
++, pDb
++){
1994 if( pDb
->pBt
==0 ) continue;
1995 sqlite3BtreeEnter(pDb
->pBt
);
1996 for(k
=sqliteHashFirst(&pDb
->pSchema
->tblHash
); k
; k
=sqliteHashNext(k
)){
1997 pTab
= (Table
*)sqliteHashData(k
);
1998 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1999 if( pIdx
->pKeyInfo
&& pIdx
->pKeyInfo
->db
==db
){
2000 sqlite3KeyInfoUnref(pIdx
->pKeyInfo
);
2005 sqlite3BtreeLeave(pDb
->pBt
);
2010 ** Create a new collating function for database "db". The name is zName
2011 ** and the encoding is enc.
2013 static int createCollation(
2018 int(*xCompare
)(void*,int,const void*,int,const void*),
2024 assert( sqlite3_mutex_held(db
->mutex
) );
2026 /* If SQLITE_UTF16 is specified as the encoding type, transform this
2027 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
2028 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
2031 testcase( enc2
==SQLITE_UTF16
);
2032 testcase( enc2
==SQLITE_UTF16_ALIGNED
);
2033 if( enc2
==SQLITE_UTF16
|| enc2
==SQLITE_UTF16_ALIGNED
){
2034 enc2
= SQLITE_UTF16NATIVE
;
2036 if( enc2
<SQLITE_UTF8
|| enc2
>SQLITE_UTF16BE
){
2037 return SQLITE_MISUSE_BKPT
;
2040 /* Check if this call is removing or replacing an existing collation
2041 ** sequence. If so, and there are active VMs, return busy. If there
2042 ** are no active VMs, invalidate any pre-compiled statements.
2044 pColl
= sqlite3FindCollSeq(db
, (u8
)enc2
, zName
, 0);
2045 if( pColl
&& pColl
->xCmp
){
2046 if( db
->nVdbeActive
){
2047 sqlite3ErrorWithMsg(db
, SQLITE_BUSY
,
2048 "unable to delete/modify collation sequence due to active statements");
2051 sqlite3ExpirePreparedStatements(db
);
2052 invalidateCachedKeyInfo(db
);
2054 /* If collation sequence pColl was created directly by a call to
2055 ** sqlite3_create_collation, and not generated by synthCollSeq(),
2056 ** then any copies made by synthCollSeq() need to be invalidated.
2057 ** Also, collation destructor - CollSeq.xDel() - function may need
2060 if( (pColl
->enc
& ~SQLITE_UTF16_ALIGNED
)==enc2
){
2061 CollSeq
*aColl
= sqlite3HashFind(&db
->aCollSeq
, zName
);
2064 CollSeq
*p
= &aColl
[j
];
2065 if( p
->enc
==pColl
->enc
){
2075 pColl
= sqlite3FindCollSeq(db
, (u8
)enc2
, zName
, 1);
2076 if( pColl
==0 ) return SQLITE_NOMEM
;
2077 pColl
->xCmp
= xCompare
;
2078 pColl
->pUser
= pCtx
;
2080 pColl
->enc
= (u8
)(enc2
| (enc
& SQLITE_UTF16_ALIGNED
));
2081 sqlite3Error(db
, SQLITE_OK
);
2087 ** This array defines hard upper bounds on limit values. The
2088 ** initializer must be kept in sync with the SQLITE_LIMIT_*
2089 ** #defines in sqlite3.h.
2091 static const int aHardLimit
[] = {
2093 SQLITE_MAX_SQL_LENGTH
,
2095 SQLITE_MAX_EXPR_DEPTH
,
2096 SQLITE_MAX_COMPOUND_SELECT
,
2098 SQLITE_MAX_FUNCTION_ARG
,
2099 SQLITE_MAX_ATTACHED
,
2100 SQLITE_MAX_LIKE_PATTERN_LENGTH
,
2101 SQLITE_MAX_VARIABLE_NUMBER
, /* IMP: R-38091-32352 */
2102 SQLITE_MAX_TRIGGER_DEPTH
,
2103 SQLITE_MAX_WORKER_THREADS
,
2107 ** Make sure the hard limits are set to reasonable values
2109 #if SQLITE_MAX_LENGTH<100
2110 # error SQLITE_MAX_LENGTH must be at least 100
2112 #if SQLITE_MAX_SQL_LENGTH<100
2113 # error SQLITE_MAX_SQL_LENGTH must be at least 100
2115 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
2116 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
2118 #if SQLITE_MAX_COMPOUND_SELECT<2
2119 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
2121 #if SQLITE_MAX_VDBE_OP<40
2122 # error SQLITE_MAX_VDBE_OP must be at least 40
2124 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
2125 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
2127 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
2128 # error SQLITE_MAX_ATTACHED must be between 0 and 125
2130 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
2131 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
2133 #if SQLITE_MAX_COLUMN>32767
2134 # error SQLITE_MAX_COLUMN must not exceed 32767
2136 #if SQLITE_MAX_TRIGGER_DEPTH<1
2137 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
2139 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
2140 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
2145 ** Change the value of a limit. Report the old value.
2146 ** If an invalid limit index is supplied, report -1.
2147 ** Make no changes but still report the old value if the
2148 ** new limit is negative.
2150 ** A new lower limit does not shrink existing constructs.
2151 ** It merely prevents new constructs that exceed the limit
2154 int sqlite3_limit(sqlite3
*db
, int limitId
, int newLimit
){
2158 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
2159 ** there is a hard upper bound set at compile-time by a C preprocessor
2160 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
2163 assert( aHardLimit
[SQLITE_LIMIT_LENGTH
]==SQLITE_MAX_LENGTH
);
2164 assert( aHardLimit
[SQLITE_LIMIT_SQL_LENGTH
]==SQLITE_MAX_SQL_LENGTH
);
2165 assert( aHardLimit
[SQLITE_LIMIT_COLUMN
]==SQLITE_MAX_COLUMN
);
2166 assert( aHardLimit
[SQLITE_LIMIT_EXPR_DEPTH
]==SQLITE_MAX_EXPR_DEPTH
);
2167 assert( aHardLimit
[SQLITE_LIMIT_COMPOUND_SELECT
]==SQLITE_MAX_COMPOUND_SELECT
);
2168 assert( aHardLimit
[SQLITE_LIMIT_VDBE_OP
]==SQLITE_MAX_VDBE_OP
);
2169 assert( aHardLimit
[SQLITE_LIMIT_FUNCTION_ARG
]==SQLITE_MAX_FUNCTION_ARG
);
2170 assert( aHardLimit
[SQLITE_LIMIT_ATTACHED
]==SQLITE_MAX_ATTACHED
);
2171 assert( aHardLimit
[SQLITE_LIMIT_LIKE_PATTERN_LENGTH
]==
2172 SQLITE_MAX_LIKE_PATTERN_LENGTH
);
2173 assert( aHardLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
]==SQLITE_MAX_VARIABLE_NUMBER
);
2174 assert( aHardLimit
[SQLITE_LIMIT_TRIGGER_DEPTH
]==SQLITE_MAX_TRIGGER_DEPTH
);
2175 assert( aHardLimit
[SQLITE_LIMIT_WORKER_THREADS
]==SQLITE_MAX_WORKER_THREADS
);
2176 assert( SQLITE_LIMIT_WORKER_THREADS
==(SQLITE_N_LIMIT
-1) );
2179 if( limitId
<0 || limitId
>=SQLITE_N_LIMIT
){
2182 oldLimit
= db
->aLimit
[limitId
];
2183 if( newLimit
>=0 ){ /* IMP: R-52476-28732 */
2184 if( newLimit
>aHardLimit
[limitId
] ){
2185 newLimit
= aHardLimit
[limitId
]; /* IMP: R-51463-25634 */
2187 db
->aLimit
[limitId
] = newLimit
;
2189 return oldLimit
; /* IMP: R-53341-35419 */
2193 ** This function is used to parse both URIs and non-URI filenames passed by the
2194 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
2195 ** URIs specified as part of ATTACH statements.
2197 ** The first argument to this function is the name of the VFS to use (or
2198 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
2199 ** query parameter. The second argument contains the URI (or non-URI filename)
2200 ** itself. When this function is called the *pFlags variable should contain
2201 ** the default flags to open the database handle with. The value stored in
2202 ** *pFlags may be updated before returning if the URI filename contains
2203 ** "cache=xxx" or "mode=xxx" query parameters.
2205 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
2206 ** the VFS that should be used to open the database file. *pzFile is set to
2207 ** point to a buffer containing the name of the file to open. It is the
2208 ** responsibility of the caller to eventually call sqlite3_free() to release
2211 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
2212 ** may be set to point to a buffer containing an English language error
2213 ** message. It is the responsibility of the caller to eventually release
2214 ** this buffer by calling sqlite3_free().
2216 int sqlite3ParseUri(
2217 const char *zDefaultVfs
, /* VFS to use if no "vfs=xxx" query option */
2218 const char *zUri
, /* Nul-terminated URI to parse */
2219 unsigned int *pFlags
, /* IN/OUT: SQLITE_OPEN_XXX flags */
2220 sqlite3_vfs
**ppVfs
, /* OUT: VFS to use */
2221 char **pzFile
, /* OUT: Filename component of URI */
2222 char **pzErrMsg
/* OUT: Error message (if rc!=SQLITE_OK) */
2225 unsigned int flags
= *pFlags
;
2226 const char *zVfs
= zDefaultVfs
;
2229 int nUri
= sqlite3Strlen30(zUri
);
2231 assert( *pzErrMsg
==0 );
2233 if( ((flags
& SQLITE_OPEN_URI
) || sqlite3GlobalConfig
.bOpenUri
)
2234 && nUri
>=5 && memcmp(zUri
, "file:", 5)==0 /* IMP: R-57884-37496 */
2237 int eState
; /* Parser state when parsing URI */
2238 int iIn
; /* Input character index */
2239 int iOut
= 0; /* Output character index */
2240 int nByte
= nUri
+2; /* Bytes of space to allocate */
2242 /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
2243 ** method that there may be extra parameters following the file-name. */
2244 flags
|= SQLITE_OPEN_URI
;
2246 for(iIn
=0; iIn
<nUri
; iIn
++) nByte
+= (zUri
[iIn
]=='&');
2247 zFile
= sqlite3_malloc(nByte
);
2248 if( !zFile
) return SQLITE_NOMEM
;
2251 #ifndef SQLITE_ALLOW_URI_AUTHORITY
2252 /* Discard the scheme and authority segments of the URI. */
2253 if( zUri
[5]=='/' && zUri
[6]=='/' ){
2255 while( zUri
[iIn
] && zUri
[iIn
]!='/' ) iIn
++;
2256 if( iIn
!=7 && (iIn
!=16 || memcmp("localhost", &zUri
[7], 9)) ){
2257 *pzErrMsg
= sqlite3_mprintf("invalid uri authority: %.*s",
2265 /* Copy the filename and any query parameters into the zFile buffer.
2266 ** Decode %HH escape codes along the way.
2268 ** Within this loop, variable eState may be set to 0, 1 or 2, depending
2269 ** on the parsing context. As follows:
2271 ** 0: Parsing file-name.
2272 ** 1: Parsing name section of a name=value query parameter.
2273 ** 2: Parsing value section of a name=value query parameter.
2276 while( (c
= zUri
[iIn
])!=0 && c
!='#' ){
2279 && sqlite3Isxdigit(zUri
[iIn
])
2280 && sqlite3Isxdigit(zUri
[iIn
+1])
2282 int octet
= (sqlite3HexToInt(zUri
[iIn
++]) << 4);
2283 octet
+= sqlite3HexToInt(zUri
[iIn
++]);
2285 assert( octet
>=0 && octet
<256 );
2287 /* This branch is taken when "%00" appears within the URI. In this
2288 ** case we ignore all text in the remainder of the path, name or
2289 ** value currently being parsed. So ignore the current character
2290 ** and skip to the next "?", "=" or "&", as appropriate. */
2291 while( (c
= zUri
[iIn
])!=0 && c
!='#'
2292 && (eState
!=0 || c
!='?')
2293 && (eState
!=1 || (c
!='=' && c
!='&'))
2294 && (eState
!=2 || c
!='&')
2301 }else if( eState
==1 && (c
=='&' || c
=='=') ){
2302 if( zFile
[iOut
-1]==0 ){
2303 /* An empty option name. Ignore this option altogether. */
2304 while( zUri
[iIn
] && zUri
[iIn
]!='#' && zUri
[iIn
-1]!='&' ) iIn
++;
2308 zFile
[iOut
++] = '\0';
2313 }else if( (eState
==0 && c
=='?') || (eState
==2 && c
=='&') ){
2319 if( eState
==1 ) zFile
[iOut
++] = '\0';
2320 zFile
[iOut
++] = '\0';
2321 zFile
[iOut
++] = '\0';
2323 /* Check if there were any options specified that should be interpreted
2324 ** here. Options that are interpreted here include "vfs" and those that
2325 ** correspond to flags that may be passed to the sqlite3_open_v2()
2327 zOpt
= &zFile
[sqlite3Strlen30(zFile
)+1];
2329 int nOpt
= sqlite3Strlen30(zOpt
);
2330 char *zVal
= &zOpt
[nOpt
+1];
2331 int nVal
= sqlite3Strlen30(zVal
);
2333 if( nOpt
==3 && memcmp("vfs", zOpt
, 3)==0 ){
2340 char *zModeType
= 0;
2344 if( nOpt
==5 && memcmp("cache", zOpt
, 5)==0 ){
2345 static struct OpenMode aCacheMode
[] = {
2346 { "shared", SQLITE_OPEN_SHAREDCACHE
},
2347 { "private", SQLITE_OPEN_PRIVATECACHE
},
2351 mask
= SQLITE_OPEN_SHAREDCACHE
|SQLITE_OPEN_PRIVATECACHE
;
2354 zModeType
= "cache";
2356 if( nOpt
==4 && memcmp("mode", zOpt
, 4)==0 ){
2357 static struct OpenMode aOpenMode
[] = {
2358 { "ro", SQLITE_OPEN_READONLY
},
2359 { "rw", SQLITE_OPEN_READWRITE
},
2360 { "rwc", SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
},
2361 { "memory", SQLITE_OPEN_MEMORY
},
2365 mask
= SQLITE_OPEN_READONLY
| SQLITE_OPEN_READWRITE
2366 | SQLITE_OPEN_CREATE
| SQLITE_OPEN_MEMORY
;
2368 limit
= mask
& flags
;
2369 zModeType
= "access";
2375 for(i
=0; aMode
[i
].z
; i
++){
2376 const char *z
= aMode
[i
].z
;
2377 if( nVal
==sqlite3Strlen30(z
) && 0==memcmp(zVal
, z
, nVal
) ){
2378 mode
= aMode
[i
].mode
;
2383 *pzErrMsg
= sqlite3_mprintf("no such %s mode: %s", zModeType
, zVal
);
2387 if( (mode
& ~SQLITE_OPEN_MEMORY
)>limit
){
2388 *pzErrMsg
= sqlite3_mprintf("%s mode not allowed: %s",
2393 flags
= (flags
& ~mask
) | mode
;
2397 zOpt
= &zVal
[nVal
+1];
2401 zFile
= sqlite3_malloc(nUri
+2);
2402 if( !zFile
) return SQLITE_NOMEM
;
2403 memcpy(zFile
, zUri
, nUri
);
2405 zFile
[nUri
+1] = '\0';
2406 flags
&= ~SQLITE_OPEN_URI
;
2409 *ppVfs
= sqlite3_vfs_find(zVfs
);
2411 *pzErrMsg
= sqlite3_mprintf("no such vfs: %s", zVfs
);
2415 if( rc
!=SQLITE_OK
){
2416 sqlite3_free(zFile
);
2426 ** This routine does the work of opening a database on behalf of
2427 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
2428 ** is UTF-8 encoded.
2430 static int openDatabase(
2431 const char *zFilename
, /* Database filename UTF-8 encoded */
2432 sqlite3
**ppDb
, /* OUT: Returned database handle */
2433 unsigned int flags
, /* Operational flags */
2434 const char *zVfs
/* Name of the VFS to use */
2436 sqlite3
*db
; /* Store allocated handle here */
2437 int rc
; /* Return code */
2438 int isThreadsafe
; /* True for threadsafe connections */
2439 char *zOpen
= 0; /* Filename argument to pass to BtreeOpen() */
2440 char *zErrMsg
= 0; /* Error message from sqlite3ParseUri() */
2443 #ifndef SQLITE_OMIT_AUTOINIT
2444 rc
= sqlite3_initialize();
2448 /* Only allow sensible combinations of bits in the flags argument.
2449 ** Throw an error if any non-sense combination is used. If we
2450 ** do not block illegal combinations here, it could trigger
2451 ** assert() statements in deeper layers. Sensible combinations
2454 ** 1: SQLITE_OPEN_READONLY
2455 ** 2: SQLITE_OPEN_READWRITE
2456 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
2458 assert( SQLITE_OPEN_READONLY
== 0x01 );
2459 assert( SQLITE_OPEN_READWRITE
== 0x02 );
2460 assert( SQLITE_OPEN_CREATE
== 0x04 );
2461 testcase( (1<<(flags
&7))==0x02 ); /* READONLY */
2462 testcase( (1<<(flags
&7))==0x04 ); /* READWRITE */
2463 testcase( (1<<(flags
&7))==0x40 ); /* READWRITE | CREATE */
2464 if( ((1<<(flags
&7)) & 0x46)==0 ){
2465 return SQLITE_MISUSE_BKPT
; /* IMP: R-65497-44594 */
2468 if( sqlite3GlobalConfig
.bCoreMutex
==0 ){
2470 }else if( flags
& SQLITE_OPEN_NOMUTEX
){
2472 }else if( flags
& SQLITE_OPEN_FULLMUTEX
){
2475 isThreadsafe
= sqlite3GlobalConfig
.bFullMutex
;
2477 if( flags
& SQLITE_OPEN_PRIVATECACHE
){
2478 flags
&= ~SQLITE_OPEN_SHAREDCACHE
;
2479 }else if( sqlite3GlobalConfig
.sharedCacheEnabled
){
2480 flags
|= SQLITE_OPEN_SHAREDCACHE
;
2483 /* Remove harmful bits from the flags parameter
2485 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
2486 ** dealt with in the previous code block. Besides these, the only
2487 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
2488 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
2489 ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
2490 ** off all other flags.
2492 flags
&= ~( SQLITE_OPEN_DELETEONCLOSE
|
2493 SQLITE_OPEN_EXCLUSIVE
|
2494 SQLITE_OPEN_MAIN_DB
|
2495 SQLITE_OPEN_TEMP_DB
|
2496 SQLITE_OPEN_TRANSIENT_DB
|
2497 SQLITE_OPEN_MAIN_JOURNAL
|
2498 SQLITE_OPEN_TEMP_JOURNAL
|
2499 SQLITE_OPEN_SUBJOURNAL
|
2500 SQLITE_OPEN_MASTER_JOURNAL
|
2501 SQLITE_OPEN_NOMUTEX
|
2502 SQLITE_OPEN_FULLMUTEX
|
2506 /* Allocate the sqlite data structure */
2507 db
= sqlite3MallocZero( sizeof(sqlite3
) );
2508 if( db
==0 ) goto opendb_out
;
2510 db
->mutex
= sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE
);
2517 sqlite3_mutex_enter(db
->mutex
);
2520 db
->magic
= SQLITE_MAGIC_BUSY
;
2521 db
->aDb
= db
->aDbStatic
;
2523 assert( sizeof(db
->aLimit
)==sizeof(aHardLimit
) );
2524 memcpy(db
->aLimit
, aHardLimit
, sizeof(db
->aLimit
));
2525 db
->aLimit
[SQLITE_LIMIT_WORKER_THREADS
] = SQLITE_DEFAULT_WORKER_THREADS
;
2527 db
->nextAutovac
= -1;
2528 db
->szMmap
= sqlite3GlobalConfig
.szMmap
;
2529 db
->nextPagesize
= 0;
2530 db
->nMaxSorterMmap
= 0x7FFFFFFF;
2531 db
->flags
|= SQLITE_ShortColNames
| SQLITE_EnableTrigger
| SQLITE_CacheSpill
2532 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
2535 #if SQLITE_DEFAULT_FILE_FORMAT<4
2536 | SQLITE_LegacyFileFmt
2538 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
2539 | SQLITE_LoadExtension
2541 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
2542 | SQLITE_RecTriggers
2544 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
2545 | SQLITE_ForeignKeys
2548 sqlite3HashInit(&db
->aCollSeq
);
2549 #ifndef SQLITE_OMIT_VIRTUALTABLE
2550 sqlite3HashInit(&db
->aModule
);
2553 /* Add the default collation sequence BINARY. BINARY works for both UTF-8
2554 ** and UTF-16, so add a version for each to avoid any unnecessary
2555 ** conversions. The only error that can occur here is a malloc() failure.
2557 createCollation(db
, "BINARY", SQLITE_UTF8
, 0, binCollFunc
, 0);
2558 createCollation(db
, "BINARY", SQLITE_UTF16BE
, 0, binCollFunc
, 0);
2559 createCollation(db
, "BINARY", SQLITE_UTF16LE
, 0, binCollFunc
, 0);
2560 createCollation(db
, "RTRIM", SQLITE_UTF8
, (void*)1, binCollFunc
, 0);
2561 if( db
->mallocFailed
){
2564 db
->pDfltColl
= sqlite3FindCollSeq(db
, SQLITE_UTF8
, "BINARY", 0);
2565 assert( db
->pDfltColl
!=0 );
2567 /* Also add a UTF-8 case-insensitive collation sequence. */
2568 createCollation(db
, "NOCASE", SQLITE_UTF8
, 0, nocaseCollatingFunc
, 0);
2570 /* Parse the filename/URI argument. */
2571 db
->openFlags
= flags
;
2572 rc
= sqlite3ParseUri(zVfs
, zFilename
, &flags
, &db
->pVfs
, &zOpen
, &zErrMsg
);
2573 if( rc
!=SQLITE_OK
){
2574 if( rc
==SQLITE_NOMEM
) db
->mallocFailed
= 1;
2575 sqlite3ErrorWithMsg(db
, rc
, zErrMsg
? "%s" : 0, zErrMsg
);
2576 sqlite3_free(zErrMsg
);
2580 /* Open the backend database driver */
2581 rc
= sqlite3BtreeOpen(db
->pVfs
, zOpen
, db
, &db
->aDb
[0].pBt
, 0,
2582 flags
| SQLITE_OPEN_MAIN_DB
);
2583 if( rc
!=SQLITE_OK
){
2584 if( rc
==SQLITE_IOERR_NOMEM
){
2587 sqlite3Error(db
, rc
);
2590 sqlite3BtreeEnter(db
->aDb
[0].pBt
);
2591 db
->aDb
[0].pSchema
= sqlite3SchemaGet(db
, db
->aDb
[0].pBt
);
2592 sqlite3BtreeLeave(db
->aDb
[0].pBt
);
2593 db
->aDb
[1].pSchema
= sqlite3SchemaGet(db
, 0);
2595 /* The default safety_level for the main database is 'full'; for the temp
2596 ** database it is 'NONE'. This matches the pager layer defaults.
2598 db
->aDb
[0].zName
= "main";
2599 db
->aDb
[0].safety_level
= 3;
2600 db
->aDb
[1].zName
= "temp";
2601 db
->aDb
[1].safety_level
= 1;
2603 db
->magic
= SQLITE_MAGIC_OPEN
;
2604 if( db
->mallocFailed
){
2608 /* Register all built-in functions, but do not attempt to read the
2609 ** database schema yet. This is delayed until the first time the database
2612 sqlite3Error(db
, SQLITE_OK
);
2613 sqlite3RegisterBuiltinFunctions(db
);
2615 /* Load automatic extensions - extensions that have been registered
2616 ** using the sqlite3_automatic_extension() API.
2618 rc
= sqlite3_errcode(db
);
2619 if( rc
==SQLITE_OK
){
2620 sqlite3AutoLoadExtensions(db
);
2621 rc
= sqlite3_errcode(db
);
2622 if( rc
!=SQLITE_OK
){
2627 #ifdef SQLITE_ENABLE_FTS1
2628 if( !db
->mallocFailed
){
2629 extern int sqlite3Fts1Init(sqlite3
*);
2630 rc
= sqlite3Fts1Init(db
);
2634 #ifdef SQLITE_ENABLE_FTS2
2635 if( !db
->mallocFailed
&& rc
==SQLITE_OK
){
2636 extern int sqlite3Fts2Init(sqlite3
*);
2637 rc
= sqlite3Fts2Init(db
);
2641 #ifdef SQLITE_ENABLE_FTS3
2642 if( !db
->mallocFailed
&& rc
==SQLITE_OK
){
2643 rc
= sqlite3Fts3Init(db
);
2647 #ifdef SQLITE_ENABLE_ICU
2648 if( !db
->mallocFailed
&& rc
==SQLITE_OK
){
2649 rc
= sqlite3IcuInit(db
);
2653 #ifdef SQLITE_ENABLE_RTREE
2654 if( !db
->mallocFailed
&& rc
==SQLITE_OK
){
2655 rc
= sqlite3RtreeInit(db
);
2659 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
2660 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
2661 ** mode. Doing nothing at all also makes NORMAL the default.
2663 #ifdef SQLITE_DEFAULT_LOCKING_MODE
2664 db
->dfltLockMode
= SQLITE_DEFAULT_LOCKING_MODE
;
2665 sqlite3PagerLockingMode(sqlite3BtreePager(db
->aDb
[0].pBt
),
2666 SQLITE_DEFAULT_LOCKING_MODE
);
2669 if( rc
) sqlite3Error(db
, rc
);
2671 /* Enable the lookaside-malloc subsystem */
2672 setupLookaside(db
, 0, sqlite3GlobalConfig
.szLookaside
,
2673 sqlite3GlobalConfig
.nLookaside
);
2675 sqlite3_wal_autocheckpoint(db
, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
);
2678 sqlite3_free(zOpen
);
2680 assert( db
->mutex
!=0 || isThreadsafe
==0 || sqlite3GlobalConfig
.bFullMutex
==0 );
2681 sqlite3_mutex_leave(db
->mutex
);
2683 rc
= sqlite3_errcode(db
);
2684 assert( db
!=0 || rc
==SQLITE_NOMEM
);
2685 if( rc
==SQLITE_NOMEM
){
2688 }else if( rc
!=SQLITE_OK
){
2689 db
->magic
= SQLITE_MAGIC_SICK
;
2692 #ifdef SQLITE_ENABLE_SQLLOG
2693 if( sqlite3GlobalConfig
.xSqllog
){
2694 /* Opening a db handle. Fourth parameter is passed 0. */
2695 void *pArg
= sqlite3GlobalConfig
.pSqllogArg
;
2696 sqlite3GlobalConfig
.xSqllog(pArg
, db
, zFilename
, 0);
2699 return sqlite3ApiExit(0, rc
);
2703 ** Open a new database handle.
2706 const char *zFilename
,
2709 return openDatabase(zFilename
, ppDb
,
2710 SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
, 0);
2712 int sqlite3_open_v2(
2713 const char *filename
, /* Database filename (UTF-8) */
2714 sqlite3
**ppDb
, /* OUT: SQLite db handle */
2715 int flags
, /* Flags */
2716 const char *zVfs
/* Name of VFS module to use */
2718 return openDatabase(filename
, ppDb
, (unsigned int)flags
, zVfs
);
2721 #ifndef SQLITE_OMIT_UTF16
2723 ** Open a new database handle.
2726 const void *zFilename
,
2729 char const *zFilename8
; /* zFilename encoded in UTF-8 instead of UTF-16 */
2730 sqlite3_value
*pVal
;
2733 assert( zFilename
);
2736 #ifndef SQLITE_OMIT_AUTOINIT
2737 rc
= sqlite3_initialize();
2740 pVal
= sqlite3ValueNew(0);
2741 sqlite3ValueSetStr(pVal
, -1, zFilename
, SQLITE_UTF16NATIVE
, SQLITE_STATIC
);
2742 zFilename8
= sqlite3ValueText(pVal
, SQLITE_UTF8
);
2744 rc
= openDatabase(zFilename8
, ppDb
,
2745 SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
, 0);
2746 assert( *ppDb
|| rc
==SQLITE_NOMEM
);
2747 if( rc
==SQLITE_OK
&& !DbHasProperty(*ppDb
, 0, DB_SchemaLoaded
) ){
2748 ENC(*ppDb
) = SQLITE_UTF16NATIVE
;
2753 sqlite3ValueFree(pVal
);
2755 return sqlite3ApiExit(0, rc
);
2757 #endif /* SQLITE_OMIT_UTF16 */
2760 ** Register a new collation sequence with the database handle db.
2762 int sqlite3_create_collation(
2767 int(*xCompare
)(void*,int,const void*,int,const void*)
2770 sqlite3_mutex_enter(db
->mutex
);
2771 assert( !db
->mallocFailed
);
2772 rc
= createCollation(db
, zName
, (u8
)enc
, pCtx
, xCompare
, 0);
2773 rc
= sqlite3ApiExit(db
, rc
);
2774 sqlite3_mutex_leave(db
->mutex
);
2779 ** Register a new collation sequence with the database handle db.
2781 int sqlite3_create_collation_v2(
2786 int(*xCompare
)(void*,int,const void*,int,const void*),
2790 sqlite3_mutex_enter(db
->mutex
);
2791 assert( !db
->mallocFailed
);
2792 rc
= createCollation(db
, zName
, (u8
)enc
, pCtx
, xCompare
, xDel
);
2793 rc
= sqlite3ApiExit(db
, rc
);
2794 sqlite3_mutex_leave(db
->mutex
);
2798 #ifndef SQLITE_OMIT_UTF16
2800 ** Register a new collation sequence with the database handle db.
2802 int sqlite3_create_collation16(
2807 int(*xCompare
)(void*,int,const void*,int,const void*)
2811 sqlite3_mutex_enter(db
->mutex
);
2812 assert( !db
->mallocFailed
);
2813 zName8
= sqlite3Utf16to8(db
, zName
, -1, SQLITE_UTF16NATIVE
);
2815 rc
= createCollation(db
, zName8
, (u8
)enc
, pCtx
, xCompare
, 0);
2816 sqlite3DbFree(db
, zName8
);
2818 rc
= sqlite3ApiExit(db
, rc
);
2819 sqlite3_mutex_leave(db
->mutex
);
2822 #endif /* SQLITE_OMIT_UTF16 */
2825 ** Register a collation sequence factory callback with the database handle
2826 ** db. Replace any previously installed collation sequence factory.
2828 int sqlite3_collation_needed(
2830 void *pCollNeededArg
,
2831 void(*xCollNeeded
)(void*,sqlite3
*,int eTextRep
,const char*)
2833 sqlite3_mutex_enter(db
->mutex
);
2834 db
->xCollNeeded
= xCollNeeded
;
2835 db
->xCollNeeded16
= 0;
2836 db
->pCollNeededArg
= pCollNeededArg
;
2837 sqlite3_mutex_leave(db
->mutex
);
2841 #ifndef SQLITE_OMIT_UTF16
2843 ** Register a collation sequence factory callback with the database handle
2844 ** db. Replace any previously installed collation sequence factory.
2846 int sqlite3_collation_needed16(
2848 void *pCollNeededArg
,
2849 void(*xCollNeeded16
)(void*,sqlite3
*,int eTextRep
,const void*)
2851 sqlite3_mutex_enter(db
->mutex
);
2852 db
->xCollNeeded
= 0;
2853 db
->xCollNeeded16
= xCollNeeded16
;
2854 db
->pCollNeededArg
= pCollNeededArg
;
2855 sqlite3_mutex_leave(db
->mutex
);
2858 #endif /* SQLITE_OMIT_UTF16 */
2860 #ifndef SQLITE_OMIT_DEPRECATED
2862 ** This function is now an anachronism. It used to be used to recover from a
2863 ** malloc() failure, but SQLite now does this automatically.
2865 int sqlite3_global_recover(void){
2871 ** Test to see whether or not the database connection is in autocommit
2872 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
2873 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
2874 ** by the next COMMIT or ROLLBACK.
2876 int sqlite3_get_autocommit(sqlite3
*db
){
2877 return db
->autoCommit
;
2881 ** The following routines are substitutes for constants SQLITE_CORRUPT,
2882 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
2883 ** constants. They serve two purposes:
2885 ** 1. Serve as a convenient place to set a breakpoint in a debugger
2886 ** to detect when version error conditions occurs.
2888 ** 2. Invoke sqlite3_log() to provide the source code location where
2889 ** a low-level error is first detected.
2891 int sqlite3CorruptError(int lineno
){
2892 testcase( sqlite3GlobalConfig
.xLog
!=0 );
2893 sqlite3_log(SQLITE_CORRUPT
,
2894 "database corruption at line %d of [%.10s]",
2895 lineno
, 20+sqlite3_sourceid());
2896 return SQLITE_CORRUPT
;
2898 int sqlite3MisuseError(int lineno
){
2899 testcase( sqlite3GlobalConfig
.xLog
!=0 );
2900 sqlite3_log(SQLITE_MISUSE
,
2901 "misuse at line %d of [%.10s]",
2902 lineno
, 20+sqlite3_sourceid());
2903 return SQLITE_MISUSE
;
2905 int sqlite3CantopenError(int lineno
){
2906 testcase( sqlite3GlobalConfig
.xLog
!=0 );
2907 sqlite3_log(SQLITE_CANTOPEN
,
2908 "cannot open file at line %d of [%.10s]",
2909 lineno
, 20+sqlite3_sourceid());
2910 return SQLITE_CANTOPEN
;
2914 #ifndef SQLITE_OMIT_DEPRECATED
2916 ** This is a convenience routine that makes sure that all thread-specific
2917 ** data for this thread has been deallocated.
2919 ** SQLite no longer uses thread-specific data so this routine is now a
2920 ** no-op. It is retained for historical compatibility.
2922 void sqlite3_thread_cleanup(void){
2927 ** Return meta information about a specific column of a database table.
2928 ** See comment in sqlite3.h (sqlite.h.in) for details.
2930 #ifdef SQLITE_ENABLE_COLUMN_METADATA
2931 int sqlite3_table_column_metadata(
2932 sqlite3
*db
, /* Connection handle */
2933 const char *zDbName
, /* Database name or NULL */
2934 const char *zTableName
, /* Table name */
2935 const char *zColumnName
, /* Column name */
2936 char const **pzDataType
, /* OUTPUT: Declared data type */
2937 char const **pzCollSeq
, /* OUTPUT: Collation sequence name */
2938 int *pNotNull
, /* OUTPUT: True if NOT NULL constraint exists */
2939 int *pPrimaryKey
, /* OUTPUT: True if column part of PK */
2940 int *pAutoinc
/* OUTPUT: True if column is auto-increment */
2948 char const *zDataType
= 0;
2949 char const *zCollSeq
= 0;
2954 /* Ensure the database schema has been loaded */
2955 sqlite3_mutex_enter(db
->mutex
);
2956 sqlite3BtreeEnterAll(db
);
2957 rc
= sqlite3Init(db
, &zErrMsg
);
2958 if( SQLITE_OK
!=rc
){
2962 /* Locate the table in question */
2963 pTab
= sqlite3FindTable(db
, zTableName
, zDbName
);
2964 if( !pTab
|| pTab
->pSelect
){
2969 /* Find the column for which info is requested */
2970 if( sqlite3IsRowid(zColumnName
) ){
2973 pCol
= &pTab
->aCol
[iCol
];
2976 for(iCol
=0; iCol
<pTab
->nCol
; iCol
++){
2977 pCol
= &pTab
->aCol
[iCol
];
2978 if( 0==sqlite3StrICmp(pCol
->zName
, zColumnName
) ){
2982 if( iCol
==pTab
->nCol
){
2988 /* The following block stores the meta information that will be returned
2989 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
2990 ** and autoinc. At this point there are two possibilities:
2992 ** 1. The specified column name was rowid", "oid" or "_rowid_"
2993 ** and there is no explicitly declared IPK column.
2995 ** 2. The table is not a view and the column name identified an
2996 ** explicitly declared column. Copy meta information from *pCol.
2999 zDataType
= pCol
->zType
;
3000 zCollSeq
= pCol
->zColl
;
3001 notnull
= pCol
->notNull
!=0;
3002 primarykey
= (pCol
->colFlags
& COLFLAG_PRIMKEY
)!=0;
3003 autoinc
= pTab
->iPKey
==iCol
&& (pTab
->tabFlags
& TF_Autoincrement
)!=0;
3005 zDataType
= "INTEGER";
3009 zCollSeq
= "BINARY";
3013 sqlite3BtreeLeaveAll(db
);
3015 /* Whether the function call succeeded or failed, set the output parameters
3016 ** to whatever their local counterparts contain. If an error did occur,
3017 ** this has the effect of zeroing all output parameters.
3019 if( pzDataType
) *pzDataType
= zDataType
;
3020 if( pzCollSeq
) *pzCollSeq
= zCollSeq
;
3021 if( pNotNull
) *pNotNull
= notnull
;
3022 if( pPrimaryKey
) *pPrimaryKey
= primarykey
;
3023 if( pAutoinc
) *pAutoinc
= autoinc
;
3025 if( SQLITE_OK
==rc
&& !pTab
){
3026 sqlite3DbFree(db
, zErrMsg
);
3027 zErrMsg
= sqlite3MPrintf(db
, "no such table column: %s.%s", zTableName
,
3031 sqlite3ErrorWithMsg(db
, rc
, (zErrMsg
?"%s":0), zErrMsg
);
3032 sqlite3DbFree(db
, zErrMsg
);
3033 rc
= sqlite3ApiExit(db
, rc
);
3034 sqlite3_mutex_leave(db
->mutex
);
3040 ** Sleep for a little while. Return the amount of time slept.
3042 int sqlite3_sleep(int ms
){
3045 pVfs
= sqlite3_vfs_find(0);
3046 if( pVfs
==0 ) return 0;
3048 /* This function works in milliseconds, but the underlying OsSleep()
3049 ** API uses microseconds. Hence the 1000's.
3051 rc
= (sqlite3OsSleep(pVfs
, 1000*ms
)/1000);
3056 ** Enable or disable the extended result codes.
3058 int sqlite3_extended_result_codes(sqlite3
*db
, int onoff
){
3059 sqlite3_mutex_enter(db
->mutex
);
3060 db
->errMask
= onoff
? 0xffffffff : 0xff;
3061 sqlite3_mutex_leave(db
->mutex
);
3066 ** Invoke the xFileControl method on a particular database.
3068 int sqlite3_file_control(sqlite3
*db
, const char *zDbName
, int op
, void *pArg
){
3069 int rc
= SQLITE_ERROR
;
3072 sqlite3_mutex_enter(db
->mutex
);
3073 pBtree
= sqlite3DbNameToBtree(db
, zDbName
);
3077 sqlite3BtreeEnter(pBtree
);
3078 pPager
= sqlite3BtreePager(pBtree
);
3079 assert( pPager
!=0 );
3080 fd
= sqlite3PagerFile(pPager
);
3082 if( op
==SQLITE_FCNTL_FILE_POINTER
){
3083 *(sqlite3_file
**)pArg
= fd
;
3085 }else if( fd
->pMethods
){
3086 rc
= sqlite3OsFileControl(fd
, op
, pArg
);
3088 rc
= SQLITE_NOTFOUND
;
3090 sqlite3BtreeLeave(pBtree
);
3092 sqlite3_mutex_leave(db
->mutex
);
3097 ** Interface to the testing logic.
3099 int sqlite3_test_control(int op
, ...){
3101 #ifndef SQLITE_OMIT_BUILTIN_TEST
3107 ** Save the current state of the PRNG.
3109 case SQLITE_TESTCTRL_PRNG_SAVE
: {
3110 sqlite3PrngSaveState();
3115 ** Restore the state of the PRNG to the last state saved using
3116 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
3117 ** this verb acts like PRNG_RESET.
3119 case SQLITE_TESTCTRL_PRNG_RESTORE
: {
3120 sqlite3PrngRestoreState();
3125 ** Reset the PRNG back to its uninitialized state. The next call
3126 ** to sqlite3_randomness() will reseed the PRNG using a single call
3127 ** to the xRandomness method of the default VFS.
3129 case SQLITE_TESTCTRL_PRNG_RESET
: {
3130 sqlite3_randomness(0,0);
3135 ** sqlite3_test_control(BITVEC_TEST, size, program)
3137 ** Run a test against a Bitvec object of size. The program argument
3138 ** is an array of integers that defines the test. Return -1 on a
3139 ** memory allocation error, 0 on success, or non-zero for an error.
3140 ** See the sqlite3BitvecBuiltinTest() for additional information.
3142 case SQLITE_TESTCTRL_BITVEC_TEST
: {
3143 int sz
= va_arg(ap
, int);
3144 int *aProg
= va_arg(ap
, int*);
3145 rc
= sqlite3BitvecBuiltinTest(sz
, aProg
);
3150 ** sqlite3_test_control(FAULT_INSTALL, xCallback)
3152 ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
3153 ** if xCallback is not NULL.
3155 ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
3156 ** is called immediately after installing the new callback and the return
3157 ** value from sqlite3FaultSim(0) becomes the return from
3158 ** sqlite3_test_control().
3160 case SQLITE_TESTCTRL_FAULT_INSTALL
: {
3161 /* MSVC is picky about pulling func ptrs from va lists.
3162 ** http://support.microsoft.com/kb/47961
3163 ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
3165 typedef int(*TESTCALLBACKFUNC_t
)(int);
3166 sqlite3GlobalConfig
.xTestCallback
= va_arg(ap
, TESTCALLBACKFUNC_t
);
3167 rc
= sqlite3FaultSim(0);
3172 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
3174 ** Register hooks to call to indicate which malloc() failures
3177 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS
: {
3178 typedef void (*void_function
)(void);
3179 void_function xBenignBegin
;
3180 void_function xBenignEnd
;
3181 xBenignBegin
= va_arg(ap
, void_function
);
3182 xBenignEnd
= va_arg(ap
, void_function
);
3183 sqlite3BenignMallocHooks(xBenignBegin
, xBenignEnd
);
3188 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
3190 ** Set the PENDING byte to the value in the argument, if X>0.
3191 ** Make no changes if X==0. Return the value of the pending byte
3192 ** as it existing before this routine was called.
3194 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
3195 ** an incompatible database file format. Changing the PENDING byte
3196 ** while any database connection is open results in undefined and
3197 ** deleterious behavior.
3199 case SQLITE_TESTCTRL_PENDING_BYTE
: {
3201 #ifndef SQLITE_OMIT_WSD
3203 unsigned int newVal
= va_arg(ap
, unsigned int);
3204 if( newVal
) sqlite3PendingByte
= newVal
;
3211 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
3213 ** This action provides a run-time test to see whether or not
3214 ** assert() was enabled at compile-time. If X is true and assert()
3215 ** is enabled, then the return value is true. If X is true and
3216 ** assert() is disabled, then the return value is zero. If X is
3217 ** false and assert() is enabled, then the assertion fires and the
3218 ** process aborts. If X is false and assert() is disabled, then the
3219 ** return value is zero.
3221 case SQLITE_TESTCTRL_ASSERT
: {
3223 assert( (x
= va_arg(ap
,int))!=0 );
3230 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
3232 ** This action provides a run-time test to see how the ALWAYS and
3233 ** NEVER macros were defined at compile-time.
3235 ** The return value is ALWAYS(X).
3237 ** The recommended test is X==2. If the return value is 2, that means
3238 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
3239 ** default setting. If the return value is 1, then ALWAYS() is either
3240 ** hard-coded to true or else it asserts if its argument is false.
3241 ** The first behavior (hard-coded to true) is the case if
3242 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
3243 ** behavior (assert if the argument to ALWAYS() is false) is the case if
3244 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
3246 ** The run-time test procedure might look something like this:
3248 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
3249 ** // ALWAYS() and NEVER() are no-op pass-through macros
3250 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
3251 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
3253 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
3256 case SQLITE_TESTCTRL_ALWAYS
: {
3257 int x
= va_arg(ap
,int);
3263 ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
3265 ** The integer returned reveals the byte-order of the computer on which
3266 ** SQLite is running:
3268 ** 1 big-endian, determined at run-time
3269 ** 10 little-endian, determined at run-time
3270 ** 432101 big-endian, determined at compile-time
3271 ** 123410 little-endian, determined at compile-time
3273 case SQLITE_TESTCTRL_BYTEORDER
: {
3274 rc
= SQLITE_BYTEORDER
*100 + SQLITE_LITTLEENDIAN
*10 + SQLITE_BIGENDIAN
;
3278 /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
3280 ** Set the nReserve size to N for the main database on the database
3283 case SQLITE_TESTCTRL_RESERVE
: {
3284 sqlite3
*db
= va_arg(ap
, sqlite3
*);
3285 int x
= va_arg(ap
,int);
3286 sqlite3_mutex_enter(db
->mutex
);
3287 sqlite3BtreeSetPageSize(db
->aDb
[0].pBt
, 0, x
, 0);
3288 sqlite3_mutex_leave(db
->mutex
);
3292 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
3294 ** Enable or disable various optimizations for testing purposes. The
3295 ** argument N is a bitmask of optimizations to be disabled. For normal
3296 ** operation N should be 0. The idea is that a test program (like the
3297 ** SQL Logic Test or SLT test module) can run the same SQL multiple times
3298 ** with various optimizations disabled to verify that the same answer
3299 ** is obtained in every case.
3301 case SQLITE_TESTCTRL_OPTIMIZATIONS
: {
3302 sqlite3
*db
= va_arg(ap
, sqlite3
*);
3303 db
->dbOptFlags
= (u16
)(va_arg(ap
, int) & 0xffff);
3307 #ifdef SQLITE_N_KEYWORD
3308 /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
3310 ** If zWord is a keyword recognized by the parser, then return the
3311 ** number of keywords. Or if zWord is not a keyword, return 0.
3313 ** This test feature is only available in the amalgamation since
3314 ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
3315 ** is built using separate source files.
3317 case SQLITE_TESTCTRL_ISKEYWORD
: {
3318 const char *zWord
= va_arg(ap
, const char*);
3319 int n
= sqlite3Strlen30(zWord
);
3320 rc
= (sqlite3KeywordCode((u8
*)zWord
, n
)!=TK_ID
) ? SQLITE_N_KEYWORD
: 0;
3325 /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
3327 ** Pass pFree into sqlite3ScratchFree().
3328 ** If sz>0 then allocate a scratch buffer into pNew.
3330 case SQLITE_TESTCTRL_SCRATCHMALLOC
: {
3331 void *pFree
, **ppNew
;
3333 sz
= va_arg(ap
, int);
3334 ppNew
= va_arg(ap
, void**);
3335 pFree
= va_arg(ap
, void*);
3336 if( sz
) *ppNew
= sqlite3ScratchMalloc(sz
);
3337 sqlite3ScratchFree(pFree
);
3341 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
3343 ** If parameter onoff is non-zero, configure the wrappers so that all
3344 ** subsequent calls to localtime() and variants fail. If onoff is zero,
3345 ** undo this setting.
3347 case SQLITE_TESTCTRL_LOCALTIME_FAULT
: {
3348 sqlite3GlobalConfig
.bLocaltimeFault
= va_arg(ap
, int);
3352 /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
3354 ** Set or clear a flag that indicates that the database file is always well-
3355 ** formed and never corrupt. This flag is clear by default, indicating that
3356 ** database files might have arbitrary corruption. Setting the flag during
3357 ** testing causes certain assert() statements in the code to be activated
3358 ** that demonstrat invariants on well-formed database files.
3360 case SQLITE_TESTCTRL_NEVER_CORRUPT
: {
3361 sqlite3GlobalConfig
.neverCorrupt
= va_arg(ap
, int);
3366 /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
3368 ** Set the VDBE coverage callback function to xCallback with context
3371 case SQLITE_TESTCTRL_VDBE_COVERAGE
: {
3372 #ifdef SQLITE_VDBE_COVERAGE
3373 typedef void (*branch_callback
)(void*,int,u8
,u8
);
3374 sqlite3GlobalConfig
.xVdbeBranch
= va_arg(ap
,branch_callback
);
3375 sqlite3GlobalConfig
.pVdbeBranchArg
= va_arg(ap
,void*);
3380 /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
3381 case SQLITE_TESTCTRL_SORTER_MMAP
: {
3382 sqlite3
*db
= va_arg(ap
, sqlite3
*);
3383 db
->nMaxSorterMmap
= va_arg(ap
, int);
3387 /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
3389 ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
3392 case SQLITE_TESTCTRL_ISINIT
: {
3393 if( sqlite3GlobalConfig
.isInit
==0 ) rc
= SQLITE_ERROR
;
3398 #endif /* SQLITE_OMIT_BUILTIN_TEST */
3403 ** This is a utility routine, useful to VFS implementations, that checks
3404 ** to see if a database file was a URI that contained a specific query
3405 ** parameter, and if so obtains the value of the query parameter.
3407 ** The zFilename argument is the filename pointer passed into the xOpen()
3408 ** method of a VFS implementation. The zParam argument is the name of the
3409 ** query parameter we seek. This routine returns the value of the zParam
3410 ** parameter if it exists. If the parameter does not exist, this routine
3411 ** returns a NULL pointer.
3413 const char *sqlite3_uri_parameter(const char *zFilename
, const char *zParam
){
3414 if( zFilename
==0 ) return 0;
3415 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
3416 while( zFilename
[0] ){
3417 int x
= strcmp(zFilename
, zParam
);
3418 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
3419 if( x
==0 ) return zFilename
;
3420 zFilename
+= sqlite3Strlen30(zFilename
) + 1;
3426 ** Return a boolean value for a query parameter.
3428 int sqlite3_uri_boolean(const char *zFilename
, const char *zParam
, int bDflt
){
3429 const char *z
= sqlite3_uri_parameter(zFilename
, zParam
);
3431 return z
? sqlite3GetBoolean(z
, bDflt
) : bDflt
;
3435 ** Return a 64-bit integer value for a query parameter.
3437 sqlite3_int64
sqlite3_uri_int64(
3438 const char *zFilename
, /* Filename as passed to xOpen */
3439 const char *zParam
, /* URI parameter sought */
3440 sqlite3_int64 bDflt
/* return if parameter is missing */
3442 const char *z
= sqlite3_uri_parameter(zFilename
, zParam
);
3444 if( z
&& sqlite3DecOrHexToI64(z
, &v
)==SQLITE_OK
){
3451 ** Return the Btree pointer identified by zDbName. Return NULL if not found.
3453 Btree
*sqlite3DbNameToBtree(sqlite3
*db
, const char *zDbName
){
3455 for(i
=0; i
<db
->nDb
; i
++){
3457 && (zDbName
==0 || sqlite3StrICmp(zDbName
, db
->aDb
[i
].zName
)==0)
3459 return db
->aDb
[i
].pBt
;
3466 ** Return the filename of the database associated with a database
3469 const char *sqlite3_db_filename(sqlite3
*db
, const char *zDbName
){
3470 Btree
*pBt
= sqlite3DbNameToBtree(db
, zDbName
);
3471 return pBt
? sqlite3BtreeGetFilename(pBt
) : 0;
3475 ** Return 1 if database is read-only or 0 if read/write. Return -1 if
3476 ** no such database exists.
3478 int sqlite3_db_readonly(sqlite3
*db
, const char *zDbName
){
3479 Btree
*pBt
= sqlite3DbNameToBtree(db
, zDbName
);
3480 return pBt
? sqlite3BtreeIsReadonly(pBt
) : -1;