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