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