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