000001 /* 000002 ** 2001 September 15 000003 ** 000004 ** The author disclaims copyright to this source code. In place of 000005 ** a legal notice, here is a blessing: 000006 ** 000007 ** May you do good and not evil. 000008 ** May you find forgiveness for yourself and forgive others. 000009 ** May you share freely, never taking more than you give. 000010 ** 000011 ************************************************************************* 000012 ** Main file for the SQLite library. The routines in this file 000013 ** implement the programmer interface to the library. Routines in 000014 ** other files are for internal use by SQLite and should not be 000015 ** accessed by users of the library. 000016 */ 000017 #include "sqliteInt.h" 000018 000019 #ifdef SQLITE_ENABLE_FTS3 000020 # include "fts3.h" 000021 #endif 000022 #ifdef SQLITE_ENABLE_RTREE 000023 # include "rtree.h" 000024 #endif 000025 #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS) 000026 # include "sqliteicu.h" 000027 #endif 000028 #ifdef SQLITE_ENABLE_JSON1 000029 int sqlite3Json1Init(sqlite3*); 000030 #endif 000031 #ifdef SQLITE_ENABLE_STMTVTAB 000032 int sqlite3StmtVtabInit(sqlite3*); 000033 #endif 000034 #ifdef SQLITE_ENABLE_FTS5 000035 int sqlite3Fts5Init(sqlite3*); 000036 #endif 000037 000038 #ifndef SQLITE_AMALGAMATION 000039 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant 000040 ** contains the text of SQLITE_VERSION macro. 000041 */ 000042 const char sqlite3_version[] = SQLITE_VERSION; 000043 #endif 000044 000045 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns 000046 ** a pointer to the to the sqlite3_version[] string constant. 000047 */ 000048 const char *sqlite3_libversion(void){ return sqlite3_version; } 000049 000050 /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a 000051 ** pointer to a string constant whose value is the same as the 000052 ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using 000053 ** an edited copy of the amalgamation, then the last four characters of 000054 ** the hash might be different from SQLITE_SOURCE_ID. 000055 */ 000056 const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } 000057 000058 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function 000059 ** returns an integer equal to SQLITE_VERSION_NUMBER. 000060 */ 000061 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; } 000062 000063 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns 000064 ** zero if and only if SQLite was compiled with mutexing code omitted due to 000065 ** the SQLITE_THREADSAFE compile-time option being set to 0. 000066 */ 000067 int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; } 000068 000069 /* 000070 ** When compiling the test fixture or with debugging enabled (on Win32), 000071 ** this variable being set to non-zero will cause OSTRACE macros to emit 000072 ** extra diagnostic information. 000073 */ 000074 #ifdef SQLITE_HAVE_OS_TRACE 000075 # ifndef SQLITE_DEBUG_OS_TRACE 000076 # define SQLITE_DEBUG_OS_TRACE 0 000077 # endif 000078 int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE; 000079 #endif 000080 000081 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE) 000082 /* 000083 ** If the following function pointer is not NULL and if 000084 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing 000085 ** I/O active are written using this function. These messages 000086 ** are intended for debugging activity only. 000087 */ 000088 SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0; 000089 #endif 000090 000091 /* 000092 ** If the following global variable points to a string which is the 000093 ** name of a directory, then that directory will be used to store 000094 ** temporary files. 000095 ** 000096 ** See also the "PRAGMA temp_store_directory" SQL command. 000097 */ 000098 char *sqlite3_temp_directory = 0; 000099 000100 /* 000101 ** If the following global variable points to a string which is the 000102 ** name of a directory, then that directory will be used to store 000103 ** all database files specified with a relative pathname. 000104 ** 000105 ** See also the "PRAGMA data_store_directory" SQL command. 000106 */ 000107 char *sqlite3_data_directory = 0; 000108 000109 /* 000110 ** Initialize SQLite. 000111 ** 000112 ** This routine must be called to initialize the memory allocation, 000113 ** VFS, and mutex subsystems prior to doing any serious work with 000114 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT 000115 ** this routine will be called automatically by key routines such as 000116 ** sqlite3_open(). 000117 ** 000118 ** This routine is a no-op except on its very first call for the process, 000119 ** or for the first call after a call to sqlite3_shutdown. 000120 ** 000121 ** The first thread to call this routine runs the initialization to 000122 ** completion. If subsequent threads call this routine before the first 000123 ** thread has finished the initialization process, then the subsequent 000124 ** threads must block until the first thread finishes with the initialization. 000125 ** 000126 ** The first thread might call this routine recursively. Recursive 000127 ** calls to this routine should not block, of course. Otherwise the 000128 ** initialization process would never complete. 000129 ** 000130 ** Let X be the first thread to enter this routine. Let Y be some other 000131 ** thread. Then while the initial invocation of this routine by X is 000132 ** incomplete, it is required that: 000133 ** 000134 ** * Calls to this routine from Y must block until the outer-most 000135 ** call by X completes. 000136 ** 000137 ** * Recursive calls to this routine from thread X return immediately 000138 ** without blocking. 000139 */ 000140 int sqlite3_initialize(void){ 000141 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */ 000142 int rc; /* Result code */ 000143 #ifdef SQLITE_EXTRA_INIT 000144 int bRunExtraInit = 0; /* Extra initialization needed */ 000145 #endif 000146 000147 #ifdef SQLITE_OMIT_WSD 000148 rc = sqlite3_wsd_init(4096, 24); 000149 if( rc!=SQLITE_OK ){ 000150 return rc; 000151 } 000152 #endif 000153 000154 /* If the following assert() fails on some obscure processor/compiler 000155 ** combination, the work-around is to set the correct pointer 000156 ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */ 000157 assert( SQLITE_PTRSIZE==sizeof(char*) ); 000158 000159 /* If SQLite is already completely initialized, then this call 000160 ** to sqlite3_initialize() should be a no-op. But the initialization 000161 ** must be complete. So isInit must not be set until the very end 000162 ** of this routine. 000163 */ 000164 if( sqlite3GlobalConfig.isInit ) return SQLITE_OK; 000165 000166 /* Make sure the mutex subsystem is initialized. If unable to 000167 ** initialize the mutex subsystem, return early with the error. 000168 ** If the system is so sick that we are unable to allocate a mutex, 000169 ** there is not much SQLite is going to be able to do. 000170 ** 000171 ** The mutex subsystem must take care of serializing its own 000172 ** initialization. 000173 */ 000174 rc = sqlite3MutexInit(); 000175 if( rc ) return rc; 000176 000177 /* Initialize the malloc() system and the recursive pInitMutex mutex. 000178 ** This operation is protected by the STATIC_MASTER mutex. Note that 000179 ** MutexAlloc() is called for a static mutex prior to initializing the 000180 ** malloc subsystem - this implies that the allocation of a static 000181 ** mutex must not require support from the malloc subsystem. 000182 */ 000183 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) 000184 sqlite3_mutex_enter(pMaster); 000185 sqlite3GlobalConfig.isMutexInit = 1; 000186 if( !sqlite3GlobalConfig.isMallocInit ){ 000187 rc = sqlite3MallocInit(); 000188 } 000189 if( rc==SQLITE_OK ){ 000190 sqlite3GlobalConfig.isMallocInit = 1; 000191 if( !sqlite3GlobalConfig.pInitMutex ){ 000192 sqlite3GlobalConfig.pInitMutex = 000193 sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); 000194 if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){ 000195 rc = SQLITE_NOMEM_BKPT; 000196 } 000197 } 000198 } 000199 if( rc==SQLITE_OK ){ 000200 sqlite3GlobalConfig.nRefInitMutex++; 000201 } 000202 sqlite3_mutex_leave(pMaster); 000203 000204 /* If rc is not SQLITE_OK at this point, then either the malloc 000205 ** subsystem could not be initialized or the system failed to allocate 000206 ** the pInitMutex mutex. Return an error in either case. */ 000207 if( rc!=SQLITE_OK ){ 000208 return rc; 000209 } 000210 000211 /* Do the rest of the initialization under the recursive mutex so 000212 ** that we will be able to handle recursive calls into 000213 ** sqlite3_initialize(). The recursive calls normally come through 000214 ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other 000215 ** recursive calls might also be possible. 000216 ** 000217 ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls 000218 ** to the xInit method, so the xInit method need not be threadsafe. 000219 ** 000220 ** The following mutex is what serializes access to the appdef pcache xInit 000221 ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the 000222 ** call to sqlite3PcacheInitialize(). 000223 */ 000224 sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex); 000225 if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){ 000226 sqlite3GlobalConfig.inProgress = 1; 000227 #ifdef SQLITE_ENABLE_SQLLOG 000228 { 000229 extern void sqlite3_init_sqllog(void); 000230 sqlite3_init_sqllog(); 000231 } 000232 #endif 000233 memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions)); 000234 sqlite3RegisterBuiltinFunctions(); 000235 if( sqlite3GlobalConfig.isPCacheInit==0 ){ 000236 rc = sqlite3PcacheInitialize(); 000237 } 000238 if( rc==SQLITE_OK ){ 000239 sqlite3GlobalConfig.isPCacheInit = 1; 000240 rc = sqlite3OsInit(); 000241 } 000242 #ifdef SQLITE_ENABLE_DESERIALIZE 000243 if( rc==SQLITE_OK ){ 000244 rc = sqlite3MemdbInit(); 000245 } 000246 #endif 000247 if( rc==SQLITE_OK ){ 000248 sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 000249 sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage); 000250 sqlite3GlobalConfig.isInit = 1; 000251 #ifdef SQLITE_EXTRA_INIT 000252 bRunExtraInit = 1; 000253 #endif 000254 } 000255 sqlite3GlobalConfig.inProgress = 0; 000256 } 000257 sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex); 000258 000259 /* Go back under the static mutex and clean up the recursive 000260 ** mutex to prevent a resource leak. 000261 */ 000262 sqlite3_mutex_enter(pMaster); 000263 sqlite3GlobalConfig.nRefInitMutex--; 000264 if( sqlite3GlobalConfig.nRefInitMutex<=0 ){ 000265 assert( sqlite3GlobalConfig.nRefInitMutex==0 ); 000266 sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex); 000267 sqlite3GlobalConfig.pInitMutex = 0; 000268 } 000269 sqlite3_mutex_leave(pMaster); 000270 000271 /* The following is just a sanity check to make sure SQLite has 000272 ** been compiled correctly. It is important to run this code, but 000273 ** we don't want to run it too often and soak up CPU cycles for no 000274 ** reason. So we run it once during initialization. 000275 */ 000276 #ifndef NDEBUG 000277 #ifndef SQLITE_OMIT_FLOATING_POINT 000278 /* This section of code's only "output" is via assert() statements. */ 000279 if( rc==SQLITE_OK ){ 000280 u64 x = (((u64)1)<<63)-1; 000281 double y; 000282 assert(sizeof(x)==8); 000283 assert(sizeof(x)==sizeof(y)); 000284 memcpy(&y, &x, 8); 000285 assert( sqlite3IsNaN(y) ); 000286 } 000287 #endif 000288 #endif 000289 000290 /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT 000291 ** compile-time option. 000292 */ 000293 #ifdef SQLITE_EXTRA_INIT 000294 if( bRunExtraInit ){ 000295 int SQLITE_EXTRA_INIT(const char*); 000296 rc = SQLITE_EXTRA_INIT(0); 000297 } 000298 #endif 000299 000300 return rc; 000301 } 000302 000303 /* 000304 ** Undo the effects of sqlite3_initialize(). Must not be called while 000305 ** there are outstanding database connections or memory allocations or 000306 ** while any part of SQLite is otherwise in use in any thread. This 000307 ** routine is not threadsafe. But it is safe to invoke this routine 000308 ** on when SQLite is already shut down. If SQLite is already shut down 000309 ** when this routine is invoked, then this routine is a harmless no-op. 000310 */ 000311 int sqlite3_shutdown(void){ 000312 #ifdef SQLITE_OMIT_WSD 000313 int rc = sqlite3_wsd_init(4096, 24); 000314 if( rc!=SQLITE_OK ){ 000315 return rc; 000316 } 000317 #endif 000318 000319 if( sqlite3GlobalConfig.isInit ){ 000320 #ifdef SQLITE_EXTRA_SHUTDOWN 000321 void SQLITE_EXTRA_SHUTDOWN(void); 000322 SQLITE_EXTRA_SHUTDOWN(); 000323 #endif 000324 sqlite3_os_end(); 000325 sqlite3_reset_auto_extension(); 000326 sqlite3GlobalConfig.isInit = 0; 000327 } 000328 if( sqlite3GlobalConfig.isPCacheInit ){ 000329 sqlite3PcacheShutdown(); 000330 sqlite3GlobalConfig.isPCacheInit = 0; 000331 } 000332 if( sqlite3GlobalConfig.isMallocInit ){ 000333 sqlite3MallocEnd(); 000334 sqlite3GlobalConfig.isMallocInit = 0; 000335 000336 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES 000337 /* The heap subsystem has now been shutdown and these values are supposed 000338 ** to be NULL or point to memory that was obtained from sqlite3_malloc(), 000339 ** which would rely on that heap subsystem; therefore, make sure these 000340 ** values cannot refer to heap memory that was just invalidated when the 000341 ** heap subsystem was shutdown. This is only done if the current call to 000342 ** this function resulted in the heap subsystem actually being shutdown. 000343 */ 000344 sqlite3_data_directory = 0; 000345 sqlite3_temp_directory = 0; 000346 #endif 000347 } 000348 if( sqlite3GlobalConfig.isMutexInit ){ 000349 sqlite3MutexEnd(); 000350 sqlite3GlobalConfig.isMutexInit = 0; 000351 } 000352 000353 return SQLITE_OK; 000354 } 000355 000356 /* 000357 ** This API allows applications to modify the global configuration of 000358 ** the SQLite library at run-time. 000359 ** 000360 ** This routine should only be called when there are no outstanding 000361 ** database connections or memory allocations. This routine is not 000362 ** threadsafe. Failure to heed these warnings can lead to unpredictable 000363 ** behavior. 000364 */ 000365 int sqlite3_config(int op, ...){ 000366 va_list ap; 000367 int rc = SQLITE_OK; 000368 000369 /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while 000370 ** the SQLite library is in use. */ 000371 if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT; 000372 000373 va_start(ap, op); 000374 switch( op ){ 000375 000376 /* Mutex configuration options are only available in a threadsafe 000377 ** compile. 000378 */ 000379 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */ 000380 case SQLITE_CONFIG_SINGLETHREAD: { 000381 /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to 000382 ** Single-thread. */ 000383 sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */ 000384 sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */ 000385 break; 000386 } 000387 #endif 000388 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */ 000389 case SQLITE_CONFIG_MULTITHREAD: { 000390 /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to 000391 ** Multi-thread. */ 000392 sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */ 000393 sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */ 000394 break; 000395 } 000396 #endif 000397 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */ 000398 case SQLITE_CONFIG_SERIALIZED: { 000399 /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to 000400 ** Serialized. */ 000401 sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */ 000402 sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */ 000403 break; 000404 } 000405 #endif 000406 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */ 000407 case SQLITE_CONFIG_MUTEX: { 000408 /* Specify an alternative mutex implementation */ 000409 sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*); 000410 break; 000411 } 000412 #endif 000413 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */ 000414 case SQLITE_CONFIG_GETMUTEX: { 000415 /* Retrieve the current mutex implementation */ 000416 *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex; 000417 break; 000418 } 000419 #endif 000420 000421 case SQLITE_CONFIG_MALLOC: { 000422 /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a 000423 ** single argument which is a pointer to an instance of the 000424 ** sqlite3_mem_methods structure. The argument specifies alternative 000425 ** low-level memory allocation routines to be used in place of the memory 000426 ** allocation routines built into SQLite. */ 000427 sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*); 000428 break; 000429 } 000430 case SQLITE_CONFIG_GETMALLOC: { 000431 /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a 000432 ** single argument which is a pointer to an instance of the 000433 ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is 000434 ** filled with the currently defined memory allocation routines. */ 000435 if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault(); 000436 *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m; 000437 break; 000438 } 000439 case SQLITE_CONFIG_MEMSTATUS: { 000440 /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes 000441 ** single argument of type int, interpreted as a boolean, which enables 000442 ** or disables the collection of memory allocation statistics. */ 000443 sqlite3GlobalConfig.bMemstat = va_arg(ap, int); 000444 break; 000445 } 000446 case SQLITE_CONFIG_SMALL_MALLOC: { 000447 sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int); 000448 break; 000449 } 000450 case SQLITE_CONFIG_PAGECACHE: { 000451 /* EVIDENCE-OF: R-18761-36601 There are three arguments to 000452 ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem), 000453 ** the size of each page cache line (sz), and the number of cache lines 000454 ** (N). */ 000455 sqlite3GlobalConfig.pPage = va_arg(ap, void*); 000456 sqlite3GlobalConfig.szPage = va_arg(ap, int); 000457 sqlite3GlobalConfig.nPage = va_arg(ap, int); 000458 break; 000459 } 000460 case SQLITE_CONFIG_PCACHE_HDRSZ: { 000461 /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes 000462 ** a single parameter which is a pointer to an integer and writes into 000463 ** that integer the number of extra bytes per page required for each page 000464 ** in SQLITE_CONFIG_PAGECACHE. */ 000465 *va_arg(ap, int*) = 000466 sqlite3HeaderSizeBtree() + 000467 sqlite3HeaderSizePcache() + 000468 sqlite3HeaderSizePcache1(); 000469 break; 000470 } 000471 000472 case SQLITE_CONFIG_PCACHE: { 000473 /* no-op */ 000474 break; 000475 } 000476 case SQLITE_CONFIG_GETPCACHE: { 000477 /* now an error */ 000478 rc = SQLITE_ERROR; 000479 break; 000480 } 000481 000482 case SQLITE_CONFIG_PCACHE2: { 000483 /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a 000484 ** single argument which is a pointer to an sqlite3_pcache_methods2 000485 ** object. This object specifies the interface to a custom page cache 000486 ** implementation. */ 000487 sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*); 000488 break; 000489 } 000490 case SQLITE_CONFIG_GETPCACHE2: { 000491 /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a 000492 ** single argument which is a pointer to an sqlite3_pcache_methods2 000493 ** object. SQLite copies of the current page cache implementation into 000494 ** that object. */ 000495 if( sqlite3GlobalConfig.pcache2.xInit==0 ){ 000496 sqlite3PCacheSetDefault(); 000497 } 000498 *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2; 000499 break; 000500 } 000501 000502 /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only 000503 ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or 000504 ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */ 000505 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) 000506 case SQLITE_CONFIG_HEAP: { 000507 /* EVIDENCE-OF: R-19854-42126 There are three arguments to 000508 ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the 000509 ** number of bytes in the memory buffer, and the minimum allocation size. 000510 */ 000511 sqlite3GlobalConfig.pHeap = va_arg(ap, void*); 000512 sqlite3GlobalConfig.nHeap = va_arg(ap, int); 000513 sqlite3GlobalConfig.mnReq = va_arg(ap, int); 000514 000515 if( sqlite3GlobalConfig.mnReq<1 ){ 000516 sqlite3GlobalConfig.mnReq = 1; 000517 }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){ 000518 /* cap min request size at 2^12 */ 000519 sqlite3GlobalConfig.mnReq = (1<<12); 000520 } 000521 000522 if( sqlite3GlobalConfig.pHeap==0 ){ 000523 /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer) 000524 ** is NULL, then SQLite reverts to using its default memory allocator 000525 ** (the system malloc() implementation), undoing any prior invocation of 000526 ** SQLITE_CONFIG_MALLOC. 000527 ** 000528 ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to 000529 ** revert to its default implementation when sqlite3_initialize() is run 000530 */ 000531 memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m)); 000532 }else{ 000533 /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the 000534 ** alternative memory allocator is engaged to handle all of SQLites 000535 ** memory allocation needs. */ 000536 #ifdef SQLITE_ENABLE_MEMSYS3 000537 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3(); 000538 #endif 000539 #ifdef SQLITE_ENABLE_MEMSYS5 000540 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5(); 000541 #endif 000542 } 000543 break; 000544 } 000545 #endif 000546 000547 case SQLITE_CONFIG_LOOKASIDE: { 000548 sqlite3GlobalConfig.szLookaside = va_arg(ap, int); 000549 sqlite3GlobalConfig.nLookaside = va_arg(ap, int); 000550 break; 000551 } 000552 000553 /* Record a pointer to the logger function and its first argument. 000554 ** The default is NULL. Logging is disabled if the function pointer is 000555 ** NULL. 000556 */ 000557 case SQLITE_CONFIG_LOG: { 000558 /* MSVC is picky about pulling func ptrs from va lists. 000559 ** http://support.microsoft.com/kb/47961 000560 ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*)); 000561 */ 000562 typedef void(*LOGFUNC_t)(void*,int,const char*); 000563 sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t); 000564 sqlite3GlobalConfig.pLogArg = va_arg(ap, void*); 000565 break; 000566 } 000567 000568 /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames 000569 ** can be changed at start-time using the 000570 ** sqlite3_config(SQLITE_CONFIG_URI,1) or 000571 ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls. 000572 */ 000573 case SQLITE_CONFIG_URI: { 000574 /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single 000575 ** argument of type int. If non-zero, then URI handling is globally 000576 ** enabled. If the parameter is zero, then URI handling is globally 000577 ** disabled. */ 000578 sqlite3GlobalConfig.bOpenUri = va_arg(ap, int); 000579 break; 000580 } 000581 000582 case SQLITE_CONFIG_COVERING_INDEX_SCAN: { 000583 /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN 000584 ** option takes a single integer argument which is interpreted as a 000585 ** boolean in order to enable or disable the use of covering indices for 000586 ** full table scans in the query optimizer. */ 000587 sqlite3GlobalConfig.bUseCis = va_arg(ap, int); 000588 break; 000589 } 000590 000591 #ifdef SQLITE_ENABLE_SQLLOG 000592 case SQLITE_CONFIG_SQLLOG: { 000593 typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int); 000594 sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t); 000595 sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *); 000596 break; 000597 } 000598 #endif 000599 000600 case SQLITE_CONFIG_MMAP_SIZE: { 000601 /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit 000602 ** integer (sqlite3_int64) values that are the default mmap size limit 000603 ** (the default setting for PRAGMA mmap_size) and the maximum allowed 000604 ** mmap size limit. */ 000605 sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64); 000606 sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64); 000607 /* EVIDENCE-OF: R-53367-43190 If either argument to this option is 000608 ** negative, then that argument is changed to its compile-time default. 000609 ** 000610 ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be 000611 ** silently truncated if necessary so that it does not exceed the 000612 ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE 000613 ** compile-time option. 000614 */ 000615 if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){ 000616 mxMmap = SQLITE_MAX_MMAP_SIZE; 000617 } 000618 if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE; 000619 if( szMmap>mxMmap) szMmap = mxMmap; 000620 sqlite3GlobalConfig.mxMmap = mxMmap; 000621 sqlite3GlobalConfig.szMmap = szMmap; 000622 break; 000623 } 000624 000625 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */ 000626 case SQLITE_CONFIG_WIN32_HEAPSIZE: { 000627 /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit 000628 ** unsigned integer value that specifies the maximum size of the created 000629 ** heap. */ 000630 sqlite3GlobalConfig.nHeap = va_arg(ap, int); 000631 break; 000632 } 000633 #endif 000634 000635 case SQLITE_CONFIG_PMASZ: { 000636 sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int); 000637 break; 000638 } 000639 000640 case SQLITE_CONFIG_STMTJRNL_SPILL: { 000641 sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int); 000642 break; 000643 } 000644 000645 #ifdef SQLITE_ENABLE_SORTER_REFERENCES 000646 case SQLITE_CONFIG_SORTERREF_SIZE: { 000647 int iVal = va_arg(ap, int); 000648 if( iVal<0 ){ 000649 iVal = SQLITE_DEFAULT_SORTERREF_SIZE; 000650 } 000651 sqlite3GlobalConfig.szSorterRef = (u32)iVal; 000652 break; 000653 } 000654 #endif /* SQLITE_ENABLE_SORTER_REFERENCES */ 000655 000656 #ifdef SQLITE_ENABLE_DESERIALIZE 000657 case SQLITE_CONFIG_MEMDB_MAXSIZE: { 000658 sqlite3GlobalConfig.mxMemdbSize = va_arg(ap, sqlite3_int64); 000659 break; 000660 } 000661 #endif /* SQLITE_ENABLE_DESERIALIZE */ 000662 000663 default: { 000664 rc = SQLITE_ERROR; 000665 break; 000666 } 000667 } 000668 va_end(ap); 000669 return rc; 000670 } 000671 000672 /* 000673 ** Set up the lookaside buffers for a database connection. 000674 ** Return SQLITE_OK on success. 000675 ** If lookaside is already active, return SQLITE_BUSY. 000676 ** 000677 ** The sz parameter is the number of bytes in each lookaside slot. 000678 ** The cnt parameter is the number of slots. If pStart is NULL the 000679 ** space for the lookaside memory is obtained from sqlite3_malloc(). 000680 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for 000681 ** the lookaside memory. 000682 */ 000683 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){ 000684 #ifndef SQLITE_OMIT_LOOKASIDE 000685 void *pStart; 000686 000687 if( sqlite3LookasideUsed(db,0)>0 ){ 000688 return SQLITE_BUSY; 000689 } 000690 /* Free any existing lookaside buffer for this handle before 000691 ** allocating a new one so we don't have to have space for 000692 ** both at the same time. 000693 */ 000694 if( db->lookaside.bMalloced ){ 000695 sqlite3_free(db->lookaside.pStart); 000696 } 000697 /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger 000698 ** than a pointer to be useful. 000699 */ 000700 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */ 000701 if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0; 000702 if( cnt<0 ) cnt = 0; 000703 if( sz==0 || cnt==0 ){ 000704 sz = 0; 000705 pStart = 0; 000706 }else if( pBuf==0 ){ 000707 sqlite3BeginBenignMalloc(); 000708 pStart = sqlite3Malloc( sz*(sqlite3_int64)cnt ); /* IMP: R-61949-35727 */ 000709 sqlite3EndBenignMalloc(); 000710 if( pStart ) cnt = sqlite3MallocSize(pStart)/sz; 000711 }else{ 000712 pStart = pBuf; 000713 } 000714 db->lookaside.pStart = pStart; 000715 db->lookaside.pInit = 0; 000716 db->lookaside.pFree = 0; 000717 db->lookaside.sz = (u16)sz; 000718 db->lookaside.szTrue = (u16)sz; 000719 if( pStart ){ 000720 int i; 000721 LookasideSlot *p; 000722 assert( sz > (int)sizeof(LookasideSlot*) ); 000723 db->lookaside.nSlot = cnt; 000724 p = (LookasideSlot*)pStart; 000725 for(i=cnt-1; i>=0; i--){ 000726 p->pNext = db->lookaside.pInit; 000727 db->lookaside.pInit = p; 000728 p = (LookasideSlot*)&((u8*)p)[sz]; 000729 } 000730 db->lookaside.pEnd = p; 000731 db->lookaside.bDisable = 0; 000732 db->lookaside.bMalloced = pBuf==0 ?1:0; 000733 }else{ 000734 db->lookaside.pStart = db; 000735 db->lookaside.pEnd = db; 000736 db->lookaside.bDisable = 1; 000737 db->lookaside.sz = 0; 000738 db->lookaside.bMalloced = 0; 000739 db->lookaside.nSlot = 0; 000740 } 000741 #endif /* SQLITE_OMIT_LOOKASIDE */ 000742 return SQLITE_OK; 000743 } 000744 000745 /* 000746 ** Return the mutex associated with a database connection. 000747 */ 000748 sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){ 000749 #ifdef SQLITE_ENABLE_API_ARMOR 000750 if( !sqlite3SafetyCheckOk(db) ){ 000751 (void)SQLITE_MISUSE_BKPT; 000752 return 0; 000753 } 000754 #endif 000755 return db->mutex; 000756 } 000757 000758 /* 000759 ** Free up as much memory as we can from the given database 000760 ** connection. 000761 */ 000762 int sqlite3_db_release_memory(sqlite3 *db){ 000763 int i; 000764 000765 #ifdef SQLITE_ENABLE_API_ARMOR 000766 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; 000767 #endif 000768 sqlite3_mutex_enter(db->mutex); 000769 sqlite3BtreeEnterAll(db); 000770 for(i=0; i<db->nDb; i++){ 000771 Btree *pBt = db->aDb[i].pBt; 000772 if( pBt ){ 000773 Pager *pPager = sqlite3BtreePager(pBt); 000774 sqlite3PagerShrink(pPager); 000775 } 000776 } 000777 sqlite3BtreeLeaveAll(db); 000778 sqlite3_mutex_leave(db->mutex); 000779 return SQLITE_OK; 000780 } 000781 000782 /* 000783 ** Flush any dirty pages in the pager-cache for any attached database 000784 ** to disk. 000785 */ 000786 int sqlite3_db_cacheflush(sqlite3 *db){ 000787 int i; 000788 int rc = SQLITE_OK; 000789 int bSeenBusy = 0; 000790 000791 #ifdef SQLITE_ENABLE_API_ARMOR 000792 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; 000793 #endif 000794 sqlite3_mutex_enter(db->mutex); 000795 sqlite3BtreeEnterAll(db); 000796 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 000797 Btree *pBt = db->aDb[i].pBt; 000798 if( pBt && sqlite3BtreeIsInTrans(pBt) ){ 000799 Pager *pPager = sqlite3BtreePager(pBt); 000800 rc = sqlite3PagerFlush(pPager); 000801 if( rc==SQLITE_BUSY ){ 000802 bSeenBusy = 1; 000803 rc = SQLITE_OK; 000804 } 000805 } 000806 } 000807 sqlite3BtreeLeaveAll(db); 000808 sqlite3_mutex_leave(db->mutex); 000809 return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc); 000810 } 000811 000812 /* 000813 ** Configuration settings for an individual database connection 000814 */ 000815 int sqlite3_db_config(sqlite3 *db, int op, ...){ 000816 va_list ap; 000817 int rc; 000818 va_start(ap, op); 000819 switch( op ){ 000820 case SQLITE_DBCONFIG_MAINDBNAME: { 000821 /* IMP: R-06824-28531 */ 000822 /* IMP: R-36257-52125 */ 000823 db->aDb[0].zDbSName = va_arg(ap,char*); 000824 rc = SQLITE_OK; 000825 break; 000826 } 000827 case SQLITE_DBCONFIG_LOOKASIDE: { 000828 void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */ 000829 int sz = va_arg(ap, int); /* IMP: R-47871-25994 */ 000830 int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */ 000831 rc = setupLookaside(db, pBuf, sz, cnt); 000832 break; 000833 } 000834 default: { 000835 static const struct { 000836 int op; /* The opcode */ 000837 u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */ 000838 } aFlagOp[] = { 000839 { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys }, 000840 { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger }, 000841 { SQLITE_DBCONFIG_ENABLE_VIEW, SQLITE_EnableView }, 000842 { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer }, 000843 { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension }, 000844 { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose }, 000845 { SQLITE_DBCONFIG_ENABLE_QPSG, SQLITE_EnableQPSG }, 000846 { SQLITE_DBCONFIG_TRIGGER_EQP, SQLITE_TriggerEQP }, 000847 { SQLITE_DBCONFIG_RESET_DATABASE, SQLITE_ResetDatabase }, 000848 { SQLITE_DBCONFIG_DEFENSIVE, SQLITE_Defensive }, 000849 { SQLITE_DBCONFIG_WRITABLE_SCHEMA, SQLITE_WriteSchema| 000850 SQLITE_NoSchemaError }, 000851 { SQLITE_DBCONFIG_LEGACY_ALTER_TABLE, SQLITE_LegacyAlter }, 000852 { SQLITE_DBCONFIG_DQS_DDL, SQLITE_DqsDDL }, 000853 { SQLITE_DBCONFIG_DQS_DML, SQLITE_DqsDML }, 000854 { SQLITE_DBCONFIG_LEGACY_FILE_FORMAT, SQLITE_LegacyFileFmt }, 000855 }; 000856 unsigned int i; 000857 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */ 000858 for(i=0; i<ArraySize(aFlagOp); i++){ 000859 if( aFlagOp[i].op==op ){ 000860 int onoff = va_arg(ap, int); 000861 int *pRes = va_arg(ap, int*); 000862 u64 oldFlags = db->flags; 000863 if( onoff>0 ){ 000864 db->flags |= aFlagOp[i].mask; 000865 }else if( onoff==0 ){ 000866 db->flags &= ~(u64)aFlagOp[i].mask; 000867 } 000868 if( oldFlags!=db->flags ){ 000869 sqlite3ExpirePreparedStatements(db, 0); 000870 } 000871 if( pRes ){ 000872 *pRes = (db->flags & aFlagOp[i].mask)!=0; 000873 } 000874 rc = SQLITE_OK; 000875 break; 000876 } 000877 } 000878 break; 000879 } 000880 } 000881 va_end(ap); 000882 return rc; 000883 } 000884 000885 /* 000886 ** This is the default collating function named "BINARY" which is always 000887 ** available. 000888 */ 000889 static int binCollFunc( 000890 void *NotUsed, 000891 int nKey1, const void *pKey1, 000892 int nKey2, const void *pKey2 000893 ){ 000894 int rc, n; 000895 UNUSED_PARAMETER(NotUsed); 000896 n = nKey1<nKey2 ? nKey1 : nKey2; 000897 /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares 000898 ** strings byte by byte using the memcmp() function from the standard C 000899 ** library. */ 000900 assert( pKey1 && pKey2 ); 000901 rc = memcmp(pKey1, pKey2, n); 000902 if( rc==0 ){ 000903 rc = nKey1 - nKey2; 000904 } 000905 return rc; 000906 } 000907 000908 /* 000909 ** This is the collating function named "RTRIM" which is always 000910 ** available. Ignore trailing spaces. 000911 */ 000912 static int rtrimCollFunc( 000913 void *pUser, 000914 int nKey1, const void *pKey1, 000915 int nKey2, const void *pKey2 000916 ){ 000917 const u8 *pK1 = (const u8*)pKey1; 000918 const u8 *pK2 = (const u8*)pKey2; 000919 while( nKey1 && pK1[nKey1-1]==' ' ) nKey1--; 000920 while( nKey2 && pK2[nKey2-1]==' ' ) nKey2--; 000921 return binCollFunc(pUser, nKey1, pKey1, nKey2, pKey2); 000922 } 000923 000924 /* 000925 ** Return true if CollSeq is the default built-in BINARY. 000926 */ 000927 int sqlite3IsBinary(const CollSeq *p){ 000928 assert( p==0 || p->xCmp!=binCollFunc || strcmp(p->zName,"BINARY")==0 ); 000929 return p==0 || p->xCmp==binCollFunc; 000930 } 000931 000932 /* 000933 ** Another built-in collating sequence: NOCASE. 000934 ** 000935 ** This collating sequence is intended to be used for "case independent 000936 ** comparison". SQLite's knowledge of upper and lower case equivalents 000937 ** extends only to the 26 characters used in the English language. 000938 ** 000939 ** At the moment there is only a UTF-8 implementation. 000940 */ 000941 static int nocaseCollatingFunc( 000942 void *NotUsed, 000943 int nKey1, const void *pKey1, 000944 int nKey2, const void *pKey2 000945 ){ 000946 int r = sqlite3StrNICmp( 000947 (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2); 000948 UNUSED_PARAMETER(NotUsed); 000949 if( 0==r ){ 000950 r = nKey1-nKey2; 000951 } 000952 return r; 000953 } 000954 000955 /* 000956 ** Return the ROWID of the most recent insert 000957 */ 000958 sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){ 000959 #ifdef SQLITE_ENABLE_API_ARMOR 000960 if( !sqlite3SafetyCheckOk(db) ){ 000961 (void)SQLITE_MISUSE_BKPT; 000962 return 0; 000963 } 000964 #endif 000965 return db->lastRowid; 000966 } 000967 000968 /* 000969 ** Set the value returned by the sqlite3_last_insert_rowid() API function. 000970 */ 000971 void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){ 000972 #ifdef SQLITE_ENABLE_API_ARMOR 000973 if( !sqlite3SafetyCheckOk(db) ){ 000974 (void)SQLITE_MISUSE_BKPT; 000975 return; 000976 } 000977 #endif 000978 sqlite3_mutex_enter(db->mutex); 000979 db->lastRowid = iRowid; 000980 sqlite3_mutex_leave(db->mutex); 000981 } 000982 000983 /* 000984 ** Return the number of changes in the most recent call to sqlite3_exec(). 000985 */ 000986 int sqlite3_changes(sqlite3 *db){ 000987 #ifdef SQLITE_ENABLE_API_ARMOR 000988 if( !sqlite3SafetyCheckOk(db) ){ 000989 (void)SQLITE_MISUSE_BKPT; 000990 return 0; 000991 } 000992 #endif 000993 return db->nChange; 000994 } 000995 000996 /* 000997 ** Return the number of changes since the database handle was opened. 000998 */ 000999 int sqlite3_total_changes(sqlite3 *db){ 001000 #ifdef SQLITE_ENABLE_API_ARMOR 001001 if( !sqlite3SafetyCheckOk(db) ){ 001002 (void)SQLITE_MISUSE_BKPT; 001003 return 0; 001004 } 001005 #endif 001006 return db->nTotalChange; 001007 } 001008 001009 /* 001010 ** Close all open savepoints. This function only manipulates fields of the 001011 ** database handle object, it does not close any savepoints that may be open 001012 ** at the b-tree/pager level. 001013 */ 001014 void sqlite3CloseSavepoints(sqlite3 *db){ 001015 while( db->pSavepoint ){ 001016 Savepoint *pTmp = db->pSavepoint; 001017 db->pSavepoint = pTmp->pNext; 001018 sqlite3DbFree(db, pTmp); 001019 } 001020 db->nSavepoint = 0; 001021 db->nStatement = 0; 001022 db->isTransactionSavepoint = 0; 001023 } 001024 001025 /* 001026 ** Invoke the destructor function associated with FuncDef p, if any. Except, 001027 ** if this is not the last copy of the function, do not invoke it. Multiple 001028 ** copies of a single function are created when create_function() is called 001029 ** with SQLITE_ANY as the encoding. 001030 */ 001031 static void functionDestroy(sqlite3 *db, FuncDef *p){ 001032 FuncDestructor *pDestructor = p->u.pDestructor; 001033 if( pDestructor ){ 001034 pDestructor->nRef--; 001035 if( pDestructor->nRef==0 ){ 001036 pDestructor->xDestroy(pDestructor->pUserData); 001037 sqlite3DbFree(db, pDestructor); 001038 } 001039 } 001040 } 001041 001042 /* 001043 ** Disconnect all sqlite3_vtab objects that belong to database connection 001044 ** db. This is called when db is being closed. 001045 */ 001046 static void disconnectAllVtab(sqlite3 *db){ 001047 #ifndef SQLITE_OMIT_VIRTUALTABLE 001048 int i; 001049 HashElem *p; 001050 sqlite3BtreeEnterAll(db); 001051 for(i=0; i<db->nDb; i++){ 001052 Schema *pSchema = db->aDb[i].pSchema; 001053 if( pSchema ){ 001054 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){ 001055 Table *pTab = (Table *)sqliteHashData(p); 001056 if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab); 001057 } 001058 } 001059 } 001060 for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){ 001061 Module *pMod = (Module *)sqliteHashData(p); 001062 if( pMod->pEpoTab ){ 001063 sqlite3VtabDisconnect(db, pMod->pEpoTab); 001064 } 001065 } 001066 sqlite3VtabUnlockList(db); 001067 sqlite3BtreeLeaveAll(db); 001068 #else 001069 UNUSED_PARAMETER(db); 001070 #endif 001071 } 001072 001073 /* 001074 ** Return TRUE if database connection db has unfinalized prepared 001075 ** statements or unfinished sqlite3_backup objects. 001076 */ 001077 static int connectionIsBusy(sqlite3 *db){ 001078 int j; 001079 assert( sqlite3_mutex_held(db->mutex) ); 001080 if( db->pVdbe ) return 1; 001081 for(j=0; j<db->nDb; j++){ 001082 Btree *pBt = db->aDb[j].pBt; 001083 if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1; 001084 } 001085 return 0; 001086 } 001087 001088 /* 001089 ** Close an existing SQLite database 001090 */ 001091 static int sqlite3Close(sqlite3 *db, int forceZombie){ 001092 if( !db ){ 001093 /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or 001094 ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */ 001095 return SQLITE_OK; 001096 } 001097 if( !sqlite3SafetyCheckSickOrOk(db) ){ 001098 return SQLITE_MISUSE_BKPT; 001099 } 001100 sqlite3_mutex_enter(db->mutex); 001101 if( db->mTrace & SQLITE_TRACE_CLOSE ){ 001102 db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0); 001103 } 001104 001105 /* Force xDisconnect calls on all virtual tables */ 001106 disconnectAllVtab(db); 001107 001108 /* If a transaction is open, the disconnectAllVtab() call above 001109 ** will not have called the xDisconnect() method on any virtual 001110 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback() 001111 ** call will do so. We need to do this before the check for active 001112 ** SQL statements below, as the v-table implementation may be storing 001113 ** some prepared statements internally. 001114 */ 001115 sqlite3VtabRollback(db); 001116 001117 /* Legacy behavior (sqlite3_close() behavior) is to return 001118 ** SQLITE_BUSY if the connection can not be closed immediately. 001119 */ 001120 if( !forceZombie && connectionIsBusy(db) ){ 001121 sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized " 001122 "statements or unfinished backups"); 001123 sqlite3_mutex_leave(db->mutex); 001124 return SQLITE_BUSY; 001125 } 001126 001127 #ifdef SQLITE_ENABLE_SQLLOG 001128 if( sqlite3GlobalConfig.xSqllog ){ 001129 /* Closing the handle. Fourth parameter is passed the value 2. */ 001130 sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2); 001131 } 001132 #endif 001133 001134 /* Convert the connection into a zombie and then close it. 001135 */ 001136 db->magic = SQLITE_MAGIC_ZOMBIE; 001137 sqlite3LeaveMutexAndCloseZombie(db); 001138 return SQLITE_OK; 001139 } 001140 001141 /* 001142 ** Two variations on the public interface for closing a database 001143 ** connection. The sqlite3_close() version returns SQLITE_BUSY and 001144 ** leaves the connection option if there are unfinalized prepared 001145 ** statements or unfinished sqlite3_backups. The sqlite3_close_v2() 001146 ** version forces the connection to become a zombie if there are 001147 ** unclosed resources, and arranges for deallocation when the last 001148 ** prepare statement or sqlite3_backup closes. 001149 */ 001150 int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); } 001151 int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); } 001152 001153 001154 /* 001155 ** Close the mutex on database connection db. 001156 ** 001157 ** Furthermore, if database connection db is a zombie (meaning that there 001158 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and 001159 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has 001160 ** finished, then free all resources. 001161 */ 001162 void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){ 001163 HashElem *i; /* Hash table iterator */ 001164 int j; 001165 001166 /* If there are outstanding sqlite3_stmt or sqlite3_backup objects 001167 ** or if the connection has not yet been closed by sqlite3_close_v2(), 001168 ** then just leave the mutex and return. 001169 */ 001170 if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){ 001171 sqlite3_mutex_leave(db->mutex); 001172 return; 001173 } 001174 001175 /* If we reach this point, it means that the database connection has 001176 ** closed all sqlite3_stmt and sqlite3_backup objects and has been 001177 ** passed to sqlite3_close (meaning that it is a zombie). Therefore, 001178 ** go ahead and free all resources. 001179 */ 001180 001181 /* If a transaction is open, roll it back. This also ensures that if 001182 ** any database schemas have been modified by an uncommitted transaction 001183 ** they are reset. And that the required b-tree mutex is held to make 001184 ** the pager rollback and schema reset an atomic operation. */ 001185 sqlite3RollbackAll(db, SQLITE_OK); 001186 001187 /* Free any outstanding Savepoint structures. */ 001188 sqlite3CloseSavepoints(db); 001189 001190 /* Close all database connections */ 001191 for(j=0; j<db->nDb; j++){ 001192 struct Db *pDb = &db->aDb[j]; 001193 if( pDb->pBt ){ 001194 sqlite3BtreeClose(pDb->pBt); 001195 pDb->pBt = 0; 001196 if( j!=1 ){ 001197 pDb->pSchema = 0; 001198 } 001199 } 001200 } 001201 /* Clear the TEMP schema separately and last */ 001202 if( db->aDb[1].pSchema ){ 001203 sqlite3SchemaClear(db->aDb[1].pSchema); 001204 } 001205 sqlite3VtabUnlockList(db); 001206 001207 /* Free up the array of auxiliary databases */ 001208 sqlite3CollapseDatabaseArray(db); 001209 assert( db->nDb<=2 ); 001210 assert( db->aDb==db->aDbStatic ); 001211 001212 /* Tell the code in notify.c that the connection no longer holds any 001213 ** locks and does not require any further unlock-notify callbacks. 001214 */ 001215 sqlite3ConnectionClosed(db); 001216 001217 for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){ 001218 FuncDef *pNext, *p; 001219 p = sqliteHashData(i); 001220 do{ 001221 functionDestroy(db, p); 001222 pNext = p->pNext; 001223 sqlite3DbFree(db, p); 001224 p = pNext; 001225 }while( p ); 001226 } 001227 sqlite3HashClear(&db->aFunc); 001228 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){ 001229 CollSeq *pColl = (CollSeq *)sqliteHashData(i); 001230 /* Invoke any destructors registered for collation sequence user data. */ 001231 for(j=0; j<3; j++){ 001232 if( pColl[j].xDel ){ 001233 pColl[j].xDel(pColl[j].pUser); 001234 } 001235 } 001236 sqlite3DbFree(db, pColl); 001237 } 001238 sqlite3HashClear(&db->aCollSeq); 001239 #ifndef SQLITE_OMIT_VIRTUALTABLE 001240 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){ 001241 Module *pMod = (Module *)sqliteHashData(i); 001242 sqlite3VtabEponymousTableClear(db, pMod); 001243 sqlite3VtabModuleUnref(db, pMod); 001244 } 001245 sqlite3HashClear(&db->aModule); 001246 #endif 001247 001248 sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */ 001249 sqlite3ValueFree(db->pErr); 001250 sqlite3CloseExtensions(db); 001251 #if SQLITE_USER_AUTHENTICATION 001252 sqlite3_free(db->auth.zAuthUser); 001253 sqlite3_free(db->auth.zAuthPW); 001254 #endif 001255 001256 db->magic = SQLITE_MAGIC_ERROR; 001257 001258 /* The temp-database schema is allocated differently from the other schema 001259 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()). 001260 ** So it needs to be freed here. Todo: Why not roll the temp schema into 001261 ** the same sqliteMalloc() as the one that allocates the database 001262 ** structure? 001263 */ 001264 sqlite3DbFree(db, db->aDb[1].pSchema); 001265 sqlite3_mutex_leave(db->mutex); 001266 db->magic = SQLITE_MAGIC_CLOSED; 001267 sqlite3_mutex_free(db->mutex); 001268 assert( sqlite3LookasideUsed(db,0)==0 ); 001269 if( db->lookaside.bMalloced ){ 001270 sqlite3_free(db->lookaside.pStart); 001271 } 001272 sqlite3_free(db); 001273 } 001274 001275 /* 001276 ** Rollback all database files. If tripCode is not SQLITE_OK, then 001277 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit 001278 ** breaker") and made to return tripCode if there are any further 001279 ** attempts to use that cursor. Read cursors remain open and valid 001280 ** but are "saved" in case the table pages are moved around. 001281 */ 001282 void sqlite3RollbackAll(sqlite3 *db, int tripCode){ 001283 int i; 001284 int inTrans = 0; 001285 int schemaChange; 001286 assert( sqlite3_mutex_held(db->mutex) ); 001287 sqlite3BeginBenignMalloc(); 001288 001289 /* Obtain all b-tree mutexes before making any calls to BtreeRollback(). 001290 ** This is important in case the transaction being rolled back has 001291 ** modified the database schema. If the b-tree mutexes are not taken 001292 ** here, then another shared-cache connection might sneak in between 001293 ** the database rollback and schema reset, which can cause false 001294 ** corruption reports in some cases. */ 001295 sqlite3BtreeEnterAll(db); 001296 schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0; 001297 001298 for(i=0; i<db->nDb; i++){ 001299 Btree *p = db->aDb[i].pBt; 001300 if( p ){ 001301 if( sqlite3BtreeIsInTrans(p) ){ 001302 inTrans = 1; 001303 } 001304 sqlite3BtreeRollback(p, tripCode, !schemaChange); 001305 } 001306 } 001307 sqlite3VtabRollback(db); 001308 sqlite3EndBenignMalloc(); 001309 001310 if( schemaChange ){ 001311 sqlite3ExpirePreparedStatements(db, 0); 001312 sqlite3ResetAllSchemasOfConnection(db); 001313 } 001314 sqlite3BtreeLeaveAll(db); 001315 001316 /* Any deferred constraint violations have now been resolved. */ 001317 db->nDeferredCons = 0; 001318 db->nDeferredImmCons = 0; 001319 db->flags &= ~(u64)SQLITE_DeferFKs; 001320 001321 /* If one has been configured, invoke the rollback-hook callback */ 001322 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){ 001323 db->xRollbackCallback(db->pRollbackArg); 001324 } 001325 } 001326 001327 /* 001328 ** Return a static string containing the name corresponding to the error code 001329 ** specified in the argument. 001330 */ 001331 #if defined(SQLITE_NEED_ERR_NAME) 001332 const char *sqlite3ErrName(int rc){ 001333 const char *zName = 0; 001334 int i, origRc = rc; 001335 for(i=0; i<2 && zName==0; i++, rc &= 0xff){ 001336 switch( rc ){ 001337 case SQLITE_OK: zName = "SQLITE_OK"; break; 001338 case SQLITE_ERROR: zName = "SQLITE_ERROR"; break; 001339 case SQLITE_ERROR_SNAPSHOT: zName = "SQLITE_ERROR_SNAPSHOT"; break; 001340 case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break; 001341 case SQLITE_PERM: zName = "SQLITE_PERM"; break; 001342 case SQLITE_ABORT: zName = "SQLITE_ABORT"; break; 001343 case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break; 001344 case SQLITE_BUSY: zName = "SQLITE_BUSY"; break; 001345 case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break; 001346 case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break; 001347 case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break; 001348 case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break; 001349 case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break; 001350 case SQLITE_READONLY: zName = "SQLITE_READONLY"; break; 001351 case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break; 001352 case SQLITE_READONLY_CANTINIT: zName = "SQLITE_READONLY_CANTINIT"; break; 001353 case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break; 001354 case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break; 001355 case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break; 001356 case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break; 001357 case SQLITE_IOERR: zName = "SQLITE_IOERR"; break; 001358 case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break; 001359 case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break; 001360 case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break; 001361 case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break; 001362 case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break; 001363 case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break; 001364 case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break; 001365 case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break; 001366 case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break; 001367 case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break; 001368 case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break; 001369 case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break; 001370 case SQLITE_IOERR_CHECKRESERVEDLOCK: 001371 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break; 001372 case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break; 001373 case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break; 001374 case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break; 001375 case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break; 001376 case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break; 001377 case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break; 001378 case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break; 001379 case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break; 001380 case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break; 001381 case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break; 001382 case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break; 001383 case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break; 001384 case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break; 001385 case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break; 001386 case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break; 001387 case SQLITE_FULL: zName = "SQLITE_FULL"; break; 001388 case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break; 001389 case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break; 001390 case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break; 001391 case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break; 001392 case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break; 001393 case SQLITE_CANTOPEN_SYMLINK: zName = "SQLITE_CANTOPEN_SYMLINK"; break; 001394 case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break; 001395 case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break; 001396 case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break; 001397 case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break; 001398 case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break; 001399 case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break; 001400 case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break; 001401 case SQLITE_CONSTRAINT_FOREIGNKEY: 001402 zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break; 001403 case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break; 001404 case SQLITE_CONSTRAINT_PRIMARYKEY: 001405 zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break; 001406 case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break; 001407 case SQLITE_CONSTRAINT_COMMITHOOK: 001408 zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break; 001409 case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break; 001410 case SQLITE_CONSTRAINT_FUNCTION: 001411 zName = "SQLITE_CONSTRAINT_FUNCTION"; break; 001412 case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break; 001413 case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break; 001414 case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break; 001415 case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break; 001416 case SQLITE_AUTH: zName = "SQLITE_AUTH"; break; 001417 case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break; 001418 case SQLITE_RANGE: zName = "SQLITE_RANGE"; break; 001419 case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break; 001420 case SQLITE_ROW: zName = "SQLITE_ROW"; break; 001421 case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break; 001422 case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break; 001423 case SQLITE_NOTICE_RECOVER_ROLLBACK: 001424 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break; 001425 case SQLITE_WARNING: zName = "SQLITE_WARNING"; break; 001426 case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break; 001427 case SQLITE_DONE: zName = "SQLITE_DONE"; break; 001428 } 001429 } 001430 if( zName==0 ){ 001431 static char zBuf[50]; 001432 sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc); 001433 zName = zBuf; 001434 } 001435 return zName; 001436 } 001437 #endif 001438 001439 /* 001440 ** Return a static string that describes the kind of error specified in the 001441 ** argument. 001442 */ 001443 const char *sqlite3ErrStr(int rc){ 001444 static const char* const aMsg[] = { 001445 /* SQLITE_OK */ "not an error", 001446 /* SQLITE_ERROR */ "SQL logic error", 001447 /* SQLITE_INTERNAL */ 0, 001448 /* SQLITE_PERM */ "access permission denied", 001449 /* SQLITE_ABORT */ "query aborted", 001450 /* SQLITE_BUSY */ "database is locked", 001451 /* SQLITE_LOCKED */ "database table is locked", 001452 /* SQLITE_NOMEM */ "out of memory", 001453 /* SQLITE_READONLY */ "attempt to write a readonly database", 001454 /* SQLITE_INTERRUPT */ "interrupted", 001455 /* SQLITE_IOERR */ "disk I/O error", 001456 /* SQLITE_CORRUPT */ "database disk image is malformed", 001457 /* SQLITE_NOTFOUND */ "unknown operation", 001458 /* SQLITE_FULL */ "database or disk is full", 001459 /* SQLITE_CANTOPEN */ "unable to open database file", 001460 /* SQLITE_PROTOCOL */ "locking protocol", 001461 /* SQLITE_EMPTY */ 0, 001462 /* SQLITE_SCHEMA */ "database schema has changed", 001463 /* SQLITE_TOOBIG */ "string or blob too big", 001464 /* SQLITE_CONSTRAINT */ "constraint failed", 001465 /* SQLITE_MISMATCH */ "datatype mismatch", 001466 /* SQLITE_MISUSE */ "bad parameter or other API misuse", 001467 #ifdef SQLITE_DISABLE_LFS 001468 /* SQLITE_NOLFS */ "large file support is disabled", 001469 #else 001470 /* SQLITE_NOLFS */ 0, 001471 #endif 001472 /* SQLITE_AUTH */ "authorization denied", 001473 /* SQLITE_FORMAT */ 0, 001474 /* SQLITE_RANGE */ "column index out of range", 001475 /* SQLITE_NOTADB */ "file is not a database", 001476 /* SQLITE_NOTICE */ "notification message", 001477 /* SQLITE_WARNING */ "warning message", 001478 }; 001479 const char *zErr = "unknown error"; 001480 switch( rc ){ 001481 case SQLITE_ABORT_ROLLBACK: { 001482 zErr = "abort due to ROLLBACK"; 001483 break; 001484 } 001485 case SQLITE_ROW: { 001486 zErr = "another row available"; 001487 break; 001488 } 001489 case SQLITE_DONE: { 001490 zErr = "no more rows available"; 001491 break; 001492 } 001493 default: { 001494 rc &= 0xff; 001495 if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){ 001496 zErr = aMsg[rc]; 001497 } 001498 break; 001499 } 001500 } 001501 return zErr; 001502 } 001503 001504 /* 001505 ** This routine implements a busy callback that sleeps and tries 001506 ** again until a timeout value is reached. The timeout value is 001507 ** an integer number of milliseconds passed in as the first 001508 ** argument. 001509 ** 001510 ** Return non-zero to retry the lock. Return zero to stop trying 001511 ** and cause SQLite to return SQLITE_BUSY. 001512 */ 001513 static int sqliteDefaultBusyCallback( 001514 void *ptr, /* Database connection */ 001515 int count, /* Number of times table has been busy */ 001516 sqlite3_file *pFile /* The file on which the lock occurred */ 001517 ){ 001518 #if SQLITE_OS_WIN || HAVE_USLEEP 001519 /* This case is for systems that have support for sleeping for fractions of 001520 ** a second. Examples: All windows systems, unix systems with usleep() */ 001521 static const u8 delays[] = 001522 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 }; 001523 static const u8 totals[] = 001524 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 }; 001525 # define NDELAY ArraySize(delays) 001526 sqlite3 *db = (sqlite3 *)ptr; 001527 int tmout = db->busyTimeout; 001528 int delay, prior; 001529 001530 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 001531 if( sqlite3OsFileControl(pFile,SQLITE_FCNTL_LOCK_TIMEOUT,&tmout)==SQLITE_OK ){ 001532 if( count ){ 001533 tmout = 0; 001534 sqlite3OsFileControl(pFile, SQLITE_FCNTL_LOCK_TIMEOUT, &tmout); 001535 return 0; 001536 }else{ 001537 return 1; 001538 } 001539 } 001540 #else 001541 UNUSED_PARAMETER(pFile); 001542 #endif 001543 assert( count>=0 ); 001544 if( count < NDELAY ){ 001545 delay = delays[count]; 001546 prior = totals[count]; 001547 }else{ 001548 delay = delays[NDELAY-1]; 001549 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1)); 001550 } 001551 if( prior + delay > tmout ){ 001552 delay = tmout - prior; 001553 if( delay<=0 ) return 0; 001554 } 001555 sqlite3OsSleep(db->pVfs, delay*1000); 001556 return 1; 001557 #else 001558 /* This case for unix systems that lack usleep() support. Sleeping 001559 ** must be done in increments of whole seconds */ 001560 sqlite3 *db = (sqlite3 *)ptr; 001561 int tmout = ((sqlite3 *)ptr)->busyTimeout; 001562 UNUSED_PARAMETER(pFile); 001563 if( (count+1)*1000 > tmout ){ 001564 return 0; 001565 } 001566 sqlite3OsSleep(db->pVfs, 1000000); 001567 return 1; 001568 #endif 001569 } 001570 001571 /* 001572 ** Invoke the given busy handler. 001573 ** 001574 ** This routine is called when an operation failed to acquire a 001575 ** lock on VFS file pFile. 001576 ** 001577 ** If this routine returns non-zero, the lock is retried. If it 001578 ** returns 0, the operation aborts with an SQLITE_BUSY error. 001579 */ 001580 int sqlite3InvokeBusyHandler(BusyHandler *p, sqlite3_file *pFile){ 001581 int rc; 001582 if( p->xBusyHandler==0 || p->nBusy<0 ) return 0; 001583 if( p->bExtraFileArg ){ 001584 /* Add an extra parameter with the pFile pointer to the end of the 001585 ** callback argument list */ 001586 int (*xTra)(void*,int,sqlite3_file*); 001587 xTra = (int(*)(void*,int,sqlite3_file*))p->xBusyHandler; 001588 rc = xTra(p->pBusyArg, p->nBusy, pFile); 001589 }else{ 001590 /* Legacy style busy handler callback */ 001591 rc = p->xBusyHandler(p->pBusyArg, p->nBusy); 001592 } 001593 if( rc==0 ){ 001594 p->nBusy = -1; 001595 }else{ 001596 p->nBusy++; 001597 } 001598 return rc; 001599 } 001600 001601 /* 001602 ** This routine sets the busy callback for an Sqlite database to the 001603 ** given callback function with the given argument. 001604 */ 001605 int sqlite3_busy_handler( 001606 sqlite3 *db, 001607 int (*xBusy)(void*,int), 001608 void *pArg 001609 ){ 001610 #ifdef SQLITE_ENABLE_API_ARMOR 001611 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; 001612 #endif 001613 sqlite3_mutex_enter(db->mutex); 001614 db->busyHandler.xBusyHandler = xBusy; 001615 db->busyHandler.pBusyArg = pArg; 001616 db->busyHandler.nBusy = 0; 001617 db->busyHandler.bExtraFileArg = 0; 001618 db->busyTimeout = 0; 001619 sqlite3_mutex_leave(db->mutex); 001620 return SQLITE_OK; 001621 } 001622 001623 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 001624 /* 001625 ** This routine sets the progress callback for an Sqlite database to the 001626 ** given callback function with the given argument. The progress callback will 001627 ** be invoked every nOps opcodes. 001628 */ 001629 void sqlite3_progress_handler( 001630 sqlite3 *db, 001631 int nOps, 001632 int (*xProgress)(void*), 001633 void *pArg 001634 ){ 001635 #ifdef SQLITE_ENABLE_API_ARMOR 001636 if( !sqlite3SafetyCheckOk(db) ){ 001637 (void)SQLITE_MISUSE_BKPT; 001638 return; 001639 } 001640 #endif 001641 sqlite3_mutex_enter(db->mutex); 001642 if( nOps>0 ){ 001643 db->xProgress = xProgress; 001644 db->nProgressOps = (unsigned)nOps; 001645 db->pProgressArg = pArg; 001646 }else{ 001647 db->xProgress = 0; 001648 db->nProgressOps = 0; 001649 db->pProgressArg = 0; 001650 } 001651 sqlite3_mutex_leave(db->mutex); 001652 } 001653 #endif 001654 001655 001656 /* 001657 ** This routine installs a default busy handler that waits for the 001658 ** specified number of milliseconds before returning 0. 001659 */ 001660 int sqlite3_busy_timeout(sqlite3 *db, int ms){ 001661 #ifdef SQLITE_ENABLE_API_ARMOR 001662 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; 001663 #endif 001664 if( ms>0 ){ 001665 sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback, 001666 (void*)db); 001667 db->busyTimeout = ms; 001668 db->busyHandler.bExtraFileArg = 1; 001669 }else{ 001670 sqlite3_busy_handler(db, 0, 0); 001671 } 001672 return SQLITE_OK; 001673 } 001674 001675 /* 001676 ** Cause any pending operation to stop at its earliest opportunity. 001677 */ 001678 void sqlite3_interrupt(sqlite3 *db){ 001679 #ifdef SQLITE_ENABLE_API_ARMOR 001680 if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){ 001681 (void)SQLITE_MISUSE_BKPT; 001682 return; 001683 } 001684 #endif 001685 db->u1.isInterrupted = 1; 001686 } 001687 001688 001689 /* 001690 ** This function is exactly the same as sqlite3_create_function(), except 001691 ** that it is designed to be called by internal code. The difference is 001692 ** that if a malloc() fails in sqlite3_create_function(), an error code 001693 ** is returned and the mallocFailed flag cleared. 001694 */ 001695 int sqlite3CreateFunc( 001696 sqlite3 *db, 001697 const char *zFunctionName, 001698 int nArg, 001699 int enc, 001700 void *pUserData, 001701 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **), 001702 void (*xStep)(sqlite3_context*,int,sqlite3_value **), 001703 void (*xFinal)(sqlite3_context*), 001704 void (*xValue)(sqlite3_context*), 001705 void (*xInverse)(sqlite3_context*,int,sqlite3_value **), 001706 FuncDestructor *pDestructor 001707 ){ 001708 FuncDef *p; 001709 int nName; 001710 int extraFlags; 001711 001712 assert( sqlite3_mutex_held(db->mutex) ); 001713 assert( xValue==0 || xSFunc==0 ); 001714 if( zFunctionName==0 /* Must have a valid name */ 001715 || (xSFunc!=0 && xFinal!=0) /* Not both xSFunc and xFinal */ 001716 || ((xFinal==0)!=(xStep==0)) /* Both or neither of xFinal and xStep */ 001717 || ((xValue==0)!=(xInverse==0)) /* Both or neither of xValue, xInverse */ 001718 || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) 001719 || (255<(nName = sqlite3Strlen30( zFunctionName))) 001720 ){ 001721 return SQLITE_MISUSE_BKPT; 001722 } 001723 001724 assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC ); 001725 assert( SQLITE_FUNC_DIRECT==SQLITE_DIRECTONLY ); 001726 extraFlags = enc & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY|SQLITE_SUBTYPE); 001727 enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY); 001728 001729 #ifndef SQLITE_OMIT_UTF16 001730 /* If SQLITE_UTF16 is specified as the encoding type, transform this 001731 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the 001732 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. 001733 ** 001734 ** If SQLITE_ANY is specified, add three versions of the function 001735 ** to the hash table. 001736 */ 001737 if( enc==SQLITE_UTF16 ){ 001738 enc = SQLITE_UTF16NATIVE; 001739 }else if( enc==SQLITE_ANY ){ 001740 int rc; 001741 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags, 001742 pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor); 001743 if( rc==SQLITE_OK ){ 001744 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags, 001745 pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor); 001746 } 001747 if( rc!=SQLITE_OK ){ 001748 return rc; 001749 } 001750 enc = SQLITE_UTF16BE; 001751 } 001752 #else 001753 enc = SQLITE_UTF8; 001754 #endif 001755 001756 /* Check if an existing function is being overridden or deleted. If so, 001757 ** and there are active VMs, then return SQLITE_BUSY. If a function 001758 ** is being overridden/deleted but there are no active VMs, allow the 001759 ** operation to continue but invalidate all precompiled statements. 001760 */ 001761 p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0); 001762 if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){ 001763 if( db->nVdbeActive ){ 001764 sqlite3ErrorWithMsg(db, SQLITE_BUSY, 001765 "unable to delete/modify user-function due to active statements"); 001766 assert( !db->mallocFailed ); 001767 return SQLITE_BUSY; 001768 }else{ 001769 sqlite3ExpirePreparedStatements(db, 0); 001770 } 001771 } 001772 001773 p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1); 001774 assert(p || db->mallocFailed); 001775 if( !p ){ 001776 return SQLITE_NOMEM_BKPT; 001777 } 001778 001779 /* If an older version of the function with a configured destructor is 001780 ** being replaced invoke the destructor function here. */ 001781 functionDestroy(db, p); 001782 001783 if( pDestructor ){ 001784 pDestructor->nRef++; 001785 } 001786 p->u.pDestructor = pDestructor; 001787 p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags; 001788 testcase( p->funcFlags & SQLITE_DETERMINISTIC ); 001789 testcase( p->funcFlags & SQLITE_DIRECTONLY ); 001790 p->xSFunc = xSFunc ? xSFunc : xStep; 001791 p->xFinalize = xFinal; 001792 p->xValue = xValue; 001793 p->xInverse = xInverse; 001794 p->pUserData = pUserData; 001795 p->nArg = (u16)nArg; 001796 return SQLITE_OK; 001797 } 001798 001799 /* 001800 ** Worker function used by utf-8 APIs that create new functions: 001801 ** 001802 ** sqlite3_create_function() 001803 ** sqlite3_create_function_v2() 001804 ** sqlite3_create_window_function() 001805 */ 001806 static int createFunctionApi( 001807 sqlite3 *db, 001808 const char *zFunc, 001809 int nArg, 001810 int enc, 001811 void *p, 001812 void (*xSFunc)(sqlite3_context*,int,sqlite3_value**), 001813 void (*xStep)(sqlite3_context*,int,sqlite3_value**), 001814 void (*xFinal)(sqlite3_context*), 001815 void (*xValue)(sqlite3_context*), 001816 void (*xInverse)(sqlite3_context*,int,sqlite3_value**), 001817 void(*xDestroy)(void*) 001818 ){ 001819 int rc = SQLITE_ERROR; 001820 FuncDestructor *pArg = 0; 001821 001822 #ifdef SQLITE_ENABLE_API_ARMOR 001823 if( !sqlite3SafetyCheckOk(db) ){ 001824 return SQLITE_MISUSE_BKPT; 001825 } 001826 #endif 001827 sqlite3_mutex_enter(db->mutex); 001828 if( xDestroy ){ 001829 pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor)); 001830 if( !pArg ){ 001831 sqlite3OomFault(db); 001832 xDestroy(p); 001833 goto out; 001834 } 001835 pArg->nRef = 0; 001836 pArg->xDestroy = xDestroy; 001837 pArg->pUserData = p; 001838 } 001839 rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, 001840 xSFunc, xStep, xFinal, xValue, xInverse, pArg 001841 ); 001842 if( pArg && pArg->nRef==0 ){ 001843 assert( rc!=SQLITE_OK ); 001844 xDestroy(p); 001845 sqlite3_free(pArg); 001846 } 001847 001848 out: 001849 rc = sqlite3ApiExit(db, rc); 001850 sqlite3_mutex_leave(db->mutex); 001851 return rc; 001852 } 001853 001854 /* 001855 ** Create new user functions. 001856 */ 001857 int sqlite3_create_function( 001858 sqlite3 *db, 001859 const char *zFunc, 001860 int nArg, 001861 int enc, 001862 void *p, 001863 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **), 001864 void (*xStep)(sqlite3_context*,int,sqlite3_value **), 001865 void (*xFinal)(sqlite3_context*) 001866 ){ 001867 return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep, 001868 xFinal, 0, 0, 0); 001869 } 001870 int sqlite3_create_function_v2( 001871 sqlite3 *db, 001872 const char *zFunc, 001873 int nArg, 001874 int enc, 001875 void *p, 001876 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **), 001877 void (*xStep)(sqlite3_context*,int,sqlite3_value **), 001878 void (*xFinal)(sqlite3_context*), 001879 void (*xDestroy)(void *) 001880 ){ 001881 return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep, 001882 xFinal, 0, 0, xDestroy); 001883 } 001884 int sqlite3_create_window_function( 001885 sqlite3 *db, 001886 const char *zFunc, 001887 int nArg, 001888 int enc, 001889 void *p, 001890 void (*xStep)(sqlite3_context*,int,sqlite3_value **), 001891 void (*xFinal)(sqlite3_context*), 001892 void (*xValue)(sqlite3_context*), 001893 void (*xInverse)(sqlite3_context*,int,sqlite3_value **), 001894 void (*xDestroy)(void *) 001895 ){ 001896 return createFunctionApi(db, zFunc, nArg, enc, p, 0, xStep, 001897 xFinal, xValue, xInverse, xDestroy); 001898 } 001899 001900 #ifndef SQLITE_OMIT_UTF16 001901 int sqlite3_create_function16( 001902 sqlite3 *db, 001903 const void *zFunctionName, 001904 int nArg, 001905 int eTextRep, 001906 void *p, 001907 void (*xSFunc)(sqlite3_context*,int,sqlite3_value**), 001908 void (*xStep)(sqlite3_context*,int,sqlite3_value**), 001909 void (*xFinal)(sqlite3_context*) 001910 ){ 001911 int rc; 001912 char *zFunc8; 001913 001914 #ifdef SQLITE_ENABLE_API_ARMOR 001915 if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT; 001916 #endif 001917 sqlite3_mutex_enter(db->mutex); 001918 assert( !db->mallocFailed ); 001919 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE); 001920 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0,0,0); 001921 sqlite3DbFree(db, zFunc8); 001922 rc = sqlite3ApiExit(db, rc); 001923 sqlite3_mutex_leave(db->mutex); 001924 return rc; 001925 } 001926 #endif 001927 001928 001929 /* 001930 ** The following is the implementation of an SQL function that always 001931 ** fails with an error message stating that the function is used in the 001932 ** wrong context. The sqlite3_overload_function() API might construct 001933 ** SQL function that use this routine so that the functions will exist 001934 ** for name resolution but are actually overloaded by the xFindFunction 001935 ** method of virtual tables. 001936 */ 001937 static void sqlite3InvalidFunction( 001938 sqlite3_context *context, /* The function calling context */ 001939 int NotUsed, /* Number of arguments to the function */ 001940 sqlite3_value **NotUsed2 /* Value of each argument */ 001941 ){ 001942 const char *zName = (const char*)sqlite3_user_data(context); 001943 char *zErr; 001944 UNUSED_PARAMETER2(NotUsed, NotUsed2); 001945 zErr = sqlite3_mprintf( 001946 "unable to use function %s in the requested context", zName); 001947 sqlite3_result_error(context, zErr, -1); 001948 sqlite3_free(zErr); 001949 } 001950 001951 /* 001952 ** Declare that a function has been overloaded by a virtual table. 001953 ** 001954 ** If the function already exists as a regular global function, then 001955 ** this routine is a no-op. If the function does not exist, then create 001956 ** a new one that always throws a run-time error. 001957 ** 001958 ** When virtual tables intend to provide an overloaded function, they 001959 ** should call this routine to make sure the global function exists. 001960 ** A global function must exist in order for name resolution to work 001961 ** properly. 001962 */ 001963 int sqlite3_overload_function( 001964 sqlite3 *db, 001965 const char *zName, 001966 int nArg 001967 ){ 001968 int rc; 001969 char *zCopy; 001970 001971 #ifdef SQLITE_ENABLE_API_ARMOR 001972 if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){ 001973 return SQLITE_MISUSE_BKPT; 001974 } 001975 #endif 001976 sqlite3_mutex_enter(db->mutex); 001977 rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0; 001978 sqlite3_mutex_leave(db->mutex); 001979 if( rc ) return SQLITE_OK; 001980 zCopy = sqlite3_mprintf(zName); 001981 if( zCopy==0 ) return SQLITE_NOMEM; 001982 return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8, 001983 zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free); 001984 } 001985 001986 #ifndef SQLITE_OMIT_TRACE 001987 /* 001988 ** Register a trace function. The pArg from the previously registered trace 001989 ** is returned. 001990 ** 001991 ** A NULL trace function means that no tracing is executes. A non-NULL 001992 ** trace is a pointer to a function that is invoked at the start of each 001993 ** SQL statement. 001994 */ 001995 #ifndef SQLITE_OMIT_DEPRECATED 001996 void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){ 001997 void *pOld; 001998 001999 #ifdef SQLITE_ENABLE_API_ARMOR 002000 if( !sqlite3SafetyCheckOk(db) ){ 002001 (void)SQLITE_MISUSE_BKPT; 002002 return 0; 002003 } 002004 #endif 002005 sqlite3_mutex_enter(db->mutex); 002006 pOld = db->pTraceArg; 002007 db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0; 002008 db->xTrace = (int(*)(u32,void*,void*,void*))xTrace; 002009 db->pTraceArg = pArg; 002010 sqlite3_mutex_leave(db->mutex); 002011 return pOld; 002012 } 002013 #endif /* SQLITE_OMIT_DEPRECATED */ 002014 002015 /* Register a trace callback using the version-2 interface. 002016 */ 002017 int sqlite3_trace_v2( 002018 sqlite3 *db, /* Trace this connection */ 002019 unsigned mTrace, /* Mask of events to be traced */ 002020 int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */ 002021 void *pArg /* Context */ 002022 ){ 002023 #ifdef SQLITE_ENABLE_API_ARMOR 002024 if( !sqlite3SafetyCheckOk(db) ){ 002025 return SQLITE_MISUSE_BKPT; 002026 } 002027 #endif 002028 sqlite3_mutex_enter(db->mutex); 002029 if( mTrace==0 ) xTrace = 0; 002030 if( xTrace==0 ) mTrace = 0; 002031 db->mTrace = mTrace; 002032 db->xTrace = xTrace; 002033 db->pTraceArg = pArg; 002034 sqlite3_mutex_leave(db->mutex); 002035 return SQLITE_OK; 002036 } 002037 002038 #ifndef SQLITE_OMIT_DEPRECATED 002039 /* 002040 ** Register a profile function. The pArg from the previously registered 002041 ** profile function is returned. 002042 ** 002043 ** A NULL profile function means that no profiling is executes. A non-NULL 002044 ** profile is a pointer to a function that is invoked at the conclusion of 002045 ** each SQL statement that is run. 002046 */ 002047 void *sqlite3_profile( 002048 sqlite3 *db, 002049 void (*xProfile)(void*,const char*,sqlite_uint64), 002050 void *pArg 002051 ){ 002052 void *pOld; 002053 002054 #ifdef SQLITE_ENABLE_API_ARMOR 002055 if( !sqlite3SafetyCheckOk(db) ){ 002056 (void)SQLITE_MISUSE_BKPT; 002057 return 0; 002058 } 002059 #endif 002060 sqlite3_mutex_enter(db->mutex); 002061 pOld = db->pProfileArg; 002062 db->xProfile = xProfile; 002063 db->pProfileArg = pArg; 002064 db->mTrace &= SQLITE_TRACE_NONLEGACY_MASK; 002065 if( db->xProfile ) db->mTrace |= SQLITE_TRACE_XPROFILE; 002066 sqlite3_mutex_leave(db->mutex); 002067 return pOld; 002068 } 002069 #endif /* SQLITE_OMIT_DEPRECATED */ 002070 #endif /* SQLITE_OMIT_TRACE */ 002071 002072 /* 002073 ** Register a function to be invoked when a transaction commits. 002074 ** If the invoked function returns non-zero, then the commit becomes a 002075 ** rollback. 002076 */ 002077 void *sqlite3_commit_hook( 002078 sqlite3 *db, /* Attach the hook to this database */ 002079 int (*xCallback)(void*), /* Function to invoke on each commit */ 002080 void *pArg /* Argument to the function */ 002081 ){ 002082 void *pOld; 002083 002084 #ifdef SQLITE_ENABLE_API_ARMOR 002085 if( !sqlite3SafetyCheckOk(db) ){ 002086 (void)SQLITE_MISUSE_BKPT; 002087 return 0; 002088 } 002089 #endif 002090 sqlite3_mutex_enter(db->mutex); 002091 pOld = db->pCommitArg; 002092 db->xCommitCallback = xCallback; 002093 db->pCommitArg = pArg; 002094 sqlite3_mutex_leave(db->mutex); 002095 return pOld; 002096 } 002097 002098 /* 002099 ** Register a callback to be invoked each time a row is updated, 002100 ** inserted or deleted using this database connection. 002101 */ 002102 void *sqlite3_update_hook( 002103 sqlite3 *db, /* Attach the hook to this database */ 002104 void (*xCallback)(void*,int,char const *,char const *,sqlite_int64), 002105 void *pArg /* Argument to the function */ 002106 ){ 002107 void *pRet; 002108 002109 #ifdef SQLITE_ENABLE_API_ARMOR 002110 if( !sqlite3SafetyCheckOk(db) ){ 002111 (void)SQLITE_MISUSE_BKPT; 002112 return 0; 002113 } 002114 #endif 002115 sqlite3_mutex_enter(db->mutex); 002116 pRet = db->pUpdateArg; 002117 db->xUpdateCallback = xCallback; 002118 db->pUpdateArg = pArg; 002119 sqlite3_mutex_leave(db->mutex); 002120 return pRet; 002121 } 002122 002123 /* 002124 ** Register a callback to be invoked each time a transaction is rolled 002125 ** back by this database connection. 002126 */ 002127 void *sqlite3_rollback_hook( 002128 sqlite3 *db, /* Attach the hook to this database */ 002129 void (*xCallback)(void*), /* Callback function */ 002130 void *pArg /* Argument to the function */ 002131 ){ 002132 void *pRet; 002133 002134 #ifdef SQLITE_ENABLE_API_ARMOR 002135 if( !sqlite3SafetyCheckOk(db) ){ 002136 (void)SQLITE_MISUSE_BKPT; 002137 return 0; 002138 } 002139 #endif 002140 sqlite3_mutex_enter(db->mutex); 002141 pRet = db->pRollbackArg; 002142 db->xRollbackCallback = xCallback; 002143 db->pRollbackArg = pArg; 002144 sqlite3_mutex_leave(db->mutex); 002145 return pRet; 002146 } 002147 002148 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK 002149 /* 002150 ** Register a callback to be invoked each time a row is updated, 002151 ** inserted or deleted using this database connection. 002152 */ 002153 void *sqlite3_preupdate_hook( 002154 sqlite3 *db, /* Attach the hook to this database */ 002155 void(*xCallback)( /* Callback function */ 002156 void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64), 002157 void *pArg /* First callback argument */ 002158 ){ 002159 void *pRet; 002160 sqlite3_mutex_enter(db->mutex); 002161 pRet = db->pPreUpdateArg; 002162 db->xPreUpdateCallback = xCallback; 002163 db->pPreUpdateArg = pArg; 002164 sqlite3_mutex_leave(db->mutex); 002165 return pRet; 002166 } 002167 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ 002168 002169 #ifndef SQLITE_OMIT_WAL 002170 /* 002171 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint(). 002172 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file 002173 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by 002174 ** wal_autocheckpoint()). 002175 */ 002176 int sqlite3WalDefaultHook( 002177 void *pClientData, /* Argument */ 002178 sqlite3 *db, /* Connection */ 002179 const char *zDb, /* Database */ 002180 int nFrame /* Size of WAL */ 002181 ){ 002182 if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){ 002183 sqlite3BeginBenignMalloc(); 002184 sqlite3_wal_checkpoint(db, zDb); 002185 sqlite3EndBenignMalloc(); 002186 } 002187 return SQLITE_OK; 002188 } 002189 #endif /* SQLITE_OMIT_WAL */ 002190 002191 /* 002192 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint 002193 ** a database after committing a transaction if there are nFrame or 002194 ** more frames in the log file. Passing zero or a negative value as the 002195 ** nFrame parameter disables automatic checkpoints entirely. 002196 ** 002197 ** The callback registered by this function replaces any existing callback 002198 ** registered using sqlite3_wal_hook(). Likewise, registering a callback 002199 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism 002200 ** configured by this function. 002201 */ 002202 int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){ 002203 #ifdef SQLITE_OMIT_WAL 002204 UNUSED_PARAMETER(db); 002205 UNUSED_PARAMETER(nFrame); 002206 #else 002207 #ifdef SQLITE_ENABLE_API_ARMOR 002208 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; 002209 #endif 002210 if( nFrame>0 ){ 002211 sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame)); 002212 }else{ 002213 sqlite3_wal_hook(db, 0, 0); 002214 } 002215 #endif 002216 return SQLITE_OK; 002217 } 002218 002219 /* 002220 ** Register a callback to be invoked each time a transaction is written 002221 ** into the write-ahead-log by this database connection. 002222 */ 002223 void *sqlite3_wal_hook( 002224 sqlite3 *db, /* Attach the hook to this db handle */ 002225 int(*xCallback)(void *, sqlite3*, const char*, int), 002226 void *pArg /* First argument passed to xCallback() */ 002227 ){ 002228 #ifndef SQLITE_OMIT_WAL 002229 void *pRet; 002230 #ifdef SQLITE_ENABLE_API_ARMOR 002231 if( !sqlite3SafetyCheckOk(db) ){ 002232 (void)SQLITE_MISUSE_BKPT; 002233 return 0; 002234 } 002235 #endif 002236 sqlite3_mutex_enter(db->mutex); 002237 pRet = db->pWalArg; 002238 db->xWalCallback = xCallback; 002239 db->pWalArg = pArg; 002240 sqlite3_mutex_leave(db->mutex); 002241 return pRet; 002242 #else 002243 return 0; 002244 #endif 002245 } 002246 002247 /* 002248 ** Checkpoint database zDb. 002249 */ 002250 int sqlite3_wal_checkpoint_v2( 002251 sqlite3 *db, /* Database handle */ 002252 const char *zDb, /* Name of attached database (or NULL) */ 002253 int eMode, /* SQLITE_CHECKPOINT_* value */ 002254 int *pnLog, /* OUT: Size of WAL log in frames */ 002255 int *pnCkpt /* OUT: Total number of frames checkpointed */ 002256 ){ 002257 #ifdef SQLITE_OMIT_WAL 002258 return SQLITE_OK; 002259 #else 002260 int rc; /* Return code */ 002261 int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */ 002262 002263 #ifdef SQLITE_ENABLE_API_ARMOR 002264 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; 002265 #endif 002266 002267 /* Initialize the output variables to -1 in case an error occurs. */ 002268 if( pnLog ) *pnLog = -1; 002269 if( pnCkpt ) *pnCkpt = -1; 002270 002271 assert( SQLITE_CHECKPOINT_PASSIVE==0 ); 002272 assert( SQLITE_CHECKPOINT_FULL==1 ); 002273 assert( SQLITE_CHECKPOINT_RESTART==2 ); 002274 assert( SQLITE_CHECKPOINT_TRUNCATE==3 ); 002275 if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){ 002276 /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint 002277 ** mode: */ 002278 return SQLITE_MISUSE; 002279 } 002280 002281 sqlite3_mutex_enter(db->mutex); 002282 if( zDb && zDb[0] ){ 002283 iDb = sqlite3FindDbName(db, zDb); 002284 } 002285 if( iDb<0 ){ 002286 rc = SQLITE_ERROR; 002287 sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb); 002288 }else{ 002289 db->busyHandler.nBusy = 0; 002290 rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt); 002291 sqlite3Error(db, rc); 002292 } 002293 rc = sqlite3ApiExit(db, rc); 002294 002295 /* If there are no active statements, clear the interrupt flag at this 002296 ** point. */ 002297 if( db->nVdbeActive==0 ){ 002298 db->u1.isInterrupted = 0; 002299 } 002300 002301 sqlite3_mutex_leave(db->mutex); 002302 return rc; 002303 #endif 002304 } 002305 002306 002307 /* 002308 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points 002309 ** to contains a zero-length string, all attached databases are 002310 ** checkpointed. 002311 */ 002312 int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){ 002313 /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to 002314 ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */ 002315 return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0); 002316 } 002317 002318 #ifndef SQLITE_OMIT_WAL 002319 /* 002320 ** Run a checkpoint on database iDb. This is a no-op if database iDb is 002321 ** not currently open in WAL mode. 002322 ** 002323 ** If a transaction is open on the database being checkpointed, this 002324 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 002325 ** an error occurs while running the checkpoint, an SQLite error code is 002326 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK. 002327 ** 002328 ** The mutex on database handle db should be held by the caller. The mutex 002329 ** associated with the specific b-tree being checkpointed is taken by 002330 ** this function while the checkpoint is running. 002331 ** 002332 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are 002333 ** checkpointed. If an error is encountered it is returned immediately - 002334 ** no attempt is made to checkpoint any remaining databases. 002335 ** 002336 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART 002337 ** or TRUNCATE. 002338 */ 002339 int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){ 002340 int rc = SQLITE_OK; /* Return code */ 002341 int i; /* Used to iterate through attached dbs */ 002342 int bBusy = 0; /* True if SQLITE_BUSY has been encountered */ 002343 002344 assert( sqlite3_mutex_held(db->mutex) ); 002345 assert( !pnLog || *pnLog==-1 ); 002346 assert( !pnCkpt || *pnCkpt==-1 ); 002347 002348 for(i=0; i<db->nDb && rc==SQLITE_OK; i++){ 002349 if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){ 002350 rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt); 002351 pnLog = 0; 002352 pnCkpt = 0; 002353 if( rc==SQLITE_BUSY ){ 002354 bBusy = 1; 002355 rc = SQLITE_OK; 002356 } 002357 } 002358 } 002359 002360 return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc; 002361 } 002362 #endif /* SQLITE_OMIT_WAL */ 002363 002364 /* 002365 ** This function returns true if main-memory should be used instead of 002366 ** a temporary file for transient pager files and statement journals. 002367 ** The value returned depends on the value of db->temp_store (runtime 002368 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The 002369 ** following table describes the relationship between these two values 002370 ** and this functions return value. 002371 ** 002372 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database 002373 ** ----------------- -------------- ------------------------------ 002374 ** 0 any file (return 0) 002375 ** 1 1 file (return 0) 002376 ** 1 2 memory (return 1) 002377 ** 1 0 file (return 0) 002378 ** 2 1 file (return 0) 002379 ** 2 2 memory (return 1) 002380 ** 2 0 memory (return 1) 002381 ** 3 any memory (return 1) 002382 */ 002383 int sqlite3TempInMemory(const sqlite3 *db){ 002384 #if SQLITE_TEMP_STORE==1 002385 return ( db->temp_store==2 ); 002386 #endif 002387 #if SQLITE_TEMP_STORE==2 002388 return ( db->temp_store!=1 ); 002389 #endif 002390 #if SQLITE_TEMP_STORE==3 002391 UNUSED_PARAMETER(db); 002392 return 1; 002393 #endif 002394 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3 002395 UNUSED_PARAMETER(db); 002396 return 0; 002397 #endif 002398 } 002399 002400 /* 002401 ** Return UTF-8 encoded English language explanation of the most recent 002402 ** error. 002403 */ 002404 const char *sqlite3_errmsg(sqlite3 *db){ 002405 const char *z; 002406 if( !db ){ 002407 return sqlite3ErrStr(SQLITE_NOMEM_BKPT); 002408 } 002409 if( !sqlite3SafetyCheckSickOrOk(db) ){ 002410 return sqlite3ErrStr(SQLITE_MISUSE_BKPT); 002411 } 002412 sqlite3_mutex_enter(db->mutex); 002413 if( db->mallocFailed ){ 002414 z = sqlite3ErrStr(SQLITE_NOMEM_BKPT); 002415 }else{ 002416 testcase( db->pErr==0 ); 002417 z = db->errCode ? (char*)sqlite3_value_text(db->pErr) : 0; 002418 assert( !db->mallocFailed ); 002419 if( z==0 ){ 002420 z = sqlite3ErrStr(db->errCode); 002421 } 002422 } 002423 sqlite3_mutex_leave(db->mutex); 002424 return z; 002425 } 002426 002427 #ifndef SQLITE_OMIT_UTF16 002428 /* 002429 ** Return UTF-16 encoded English language explanation of the most recent 002430 ** error. 002431 */ 002432 const void *sqlite3_errmsg16(sqlite3 *db){ 002433 static const u16 outOfMem[] = { 002434 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0 002435 }; 002436 static const u16 misuse[] = { 002437 'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ', 002438 'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ', 002439 'm', 'i', 's', 'u', 's', 'e', 0 002440 }; 002441 002442 const void *z; 002443 if( !db ){ 002444 return (void *)outOfMem; 002445 } 002446 if( !sqlite3SafetyCheckSickOrOk(db) ){ 002447 return (void *)misuse; 002448 } 002449 sqlite3_mutex_enter(db->mutex); 002450 if( db->mallocFailed ){ 002451 z = (void *)outOfMem; 002452 }else{ 002453 z = sqlite3_value_text16(db->pErr); 002454 if( z==0 ){ 002455 sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode)); 002456 z = sqlite3_value_text16(db->pErr); 002457 } 002458 /* A malloc() may have failed within the call to sqlite3_value_text16() 002459 ** above. If this is the case, then the db->mallocFailed flag needs to 002460 ** be cleared before returning. Do this directly, instead of via 002461 ** sqlite3ApiExit(), to avoid setting the database handle error message. 002462 */ 002463 sqlite3OomClear(db); 002464 } 002465 sqlite3_mutex_leave(db->mutex); 002466 return z; 002467 } 002468 #endif /* SQLITE_OMIT_UTF16 */ 002469 002470 /* 002471 ** Return the most recent error code generated by an SQLite routine. If NULL is 002472 ** passed to this function, we assume a malloc() failed during sqlite3_open(). 002473 */ 002474 int sqlite3_errcode(sqlite3 *db){ 002475 if( db && !sqlite3SafetyCheckSickOrOk(db) ){ 002476 return SQLITE_MISUSE_BKPT; 002477 } 002478 if( !db || db->mallocFailed ){ 002479 return SQLITE_NOMEM_BKPT; 002480 } 002481 return db->errCode & db->errMask; 002482 } 002483 int sqlite3_extended_errcode(sqlite3 *db){ 002484 if( db && !sqlite3SafetyCheckSickOrOk(db) ){ 002485 return SQLITE_MISUSE_BKPT; 002486 } 002487 if( !db || db->mallocFailed ){ 002488 return SQLITE_NOMEM_BKPT; 002489 } 002490 return db->errCode; 002491 } 002492 int sqlite3_system_errno(sqlite3 *db){ 002493 return db ? db->iSysErrno : 0; 002494 } 002495 002496 /* 002497 ** Return a string that describes the kind of error specified in the 002498 ** argument. For now, this simply calls the internal sqlite3ErrStr() 002499 ** function. 002500 */ 002501 const char *sqlite3_errstr(int rc){ 002502 return sqlite3ErrStr(rc); 002503 } 002504 002505 /* 002506 ** Create a new collating function for database "db". The name is zName 002507 ** and the encoding is enc. 002508 */ 002509 static int createCollation( 002510 sqlite3* db, 002511 const char *zName, 002512 u8 enc, 002513 void* pCtx, 002514 int(*xCompare)(void*,int,const void*,int,const void*), 002515 void(*xDel)(void*) 002516 ){ 002517 CollSeq *pColl; 002518 int enc2; 002519 002520 assert( sqlite3_mutex_held(db->mutex) ); 002521 002522 /* If SQLITE_UTF16 is specified as the encoding type, transform this 002523 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the 002524 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. 002525 */ 002526 enc2 = enc; 002527 testcase( enc2==SQLITE_UTF16 ); 002528 testcase( enc2==SQLITE_UTF16_ALIGNED ); 002529 if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){ 002530 enc2 = SQLITE_UTF16NATIVE; 002531 } 002532 if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){ 002533 return SQLITE_MISUSE_BKPT; 002534 } 002535 002536 /* Check if this call is removing or replacing an existing collation 002537 ** sequence. If so, and there are active VMs, return busy. If there 002538 ** are no active VMs, invalidate any pre-compiled statements. 002539 */ 002540 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0); 002541 if( pColl && pColl->xCmp ){ 002542 if( db->nVdbeActive ){ 002543 sqlite3ErrorWithMsg(db, SQLITE_BUSY, 002544 "unable to delete/modify collation sequence due to active statements"); 002545 return SQLITE_BUSY; 002546 } 002547 sqlite3ExpirePreparedStatements(db, 0); 002548 002549 /* If collation sequence pColl was created directly by a call to 002550 ** sqlite3_create_collation, and not generated by synthCollSeq(), 002551 ** then any copies made by synthCollSeq() need to be invalidated. 002552 ** Also, collation destructor - CollSeq.xDel() - function may need 002553 ** to be called. 002554 */ 002555 if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){ 002556 CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName); 002557 int j; 002558 for(j=0; j<3; j++){ 002559 CollSeq *p = &aColl[j]; 002560 if( p->enc==pColl->enc ){ 002561 if( p->xDel ){ 002562 p->xDel(p->pUser); 002563 } 002564 p->xCmp = 0; 002565 } 002566 } 002567 } 002568 } 002569 002570 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1); 002571 if( pColl==0 ) return SQLITE_NOMEM_BKPT; 002572 pColl->xCmp = xCompare; 002573 pColl->pUser = pCtx; 002574 pColl->xDel = xDel; 002575 pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED)); 002576 sqlite3Error(db, SQLITE_OK); 002577 return SQLITE_OK; 002578 } 002579 002580 002581 /* 002582 ** This array defines hard upper bounds on limit values. The 002583 ** initializer must be kept in sync with the SQLITE_LIMIT_* 002584 ** #defines in sqlite3.h. 002585 */ 002586 static const int aHardLimit[] = { 002587 SQLITE_MAX_LENGTH, 002588 SQLITE_MAX_SQL_LENGTH, 002589 SQLITE_MAX_COLUMN, 002590 SQLITE_MAX_EXPR_DEPTH, 002591 SQLITE_MAX_COMPOUND_SELECT, 002592 SQLITE_MAX_VDBE_OP, 002593 SQLITE_MAX_FUNCTION_ARG, 002594 SQLITE_MAX_ATTACHED, 002595 SQLITE_MAX_LIKE_PATTERN_LENGTH, 002596 SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */ 002597 SQLITE_MAX_TRIGGER_DEPTH, 002598 SQLITE_MAX_WORKER_THREADS, 002599 }; 002600 002601 /* 002602 ** Make sure the hard limits are set to reasonable values 002603 */ 002604 #if SQLITE_MAX_LENGTH<100 002605 # error SQLITE_MAX_LENGTH must be at least 100 002606 #endif 002607 #if SQLITE_MAX_SQL_LENGTH<100 002608 # error SQLITE_MAX_SQL_LENGTH must be at least 100 002609 #endif 002610 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH 002611 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH 002612 #endif 002613 #if SQLITE_MAX_COMPOUND_SELECT<2 002614 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2 002615 #endif 002616 #if SQLITE_MAX_VDBE_OP<40 002617 # error SQLITE_MAX_VDBE_OP must be at least 40 002618 #endif 002619 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127 002620 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127 002621 #endif 002622 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125 002623 # error SQLITE_MAX_ATTACHED must be between 0 and 125 002624 #endif 002625 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1 002626 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1 002627 #endif 002628 #if SQLITE_MAX_COLUMN>32767 002629 # error SQLITE_MAX_COLUMN must not exceed 32767 002630 #endif 002631 #if SQLITE_MAX_TRIGGER_DEPTH<1 002632 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1 002633 #endif 002634 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50 002635 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50 002636 #endif 002637 002638 002639 /* 002640 ** Change the value of a limit. Report the old value. 002641 ** If an invalid limit index is supplied, report -1. 002642 ** Make no changes but still report the old value if the 002643 ** new limit is negative. 002644 ** 002645 ** A new lower limit does not shrink existing constructs. 002646 ** It merely prevents new constructs that exceed the limit 002647 ** from forming. 002648 */ 002649 int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){ 002650 int oldLimit; 002651 002652 #ifdef SQLITE_ENABLE_API_ARMOR 002653 if( !sqlite3SafetyCheckOk(db) ){ 002654 (void)SQLITE_MISUSE_BKPT; 002655 return -1; 002656 } 002657 #endif 002658 002659 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME 002660 ** there is a hard upper bound set at compile-time by a C preprocessor 002661 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to 002662 ** "_MAX_".) 002663 */ 002664 assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH ); 002665 assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH ); 002666 assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN ); 002667 assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH ); 002668 assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT); 002669 assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP ); 002670 assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG ); 002671 assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED ); 002672 assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]== 002673 SQLITE_MAX_LIKE_PATTERN_LENGTH ); 002674 assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER); 002675 assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH ); 002676 assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS ); 002677 assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) ); 002678 002679 002680 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){ 002681 return -1; 002682 } 002683 oldLimit = db->aLimit[limitId]; 002684 if( newLimit>=0 ){ /* IMP: R-52476-28732 */ 002685 if( newLimit>aHardLimit[limitId] ){ 002686 newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */ 002687 } 002688 db->aLimit[limitId] = newLimit; 002689 } 002690 return oldLimit; /* IMP: R-53341-35419 */ 002691 } 002692 002693 /* 002694 ** This function is used to parse both URIs and non-URI filenames passed by the 002695 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database 002696 ** URIs specified as part of ATTACH statements. 002697 ** 002698 ** The first argument to this function is the name of the VFS to use (or 002699 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx" 002700 ** query parameter. The second argument contains the URI (or non-URI filename) 002701 ** itself. When this function is called the *pFlags variable should contain 002702 ** the default flags to open the database handle with. The value stored in 002703 ** *pFlags may be updated before returning if the URI filename contains 002704 ** "cache=xxx" or "mode=xxx" query parameters. 002705 ** 002706 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to 002707 ** the VFS that should be used to open the database file. *pzFile is set to 002708 ** point to a buffer containing the name of the file to open. It is the 002709 ** responsibility of the caller to eventually call sqlite3_free() to release 002710 ** this buffer. 002711 ** 002712 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg 002713 ** may be set to point to a buffer containing an English language error 002714 ** message. It is the responsibility of the caller to eventually release 002715 ** this buffer by calling sqlite3_free(). 002716 */ 002717 int sqlite3ParseUri( 002718 const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */ 002719 const char *zUri, /* Nul-terminated URI to parse */ 002720 unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */ 002721 sqlite3_vfs **ppVfs, /* OUT: VFS to use */ 002722 char **pzFile, /* OUT: Filename component of URI */ 002723 char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */ 002724 ){ 002725 int rc = SQLITE_OK; 002726 unsigned int flags = *pFlags; 002727 const char *zVfs = zDefaultVfs; 002728 char *zFile; 002729 char c; 002730 int nUri = sqlite3Strlen30(zUri); 002731 002732 assert( *pzErrMsg==0 ); 002733 002734 if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */ 002735 || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */ 002736 && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */ 002737 ){ 002738 char *zOpt; 002739 int eState; /* Parser state when parsing URI */ 002740 int iIn; /* Input character index */ 002741 int iOut = 0; /* Output character index */ 002742 u64 nByte = nUri+2; /* Bytes of space to allocate */ 002743 002744 /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen 002745 ** method that there may be extra parameters following the file-name. */ 002746 flags |= SQLITE_OPEN_URI; 002747 002748 for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&'); 002749 zFile = sqlite3_malloc64(nByte); 002750 if( !zFile ) return SQLITE_NOMEM_BKPT; 002751 002752 iIn = 5; 002753 #ifdef SQLITE_ALLOW_URI_AUTHORITY 002754 if( strncmp(zUri+5, "///", 3)==0 ){ 002755 iIn = 7; 002756 /* The following condition causes URIs with five leading / characters 002757 ** like file://///host/path to be converted into UNCs like //host/path. 002758 ** The correct URI for that UNC has only two or four leading / characters 002759 ** file://host/path or file:////host/path. But 5 leading slashes is a 002760 ** common error, we are told, so we handle it as a special case. */ 002761 if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; } 002762 }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){ 002763 iIn = 16; 002764 } 002765 #else 002766 /* Discard the scheme and authority segments of the URI. */ 002767 if( zUri[5]=='/' && zUri[6]=='/' ){ 002768 iIn = 7; 002769 while( zUri[iIn] && zUri[iIn]!='/' ) iIn++; 002770 if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){ 002771 *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", 002772 iIn-7, &zUri[7]); 002773 rc = SQLITE_ERROR; 002774 goto parse_uri_out; 002775 } 002776 } 002777 #endif 002778 002779 /* Copy the filename and any query parameters into the zFile buffer. 002780 ** Decode %HH escape codes along the way. 002781 ** 002782 ** Within this loop, variable eState may be set to 0, 1 or 2, depending 002783 ** on the parsing context. As follows: 002784 ** 002785 ** 0: Parsing file-name. 002786 ** 1: Parsing name section of a name=value query parameter. 002787 ** 2: Parsing value section of a name=value query parameter. 002788 */ 002789 eState = 0; 002790 while( (c = zUri[iIn])!=0 && c!='#' ){ 002791 iIn++; 002792 if( c=='%' 002793 && sqlite3Isxdigit(zUri[iIn]) 002794 && sqlite3Isxdigit(zUri[iIn+1]) 002795 ){ 002796 int octet = (sqlite3HexToInt(zUri[iIn++]) << 4); 002797 octet += sqlite3HexToInt(zUri[iIn++]); 002798 002799 assert( octet>=0 && octet<256 ); 002800 if( octet==0 ){ 002801 #ifndef SQLITE_ENABLE_URI_00_ERROR 002802 /* This branch is taken when "%00" appears within the URI. In this 002803 ** case we ignore all text in the remainder of the path, name or 002804 ** value currently being parsed. So ignore the current character 002805 ** and skip to the next "?", "=" or "&", as appropriate. */ 002806 while( (c = zUri[iIn])!=0 && c!='#' 002807 && (eState!=0 || c!='?') 002808 && (eState!=1 || (c!='=' && c!='&')) 002809 && (eState!=2 || c!='&') 002810 ){ 002811 iIn++; 002812 } 002813 continue; 002814 #else 002815 /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */ 002816 *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri"); 002817 rc = SQLITE_ERROR; 002818 goto parse_uri_out; 002819 #endif 002820 } 002821 c = octet; 002822 }else if( eState==1 && (c=='&' || c=='=') ){ 002823 if( zFile[iOut-1]==0 ){ 002824 /* An empty option name. Ignore this option altogether. */ 002825 while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++; 002826 continue; 002827 } 002828 if( c=='&' ){ 002829 zFile[iOut++] = '\0'; 002830 }else{ 002831 eState = 2; 002832 } 002833 c = 0; 002834 }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){ 002835 c = 0; 002836 eState = 1; 002837 } 002838 zFile[iOut++] = c; 002839 } 002840 if( eState==1 ) zFile[iOut++] = '\0'; 002841 zFile[iOut++] = '\0'; 002842 zFile[iOut++] = '\0'; 002843 002844 /* Check if there were any options specified that should be interpreted 002845 ** here. Options that are interpreted here include "vfs" and those that 002846 ** correspond to flags that may be passed to the sqlite3_open_v2() 002847 ** method. */ 002848 zOpt = &zFile[sqlite3Strlen30(zFile)+1]; 002849 while( zOpt[0] ){ 002850 int nOpt = sqlite3Strlen30(zOpt); 002851 char *zVal = &zOpt[nOpt+1]; 002852 int nVal = sqlite3Strlen30(zVal); 002853 002854 if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){ 002855 zVfs = zVal; 002856 }else{ 002857 struct OpenMode { 002858 const char *z; 002859 int mode; 002860 } *aMode = 0; 002861 char *zModeType = 0; 002862 int mask = 0; 002863 int limit = 0; 002864 002865 if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){ 002866 static struct OpenMode aCacheMode[] = { 002867 { "shared", SQLITE_OPEN_SHAREDCACHE }, 002868 { "private", SQLITE_OPEN_PRIVATECACHE }, 002869 { 0, 0 } 002870 }; 002871 002872 mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE; 002873 aMode = aCacheMode; 002874 limit = mask; 002875 zModeType = "cache"; 002876 } 002877 if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){ 002878 static struct OpenMode aOpenMode[] = { 002879 { "ro", SQLITE_OPEN_READONLY }, 002880 { "rw", SQLITE_OPEN_READWRITE }, 002881 { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE }, 002882 { "memory", SQLITE_OPEN_MEMORY }, 002883 { 0, 0 } 002884 }; 002885 002886 mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE 002887 | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY; 002888 aMode = aOpenMode; 002889 limit = mask & flags; 002890 zModeType = "access"; 002891 } 002892 002893 if( aMode ){ 002894 int i; 002895 int mode = 0; 002896 for(i=0; aMode[i].z; i++){ 002897 const char *z = aMode[i].z; 002898 if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){ 002899 mode = aMode[i].mode; 002900 break; 002901 } 002902 } 002903 if( mode==0 ){ 002904 *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal); 002905 rc = SQLITE_ERROR; 002906 goto parse_uri_out; 002907 } 002908 if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){ 002909 *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s", 002910 zModeType, zVal); 002911 rc = SQLITE_PERM; 002912 goto parse_uri_out; 002913 } 002914 flags = (flags & ~mask) | mode; 002915 } 002916 } 002917 002918 zOpt = &zVal[nVal+1]; 002919 } 002920 002921 }else{ 002922 zFile = sqlite3_malloc64(nUri+2); 002923 if( !zFile ) return SQLITE_NOMEM_BKPT; 002924 if( nUri ){ 002925 memcpy(zFile, zUri, nUri); 002926 } 002927 zFile[nUri] = '\0'; 002928 zFile[nUri+1] = '\0'; 002929 flags &= ~SQLITE_OPEN_URI; 002930 } 002931 002932 *ppVfs = sqlite3_vfs_find(zVfs); 002933 if( *ppVfs==0 ){ 002934 *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs); 002935 rc = SQLITE_ERROR; 002936 } 002937 parse_uri_out: 002938 if( rc!=SQLITE_OK ){ 002939 sqlite3_free(zFile); 002940 zFile = 0; 002941 } 002942 *pFlags = flags; 002943 *pzFile = zFile; 002944 return rc; 002945 } 002946 002947 #if defined(SQLITE_HAS_CODEC) 002948 /* 002949 ** Process URI filename query parameters relevant to the SQLite Encryption 002950 ** Extension. Return true if any of the relevant query parameters are 002951 ** seen and return false if not. 002952 */ 002953 int sqlite3CodecQueryParameters( 002954 sqlite3 *db, /* Database connection */ 002955 const char *zDb, /* Which schema is being created/attached */ 002956 const char *zUri /* URI filename */ 002957 ){ 002958 const char *zKey; 002959 if( (zKey = sqlite3_uri_parameter(zUri, "hexkey"))!=0 && zKey[0] ){ 002960 u8 iByte; 002961 int i; 002962 char zDecoded[40]; 002963 for(i=0, iByte=0; i<sizeof(zDecoded)*2 && sqlite3Isxdigit(zKey[i]); i++){ 002964 iByte = (iByte<<4) + sqlite3HexToInt(zKey[i]); 002965 if( (i&1)!=0 ) zDecoded[i/2] = iByte; 002966 } 002967 sqlite3_key_v2(db, zDb, zDecoded, i/2); 002968 return 1; 002969 }else if( (zKey = sqlite3_uri_parameter(zUri, "key"))!=0 ){ 002970 sqlite3_key_v2(db, zDb, zKey, sqlite3Strlen30(zKey)); 002971 return 1; 002972 }else if( (zKey = sqlite3_uri_parameter(zUri, "textkey"))!=0 ){ 002973 sqlite3_key_v2(db, zDb, zKey, -1); 002974 return 1; 002975 }else{ 002976 return 0; 002977 } 002978 } 002979 #endif 002980 002981 002982 /* 002983 ** This routine does the work of opening a database on behalf of 002984 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename" 002985 ** is UTF-8 encoded. 002986 */ 002987 static int openDatabase( 002988 const char *zFilename, /* Database filename UTF-8 encoded */ 002989 sqlite3 **ppDb, /* OUT: Returned database handle */ 002990 unsigned int flags, /* Operational flags */ 002991 const char *zVfs /* Name of the VFS to use */ 002992 ){ 002993 sqlite3 *db; /* Store allocated handle here */ 002994 int rc; /* Return code */ 002995 int isThreadsafe; /* True for threadsafe connections */ 002996 char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */ 002997 char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */ 002998 002999 #ifdef SQLITE_ENABLE_API_ARMOR 003000 if( ppDb==0 ) return SQLITE_MISUSE_BKPT; 003001 #endif 003002 *ppDb = 0; 003003 #ifndef SQLITE_OMIT_AUTOINIT 003004 rc = sqlite3_initialize(); 003005 if( rc ) return rc; 003006 #endif 003007 003008 if( sqlite3GlobalConfig.bCoreMutex==0 ){ 003009 isThreadsafe = 0; 003010 }else if( flags & SQLITE_OPEN_NOMUTEX ){ 003011 isThreadsafe = 0; 003012 }else if( flags & SQLITE_OPEN_FULLMUTEX ){ 003013 isThreadsafe = 1; 003014 }else{ 003015 isThreadsafe = sqlite3GlobalConfig.bFullMutex; 003016 } 003017 003018 if( flags & SQLITE_OPEN_PRIVATECACHE ){ 003019 flags &= ~SQLITE_OPEN_SHAREDCACHE; 003020 }else if( sqlite3GlobalConfig.sharedCacheEnabled ){ 003021 flags |= SQLITE_OPEN_SHAREDCACHE; 003022 } 003023 003024 /* Remove harmful bits from the flags parameter 003025 ** 003026 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were 003027 ** dealt with in the previous code block. Besides these, the only 003028 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY, 003029 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE, 003030 ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask 003031 ** off all other flags. 003032 */ 003033 flags &= ~( SQLITE_OPEN_DELETEONCLOSE | 003034 SQLITE_OPEN_EXCLUSIVE | 003035 SQLITE_OPEN_MAIN_DB | 003036 SQLITE_OPEN_TEMP_DB | 003037 SQLITE_OPEN_TRANSIENT_DB | 003038 SQLITE_OPEN_MAIN_JOURNAL | 003039 SQLITE_OPEN_TEMP_JOURNAL | 003040 SQLITE_OPEN_SUBJOURNAL | 003041 SQLITE_OPEN_MASTER_JOURNAL | 003042 SQLITE_OPEN_NOMUTEX | 003043 SQLITE_OPEN_FULLMUTEX | 003044 SQLITE_OPEN_WAL 003045 ); 003046 003047 /* Allocate the sqlite data structure */ 003048 db = sqlite3MallocZero( sizeof(sqlite3) ); 003049 if( db==0 ) goto opendb_out; 003050 if( isThreadsafe 003051 #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS 003052 || sqlite3GlobalConfig.bCoreMutex 003053 #endif 003054 ){ 003055 db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); 003056 if( db->mutex==0 ){ 003057 sqlite3_free(db); 003058 db = 0; 003059 goto opendb_out; 003060 } 003061 if( isThreadsafe==0 ){ 003062 sqlite3MutexWarnOnContention(db->mutex); 003063 } 003064 } 003065 sqlite3_mutex_enter(db->mutex); 003066 db->errMask = 0xff; 003067 db->nDb = 2; 003068 db->magic = SQLITE_MAGIC_BUSY; 003069 db->aDb = db->aDbStatic; 003070 db->lookaside.bDisable = 1; 003071 db->lookaside.sz = 0; 003072 003073 assert( sizeof(db->aLimit)==sizeof(aHardLimit) ); 003074 memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit)); 003075 db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS; 003076 db->autoCommit = 1; 003077 db->nextAutovac = -1; 003078 db->szMmap = sqlite3GlobalConfig.szMmap; 003079 db->nextPagesize = 0; 003080 db->nMaxSorterMmap = 0x7FFFFFFF; 003081 db->flags |= SQLITE_ShortColNames 003082 | SQLITE_EnableTrigger 003083 | SQLITE_EnableView 003084 | SQLITE_CacheSpill 003085 003086 /* The SQLITE_DQS compile-time option determines the default settings 003087 ** for SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML. 003088 ** 003089 ** SQLITE_DQS SQLITE_DBCONFIG_DQS_DDL SQLITE_DBCONFIG_DQS_DML 003090 ** ---------- ----------------------- ----------------------- 003091 ** undefined on on 003092 ** 3 on on 003093 ** 2 on off 003094 ** 1 off on 003095 ** 0 off off 003096 ** 003097 ** Legacy behavior is 3 (double-quoted string literals are allowed anywhere) 003098 ** and so that is the default. But developers are encouranged to use 003099 ** -DSQLITE_DQS=0 (best) or -DSQLITE_DQS=1 (second choice) if possible. 003100 */ 003101 #if !defined(SQLITE_DQS) 003102 # define SQLITE_DQS 3 003103 #endif 003104 #if (SQLITE_DQS&1)==1 003105 | SQLITE_DqsDML 003106 #endif 003107 #if (SQLITE_DQS&2)==2 003108 | SQLITE_DqsDDL 003109 #endif 003110 003111 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX 003112 | SQLITE_AutoIndex 003113 #endif 003114 #if SQLITE_DEFAULT_CKPTFULLFSYNC 003115 | SQLITE_CkptFullFSync 003116 #endif 003117 #if SQLITE_DEFAULT_FILE_FORMAT<4 003118 | SQLITE_LegacyFileFmt 003119 #endif 003120 #ifdef SQLITE_ENABLE_LOAD_EXTENSION 003121 | SQLITE_LoadExtension 003122 #endif 003123 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS 003124 | SQLITE_RecTriggers 003125 #endif 003126 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS 003127 | SQLITE_ForeignKeys 003128 #endif 003129 #if defined(SQLITE_REVERSE_UNORDERED_SELECTS) 003130 | SQLITE_ReverseOrder 003131 #endif 003132 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK) 003133 | SQLITE_CellSizeCk 003134 #endif 003135 #if defined(SQLITE_ENABLE_FTS3_TOKENIZER) 003136 | SQLITE_Fts3Tokenizer 003137 #endif 003138 #if defined(SQLITE_ENABLE_QPSG) 003139 | SQLITE_EnableQPSG 003140 #endif 003141 #if defined(SQLITE_DEFAULT_DEFENSIVE) 003142 | SQLITE_Defensive 003143 #endif 003144 ; 003145 sqlite3HashInit(&db->aCollSeq); 003146 #ifndef SQLITE_OMIT_VIRTUALTABLE 003147 sqlite3HashInit(&db->aModule); 003148 #endif 003149 003150 /* Add the default collation sequence BINARY. BINARY works for both UTF-8 003151 ** and UTF-16, so add a version for each to avoid any unnecessary 003152 ** conversions. The only error that can occur here is a malloc() failure. 003153 ** 003154 ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating 003155 ** functions: 003156 */ 003157 createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0); 003158 createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0); 003159 createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0); 003160 createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0); 003161 createCollation(db, "RTRIM", SQLITE_UTF8, 0, rtrimCollFunc, 0); 003162 if( db->mallocFailed ){ 003163 goto opendb_out; 003164 } 003165 /* EVIDENCE-OF: R-08308-17224 The default collating function for all 003166 ** strings is BINARY. 003167 */ 003168 db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0); 003169 assert( db->pDfltColl!=0 ); 003170 003171 /* Parse the filename/URI argument 003172 ** 003173 ** Only allow sensible combinations of bits in the flags argument. 003174 ** Throw an error if any non-sense combination is used. If we 003175 ** do not block illegal combinations here, it could trigger 003176 ** assert() statements in deeper layers. Sensible combinations 003177 ** are: 003178 ** 003179 ** 1: SQLITE_OPEN_READONLY 003180 ** 2: SQLITE_OPEN_READWRITE 003181 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE 003182 */ 003183 db->openFlags = flags; 003184 assert( SQLITE_OPEN_READONLY == 0x01 ); 003185 assert( SQLITE_OPEN_READWRITE == 0x02 ); 003186 assert( SQLITE_OPEN_CREATE == 0x04 ); 003187 testcase( (1<<(flags&7))==0x02 ); /* READONLY */ 003188 testcase( (1<<(flags&7))==0x04 ); /* READWRITE */ 003189 testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */ 003190 if( ((1<<(flags&7)) & 0x46)==0 ){ 003191 rc = SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */ 003192 }else{ 003193 rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg); 003194 } 003195 if( rc!=SQLITE_OK ){ 003196 if( rc==SQLITE_NOMEM ) sqlite3OomFault(db); 003197 sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg); 003198 sqlite3_free(zErrMsg); 003199 goto opendb_out; 003200 } 003201 003202 /* Open the backend database driver */ 003203 rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0, 003204 flags | SQLITE_OPEN_MAIN_DB); 003205 if( rc!=SQLITE_OK ){ 003206 if( rc==SQLITE_IOERR_NOMEM ){ 003207 rc = SQLITE_NOMEM_BKPT; 003208 } 003209 sqlite3Error(db, rc); 003210 goto opendb_out; 003211 } 003212 sqlite3BtreeEnter(db->aDb[0].pBt); 003213 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt); 003214 if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db); 003215 sqlite3BtreeLeave(db->aDb[0].pBt); 003216 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0); 003217 003218 /* The default safety_level for the main database is FULL; for the temp 003219 ** database it is OFF. This matches the pager layer defaults. 003220 */ 003221 db->aDb[0].zDbSName = "main"; 003222 db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1; 003223 db->aDb[1].zDbSName = "temp"; 003224 db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF; 003225 003226 db->magic = SQLITE_MAGIC_OPEN; 003227 if( db->mallocFailed ){ 003228 goto opendb_out; 003229 } 003230 003231 /* Register all built-in functions, but do not attempt to read the 003232 ** database schema yet. This is delayed until the first time the database 003233 ** is accessed. 003234 */ 003235 sqlite3Error(db, SQLITE_OK); 003236 sqlite3RegisterPerConnectionBuiltinFunctions(db); 003237 rc = sqlite3_errcode(db); 003238 003239 #ifdef SQLITE_ENABLE_FTS5 003240 /* Register any built-in FTS5 module before loading the automatic 003241 ** extensions. This allows automatic extensions to register FTS5 003242 ** tokenizers and auxiliary functions. */ 003243 if( !db->mallocFailed && rc==SQLITE_OK ){ 003244 rc = sqlite3Fts5Init(db); 003245 } 003246 #endif 003247 003248 /* Load automatic extensions - extensions that have been registered 003249 ** using the sqlite3_automatic_extension() API. 003250 */ 003251 if( rc==SQLITE_OK ){ 003252 sqlite3AutoLoadExtensions(db); 003253 rc = sqlite3_errcode(db); 003254 if( rc!=SQLITE_OK ){ 003255 goto opendb_out; 003256 } 003257 } 003258 003259 #ifdef SQLITE_ENABLE_FTS1 003260 if( !db->mallocFailed ){ 003261 extern int sqlite3Fts1Init(sqlite3*); 003262 rc = sqlite3Fts1Init(db); 003263 } 003264 #endif 003265 003266 #ifdef SQLITE_ENABLE_FTS2 003267 if( !db->mallocFailed && rc==SQLITE_OK ){ 003268 extern int sqlite3Fts2Init(sqlite3*); 003269 rc = sqlite3Fts2Init(db); 003270 } 003271 #endif 003272 003273 #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */ 003274 if( !db->mallocFailed && rc==SQLITE_OK ){ 003275 rc = sqlite3Fts3Init(db); 003276 } 003277 #endif 003278 003279 #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS) 003280 if( !db->mallocFailed && rc==SQLITE_OK ){ 003281 rc = sqlite3IcuInit(db); 003282 } 003283 #endif 003284 003285 #ifdef SQLITE_ENABLE_RTREE 003286 if( !db->mallocFailed && rc==SQLITE_OK){ 003287 rc = sqlite3RtreeInit(db); 003288 } 003289 #endif 003290 003291 #ifdef SQLITE_ENABLE_DBPAGE_VTAB 003292 if( !db->mallocFailed && rc==SQLITE_OK){ 003293 rc = sqlite3DbpageRegister(db); 003294 } 003295 #endif 003296 003297 #ifdef SQLITE_ENABLE_DBSTAT_VTAB 003298 if( !db->mallocFailed && rc==SQLITE_OK){ 003299 rc = sqlite3DbstatRegister(db); 003300 } 003301 #endif 003302 003303 #ifdef SQLITE_ENABLE_JSON1 003304 if( !db->mallocFailed && rc==SQLITE_OK){ 003305 rc = sqlite3Json1Init(db); 003306 } 003307 #endif 003308 003309 #ifdef SQLITE_ENABLE_STMTVTAB 003310 if( !db->mallocFailed && rc==SQLITE_OK){ 003311 rc = sqlite3StmtVtabInit(db); 003312 } 003313 #endif 003314 003315 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking 003316 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking 003317 ** mode. Doing nothing at all also makes NORMAL the default. 003318 */ 003319 #ifdef SQLITE_DEFAULT_LOCKING_MODE 003320 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE; 003321 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt), 003322 SQLITE_DEFAULT_LOCKING_MODE); 003323 #endif 003324 003325 if( rc ) sqlite3Error(db, rc); 003326 003327 /* Enable the lookaside-malloc subsystem */ 003328 setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside, 003329 sqlite3GlobalConfig.nLookaside); 003330 003331 sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT); 003332 003333 opendb_out: 003334 if( db ){ 003335 assert( db->mutex!=0 || isThreadsafe==0 003336 || sqlite3GlobalConfig.bFullMutex==0 ); 003337 sqlite3_mutex_leave(db->mutex); 003338 } 003339 rc = sqlite3_errcode(db); 003340 assert( db!=0 || rc==SQLITE_NOMEM ); 003341 if( rc==SQLITE_NOMEM ){ 003342 sqlite3_close(db); 003343 db = 0; 003344 }else if( rc!=SQLITE_OK ){ 003345 db->magic = SQLITE_MAGIC_SICK; 003346 } 003347 *ppDb = db; 003348 #ifdef SQLITE_ENABLE_SQLLOG 003349 if( sqlite3GlobalConfig.xSqllog ){ 003350 /* Opening a db handle. Fourth parameter is passed 0. */ 003351 void *pArg = sqlite3GlobalConfig.pSqllogArg; 003352 sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0); 003353 } 003354 #endif 003355 #if defined(SQLITE_HAS_CODEC) 003356 if( rc==SQLITE_OK ) sqlite3CodecQueryParameters(db, 0, zOpen); 003357 #endif 003358 sqlite3_free(zOpen); 003359 return rc & 0xff; 003360 } 003361 003362 003363 /* 003364 ** Open a new database handle. 003365 */ 003366 int sqlite3_open( 003367 const char *zFilename, 003368 sqlite3 **ppDb 003369 ){ 003370 return openDatabase(zFilename, ppDb, 003371 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); 003372 } 003373 int sqlite3_open_v2( 003374 const char *filename, /* Database filename (UTF-8) */ 003375 sqlite3 **ppDb, /* OUT: SQLite db handle */ 003376 int flags, /* Flags */ 003377 const char *zVfs /* Name of VFS module to use */ 003378 ){ 003379 return openDatabase(filename, ppDb, (unsigned int)flags, zVfs); 003380 } 003381 003382 #ifndef SQLITE_OMIT_UTF16 003383 /* 003384 ** Open a new database handle. 003385 */ 003386 int sqlite3_open16( 003387 const void *zFilename, 003388 sqlite3 **ppDb 003389 ){ 003390 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */ 003391 sqlite3_value *pVal; 003392 int rc; 003393 003394 #ifdef SQLITE_ENABLE_API_ARMOR 003395 if( ppDb==0 ) return SQLITE_MISUSE_BKPT; 003396 #endif 003397 *ppDb = 0; 003398 #ifndef SQLITE_OMIT_AUTOINIT 003399 rc = sqlite3_initialize(); 003400 if( rc ) return rc; 003401 #endif 003402 if( zFilename==0 ) zFilename = "\000\000"; 003403 pVal = sqlite3ValueNew(0); 003404 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC); 003405 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8); 003406 if( zFilename8 ){ 003407 rc = openDatabase(zFilename8, ppDb, 003408 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); 003409 assert( *ppDb || rc==SQLITE_NOMEM ); 003410 if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){ 003411 SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE; 003412 } 003413 }else{ 003414 rc = SQLITE_NOMEM_BKPT; 003415 } 003416 sqlite3ValueFree(pVal); 003417 003418 return rc & 0xff; 003419 } 003420 #endif /* SQLITE_OMIT_UTF16 */ 003421 003422 /* 003423 ** Register a new collation sequence with the database handle db. 003424 */ 003425 int sqlite3_create_collation( 003426 sqlite3* db, 003427 const char *zName, 003428 int enc, 003429 void* pCtx, 003430 int(*xCompare)(void*,int,const void*,int,const void*) 003431 ){ 003432 return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0); 003433 } 003434 003435 /* 003436 ** Register a new collation sequence with the database handle db. 003437 */ 003438 int sqlite3_create_collation_v2( 003439 sqlite3* db, 003440 const char *zName, 003441 int enc, 003442 void* pCtx, 003443 int(*xCompare)(void*,int,const void*,int,const void*), 003444 void(*xDel)(void*) 003445 ){ 003446 int rc; 003447 003448 #ifdef SQLITE_ENABLE_API_ARMOR 003449 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; 003450 #endif 003451 sqlite3_mutex_enter(db->mutex); 003452 assert( !db->mallocFailed ); 003453 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel); 003454 rc = sqlite3ApiExit(db, rc); 003455 sqlite3_mutex_leave(db->mutex); 003456 return rc; 003457 } 003458 003459 #ifndef SQLITE_OMIT_UTF16 003460 /* 003461 ** Register a new collation sequence with the database handle db. 003462 */ 003463 int sqlite3_create_collation16( 003464 sqlite3* db, 003465 const void *zName, 003466 int enc, 003467 void* pCtx, 003468 int(*xCompare)(void*,int,const void*,int,const void*) 003469 ){ 003470 int rc = SQLITE_OK; 003471 char *zName8; 003472 003473 #ifdef SQLITE_ENABLE_API_ARMOR 003474 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; 003475 #endif 003476 sqlite3_mutex_enter(db->mutex); 003477 assert( !db->mallocFailed ); 003478 zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE); 003479 if( zName8 ){ 003480 rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0); 003481 sqlite3DbFree(db, zName8); 003482 } 003483 rc = sqlite3ApiExit(db, rc); 003484 sqlite3_mutex_leave(db->mutex); 003485 return rc; 003486 } 003487 #endif /* SQLITE_OMIT_UTF16 */ 003488 003489 /* 003490 ** Register a collation sequence factory callback with the database handle 003491 ** db. Replace any previously installed collation sequence factory. 003492 */ 003493 int sqlite3_collation_needed( 003494 sqlite3 *db, 003495 void *pCollNeededArg, 003496 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*) 003497 ){ 003498 #ifdef SQLITE_ENABLE_API_ARMOR 003499 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; 003500 #endif 003501 sqlite3_mutex_enter(db->mutex); 003502 db->xCollNeeded = xCollNeeded; 003503 db->xCollNeeded16 = 0; 003504 db->pCollNeededArg = pCollNeededArg; 003505 sqlite3_mutex_leave(db->mutex); 003506 return SQLITE_OK; 003507 } 003508 003509 #ifndef SQLITE_OMIT_UTF16 003510 /* 003511 ** Register a collation sequence factory callback with the database handle 003512 ** db. Replace any previously installed collation sequence factory. 003513 */ 003514 int sqlite3_collation_needed16( 003515 sqlite3 *db, 003516 void *pCollNeededArg, 003517 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*) 003518 ){ 003519 #ifdef SQLITE_ENABLE_API_ARMOR 003520 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; 003521 #endif 003522 sqlite3_mutex_enter(db->mutex); 003523 db->xCollNeeded = 0; 003524 db->xCollNeeded16 = xCollNeeded16; 003525 db->pCollNeededArg = pCollNeededArg; 003526 sqlite3_mutex_leave(db->mutex); 003527 return SQLITE_OK; 003528 } 003529 #endif /* SQLITE_OMIT_UTF16 */ 003530 003531 #ifndef SQLITE_OMIT_DEPRECATED 003532 /* 003533 ** This function is now an anachronism. It used to be used to recover from a 003534 ** malloc() failure, but SQLite now does this automatically. 003535 */ 003536 int sqlite3_global_recover(void){ 003537 return SQLITE_OK; 003538 } 003539 #endif 003540 003541 /* 003542 ** Test to see whether or not the database connection is in autocommit 003543 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on 003544 ** by default. Autocommit is disabled by a BEGIN statement and reenabled 003545 ** by the next COMMIT or ROLLBACK. 003546 */ 003547 int sqlite3_get_autocommit(sqlite3 *db){ 003548 #ifdef SQLITE_ENABLE_API_ARMOR 003549 if( !sqlite3SafetyCheckOk(db) ){ 003550 (void)SQLITE_MISUSE_BKPT; 003551 return 0; 003552 } 003553 #endif 003554 return db->autoCommit; 003555 } 003556 003557 /* 003558 ** The following routines are substitutes for constants SQLITE_CORRUPT, 003559 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error 003560 ** constants. They serve two purposes: 003561 ** 003562 ** 1. Serve as a convenient place to set a breakpoint in a debugger 003563 ** to detect when version error conditions occurs. 003564 ** 003565 ** 2. Invoke sqlite3_log() to provide the source code location where 003566 ** a low-level error is first detected. 003567 */ 003568 int sqlite3ReportError(int iErr, int lineno, const char *zType){ 003569 sqlite3_log(iErr, "%s at line %d of [%.10s]", 003570 zType, lineno, 20+sqlite3_sourceid()); 003571 return iErr; 003572 } 003573 int sqlite3CorruptError(int lineno){ 003574 testcase( sqlite3GlobalConfig.xLog!=0 ); 003575 return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption"); 003576 } 003577 int sqlite3MisuseError(int lineno){ 003578 testcase( sqlite3GlobalConfig.xLog!=0 ); 003579 return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse"); 003580 } 003581 int sqlite3CantopenError(int lineno){ 003582 testcase( sqlite3GlobalConfig.xLog!=0 ); 003583 return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file"); 003584 } 003585 #ifdef SQLITE_DEBUG 003586 int sqlite3CorruptPgnoError(int lineno, Pgno pgno){ 003587 char zMsg[100]; 003588 sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno); 003589 testcase( sqlite3GlobalConfig.xLog!=0 ); 003590 return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg); 003591 } 003592 int sqlite3NomemError(int lineno){ 003593 testcase( sqlite3GlobalConfig.xLog!=0 ); 003594 return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM"); 003595 } 003596 int sqlite3IoerrnomemError(int lineno){ 003597 testcase( sqlite3GlobalConfig.xLog!=0 ); 003598 return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error"); 003599 } 003600 #endif 003601 003602 #ifndef SQLITE_OMIT_DEPRECATED 003603 /* 003604 ** This is a convenience routine that makes sure that all thread-specific 003605 ** data for this thread has been deallocated. 003606 ** 003607 ** SQLite no longer uses thread-specific data so this routine is now a 003608 ** no-op. It is retained for historical compatibility. 003609 */ 003610 void sqlite3_thread_cleanup(void){ 003611 } 003612 #endif 003613 003614 /* 003615 ** Return meta information about a specific column of a database table. 003616 ** See comment in sqlite3.h (sqlite.h.in) for details. 003617 */ 003618 int sqlite3_table_column_metadata( 003619 sqlite3 *db, /* Connection handle */ 003620 const char *zDbName, /* Database name or NULL */ 003621 const char *zTableName, /* Table name */ 003622 const char *zColumnName, /* Column name */ 003623 char const **pzDataType, /* OUTPUT: Declared data type */ 003624 char const **pzCollSeq, /* OUTPUT: Collation sequence name */ 003625 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ 003626 int *pPrimaryKey, /* OUTPUT: True if column part of PK */ 003627 int *pAutoinc /* OUTPUT: True if column is auto-increment */ 003628 ){ 003629 int rc; 003630 char *zErrMsg = 0; 003631 Table *pTab = 0; 003632 Column *pCol = 0; 003633 int iCol = 0; 003634 char const *zDataType = 0; 003635 char const *zCollSeq = 0; 003636 int notnull = 0; 003637 int primarykey = 0; 003638 int autoinc = 0; 003639 003640 003641 #ifdef SQLITE_ENABLE_API_ARMOR 003642 if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){ 003643 return SQLITE_MISUSE_BKPT; 003644 } 003645 #endif 003646 003647 /* Ensure the database schema has been loaded */ 003648 sqlite3_mutex_enter(db->mutex); 003649 sqlite3BtreeEnterAll(db); 003650 rc = sqlite3Init(db, &zErrMsg); 003651 if( SQLITE_OK!=rc ){ 003652 goto error_out; 003653 } 003654 003655 /* Locate the table in question */ 003656 pTab = sqlite3FindTable(db, zTableName, zDbName); 003657 if( !pTab || pTab->pSelect ){ 003658 pTab = 0; 003659 goto error_out; 003660 } 003661 003662 /* Find the column for which info is requested */ 003663 if( zColumnName==0 ){ 003664 /* Query for existance of table only */ 003665 }else{ 003666 for(iCol=0; iCol<pTab->nCol; iCol++){ 003667 pCol = &pTab->aCol[iCol]; 003668 if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){ 003669 break; 003670 } 003671 } 003672 if( iCol==pTab->nCol ){ 003673 if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){ 003674 iCol = pTab->iPKey; 003675 pCol = iCol>=0 ? &pTab->aCol[iCol] : 0; 003676 }else{ 003677 pTab = 0; 003678 goto error_out; 003679 } 003680 } 003681 } 003682 003683 /* The following block stores the meta information that will be returned 003684 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey 003685 ** and autoinc. At this point there are two possibilities: 003686 ** 003687 ** 1. The specified column name was rowid", "oid" or "_rowid_" 003688 ** and there is no explicitly declared IPK column. 003689 ** 003690 ** 2. The table is not a view and the column name identified an 003691 ** explicitly declared column. Copy meta information from *pCol. 003692 */ 003693 if( pCol ){ 003694 zDataType = sqlite3ColumnType(pCol,0); 003695 zCollSeq = pCol->zColl; 003696 notnull = pCol->notNull!=0; 003697 primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0; 003698 autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0; 003699 }else{ 003700 zDataType = "INTEGER"; 003701 primarykey = 1; 003702 } 003703 if( !zCollSeq ){ 003704 zCollSeq = sqlite3StrBINARY; 003705 } 003706 003707 error_out: 003708 sqlite3BtreeLeaveAll(db); 003709 003710 /* Whether the function call succeeded or failed, set the output parameters 003711 ** to whatever their local counterparts contain. If an error did occur, 003712 ** this has the effect of zeroing all output parameters. 003713 */ 003714 if( pzDataType ) *pzDataType = zDataType; 003715 if( pzCollSeq ) *pzCollSeq = zCollSeq; 003716 if( pNotNull ) *pNotNull = notnull; 003717 if( pPrimaryKey ) *pPrimaryKey = primarykey; 003718 if( pAutoinc ) *pAutoinc = autoinc; 003719 003720 if( SQLITE_OK==rc && !pTab ){ 003721 sqlite3DbFree(db, zErrMsg); 003722 zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName, 003723 zColumnName); 003724 rc = SQLITE_ERROR; 003725 } 003726 sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg); 003727 sqlite3DbFree(db, zErrMsg); 003728 rc = sqlite3ApiExit(db, rc); 003729 sqlite3_mutex_leave(db->mutex); 003730 return rc; 003731 } 003732 003733 /* 003734 ** Sleep for a little while. Return the amount of time slept. 003735 */ 003736 int sqlite3_sleep(int ms){ 003737 sqlite3_vfs *pVfs; 003738 int rc; 003739 pVfs = sqlite3_vfs_find(0); 003740 if( pVfs==0 ) return 0; 003741 003742 /* This function works in milliseconds, but the underlying OsSleep() 003743 ** API uses microseconds. Hence the 1000's. 003744 */ 003745 rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000); 003746 return rc; 003747 } 003748 003749 /* 003750 ** Enable or disable the extended result codes. 003751 */ 003752 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){ 003753 #ifdef SQLITE_ENABLE_API_ARMOR 003754 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; 003755 #endif 003756 sqlite3_mutex_enter(db->mutex); 003757 db->errMask = onoff ? 0xffffffff : 0xff; 003758 sqlite3_mutex_leave(db->mutex); 003759 return SQLITE_OK; 003760 } 003761 003762 /* 003763 ** Invoke the xFileControl method on a particular database. 003764 */ 003765 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){ 003766 int rc = SQLITE_ERROR; 003767 Btree *pBtree; 003768 003769 #ifdef SQLITE_ENABLE_API_ARMOR 003770 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; 003771 #endif 003772 sqlite3_mutex_enter(db->mutex); 003773 pBtree = sqlite3DbNameToBtree(db, zDbName); 003774 if( pBtree ){ 003775 Pager *pPager; 003776 sqlite3_file *fd; 003777 sqlite3BtreeEnter(pBtree); 003778 pPager = sqlite3BtreePager(pBtree); 003779 assert( pPager!=0 ); 003780 fd = sqlite3PagerFile(pPager); 003781 assert( fd!=0 ); 003782 if( op==SQLITE_FCNTL_FILE_POINTER ){ 003783 *(sqlite3_file**)pArg = fd; 003784 rc = SQLITE_OK; 003785 }else if( op==SQLITE_FCNTL_VFS_POINTER ){ 003786 *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager); 003787 rc = SQLITE_OK; 003788 }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){ 003789 *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager); 003790 rc = SQLITE_OK; 003791 }else if( op==SQLITE_FCNTL_DATA_VERSION ){ 003792 *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager); 003793 rc = SQLITE_OK; 003794 }else{ 003795 rc = sqlite3OsFileControl(fd, op, pArg); 003796 } 003797 sqlite3BtreeLeave(pBtree); 003798 } 003799 sqlite3_mutex_leave(db->mutex); 003800 return rc; 003801 } 003802 003803 /* 003804 ** Interface to the testing logic. 003805 */ 003806 int sqlite3_test_control(int op, ...){ 003807 int rc = 0; 003808 #ifdef SQLITE_UNTESTABLE 003809 UNUSED_PARAMETER(op); 003810 #else 003811 va_list ap; 003812 va_start(ap, op); 003813 switch( op ){ 003814 003815 /* 003816 ** Save the current state of the PRNG. 003817 */ 003818 case SQLITE_TESTCTRL_PRNG_SAVE: { 003819 sqlite3PrngSaveState(); 003820 break; 003821 } 003822 003823 /* 003824 ** Restore the state of the PRNG to the last state saved using 003825 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then 003826 ** this verb acts like PRNG_RESET. 003827 */ 003828 case SQLITE_TESTCTRL_PRNG_RESTORE: { 003829 sqlite3PrngRestoreState(); 003830 break; 003831 } 003832 003833 /* sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, int x, sqlite3 *db); 003834 ** 003835 ** Control the seed for the pseudo-random number generator (PRNG) that 003836 ** is built into SQLite. Cases: 003837 ** 003838 ** x!=0 && db!=0 Seed the PRNG to the current value of the 003839 ** schema cookie in the main database for db, or 003840 ** x if the schema cookie is zero. This case 003841 ** is convenient to use with database fuzzers 003842 ** as it allows the fuzzer some control over the 003843 ** the PRNG seed. 003844 ** 003845 ** x!=0 && db==0 Seed the PRNG to the value of x. 003846 ** 003847 ** x==0 && db==0 Revert to default behavior of using the 003848 ** xRandomness method on the primary VFS. 003849 ** 003850 ** This test-control also resets the PRNG so that the new seed will 003851 ** be used for the next call to sqlite3_randomness(). 003852 */ 003853 case SQLITE_TESTCTRL_PRNG_SEED: { 003854 int x = va_arg(ap, int); 003855 int y; 003856 sqlite3 *db = va_arg(ap, sqlite3*); 003857 assert( db==0 || db->aDb[0].pSchema!=0 ); 003858 if( db && (y = db->aDb[0].pSchema->schema_cookie)!=0 ){ x = y; } 003859 sqlite3Config.iPrngSeed = x; 003860 sqlite3_randomness(0,0); 003861 break; 003862 } 003863 003864 /* 003865 ** sqlite3_test_control(BITVEC_TEST, size, program) 003866 ** 003867 ** Run a test against a Bitvec object of size. The program argument 003868 ** is an array of integers that defines the test. Return -1 on a 003869 ** memory allocation error, 0 on success, or non-zero for an error. 003870 ** See the sqlite3BitvecBuiltinTest() for additional information. 003871 */ 003872 case SQLITE_TESTCTRL_BITVEC_TEST: { 003873 int sz = va_arg(ap, int); 003874 int *aProg = va_arg(ap, int*); 003875 rc = sqlite3BitvecBuiltinTest(sz, aProg); 003876 break; 003877 } 003878 003879 /* 003880 ** sqlite3_test_control(FAULT_INSTALL, xCallback) 003881 ** 003882 ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called, 003883 ** if xCallback is not NULL. 003884 ** 003885 ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0) 003886 ** is called immediately after installing the new callback and the return 003887 ** value from sqlite3FaultSim(0) becomes the return from 003888 ** sqlite3_test_control(). 003889 */ 003890 case SQLITE_TESTCTRL_FAULT_INSTALL: { 003891 /* MSVC is picky about pulling func ptrs from va lists. 003892 ** http://support.microsoft.com/kb/47961 003893 ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int)); 003894 */ 003895 typedef int(*TESTCALLBACKFUNC_t)(int); 003896 sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t); 003897 rc = sqlite3FaultSim(0); 003898 break; 003899 } 003900 003901 /* 003902 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd) 003903 ** 003904 ** Register hooks to call to indicate which malloc() failures 003905 ** are benign. 003906 */ 003907 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: { 003908 typedef void (*void_function)(void); 003909 void_function xBenignBegin; 003910 void_function xBenignEnd; 003911 xBenignBegin = va_arg(ap, void_function); 003912 xBenignEnd = va_arg(ap, void_function); 003913 sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd); 003914 break; 003915 } 003916 003917 /* 003918 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X) 003919 ** 003920 ** Set the PENDING byte to the value in the argument, if X>0. 003921 ** Make no changes if X==0. Return the value of the pending byte 003922 ** as it existing before this routine was called. 003923 ** 003924 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in 003925 ** an incompatible database file format. Changing the PENDING byte 003926 ** while any database connection is open results in undefined and 003927 ** deleterious behavior. 003928 */ 003929 case SQLITE_TESTCTRL_PENDING_BYTE: { 003930 rc = PENDING_BYTE; 003931 #ifndef SQLITE_OMIT_WSD 003932 { 003933 unsigned int newVal = va_arg(ap, unsigned int); 003934 if( newVal ) sqlite3PendingByte = newVal; 003935 } 003936 #endif 003937 break; 003938 } 003939 003940 /* 003941 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X) 003942 ** 003943 ** This action provides a run-time test to see whether or not 003944 ** assert() was enabled at compile-time. If X is true and assert() 003945 ** is enabled, then the return value is true. If X is true and 003946 ** assert() is disabled, then the return value is zero. If X is 003947 ** false and assert() is enabled, then the assertion fires and the 003948 ** process aborts. If X is false and assert() is disabled, then the 003949 ** return value is zero. 003950 */ 003951 case SQLITE_TESTCTRL_ASSERT: { 003952 volatile int x = 0; 003953 assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 ); 003954 rc = x; 003955 break; 003956 } 003957 003958 003959 /* 003960 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X) 003961 ** 003962 ** This action provides a run-time test to see how the ALWAYS and 003963 ** NEVER macros were defined at compile-time. 003964 ** 003965 ** The return value is ALWAYS(X) if X is true, or 0 if X is false. 003966 ** 003967 ** The recommended test is X==2. If the return value is 2, that means 003968 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the 003969 ** default setting. If the return value is 1, then ALWAYS() is either 003970 ** hard-coded to true or else it asserts if its argument is false. 003971 ** The first behavior (hard-coded to true) is the case if 003972 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second 003973 ** behavior (assert if the argument to ALWAYS() is false) is the case if 003974 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled. 003975 ** 003976 ** The run-time test procedure might look something like this: 003977 ** 003978 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){ 003979 ** // ALWAYS() and NEVER() are no-op pass-through macros 003980 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){ 003981 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false. 003982 ** }else{ 003983 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0. 003984 ** } 003985 */ 003986 case SQLITE_TESTCTRL_ALWAYS: { 003987 int x = va_arg(ap,int); 003988 rc = x ? ALWAYS(x) : 0; 003989 break; 003990 } 003991 003992 /* 003993 ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER); 003994 ** 003995 ** The integer returned reveals the byte-order of the computer on which 003996 ** SQLite is running: 003997 ** 003998 ** 1 big-endian, determined at run-time 003999 ** 10 little-endian, determined at run-time 004000 ** 432101 big-endian, determined at compile-time 004001 ** 123410 little-endian, determined at compile-time 004002 */ 004003 case SQLITE_TESTCTRL_BYTEORDER: { 004004 rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN; 004005 break; 004006 } 004007 004008 /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N) 004009 ** 004010 ** Set the nReserve size to N for the main database on the database 004011 ** connection db. 004012 */ 004013 case SQLITE_TESTCTRL_RESERVE: { 004014 sqlite3 *db = va_arg(ap, sqlite3*); 004015 int x = va_arg(ap,int); 004016 sqlite3_mutex_enter(db->mutex); 004017 sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0); 004018 sqlite3_mutex_leave(db->mutex); 004019 break; 004020 } 004021 004022 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N) 004023 ** 004024 ** Enable or disable various optimizations for testing purposes. The 004025 ** argument N is a bitmask of optimizations to be disabled. For normal 004026 ** operation N should be 0. The idea is that a test program (like the 004027 ** SQL Logic Test or SLT test module) can run the same SQL multiple times 004028 ** with various optimizations disabled to verify that the same answer 004029 ** is obtained in every case. 004030 */ 004031 case SQLITE_TESTCTRL_OPTIMIZATIONS: { 004032 sqlite3 *db = va_arg(ap, sqlite3*); 004033 db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff); 004034 break; 004035 } 004036 004037 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff); 004038 ** 004039 ** If parameter onoff is non-zero, subsequent calls to localtime() 004040 ** and its variants fail. If onoff is zero, undo this setting. 004041 */ 004042 case SQLITE_TESTCTRL_LOCALTIME_FAULT: { 004043 sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int); 004044 break; 004045 } 004046 004047 /* sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCS, int onoff); 004048 ** 004049 ** If parameter onoff is non-zero, internal-use-only SQL functions 004050 ** are visible to ordinary SQL. This is useful for testing but is 004051 ** unsafe because invalid parameters to those internal-use-only functions 004052 ** can result in crashes or segfaults. 004053 */ 004054 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: { 004055 sqlite3GlobalConfig.bInternalFunctions = va_arg(ap, int); 004056 break; 004057 } 004058 004059 /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int); 004060 ** 004061 ** Set or clear a flag that indicates that the database file is always well- 004062 ** formed and never corrupt. This flag is clear by default, indicating that 004063 ** database files might have arbitrary corruption. Setting the flag during 004064 ** testing causes certain assert() statements in the code to be activated 004065 ** that demonstrat invariants on well-formed database files. 004066 */ 004067 case SQLITE_TESTCTRL_NEVER_CORRUPT: { 004068 sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int); 004069 break; 004070 } 004071 004072 /* sqlite3_test_control(SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS, int); 004073 ** 004074 ** Set or clear a flag that causes SQLite to verify that type, name, 004075 ** and tbl_name fields of the sqlite_master table. This is normally 004076 ** on, but it is sometimes useful to turn it off for testing. 004077 */ 004078 case SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS: { 004079 sqlite3GlobalConfig.bExtraSchemaChecks = va_arg(ap, int); 004080 break; 004081 } 004082 004083 /* Set the threshold at which OP_Once counters reset back to zero. 004084 ** By default this is 0x7ffffffe (over 2 billion), but that value is 004085 ** too big to test in a reasonable amount of time, so this control is 004086 ** provided to set a small and easily reachable reset value. 004087 */ 004088 case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: { 004089 sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int); 004090 break; 004091 } 004092 004093 /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr); 004094 ** 004095 ** Set the VDBE coverage callback function to xCallback with context 004096 ** pointer ptr. 004097 */ 004098 case SQLITE_TESTCTRL_VDBE_COVERAGE: { 004099 #ifdef SQLITE_VDBE_COVERAGE 004100 typedef void (*branch_callback)(void*,unsigned int, 004101 unsigned char,unsigned char); 004102 sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback); 004103 sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*); 004104 #endif 004105 break; 004106 } 004107 004108 /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */ 004109 case SQLITE_TESTCTRL_SORTER_MMAP: { 004110 sqlite3 *db = va_arg(ap, sqlite3*); 004111 db->nMaxSorterMmap = va_arg(ap, int); 004112 break; 004113 } 004114 004115 /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT); 004116 ** 004117 ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if 004118 ** not. 004119 */ 004120 case SQLITE_TESTCTRL_ISINIT: { 004121 if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR; 004122 break; 004123 } 004124 004125 /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum); 004126 ** 004127 ** This test control is used to create imposter tables. "db" is a pointer 004128 ** to the database connection. dbName is the database name (ex: "main" or 004129 ** "temp") which will receive the imposter. "onOff" turns imposter mode on 004130 ** or off. "tnum" is the root page of the b-tree to which the imposter 004131 ** table should connect. 004132 ** 004133 ** Enable imposter mode only when the schema has already been parsed. Then 004134 ** run a single CREATE TABLE statement to construct the imposter table in 004135 ** the parsed schema. Then turn imposter mode back off again. 004136 ** 004137 ** If onOff==0 and tnum>0 then reset the schema for all databases, causing 004138 ** the schema to be reparsed the next time it is needed. This has the 004139 ** effect of erasing all imposter tables. 004140 */ 004141 case SQLITE_TESTCTRL_IMPOSTER: { 004142 sqlite3 *db = va_arg(ap, sqlite3*); 004143 sqlite3_mutex_enter(db->mutex); 004144 db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*)); 004145 db->init.busy = db->init.imposterTable = va_arg(ap,int); 004146 db->init.newTnum = va_arg(ap,int); 004147 if( db->init.busy==0 && db->init.newTnum>0 ){ 004148 sqlite3ResetAllSchemasOfConnection(db); 004149 } 004150 sqlite3_mutex_leave(db->mutex); 004151 break; 004152 } 004153 004154 #if defined(YYCOVERAGE) 004155 /* sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out) 004156 ** 004157 ** This test control (only available when SQLite is compiled with 004158 ** -DYYCOVERAGE) writes a report onto "out" that shows all 004159 ** state/lookahead combinations in the parser state machine 004160 ** which are never exercised. If any state is missed, make the 004161 ** return code SQLITE_ERROR. 004162 */ 004163 case SQLITE_TESTCTRL_PARSER_COVERAGE: { 004164 FILE *out = va_arg(ap, FILE*); 004165 if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR; 004166 break; 004167 } 004168 #endif /* defined(YYCOVERAGE) */ 004169 004170 /* sqlite3_test_control(SQLITE_TESTCTRL_RESULT_INTREAL, sqlite3_context*); 004171 ** 004172 ** This test-control causes the most recent sqlite3_result_int64() value 004173 ** to be interpreted as a MEM_IntReal instead of as an MEM_Int. Normally, 004174 ** MEM_IntReal values only arise during an INSERT operation of integer 004175 ** values into a REAL column, so they can be challenging to test. This 004176 ** test-control enables us to write an intreal() SQL function that can 004177 ** inject an intreal() value at arbitrary places in an SQL statement, 004178 ** for testing purposes. 004179 */ 004180 case SQLITE_TESTCTRL_RESULT_INTREAL: { 004181 sqlite3_context *pCtx = va_arg(ap, sqlite3_context*); 004182 sqlite3ResultIntReal(pCtx); 004183 break; 004184 } 004185 } 004186 va_end(ap); 004187 #endif /* SQLITE_UNTESTABLE */ 004188 return rc; 004189 } 004190 004191 #ifdef SQLITE_DEBUG 004192 /* 004193 ** This routine appears inside assert() statements only. 004194 ** 004195 ** Return the number of URI parameters that follow the filename. 004196 */ 004197 int sqlite3UriCount(const char *z){ 004198 int n = 0; 004199 if( z==0 ) return 0; 004200 z += strlen(z)+1; 004201 while( z[0] ){ 004202 z += strlen(z)+1; 004203 z += strlen(z)+1; 004204 n++; 004205 } 004206 return n; 004207 } 004208 #endif /* SQLITE_DEBUG */ 004209 004210 /* 004211 ** This is a utility routine, useful to VFS implementations, that checks 004212 ** to see if a database file was a URI that contained a specific query 004213 ** parameter, and if so obtains the value of the query parameter. 004214 ** 004215 ** The zFilename argument is the filename pointer passed into the xOpen() 004216 ** method of a VFS implementation. The zParam argument is the name of the 004217 ** query parameter we seek. This routine returns the value of the zParam 004218 ** parameter if it exists. If the parameter does not exist, this routine 004219 ** returns a NULL pointer. 004220 */ 004221 const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){ 004222 if( zFilename==0 || zParam==0 ) return 0; 004223 zFilename += sqlite3Strlen30(zFilename) + 1; 004224 while( zFilename[0] ){ 004225 int x = strcmp(zFilename, zParam); 004226 zFilename += sqlite3Strlen30(zFilename) + 1; 004227 if( x==0 ) return zFilename; 004228 zFilename += sqlite3Strlen30(zFilename) + 1; 004229 } 004230 return 0; 004231 } 004232 004233 /* 004234 ** Return a boolean value for a query parameter. 004235 */ 004236 int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){ 004237 const char *z = sqlite3_uri_parameter(zFilename, zParam); 004238 bDflt = bDflt!=0; 004239 return z ? sqlite3GetBoolean(z, bDflt) : bDflt; 004240 } 004241 004242 /* 004243 ** Return a 64-bit integer value for a query parameter. 004244 */ 004245 sqlite3_int64 sqlite3_uri_int64( 004246 const char *zFilename, /* Filename as passed to xOpen */ 004247 const char *zParam, /* URI parameter sought */ 004248 sqlite3_int64 bDflt /* return if parameter is missing */ 004249 ){ 004250 const char *z = sqlite3_uri_parameter(zFilename, zParam); 004251 sqlite3_int64 v; 004252 if( z && sqlite3DecOrHexToI64(z, &v)==0 ){ 004253 bDflt = v; 004254 } 004255 return bDflt; 004256 } 004257 004258 /* 004259 ** Return the Btree pointer identified by zDbName. Return NULL if not found. 004260 */ 004261 Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){ 004262 int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0; 004263 return iDb<0 ? 0 : db->aDb[iDb].pBt; 004264 } 004265 004266 /* 004267 ** Return the filename of the database associated with a database 004268 ** connection. 004269 */ 004270 const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){ 004271 Btree *pBt; 004272 #ifdef SQLITE_ENABLE_API_ARMOR 004273 if( !sqlite3SafetyCheckOk(db) ){ 004274 (void)SQLITE_MISUSE_BKPT; 004275 return 0; 004276 } 004277 #endif 004278 pBt = sqlite3DbNameToBtree(db, zDbName); 004279 return pBt ? sqlite3BtreeGetFilename(pBt) : 0; 004280 } 004281 004282 /* 004283 ** Return 1 if database is read-only or 0 if read/write. Return -1 if 004284 ** no such database exists. 004285 */ 004286 int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){ 004287 Btree *pBt; 004288 #ifdef SQLITE_ENABLE_API_ARMOR 004289 if( !sqlite3SafetyCheckOk(db) ){ 004290 (void)SQLITE_MISUSE_BKPT; 004291 return -1; 004292 } 004293 #endif 004294 pBt = sqlite3DbNameToBtree(db, zDbName); 004295 return pBt ? sqlite3BtreeIsReadonly(pBt) : -1; 004296 } 004297 004298 #ifdef SQLITE_ENABLE_SNAPSHOT 004299 /* 004300 ** Obtain a snapshot handle for the snapshot of database zDb currently 004301 ** being read by handle db. 004302 */ 004303 int sqlite3_snapshot_get( 004304 sqlite3 *db, 004305 const char *zDb, 004306 sqlite3_snapshot **ppSnapshot 004307 ){ 004308 int rc = SQLITE_ERROR; 004309 #ifndef SQLITE_OMIT_WAL 004310 004311 #ifdef SQLITE_ENABLE_API_ARMOR 004312 if( !sqlite3SafetyCheckOk(db) ){ 004313 return SQLITE_MISUSE_BKPT; 004314 } 004315 #endif 004316 sqlite3_mutex_enter(db->mutex); 004317 004318 if( db->autoCommit==0 ){ 004319 int iDb = sqlite3FindDbName(db, zDb); 004320 if( iDb==0 || iDb>1 ){ 004321 Btree *pBt = db->aDb[iDb].pBt; 004322 if( 0==sqlite3BtreeIsInTrans(pBt) ){ 004323 rc = sqlite3BtreeBeginTrans(pBt, 0, 0); 004324 if( rc==SQLITE_OK ){ 004325 rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot); 004326 } 004327 } 004328 } 004329 } 004330 004331 sqlite3_mutex_leave(db->mutex); 004332 #endif /* SQLITE_OMIT_WAL */ 004333 return rc; 004334 } 004335 004336 /* 004337 ** Open a read-transaction on the snapshot idendified by pSnapshot. 004338 */ 004339 int sqlite3_snapshot_open( 004340 sqlite3 *db, 004341 const char *zDb, 004342 sqlite3_snapshot *pSnapshot 004343 ){ 004344 int rc = SQLITE_ERROR; 004345 #ifndef SQLITE_OMIT_WAL 004346 004347 #ifdef SQLITE_ENABLE_API_ARMOR 004348 if( !sqlite3SafetyCheckOk(db) ){ 004349 return SQLITE_MISUSE_BKPT; 004350 } 004351 #endif 004352 sqlite3_mutex_enter(db->mutex); 004353 if( db->autoCommit==0 ){ 004354 int iDb; 004355 iDb = sqlite3FindDbName(db, zDb); 004356 if( iDb==0 || iDb>1 ){ 004357 Btree *pBt = db->aDb[iDb].pBt; 004358 if( sqlite3BtreeIsInTrans(pBt)==0 ){ 004359 Pager *pPager = sqlite3BtreePager(pBt); 004360 int bUnlock = 0; 004361 if( sqlite3BtreeIsInReadTrans(pBt) ){ 004362 if( db->nVdbeActive==0 ){ 004363 rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot); 004364 if( rc==SQLITE_OK ){ 004365 bUnlock = 1; 004366 rc = sqlite3BtreeCommit(pBt); 004367 } 004368 } 004369 }else{ 004370 rc = SQLITE_OK; 004371 } 004372 if( rc==SQLITE_OK ){ 004373 rc = sqlite3PagerSnapshotOpen(pPager, pSnapshot); 004374 } 004375 if( rc==SQLITE_OK ){ 004376 rc = sqlite3BtreeBeginTrans(pBt, 0, 0); 004377 sqlite3PagerSnapshotOpen(pPager, 0); 004378 } 004379 if( bUnlock ){ 004380 sqlite3PagerSnapshotUnlock(pPager); 004381 } 004382 } 004383 } 004384 } 004385 004386 sqlite3_mutex_leave(db->mutex); 004387 #endif /* SQLITE_OMIT_WAL */ 004388 return rc; 004389 } 004390 004391 /* 004392 ** Recover as many snapshots as possible from the wal file associated with 004393 ** schema zDb of database db. 004394 */ 004395 int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){ 004396 int rc = SQLITE_ERROR; 004397 int iDb; 004398 #ifndef SQLITE_OMIT_WAL 004399 004400 #ifdef SQLITE_ENABLE_API_ARMOR 004401 if( !sqlite3SafetyCheckOk(db) ){ 004402 return SQLITE_MISUSE_BKPT; 004403 } 004404 #endif 004405 004406 sqlite3_mutex_enter(db->mutex); 004407 iDb = sqlite3FindDbName(db, zDb); 004408 if( iDb==0 || iDb>1 ){ 004409 Btree *pBt = db->aDb[iDb].pBt; 004410 if( 0==sqlite3BtreeIsInReadTrans(pBt) ){ 004411 rc = sqlite3BtreeBeginTrans(pBt, 0, 0); 004412 if( rc==SQLITE_OK ){ 004413 rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt)); 004414 sqlite3BtreeCommit(pBt); 004415 } 004416 } 004417 } 004418 sqlite3_mutex_leave(db->mutex); 004419 #endif /* SQLITE_OMIT_WAL */ 004420 return rc; 004421 } 004422 004423 /* 004424 ** Free a snapshot handle obtained from sqlite3_snapshot_get(). 004425 */ 004426 void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){ 004427 sqlite3_free(pSnapshot); 004428 } 004429 #endif /* SQLITE_ENABLE_SNAPSHOT */ 004430 004431 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS 004432 /* 004433 ** Given the name of a compile-time option, return true if that option 004434 ** was used and false if not. 004435 ** 004436 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix 004437 ** is not required for a match. 004438 */ 004439 int sqlite3_compileoption_used(const char *zOptName){ 004440 int i, n; 004441 int nOpt; 004442 const char **azCompileOpt; 004443 004444 #if SQLITE_ENABLE_API_ARMOR 004445 if( zOptName==0 ){ 004446 (void)SQLITE_MISUSE_BKPT; 004447 return 0; 004448 } 004449 #endif 004450 004451 azCompileOpt = sqlite3CompileOptions(&nOpt); 004452 004453 if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7; 004454 n = sqlite3Strlen30(zOptName); 004455 004456 /* Since nOpt is normally in single digits, a linear search is 004457 ** adequate. No need for a binary search. */ 004458 for(i=0; i<nOpt; i++){ 004459 if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0 004460 && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0 004461 ){ 004462 return 1; 004463 } 004464 } 004465 return 0; 004466 } 004467 004468 /* 004469 ** Return the N-th compile-time option string. If N is out of range, 004470 ** return a NULL pointer. 004471 */ 004472 const char *sqlite3_compileoption_get(int N){ 004473 int nOpt; 004474 const char **azCompileOpt; 004475 azCompileOpt = sqlite3CompileOptions(&nOpt); 004476 if( N>=0 && N<nOpt ){ 004477 return azCompileOpt[N]; 004478 } 004479 return 0; 004480 } 004481 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */