1 /* 2 ** 2001 September 15 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** a legal notice, here is a blessing: 6 ** 7 ** May you do good and not evil. 8 ** May you find forgiveness for yourself and forgive others. 9 ** May you share freely, never taking more than you give. 10 ** 11 ************************************************************************* 12 ** Main file for the SQLite library. The routines in this file 13 ** implement the programmer interface to the library. Routines in 14 ** other files are for internal use by SQLite and should not be 15 ** accessed by users of the library. 16 */ 17 #include "sqliteInt.h" 18 19 #ifdef SQLITE_ENABLE_FTS3 20 # include "fts3.h" 21 #endif 22 #ifdef SQLITE_ENABLE_RTREE 23 # include "rtree.h" 24 #endif 25 #ifdef SQLITE_ENABLE_ICU 26 # include "sqliteicu.h" 27 #endif 28 #ifdef SQLITE_ENABLE_JSON1 29 int sqlite3Json1Init(sqlite3*); 30 #endif 31 #ifdef SQLITE_ENABLE_FTS5 32 int sqlite3Fts5Init(sqlite3*); 33 #endif 34 35 #ifndef SQLITE_AMALGAMATION 36 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant 37 ** contains the text of SQLITE_VERSION macro. 38 */ 39 const char sqlite3_version[] = SQLITE_VERSION; 40 #endif 41 42 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns 43 ** a pointer to the to the sqlite3_version[] string constant. 44 */ 45 const char *sqlite3_libversion(void){ return sqlite3_version; } 46 47 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a 48 ** pointer to a string constant whose value is the same as the 49 ** SQLITE_SOURCE_ID C preprocessor macro. 50 */ 51 const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } 52 53 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function 54 ** returns an integer equal to SQLITE_VERSION_NUMBER. 55 */ 56 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; } 57 58 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns 59 ** zero if and only if SQLite was compiled with mutexing code omitted due to 60 ** the SQLITE_THREADSAFE compile-time option being set to 0. 61 */ 62 int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; } 63 64 /* 65 ** When compiling the test fixture or with debugging enabled (on Win32), 66 ** this variable being set to non-zero will cause OSTRACE macros to emit 67 ** extra diagnostic information. 68 */ 69 #ifdef SQLITE_HAVE_OS_TRACE 70 # ifndef SQLITE_DEBUG_OS_TRACE 71 # define SQLITE_DEBUG_OS_TRACE 0 72 # endif 73 int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE; 74 #endif 75 76 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE) 77 /* 78 ** If the following function pointer is not NULL and if 79 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing 80 ** I/O active are written using this function. These messages 81 ** are intended for debugging activity only. 82 */ 83 SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0; 84 #endif 85 86 /* 87 ** If the following global variable points to a string which is the 88 ** name of a directory, then that directory will be used to store 89 ** temporary files. 90 ** 91 ** See also the "PRAGMA temp_store_directory" SQL command. 92 */ 93 char *sqlite3_temp_directory = 0; 94 95 /* 96 ** If the following global variable points to a string which is the 97 ** name of a directory, then that directory will be used to store 98 ** all database files specified with a relative pathname. 99 ** 100 ** See also the "PRAGMA data_store_directory" SQL command. 101 */ 102 char *sqlite3_data_directory = 0; 103 104 /* 105 ** Initialize SQLite. 106 ** 107 ** This routine must be called to initialize the memory allocation, 108 ** VFS, and mutex subsystems prior to doing any serious work with 109 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT 110 ** this routine will be called automatically by key routines such as 111 ** sqlite3_open(). 112 ** 113 ** This routine is a no-op except on its very first call for the process, 114 ** or for the first call after a call to sqlite3_shutdown. 115 ** 116 ** The first thread to call this routine runs the initialization to 117 ** completion. If subsequent threads call this routine before the first 118 ** thread has finished the initialization process, then the subsequent 119 ** threads must block until the first thread finishes with the initialization. 120 ** 121 ** The first thread might call this routine recursively. Recursive 122 ** calls to this routine should not block, of course. Otherwise the 123 ** initialization process would never complete. 124 ** 125 ** Let X be the first thread to enter this routine. Let Y be some other 126 ** thread. Then while the initial invocation of this routine by X is 127 ** incomplete, it is required that: 128 ** 129 ** * Calls to this routine from Y must block until the outer-most 130 ** call by X completes. 131 ** 132 ** * Recursive calls to this routine from thread X return immediately 133 ** without blocking. 134 */ 135 int sqlite3_initialize(void){ 136 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */ 137 int rc; /* Result code */ 138 #ifdef SQLITE_EXTRA_INIT 139 int bRunExtraInit = 0; /* Extra initialization needed */ 140 #endif 141 142 #ifdef SQLITE_OMIT_WSD 143 rc = sqlite3_wsd_init(4096, 24); 144 if( rc!=SQLITE_OK ){ 145 return rc; 146 } 147 #endif 148 149 /* If the following assert() fails on some obscure processor/compiler 150 ** combination, the work-around is to set the correct pointer 151 ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */ 152 assert( SQLITE_PTRSIZE==sizeof(char*) ); 153 154 /* If SQLite is already completely initialized, then this call 155 ** to sqlite3_initialize() should be a no-op. But the initialization 156 ** must be complete. So isInit must not be set until the very end 157 ** of this routine. 158 */ 159 if( sqlite3GlobalConfig.isInit ) return SQLITE_OK; 160 161 /* Make sure the mutex subsystem is initialized. If unable to 162 ** initialize the mutex subsystem, return early with the error. 163 ** If the system is so sick that we are unable to allocate a mutex, 164 ** there is not much SQLite is going to be able to do. 165 ** 166 ** The mutex subsystem must take care of serializing its own 167 ** initialization. 168 */ 169 rc = sqlite3MutexInit(); 170 if( rc ) return rc; 171 172 /* Initialize the malloc() system and the recursive pInitMutex mutex. 173 ** This operation is protected by the STATIC_MASTER mutex. Note that 174 ** MutexAlloc() is called for a static mutex prior to initializing the 175 ** malloc subsystem - this implies that the allocation of a static 176 ** mutex must not require support from the malloc subsystem. 177 */ 178 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) 179 sqlite3_mutex_enter(pMaster); 180 sqlite3GlobalConfig.isMutexInit = 1; 181 if( !sqlite3GlobalConfig.isMallocInit ){ 182 rc = sqlite3MallocInit(); 183 } 184 if( rc==SQLITE_OK ){ 185 sqlite3GlobalConfig.isMallocInit = 1; 186 if( !sqlite3GlobalConfig.pInitMutex ){ 187 sqlite3GlobalConfig.pInitMutex = 188 sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); 189 if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){ 190 rc = SQLITE_NOMEM; 191 } 192 } 193 } 194 if( rc==SQLITE_OK ){ 195 sqlite3GlobalConfig.nRefInitMutex++; 196 } 197 sqlite3_mutex_leave(pMaster); 198 199 /* If rc is not SQLITE_OK at this point, then either the malloc 200 ** subsystem could not be initialized or the system failed to allocate 201 ** the pInitMutex mutex. Return an error in either case. */ 202 if( rc!=SQLITE_OK ){ 203 return rc; 204 } 205 206 /* Do the rest of the initialization under the recursive mutex so 207 ** that we will be able to handle recursive calls into 208 ** sqlite3_initialize(). The recursive calls normally come through 209 ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other 210 ** recursive calls might also be possible. 211 ** 212 ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls 213 ** to the xInit method, so the xInit method need not be threadsafe. 214 ** 215 ** The following mutex is what serializes access to the appdef pcache xInit 216 ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the 217 ** call to sqlite3PcacheInitialize(). 218 */ 219 sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex); 220 if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){ 221 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions); 222 sqlite3GlobalConfig.inProgress = 1; 223 memset(pHash, 0, sizeof(sqlite3GlobalFunctions)); 224 sqlite3RegisterGlobalFunctions(); 225 if( sqlite3GlobalConfig.isPCacheInit==0 ){ 226 rc = sqlite3PcacheInitialize(); 227 } 228 if( rc==SQLITE_OK ){ 229 sqlite3GlobalConfig.isPCacheInit = 1; 230 rc = sqlite3OsInit(); 231 } 232 if( rc==SQLITE_OK ){ 233 sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 234 sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage); 235 sqlite3GlobalConfig.isInit = 1; 236 #ifdef SQLITE_EXTRA_INIT 237 bRunExtraInit = 1; 238 #endif 239 } 240 sqlite3GlobalConfig.inProgress = 0; 241 } 242 sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex); 243 244 /* Go back under the static mutex and clean up the recursive 245 ** mutex to prevent a resource leak. 246 */ 247 sqlite3_mutex_enter(pMaster); 248 sqlite3GlobalConfig.nRefInitMutex--; 249 if( sqlite3GlobalConfig.nRefInitMutex<=0 ){ 250 assert( sqlite3GlobalConfig.nRefInitMutex==0 ); 251 sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex); 252 sqlite3GlobalConfig.pInitMutex = 0; 253 } 254 sqlite3_mutex_leave(pMaster); 255 256 /* The following is just a sanity check to make sure SQLite has 257 ** been compiled correctly. It is important to run this code, but 258 ** we don't want to run it too often and soak up CPU cycles for no 259 ** reason. So we run it once during initialization. 260 */ 261 #ifndef NDEBUG 262 #ifndef SQLITE_OMIT_FLOATING_POINT 263 /* This section of code's only "output" is via assert() statements. */ 264 if ( rc==SQLITE_OK ){ 265 u64 x = (((u64)1)<<63)-1; 266 double y; 267 assert(sizeof(x)==8); 268 assert(sizeof(x)==sizeof(y)); 269 memcpy(&y, &x, 8); 270 assert( sqlite3IsNaN(y) ); 271 } 272 #endif 273 #endif 274 275 /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT 276 ** compile-time option. 277 */ 278 #ifdef SQLITE_EXTRA_INIT 279 if( bRunExtraInit ){ 280 int SQLITE_EXTRA_INIT(const char*); 281 rc = SQLITE_EXTRA_INIT(0); 282 } 283 #endif 284 285 return rc; 286 } 287 288 /* 289 ** Undo the effects of sqlite3_initialize(). Must not be called while 290 ** there are outstanding database connections or memory allocations or 291 ** while any part of SQLite is otherwise in use in any thread. This 292 ** routine is not threadsafe. But it is safe to invoke this routine 293 ** on when SQLite is already shut down. If SQLite is already shut down 294 ** when this routine is invoked, then this routine is a harmless no-op. 295 */ 296 int sqlite3_shutdown(void){ 297 #ifdef SQLITE_OMIT_WSD 298 int rc = sqlite3_wsd_init(4096, 24); 299 if( rc!=SQLITE_OK ){ 300 return rc; 301 } 302 #endif 303 304 if( sqlite3GlobalConfig.isInit ){ 305 #ifdef SQLITE_EXTRA_SHUTDOWN 306 void SQLITE_EXTRA_SHUTDOWN(void); 307 SQLITE_EXTRA_SHUTDOWN(); 308 #endif 309 sqlite3_os_end(); 310 sqlite3_reset_auto_extension(); 311 sqlite3GlobalConfig.isInit = 0; 312 } 313 if( sqlite3GlobalConfig.isPCacheInit ){ 314 sqlite3PcacheShutdown(); 315 sqlite3GlobalConfig.isPCacheInit = 0; 316 } 317 if( sqlite3GlobalConfig.isMallocInit ){ 318 sqlite3MallocEnd(); 319 sqlite3GlobalConfig.isMallocInit = 0; 320 321 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES 322 /* The heap subsystem has now been shutdown and these values are supposed 323 ** to be NULL or point to memory that was obtained from sqlite3_malloc(), 324 ** which would rely on that heap subsystem; therefore, make sure these 325 ** values cannot refer to heap memory that was just invalidated when the 326 ** heap subsystem was shutdown. This is only done if the current call to 327 ** this function resulted in the heap subsystem actually being shutdown. 328 */ 329 sqlite3_data_directory = 0; 330 sqlite3_temp_directory = 0; 331 #endif 332 } 333 if( sqlite3GlobalConfig.isMutexInit ){ 334 sqlite3MutexEnd(); 335 sqlite3GlobalConfig.isMutexInit = 0; 336 } 337 338 return SQLITE_OK; 339 } 340 341 /* 342 ** This API allows applications to modify the global configuration of 343 ** the SQLite library at run-time. 344 ** 345 ** This routine should only be called when there are no outstanding 346 ** database connections or memory allocations. This routine is not 347 ** threadsafe. Failure to heed these warnings can lead to unpredictable 348 ** behavior. 349 */ 350 int sqlite3_config(int op, ...){ 351 va_list ap; 352 int rc = SQLITE_OK; 353 354 /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while 355 ** the SQLite library is in use. */ 356 if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT; 357 358 va_start(ap, op); 359 switch( op ){ 360 361 /* Mutex configuration options are only available in a threadsafe 362 ** compile. 363 */ 364 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */ 365 case SQLITE_CONFIG_SINGLETHREAD: { 366 /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to 367 ** Single-thread. */ 368 sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */ 369 sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */ 370 break; 371 } 372 #endif 373 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */ 374 case SQLITE_CONFIG_MULTITHREAD: { 375 /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to 376 ** Multi-thread. */ 377 sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */ 378 sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */ 379 break; 380 } 381 #endif 382 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */ 383 case SQLITE_CONFIG_SERIALIZED: { 384 /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to 385 ** Serialized. */ 386 sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */ 387 sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */ 388 break; 389 } 390 #endif 391 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */ 392 case SQLITE_CONFIG_MUTEX: { 393 /* Specify an alternative mutex implementation */ 394 sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*); 395 break; 396 } 397 #endif 398 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */ 399 case SQLITE_CONFIG_GETMUTEX: { 400 /* Retrieve the current mutex implementation */ 401 *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex; 402 break; 403 } 404 #endif 405 406 case SQLITE_CONFIG_MALLOC: { 407 /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a 408 ** single argument which is a pointer to an instance of the 409 ** sqlite3_mem_methods structure. The argument specifies alternative 410 ** low-level memory allocation routines to be used in place of the memory 411 ** allocation routines built into SQLite. */ 412 sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*); 413 break; 414 } 415 case SQLITE_CONFIG_GETMALLOC: { 416 /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a 417 ** single argument which is a pointer to an instance of the 418 ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is 419 ** filled with the currently defined memory allocation routines. */ 420 if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault(); 421 *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m; 422 break; 423 } 424 case SQLITE_CONFIG_MEMSTATUS: { 425 /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes 426 ** single argument of type int, interpreted as a boolean, which enables 427 ** or disables the collection of memory allocation statistics. */ 428 sqlite3GlobalConfig.bMemstat = va_arg(ap, int); 429 break; 430 } 431 case SQLITE_CONFIG_SCRATCH: { 432 /* EVIDENCE-OF: R-08404-60887 There are three arguments to 433 ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from 434 ** which the scratch allocations will be drawn, the size of each scratch 435 ** allocation (sz), and the maximum number of scratch allocations (N). */ 436 sqlite3GlobalConfig.pScratch = va_arg(ap, void*); 437 sqlite3GlobalConfig.szScratch = va_arg(ap, int); 438 sqlite3GlobalConfig.nScratch = va_arg(ap, int); 439 break; 440 } 441 case SQLITE_CONFIG_PAGECACHE: { 442 /* EVIDENCE-OF: R-31408-40510 There are three arguments to 443 ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory, the size 444 ** of each page buffer (sz), and the number of pages (N). */ 445 sqlite3GlobalConfig.pPage = va_arg(ap, void*); 446 sqlite3GlobalConfig.szPage = va_arg(ap, int); 447 sqlite3GlobalConfig.nPage = va_arg(ap, int); 448 break; 449 } 450 case SQLITE_CONFIG_PCACHE_HDRSZ: { 451 /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes 452 ** a single parameter which is a pointer to an integer and writes into 453 ** that integer the number of extra bytes per page required for each page 454 ** in SQLITE_CONFIG_PAGECACHE. */ 455 *va_arg(ap, int*) = 456 sqlite3HeaderSizeBtree() + 457 sqlite3HeaderSizePcache() + 458 sqlite3HeaderSizePcache1(); 459 break; 460 } 461 462 case SQLITE_CONFIG_PCACHE: { 463 /* no-op */ 464 break; 465 } 466 case SQLITE_CONFIG_GETPCACHE: { 467 /* now an error */ 468 rc = SQLITE_ERROR; 469 break; 470 } 471 472 case SQLITE_CONFIG_PCACHE2: { 473 /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a 474 ** single argument which is a pointer to an sqlite3_pcache_methods2 475 ** object. This object specifies the interface to a custom page cache 476 ** implementation. */ 477 sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*); 478 break; 479 } 480 case SQLITE_CONFIG_GETPCACHE2: { 481 /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a 482 ** single argument which is a pointer to an sqlite3_pcache_methods2 483 ** object. SQLite copies of the current page cache implementation into 484 ** that object. */ 485 if( sqlite3GlobalConfig.pcache2.xInit==0 ){ 486 sqlite3PCacheSetDefault(); 487 } 488 *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2; 489 break; 490 } 491 492 /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only 493 ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or 494 ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */ 495 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) 496 case SQLITE_CONFIG_HEAP: { 497 /* EVIDENCE-OF: R-19854-42126 There are three arguments to 498 ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the 499 ** number of bytes in the memory buffer, and the minimum allocation size. 500 */ 501 sqlite3GlobalConfig.pHeap = va_arg(ap, void*); 502 sqlite3GlobalConfig.nHeap = va_arg(ap, int); 503 sqlite3GlobalConfig.mnReq = va_arg(ap, int); 504 505 if( sqlite3GlobalConfig.mnReq<1 ){ 506 sqlite3GlobalConfig.mnReq = 1; 507 }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){ 508 /* cap min request size at 2^12 */ 509 sqlite3GlobalConfig.mnReq = (1<<12); 510 } 511 512 if( sqlite3GlobalConfig.pHeap==0 ){ 513 /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer) 514 ** is NULL, then SQLite reverts to using its default memory allocator 515 ** (the system malloc() implementation), undoing any prior invocation of 516 ** SQLITE_CONFIG_MALLOC. 517 ** 518 ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to 519 ** revert to its default implementation when sqlite3_initialize() is run 520 */ 521 memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m)); 522 }else{ 523 /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the 524 ** alternative memory allocator is engaged to handle all of SQLites 525 ** memory allocation needs. */ 526 #ifdef SQLITE_ENABLE_MEMSYS3 527 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3(); 528 #endif 529 #ifdef SQLITE_ENABLE_MEMSYS5 530 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5(); 531 #endif 532 } 533 break; 534 } 535 #endif 536 537 case SQLITE_CONFIG_LOOKASIDE: { 538 sqlite3GlobalConfig.szLookaside = va_arg(ap, int); 539 sqlite3GlobalConfig.nLookaside = va_arg(ap, int); 540 break; 541 } 542 543 /* Record a pointer to the logger function and its first argument. 544 ** The default is NULL. Logging is disabled if the function pointer is 545 ** NULL. 546 */ 547 case SQLITE_CONFIG_LOG: { 548 /* MSVC is picky about pulling func ptrs from va lists. 549 ** http://support.microsoft.com/kb/47961 550 ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*)); 551 */ 552 typedef void(*LOGFUNC_t)(void*,int,const char*); 553 sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t); 554 sqlite3GlobalConfig.pLogArg = va_arg(ap, void*); 555 break; 556 } 557 558 /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames 559 ** can be changed at start-time using the 560 ** sqlite3_config(SQLITE_CONFIG_URI,1) or 561 ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls. 562 */ 563 case SQLITE_CONFIG_URI: { 564 /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single 565 ** argument of type int. If non-zero, then URI handling is globally 566 ** enabled. If the parameter is zero, then URI handling is globally 567 ** disabled. */ 568 sqlite3GlobalConfig.bOpenUri = va_arg(ap, int); 569 break; 570 } 571 572 case SQLITE_CONFIG_COVERING_INDEX_SCAN: { 573 /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN 574 ** option takes a single integer argument which is interpreted as a 575 ** boolean in order to enable or disable the use of covering indices for 576 ** full table scans in the query optimizer. */ 577 sqlite3GlobalConfig.bUseCis = va_arg(ap, int); 578 break; 579 } 580 581 #ifdef SQLITE_ENABLE_SQLLOG 582 case SQLITE_CONFIG_SQLLOG: { 583 typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int); 584 sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t); 585 sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *); 586 break; 587 } 588 #endif 589 590 case SQLITE_CONFIG_MMAP_SIZE: { 591 /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit 592 ** integer (sqlite3_int64) values that are the default mmap size limit 593 ** (the default setting for PRAGMA mmap_size) and the maximum allowed 594 ** mmap size limit. */ 595 sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64); 596 sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64); 597 /* EVIDENCE-OF: R-53367-43190 If either argument to this option is 598 ** negative, then that argument is changed to its compile-time default. 599 ** 600 ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be 601 ** silently truncated if necessary so that it does not exceed the 602 ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE 603 ** compile-time option. 604 */ 605 if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){ 606 mxMmap = SQLITE_MAX_MMAP_SIZE; 607 } 608 if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE; 609 if( szMmap>mxMmap) szMmap = mxMmap; 610 sqlite3GlobalConfig.mxMmap = mxMmap; 611 sqlite3GlobalConfig.szMmap = szMmap; 612 break; 613 } 614 615 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */ 616 case SQLITE_CONFIG_WIN32_HEAPSIZE: { 617 /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit 618 ** unsigned integer value that specifies the maximum size of the created 619 ** heap. */ 620 sqlite3GlobalConfig.nHeap = va_arg(ap, int); 621 break; 622 } 623 #endif 624 625 case SQLITE_CONFIG_PMASZ: { 626 sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int); 627 break; 628 } 629 630 default: { 631 rc = SQLITE_ERROR; 632 break; 633 } 634 } 635 va_end(ap); 636 return rc; 637 } 638 639 /* 640 ** Set up the lookaside buffers for a database connection. 641 ** Return SQLITE_OK on success. 642 ** If lookaside is already active, return SQLITE_BUSY. 643 ** 644 ** The sz parameter is the number of bytes in each lookaside slot. 645 ** The cnt parameter is the number of slots. If pStart is NULL the 646 ** space for the lookaside memory is obtained from sqlite3_malloc(). 647 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for 648 ** the lookaside memory. 649 */ 650 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){ 651 #ifndef SQLITE_OMIT_LOOKASIDE 652 void *pStart; 653 if( db->lookaside.nOut ){ 654 return SQLITE_BUSY; 655 } 656 /* Free any existing lookaside buffer for this handle before 657 ** allocating a new one so we don't have to have space for 658 ** both at the same time. 659 */ 660 if( db->lookaside.bMalloced ){ 661 sqlite3_free(db->lookaside.pStart); 662 } 663 /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger 664 ** than a pointer to be useful. 665 */ 666 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */ 667 if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0; 668 if( cnt<0 ) cnt = 0; 669 if( sz==0 || cnt==0 ){ 670 sz = 0; 671 pStart = 0; 672 }else if( pBuf==0 ){ 673 sqlite3BeginBenignMalloc(); 674 pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */ 675 sqlite3EndBenignMalloc(); 676 if( pStart ) cnt = sqlite3MallocSize(pStart)/sz; 677 }else{ 678 pStart = pBuf; 679 } 680 db->lookaside.pStart = pStart; 681 db->lookaside.pFree = 0; 682 db->lookaside.sz = (u16)sz; 683 if( pStart ){ 684 int i; 685 LookasideSlot *p; 686 assert( sz > (int)sizeof(LookasideSlot*) ); 687 p = (LookasideSlot*)pStart; 688 for(i=cnt-1; i>=0; i--){ 689 p->pNext = db->lookaside.pFree; 690 db->lookaside.pFree = p; 691 p = (LookasideSlot*)&((u8*)p)[sz]; 692 } 693 db->lookaside.pEnd = p; 694 db->lookaside.bEnabled = 1; 695 db->lookaside.bMalloced = pBuf==0 ?1:0; 696 }else{ 697 db->lookaside.pStart = db; 698 db->lookaside.pEnd = db; 699 db->lookaside.bEnabled = 0; 700 db->lookaside.bMalloced = 0; 701 } 702 #endif /* SQLITE_OMIT_LOOKASIDE */ 703 return SQLITE_OK; 704 } 705 706 /* 707 ** Return the mutex associated with a database connection. 708 */ 709 sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){ 710 #ifdef SQLITE_ENABLE_API_ARMOR 711 if( !sqlite3SafetyCheckOk(db) ){ 712 (void)SQLITE_MISUSE_BKPT; 713 return 0; 714 } 715 #endif 716 return db->mutex; 717 } 718 719 /* 720 ** Free up as much memory as we can from the given database 721 ** connection. 722 */ 723 int sqlite3_db_release_memory(sqlite3 *db){ 724 int i; 725 726 #ifdef SQLITE_ENABLE_API_ARMOR 727 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; 728 #endif 729 sqlite3_mutex_enter(db->mutex); 730 sqlite3BtreeEnterAll(db); 731 for(i=0; i<db->nDb; i++){ 732 Btree *pBt = db->aDb[i].pBt; 733 if( pBt ){ 734 Pager *pPager = sqlite3BtreePager(pBt); 735 sqlite3PagerShrink(pPager); 736 } 737 } 738 sqlite3BtreeLeaveAll(db); 739 sqlite3_mutex_leave(db->mutex); 740 return SQLITE_OK; 741 } 742 743 /* 744 ** Flush any dirty pages in the pager-cache for any attached database 745 ** to disk. 746 */ 747 int sqlite3_db_cacheflush(sqlite3 *db){ 748 int i; 749 int rc = SQLITE_OK; 750 int bSeenBusy = 0; 751 752 #ifdef SQLITE_ENABLE_API_ARMOR 753 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; 754 #endif 755 sqlite3_mutex_enter(db->mutex); 756 sqlite3BtreeEnterAll(db); 757 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 758 Btree *pBt = db->aDb[i].pBt; 759 if( pBt && sqlite3BtreeIsInTrans(pBt) ){ 760 Pager *pPager = sqlite3BtreePager(pBt); 761 rc = sqlite3PagerFlush(pPager); 762 if( rc==SQLITE_BUSY ){ 763 bSeenBusy = 1; 764 rc = SQLITE_OK; 765 } 766 } 767 } 768 sqlite3BtreeLeaveAll(db); 769 sqlite3_mutex_leave(db->mutex); 770 return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc); 771 } 772 773 /* 774 ** Configuration settings for an individual database connection 775 */ 776 int sqlite3_db_config(sqlite3 *db, int op, ...){ 777 va_list ap; 778 int rc; 779 va_start(ap, op); 780 switch( op ){ 781 case SQLITE_DBCONFIG_LOOKASIDE: { 782 void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */ 783 int sz = va_arg(ap, int); /* IMP: R-47871-25994 */ 784 int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */ 785 rc = setupLookaside(db, pBuf, sz, cnt); 786 break; 787 } 788 default: { 789 static const struct { 790 int op; /* The opcode */ 791 u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */ 792 } aFlagOp[] = { 793 { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys }, 794 { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger }, 795 }; 796 unsigned int i; 797 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */ 798 for(i=0; i<ArraySize(aFlagOp); i++){ 799 if( aFlagOp[i].op==op ){ 800 int onoff = va_arg(ap, int); 801 int *pRes = va_arg(ap, int*); 802 int oldFlags = db->flags; 803 if( onoff>0 ){ 804 db->flags |= aFlagOp[i].mask; 805 }else if( onoff==0 ){ 806 db->flags &= ~aFlagOp[i].mask; 807 } 808 if( oldFlags!=db->flags ){ 809 sqlite3ExpirePreparedStatements(db); 810 } 811 if( pRes ){ 812 *pRes = (db->flags & aFlagOp[i].mask)!=0; 813 } 814 rc = SQLITE_OK; 815 break; 816 } 817 } 818 break; 819 } 820 } 821 va_end(ap); 822 return rc; 823 } 824 825 826 /* 827 ** Return true if the buffer z[0..n-1] contains all spaces. 828 */ 829 static int allSpaces(const char *z, int n){ 830 while( n>0 && z[n-1]==' ' ){ n--; } 831 return n==0; 832 } 833 834 /* 835 ** This is the default collating function named "BINARY" which is always 836 ** available. 837 ** 838 ** If the padFlag argument is not NULL then space padding at the end 839 ** of strings is ignored. This implements the RTRIM collation. 840 */ 841 static int binCollFunc( 842 void *padFlag, 843 int nKey1, const void *pKey1, 844 int nKey2, const void *pKey2 845 ){ 846 int rc, n; 847 n = nKey1<nKey2 ? nKey1 : nKey2; 848 /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares 849 ** strings byte by byte using the memcmp() function from the standard C 850 ** library. */ 851 rc = memcmp(pKey1, pKey2, n); 852 if( rc==0 ){ 853 if( padFlag 854 && allSpaces(((char*)pKey1)+n, nKey1-n) 855 && allSpaces(((char*)pKey2)+n, nKey2-n) 856 ){ 857 /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra 858 ** spaces at the end of either string do not change the result. In other 859 ** words, strings will compare equal to one another as long as they 860 ** differ only in the number of spaces at the end. 861 */ 862 }else{ 863 rc = nKey1 - nKey2; 864 } 865 } 866 return rc; 867 } 868 869 /* 870 ** Another built-in collating sequence: NOCASE. 871 ** 872 ** This collating sequence is intended to be used for "case independent 873 ** comparison". SQLite's knowledge of upper and lower case equivalents 874 ** extends only to the 26 characters used in the English language. 875 ** 876 ** At the moment there is only a UTF-8 implementation. 877 */ 878 static int nocaseCollatingFunc( 879 void *NotUsed, 880 int nKey1, const void *pKey1, 881 int nKey2, const void *pKey2 882 ){ 883 int r = sqlite3StrNICmp( 884 (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2); 885 UNUSED_PARAMETER(NotUsed); 886 if( 0==r ){ 887 r = nKey1-nKey2; 888 } 889 return r; 890 } 891 892 /* 893 ** Return the ROWID of the most recent insert 894 */ 895 sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){ 896 #ifdef SQLITE_ENABLE_API_ARMOR 897 if( !sqlite3SafetyCheckOk(db) ){ 898 (void)SQLITE_MISUSE_BKPT; 899 return 0; 900 } 901 #endif 902 return db->lastRowid; 903 } 904 905 /* 906 ** Return the number of changes in the most recent call to sqlite3_exec(). 907 */ 908 int sqlite3_changes(sqlite3 *db){ 909 #ifdef SQLITE_ENABLE_API_ARMOR 910 if( !sqlite3SafetyCheckOk(db) ){ 911 (void)SQLITE_MISUSE_BKPT; 912 return 0; 913 } 914 #endif 915 return db->nChange; 916 } 917 918 /* 919 ** Return the number of changes since the database handle was opened. 920 */ 921 int sqlite3_total_changes(sqlite3 *db){ 922 #ifdef SQLITE_ENABLE_API_ARMOR 923 if( !sqlite3SafetyCheckOk(db) ){ 924 (void)SQLITE_MISUSE_BKPT; 925 return 0; 926 } 927 #endif 928 return db->nTotalChange; 929 } 930 931 /* 932 ** Close all open savepoints. This function only manipulates fields of the 933 ** database handle object, it does not close any savepoints that may be open 934 ** at the b-tree/pager level. 935 */ 936 void sqlite3CloseSavepoints(sqlite3 *db){ 937 while( db->pSavepoint ){ 938 Savepoint *pTmp = db->pSavepoint; 939 db->pSavepoint = pTmp->pNext; 940 sqlite3DbFree(db, pTmp); 941 } 942 db->nSavepoint = 0; 943 db->nStatement = 0; 944 db->isTransactionSavepoint = 0; 945 } 946 947 /* 948 ** Invoke the destructor function associated with FuncDef p, if any. Except, 949 ** if this is not the last copy of the function, do not invoke it. Multiple 950 ** copies of a single function are created when create_function() is called 951 ** with SQLITE_ANY as the encoding. 952 */ 953 static void functionDestroy(sqlite3 *db, FuncDef *p){ 954 FuncDestructor *pDestructor = p->pDestructor; 955 if( pDestructor ){ 956 pDestructor->nRef--; 957 if( pDestructor->nRef==0 ){ 958 pDestructor->xDestroy(pDestructor->pUserData); 959 sqlite3DbFree(db, pDestructor); 960 } 961 } 962 } 963 964 /* 965 ** Disconnect all sqlite3_vtab objects that belong to database connection 966 ** db. This is called when db is being closed. 967 */ 968 static void disconnectAllVtab(sqlite3 *db){ 969 #ifndef SQLITE_OMIT_VIRTUALTABLE 970 int i; 971 HashElem *p; 972 sqlite3BtreeEnterAll(db); 973 for(i=0; i<db->nDb; i++){ 974 Schema *pSchema = db->aDb[i].pSchema; 975 if( db->aDb[i].pSchema ){ 976 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){ 977 Table *pTab = (Table *)sqliteHashData(p); 978 if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab); 979 } 980 } 981 } 982 for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){ 983 Module *pMod = (Module *)sqliteHashData(p); 984 if( pMod->pEpoTab ){ 985 sqlite3VtabDisconnect(db, pMod->pEpoTab); 986 } 987 } 988 sqlite3VtabUnlockList(db); 989 sqlite3BtreeLeaveAll(db); 990 #else 991 UNUSED_PARAMETER(db); 992 #endif 993 } 994 995 /* 996 ** Return TRUE if database connection db has unfinalized prepared 997 ** statements or unfinished sqlite3_backup objects. 998 */ 999 static int connectionIsBusy(sqlite3 *db){ 1000 int j; 1001 assert( sqlite3_mutex_held(db->mutex) ); 1002 if( db->pVdbe ) return 1; 1003 for(j=0; j<db->nDb; j++){ 1004 Btree *pBt = db->aDb[j].pBt; 1005 if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1; 1006 } 1007 return 0; 1008 } 1009 1010 /* 1011 ** Close an existing SQLite database 1012 */ 1013 static int sqlite3Close(sqlite3 *db, int forceZombie){ 1014 if( !db ){ 1015 /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or 1016 ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */ 1017 return SQLITE_OK; 1018 } 1019 if( !sqlite3SafetyCheckSickOrOk(db) ){ 1020 return SQLITE_MISUSE_BKPT; 1021 } 1022 sqlite3_mutex_enter(db->mutex); 1023 1024 /* Force xDisconnect calls on all virtual tables */ 1025 disconnectAllVtab(db); 1026 1027 /* If a transaction is open, the disconnectAllVtab() call above 1028 ** will not have called the xDisconnect() method on any virtual 1029 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback() 1030 ** call will do so. We need to do this before the check for active 1031 ** SQL statements below, as the v-table implementation may be storing 1032 ** some prepared statements internally. 1033 */ 1034 sqlite3VtabRollback(db); 1035 1036 /* Legacy behavior (sqlite3_close() behavior) is to return 1037 ** SQLITE_BUSY if the connection can not be closed immediately. 1038 */ 1039 if( !forceZombie && connectionIsBusy(db) ){ 1040 sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized " 1041 "statements or unfinished backups"); 1042 sqlite3_mutex_leave(db->mutex); 1043 return SQLITE_BUSY; 1044 } 1045 1046 #ifdef SQLITE_ENABLE_SQLLOG 1047 if( sqlite3GlobalConfig.xSqllog ){ 1048 /* Closing the handle. Fourth parameter is passed the value 2. */ 1049 sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2); 1050 } 1051 #endif 1052 1053 /* Convert the connection into a zombie and then close it. 1054 */ 1055 db->magic = SQLITE_MAGIC_ZOMBIE; 1056 sqlite3LeaveMutexAndCloseZombie(db); 1057 return SQLITE_OK; 1058 } 1059 1060 /* 1061 ** Two variations on the public interface for closing a database 1062 ** connection. The sqlite3_close() version returns SQLITE_BUSY and 1063 ** leaves the connection option if there are unfinalized prepared 1064 ** statements or unfinished sqlite3_backups. The sqlite3_close_v2() 1065 ** version forces the connection to become a zombie if there are 1066 ** unclosed resources, and arranges for deallocation when the last 1067 ** prepare statement or sqlite3_backup closes. 1068 */ 1069 int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); } 1070 int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); } 1071 1072 1073 /* 1074 ** Close the mutex on database connection db. 1075 ** 1076 ** Furthermore, if database connection db is a zombie (meaning that there 1077 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and 1078 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has 1079 ** finished, then free all resources. 1080 */ 1081 void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){ 1082 HashElem *i; /* Hash table iterator */ 1083 int j; 1084 1085 /* If there are outstanding sqlite3_stmt or sqlite3_backup objects 1086 ** or if the connection has not yet been closed by sqlite3_close_v2(), 1087 ** then just leave the mutex and return. 1088 */ 1089 if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){ 1090 sqlite3_mutex_leave(db->mutex); 1091 return; 1092 } 1093 1094 /* If we reach this point, it means that the database connection has 1095 ** closed all sqlite3_stmt and sqlite3_backup objects and has been 1096 ** passed to sqlite3_close (meaning that it is a zombie). Therefore, 1097 ** go ahead and free all resources. 1098 */ 1099 1100 /* If a transaction is open, roll it back. This also ensures that if 1101 ** any database schemas have been modified by an uncommitted transaction 1102 ** they are reset. And that the required b-tree mutex is held to make 1103 ** the pager rollback and schema reset an atomic operation. */ 1104 sqlite3RollbackAll(db, SQLITE_OK); 1105 1106 /* Free any outstanding Savepoint structures. */ 1107 sqlite3CloseSavepoints(db); 1108 1109 /* Close all database connections */ 1110 for(j=0; j<db->nDb; j++){ 1111 struct Db *pDb = &db->aDb[j]; 1112 if( pDb->pBt ){ 1113 sqlite3BtreeClose(pDb->pBt); 1114 pDb->pBt = 0; 1115 if( j!=1 ){ 1116 pDb->pSchema = 0; 1117 } 1118 } 1119 } 1120 /* Clear the TEMP schema separately and last */ 1121 if( db->aDb[1].pSchema ){ 1122 sqlite3SchemaClear(db->aDb[1].pSchema); 1123 } 1124 sqlite3VtabUnlockList(db); 1125 1126 /* Free up the array of auxiliary databases */ 1127 sqlite3CollapseDatabaseArray(db); 1128 assert( db->nDb<=2 ); 1129 assert( db->aDb==db->aDbStatic ); 1130 1131 /* Tell the code in notify.c that the connection no longer holds any 1132 ** locks and does not require any further unlock-notify callbacks. 1133 */ 1134 sqlite3ConnectionClosed(db); 1135 1136 for(j=0; j<ArraySize(db->aFunc.a); j++){ 1137 FuncDef *pNext, *pHash, *p; 1138 for(p=db->aFunc.a[j]; p; p=pHash){ 1139 pHash = p->pHash; 1140 while( p ){ 1141 functionDestroy(db, p); 1142 pNext = p->pNext; 1143 sqlite3DbFree(db, p); 1144 p = pNext; 1145 } 1146 } 1147 } 1148 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){ 1149 CollSeq *pColl = (CollSeq *)sqliteHashData(i); 1150 /* Invoke any destructors registered for collation sequence user data. */ 1151 for(j=0; j<3; j++){ 1152 if( pColl[j].xDel ){ 1153 pColl[j].xDel(pColl[j].pUser); 1154 } 1155 } 1156 sqlite3DbFree(db, pColl); 1157 } 1158 sqlite3HashClear(&db->aCollSeq); 1159 #ifndef SQLITE_OMIT_VIRTUALTABLE 1160 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){ 1161 Module *pMod = (Module *)sqliteHashData(i); 1162 if( pMod->xDestroy ){ 1163 pMod->xDestroy(pMod->pAux); 1164 } 1165 sqlite3VtabEponymousTableClear(db, pMod); 1166 sqlite3DbFree(db, pMod); 1167 } 1168 sqlite3HashClear(&db->aModule); 1169 #endif 1170 1171 sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */ 1172 sqlite3ValueFree(db->pErr); 1173 sqlite3CloseExtensions(db); 1174 #if SQLITE_USER_AUTHENTICATION 1175 sqlite3_free(db->auth.zAuthUser); 1176 sqlite3_free(db->auth.zAuthPW); 1177 #endif 1178 1179 db->magic = SQLITE_MAGIC_ERROR; 1180 1181 /* The temp-database schema is allocated differently from the other schema 1182 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()). 1183 ** So it needs to be freed here. Todo: Why not roll the temp schema into 1184 ** the same sqliteMalloc() as the one that allocates the database 1185 ** structure? 1186 */ 1187 sqlite3DbFree(db, db->aDb[1].pSchema); 1188 sqlite3_mutex_leave(db->mutex); 1189 db->magic = SQLITE_MAGIC_CLOSED; 1190 sqlite3_mutex_free(db->mutex); 1191 assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */ 1192 if( db->lookaside.bMalloced ){ 1193 sqlite3_free(db->lookaside.pStart); 1194 } 1195 sqlite3_free(db); 1196 } 1197 1198 /* 1199 ** Rollback all database files. If tripCode is not SQLITE_OK, then 1200 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit 1201 ** breaker") and made to return tripCode if there are any further 1202 ** attempts to use that cursor. Read cursors remain open and valid 1203 ** but are "saved" in case the table pages are moved around. 1204 */ 1205 void sqlite3RollbackAll(sqlite3 *db, int tripCode){ 1206 int i; 1207 int inTrans = 0; 1208 int schemaChange; 1209 assert( sqlite3_mutex_held(db->mutex) ); 1210 sqlite3BeginBenignMalloc(); 1211 1212 /* Obtain all b-tree mutexes before making any calls to BtreeRollback(). 1213 ** This is important in case the transaction being rolled back has 1214 ** modified the database schema. If the b-tree mutexes are not taken 1215 ** here, then another shared-cache connection might sneak in between 1216 ** the database rollback and schema reset, which can cause false 1217 ** corruption reports in some cases. */ 1218 sqlite3BtreeEnterAll(db); 1219 schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0; 1220 1221 for(i=0; i<db->nDb; i++){ 1222 Btree *p = db->aDb[i].pBt; 1223 if( p ){ 1224 if( sqlite3BtreeIsInTrans(p) ){ 1225 inTrans = 1; 1226 } 1227 sqlite3BtreeRollback(p, tripCode, !schemaChange); 1228 } 1229 } 1230 sqlite3VtabRollback(db); 1231 sqlite3EndBenignMalloc(); 1232 1233 if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){ 1234 sqlite3ExpirePreparedStatements(db); 1235 sqlite3ResetAllSchemasOfConnection(db); 1236 } 1237 sqlite3BtreeLeaveAll(db); 1238 1239 /* Any deferred constraint violations have now been resolved. */ 1240 db->nDeferredCons = 0; 1241 db->nDeferredImmCons = 0; 1242 db->flags &= ~SQLITE_DeferFKs; 1243 1244 /* If one has been configured, invoke the rollback-hook callback */ 1245 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){ 1246 db->xRollbackCallback(db->pRollbackArg); 1247 } 1248 } 1249 1250 /* 1251 ** Return a static string containing the name corresponding to the error code 1252 ** specified in the argument. 1253 */ 1254 #if defined(SQLITE_NEED_ERR_NAME) 1255 const char *sqlite3ErrName(int rc){ 1256 const char *zName = 0; 1257 int i, origRc = rc; 1258 for(i=0; i<2 && zName==0; i++, rc &= 0xff){ 1259 switch( rc ){ 1260 case SQLITE_OK: zName = "SQLITE_OK"; break; 1261 case SQLITE_ERROR: zName = "SQLITE_ERROR"; break; 1262 case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break; 1263 case SQLITE_PERM: zName = "SQLITE_PERM"; break; 1264 case SQLITE_ABORT: zName = "SQLITE_ABORT"; break; 1265 case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break; 1266 case SQLITE_BUSY: zName = "SQLITE_BUSY"; break; 1267 case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break; 1268 case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break; 1269 case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break; 1270 case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break; 1271 case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break; 1272 case SQLITE_READONLY: zName = "SQLITE_READONLY"; break; 1273 case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break; 1274 case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break; 1275 case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break; 1276 case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break; 1277 case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break; 1278 case SQLITE_IOERR: zName = "SQLITE_IOERR"; break; 1279 case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break; 1280 case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break; 1281 case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break; 1282 case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break; 1283 case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break; 1284 case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break; 1285 case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break; 1286 case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break; 1287 case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break; 1288 case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break; 1289 case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break; 1290 case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break; 1291 case SQLITE_IOERR_CHECKRESERVEDLOCK: 1292 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break; 1293 case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break; 1294 case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break; 1295 case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break; 1296 case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break; 1297 case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break; 1298 case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break; 1299 case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break; 1300 case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break; 1301 case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break; 1302 case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break; 1303 case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break; 1304 case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break; 1305 case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break; 1306 case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break; 1307 case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break; 1308 case SQLITE_FULL: zName = "SQLITE_FULL"; break; 1309 case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break; 1310 case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break; 1311 case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break; 1312 case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break; 1313 case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break; 1314 case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break; 1315 case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break; 1316 case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break; 1317 case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break; 1318 case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break; 1319 case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break; 1320 case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break; 1321 case SQLITE_CONSTRAINT_FOREIGNKEY: 1322 zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break; 1323 case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break; 1324 case SQLITE_CONSTRAINT_PRIMARYKEY: 1325 zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break; 1326 case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break; 1327 case SQLITE_CONSTRAINT_COMMITHOOK: 1328 zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break; 1329 case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break; 1330 case SQLITE_CONSTRAINT_FUNCTION: 1331 zName = "SQLITE_CONSTRAINT_FUNCTION"; break; 1332 case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break; 1333 case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break; 1334 case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break; 1335 case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break; 1336 case SQLITE_AUTH: zName = "SQLITE_AUTH"; break; 1337 case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break; 1338 case SQLITE_RANGE: zName = "SQLITE_RANGE"; break; 1339 case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break; 1340 case SQLITE_ROW: zName = "SQLITE_ROW"; break; 1341 case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break; 1342 case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break; 1343 case SQLITE_NOTICE_RECOVER_ROLLBACK: 1344 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break; 1345 case SQLITE_WARNING: zName = "SQLITE_WARNING"; break; 1346 case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break; 1347 case SQLITE_DONE: zName = "SQLITE_DONE"; break; 1348 } 1349 } 1350 if( zName==0 ){ 1351 static char zBuf[50]; 1352 sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc); 1353 zName = zBuf; 1354 } 1355 return zName; 1356 } 1357 #endif 1358 1359 /* 1360 ** Return a static string that describes the kind of error specified in the 1361 ** argument. 1362 */ 1363 const char *sqlite3ErrStr(int rc){ 1364 static const char* const aMsg[] = { 1365 /* SQLITE_OK */ "not an error", 1366 /* SQLITE_ERROR */ "SQL logic error or missing database", 1367 /* SQLITE_INTERNAL */ 0, 1368 /* SQLITE_PERM */ "access permission denied", 1369 /* SQLITE_ABORT */ "callback requested query abort", 1370 /* SQLITE_BUSY */ "database is locked", 1371 /* SQLITE_LOCKED */ "database table is locked", 1372 /* SQLITE_NOMEM */ "out of memory", 1373 /* SQLITE_READONLY */ "attempt to write a readonly database", 1374 /* SQLITE_INTERRUPT */ "interrupted", 1375 /* SQLITE_IOERR */ "disk I/O error", 1376 /* SQLITE_CORRUPT */ "database disk image is malformed", 1377 /* SQLITE_NOTFOUND */ "unknown operation", 1378 /* SQLITE_FULL */ "database or disk is full", 1379 /* SQLITE_CANTOPEN */ "unable to open database file", 1380 /* SQLITE_PROTOCOL */ "locking protocol", 1381 /* SQLITE_EMPTY */ "table contains no data", 1382 /* SQLITE_SCHEMA */ "database schema has changed", 1383 /* SQLITE_TOOBIG */ "string or blob too big", 1384 /* SQLITE_CONSTRAINT */ "constraint failed", 1385 /* SQLITE_MISMATCH */ "datatype mismatch", 1386 /* SQLITE_MISUSE */ "library routine called out of sequence", 1387 /* SQLITE_NOLFS */ "large file support is disabled", 1388 /* SQLITE_AUTH */ "authorization denied", 1389 /* SQLITE_FORMAT */ "auxiliary database format error", 1390 /* SQLITE_RANGE */ "bind or column index out of range", 1391 /* SQLITE_NOTADB */ "file is encrypted or is not a database", 1392 }; 1393 const char *zErr = "unknown error"; 1394 switch( rc ){ 1395 case SQLITE_ABORT_ROLLBACK: { 1396 zErr = "abort due to ROLLBACK"; 1397 break; 1398 } 1399 default: { 1400 rc &= 0xff; 1401 if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){ 1402 zErr = aMsg[rc]; 1403 } 1404 break; 1405 } 1406 } 1407 return zErr; 1408 } 1409 1410 /* 1411 ** This routine implements a busy callback that sleeps and tries 1412 ** again until a timeout value is reached. The timeout value is 1413 ** an integer number of milliseconds passed in as the first 1414 ** argument. 1415 */ 1416 static int sqliteDefaultBusyCallback( 1417 void *ptr, /* Database connection */ 1418 int count /* Number of times table has been busy */ 1419 ){ 1420 #if SQLITE_OS_WIN || HAVE_USLEEP 1421 static const u8 delays[] = 1422 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 }; 1423 static const u8 totals[] = 1424 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 }; 1425 # define NDELAY ArraySize(delays) 1426 sqlite3 *db = (sqlite3 *)ptr; 1427 int timeout = db->busyTimeout; 1428 int delay, prior; 1429 1430 assert( count>=0 ); 1431 if( count < NDELAY ){ 1432 delay = delays[count]; 1433 prior = totals[count]; 1434 }else{ 1435 delay = delays[NDELAY-1]; 1436 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1)); 1437 } 1438 if( prior + delay > timeout ){ 1439 delay = timeout - prior; 1440 if( delay<=0 ) return 0; 1441 } 1442 sqlite3OsSleep(db->pVfs, delay*1000); 1443 return 1; 1444 #else 1445 sqlite3 *db = (sqlite3 *)ptr; 1446 int timeout = ((sqlite3 *)ptr)->busyTimeout; 1447 if( (count+1)*1000 > timeout ){ 1448 return 0; 1449 } 1450 sqlite3OsSleep(db->pVfs, 1000000); 1451 return 1; 1452 #endif 1453 } 1454 1455 /* 1456 ** Invoke the given busy handler. 1457 ** 1458 ** This routine is called when an operation failed with a lock. 1459 ** If this routine returns non-zero, the lock is retried. If it 1460 ** returns 0, the operation aborts with an SQLITE_BUSY error. 1461 */ 1462 int sqlite3InvokeBusyHandler(BusyHandler *p){ 1463 int rc; 1464 if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0; 1465 rc = p->xFunc(p->pArg, p->nBusy); 1466 if( rc==0 ){ 1467 p->nBusy = -1; 1468 }else{ 1469 p->nBusy++; 1470 } 1471 return rc; 1472 } 1473 1474 /* 1475 ** This routine sets the busy callback for an Sqlite database to the 1476 ** given callback function with the given argument. 1477 */ 1478 int sqlite3_busy_handler( 1479 sqlite3 *db, 1480 int (*xBusy)(void*,int), 1481 void *pArg 1482 ){ 1483 #ifdef SQLITE_ENABLE_API_ARMOR 1484 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; 1485 #endif 1486 sqlite3_mutex_enter(db->mutex); 1487 db->busyHandler.xFunc = xBusy; 1488 db->busyHandler.pArg = pArg; 1489 db->busyHandler.nBusy = 0; 1490 db->busyTimeout = 0; 1491 sqlite3_mutex_leave(db->mutex); 1492 return SQLITE_OK; 1493 } 1494 1495 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 1496 /* 1497 ** This routine sets the progress callback for an Sqlite database to the 1498 ** given callback function with the given argument. The progress callback will 1499 ** be invoked every nOps opcodes. 1500 */ 1501 void sqlite3_progress_handler( 1502 sqlite3 *db, 1503 int nOps, 1504 int (*xProgress)(void*), 1505 void *pArg 1506 ){ 1507 #ifdef SQLITE_ENABLE_API_ARMOR 1508 if( !sqlite3SafetyCheckOk(db) ){ 1509 (void)SQLITE_MISUSE_BKPT; 1510 return; 1511 } 1512 #endif 1513 sqlite3_mutex_enter(db->mutex); 1514 if( nOps>0 ){ 1515 db->xProgress = xProgress; 1516 db->nProgressOps = (unsigned)nOps; 1517 db->pProgressArg = pArg; 1518 }else{ 1519 db->xProgress = 0; 1520 db->nProgressOps = 0; 1521 db->pProgressArg = 0; 1522 } 1523 sqlite3_mutex_leave(db->mutex); 1524 } 1525 #endif 1526 1527 1528 /* 1529 ** This routine installs a default busy handler that waits for the 1530 ** specified number of milliseconds before returning 0. 1531 */ 1532 int sqlite3_busy_timeout(sqlite3 *db, int ms){ 1533 #ifdef SQLITE_ENABLE_API_ARMOR 1534 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; 1535 #endif 1536 if( ms>0 ){ 1537 sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db); 1538 db->busyTimeout = ms; 1539 }else{ 1540 sqlite3_busy_handler(db, 0, 0); 1541 } 1542 return SQLITE_OK; 1543 } 1544 1545 /* 1546 ** Cause any pending operation to stop at its earliest opportunity. 1547 */ 1548 void sqlite3_interrupt(sqlite3 *db){ 1549 #ifdef SQLITE_ENABLE_API_ARMOR 1550 if( !sqlite3SafetyCheckOk(db) ){ 1551 (void)SQLITE_MISUSE_BKPT; 1552 return; 1553 } 1554 #endif 1555 db->u1.isInterrupted = 1; 1556 } 1557 1558 1559 /* 1560 ** This function is exactly the same as sqlite3_create_function(), except 1561 ** that it is designed to be called by internal code. The difference is 1562 ** that if a malloc() fails in sqlite3_create_function(), an error code 1563 ** is returned and the mallocFailed flag cleared. 1564 */ 1565 int sqlite3CreateFunc( 1566 sqlite3 *db, 1567 const char *zFunctionName, 1568 int nArg, 1569 int enc, 1570 void *pUserData, 1571 void (*xFunc)(sqlite3_context*,int,sqlite3_value **), 1572 void (*xStep)(sqlite3_context*,int,sqlite3_value **), 1573 void (*xFinal)(sqlite3_context*), 1574 FuncDestructor *pDestructor 1575 ){ 1576 FuncDef *p; 1577 int nName; 1578 int extraFlags; 1579 1580 assert( sqlite3_mutex_held(db->mutex) ); 1581 if( zFunctionName==0 || 1582 (xFunc && (xFinal || xStep)) || 1583 (!xFunc && (xFinal && !xStep)) || 1584 (!xFunc && (!xFinal && xStep)) || 1585 (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) || 1586 (255<(nName = sqlite3Strlen30( zFunctionName))) ){ 1587 return SQLITE_MISUSE_BKPT; 1588 } 1589 1590 assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC ); 1591 extraFlags = enc & SQLITE_DETERMINISTIC; 1592 enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY); 1593 1594 #ifndef SQLITE_OMIT_UTF16 1595 /* If SQLITE_UTF16 is specified as the encoding type, transform this 1596 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the 1597 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. 1598 ** 1599 ** If SQLITE_ANY is specified, add three versions of the function 1600 ** to the hash table. 1601 */ 1602 if( enc==SQLITE_UTF16 ){ 1603 enc = SQLITE_UTF16NATIVE; 1604 }else if( enc==SQLITE_ANY ){ 1605 int rc; 1606 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags, 1607 pUserData, xFunc, xStep, xFinal, pDestructor); 1608 if( rc==SQLITE_OK ){ 1609 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags, 1610 pUserData, xFunc, xStep, xFinal, pDestructor); 1611 } 1612 if( rc!=SQLITE_OK ){ 1613 return rc; 1614 } 1615 enc = SQLITE_UTF16BE; 1616 } 1617 #else 1618 enc = SQLITE_UTF8; 1619 #endif 1620 1621 /* Check if an existing function is being overridden or deleted. If so, 1622 ** and there are active VMs, then return SQLITE_BUSY. If a function 1623 ** is being overridden/deleted but there are no active VMs, allow the 1624 ** operation to continue but invalidate all precompiled statements. 1625 */ 1626 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0); 1627 if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){ 1628 if( db->nVdbeActive ){ 1629 sqlite3ErrorWithMsg(db, SQLITE_BUSY, 1630 "unable to delete/modify user-function due to active statements"); 1631 assert( !db->mallocFailed ); 1632 return SQLITE_BUSY; 1633 }else{ 1634 sqlite3ExpirePreparedStatements(db); 1635 } 1636 } 1637 1638 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1); 1639 assert(p || db->mallocFailed); 1640 if( !p ){ 1641 return SQLITE_NOMEM; 1642 } 1643 1644 /* If an older version of the function with a configured destructor is 1645 ** being replaced invoke the destructor function here. */ 1646 functionDestroy(db, p); 1647 1648 if( pDestructor ){ 1649 pDestructor->nRef++; 1650 } 1651 p->pDestructor = pDestructor; 1652 p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags; 1653 testcase( p->funcFlags & SQLITE_DETERMINISTIC ); 1654 p->xFunc = xFunc; 1655 p->xStep = xStep; 1656 p->xFinalize = xFinal; 1657 p->pUserData = pUserData; 1658 p->nArg = (u16)nArg; 1659 return SQLITE_OK; 1660 } 1661 1662 /* 1663 ** Create new user functions. 1664 */ 1665 int sqlite3_create_function( 1666 sqlite3 *db, 1667 const char *zFunc, 1668 int nArg, 1669 int enc, 1670 void *p, 1671 void (*xFunc)(sqlite3_context*,int,sqlite3_value **), 1672 void (*xStep)(sqlite3_context*,int,sqlite3_value **), 1673 void (*xFinal)(sqlite3_context*) 1674 ){ 1675 return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep, 1676 xFinal, 0); 1677 } 1678 1679 int sqlite3_create_function_v2( 1680 sqlite3 *db, 1681 const char *zFunc, 1682 int nArg, 1683 int enc, 1684 void *p, 1685 void (*xFunc)(sqlite3_context*,int,sqlite3_value **), 1686 void (*xStep)(sqlite3_context*,int,sqlite3_value **), 1687 void (*xFinal)(sqlite3_context*), 1688 void (*xDestroy)(void *) 1689 ){ 1690 int rc = SQLITE_ERROR; 1691 FuncDestructor *pArg = 0; 1692 1693 #ifdef SQLITE_ENABLE_API_ARMOR 1694 if( !sqlite3SafetyCheckOk(db) ){ 1695 return SQLITE_MISUSE_BKPT; 1696 } 1697 #endif 1698 sqlite3_mutex_enter(db->mutex); 1699 if( xDestroy ){ 1700 pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor)); 1701 if( !pArg ){ 1702 xDestroy(p); 1703 goto out; 1704 } 1705 pArg->xDestroy = xDestroy; 1706 pArg->pUserData = p; 1707 } 1708 rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg); 1709 if( pArg && pArg->nRef==0 ){ 1710 assert( rc!=SQLITE_OK ); 1711 xDestroy(p); 1712 sqlite3DbFree(db, pArg); 1713 } 1714 1715 out: 1716 rc = sqlite3ApiExit(db, rc); 1717 sqlite3_mutex_leave(db->mutex); 1718 return rc; 1719 } 1720 1721 #ifndef SQLITE_OMIT_UTF16 1722 int sqlite3_create_function16( 1723 sqlite3 *db, 1724 const void *zFunctionName, 1725 int nArg, 1726 int eTextRep, 1727 void *p, 1728 void (*xFunc)(sqlite3_context*,int,sqlite3_value**), 1729 void (*xStep)(sqlite3_context*,int,sqlite3_value**), 1730 void (*xFinal)(sqlite3_context*) 1731 ){ 1732 int rc; 1733 char *zFunc8; 1734 1735 #ifdef SQLITE_ENABLE_API_ARMOR 1736 if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT; 1737 #endif 1738 sqlite3_mutex_enter(db->mutex); 1739 assert( !db->mallocFailed ); 1740 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE); 1741 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0); 1742 sqlite3DbFree(db, zFunc8); 1743 rc = sqlite3ApiExit(db, rc); 1744 sqlite3_mutex_leave(db->mutex); 1745 return rc; 1746 } 1747 #endif 1748 1749 1750 /* 1751 ** Declare that a function has been overloaded by a virtual table. 1752 ** 1753 ** If the function already exists as a regular global function, then 1754 ** this routine is a no-op. If the function does not exist, then create 1755 ** a new one that always throws a run-time error. 1756 ** 1757 ** When virtual tables intend to provide an overloaded function, they 1758 ** should call this routine to make sure the global function exists. 1759 ** A global function must exist in order for name resolution to work 1760 ** properly. 1761 */ 1762 int sqlite3_overload_function( 1763 sqlite3 *db, 1764 const char *zName, 1765 int nArg 1766 ){ 1767 int nName = sqlite3Strlen30(zName); 1768 int rc = SQLITE_OK; 1769 1770 #ifdef SQLITE_ENABLE_API_ARMOR 1771 if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){ 1772 return SQLITE_MISUSE_BKPT; 1773 } 1774 #endif 1775 sqlite3_mutex_enter(db->mutex); 1776 if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){ 1777 rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8, 1778 0, sqlite3InvalidFunction, 0, 0, 0); 1779 } 1780 rc = sqlite3ApiExit(db, rc); 1781 sqlite3_mutex_leave(db->mutex); 1782 return rc; 1783 } 1784 1785 #ifndef SQLITE_OMIT_TRACE 1786 /* 1787 ** Register a trace function. The pArg from the previously registered trace 1788 ** is returned. 1789 ** 1790 ** A NULL trace function means that no tracing is executes. A non-NULL 1791 ** trace is a pointer to a function that is invoked at the start of each 1792 ** SQL statement. 1793 */ 1794 void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){ 1795 void *pOld; 1796 1797 #ifdef SQLITE_ENABLE_API_ARMOR 1798 if( !sqlite3SafetyCheckOk(db) ){ 1799 (void)SQLITE_MISUSE_BKPT; 1800 return 0; 1801 } 1802 #endif 1803 sqlite3_mutex_enter(db->mutex); 1804 pOld = db->pTraceArg; 1805 db->xTrace = xTrace; 1806 db->pTraceArg = pArg; 1807 sqlite3_mutex_leave(db->mutex); 1808 return pOld; 1809 } 1810 /* 1811 ** Register a profile function. The pArg from the previously registered 1812 ** profile function is returned. 1813 ** 1814 ** A NULL profile function means that no profiling is executes. A non-NULL 1815 ** profile is a pointer to a function that is invoked at the conclusion of 1816 ** each SQL statement that is run. 1817 */ 1818 void *sqlite3_profile( 1819 sqlite3 *db, 1820 void (*xProfile)(void*,const char*,sqlite_uint64), 1821 void *pArg 1822 ){ 1823 void *pOld; 1824 1825 #ifdef SQLITE_ENABLE_API_ARMOR 1826 if( !sqlite3SafetyCheckOk(db) ){ 1827 (void)SQLITE_MISUSE_BKPT; 1828 return 0; 1829 } 1830 #endif 1831 sqlite3_mutex_enter(db->mutex); 1832 pOld = db->pProfileArg; 1833 db->xProfile = xProfile; 1834 db->pProfileArg = pArg; 1835 sqlite3_mutex_leave(db->mutex); 1836 return pOld; 1837 } 1838 #endif /* SQLITE_OMIT_TRACE */ 1839 1840 /* 1841 ** Register a function to be invoked when a transaction commits. 1842 ** If the invoked function returns non-zero, then the commit becomes a 1843 ** rollback. 1844 */ 1845 void *sqlite3_commit_hook( 1846 sqlite3 *db, /* Attach the hook to this database */ 1847 int (*xCallback)(void*), /* Function to invoke on each commit */ 1848 void *pArg /* Argument to the function */ 1849 ){ 1850 void *pOld; 1851 1852 #ifdef SQLITE_ENABLE_API_ARMOR 1853 if( !sqlite3SafetyCheckOk(db) ){ 1854 (void)SQLITE_MISUSE_BKPT; 1855 return 0; 1856 } 1857 #endif 1858 sqlite3_mutex_enter(db->mutex); 1859 pOld = db->pCommitArg; 1860 db->xCommitCallback = xCallback; 1861 db->pCommitArg = pArg; 1862 sqlite3_mutex_leave(db->mutex); 1863 return pOld; 1864 } 1865 1866 /* 1867 ** Register a callback to be invoked each time a row is updated, 1868 ** inserted or deleted using this database connection. 1869 */ 1870 void *sqlite3_update_hook( 1871 sqlite3 *db, /* Attach the hook to this database */ 1872 void (*xCallback)(void*,int,char const *,char const *,sqlite_int64), 1873 void *pArg /* Argument to the function */ 1874 ){ 1875 void *pRet; 1876 1877 #ifdef SQLITE_ENABLE_API_ARMOR 1878 if( !sqlite3SafetyCheckOk(db) ){ 1879 (void)SQLITE_MISUSE_BKPT; 1880 return 0; 1881 } 1882 #endif 1883 sqlite3_mutex_enter(db->mutex); 1884 pRet = db->pUpdateArg; 1885 db->xUpdateCallback = xCallback; 1886 db->pUpdateArg = pArg; 1887 sqlite3_mutex_leave(db->mutex); 1888 return pRet; 1889 } 1890 1891 /* 1892 ** Register a callback to be invoked each time a transaction is rolled 1893 ** back by this database connection. 1894 */ 1895 void *sqlite3_rollback_hook( 1896 sqlite3 *db, /* Attach the hook to this database */ 1897 void (*xCallback)(void*), /* Callback function */ 1898 void *pArg /* Argument to the function */ 1899 ){ 1900 void *pRet; 1901 1902 #ifdef SQLITE_ENABLE_API_ARMOR 1903 if( !sqlite3SafetyCheckOk(db) ){ 1904 (void)SQLITE_MISUSE_BKPT; 1905 return 0; 1906 } 1907 #endif 1908 sqlite3_mutex_enter(db->mutex); 1909 pRet = db->pRollbackArg; 1910 db->xRollbackCallback = xCallback; 1911 db->pRollbackArg = pArg; 1912 sqlite3_mutex_leave(db->mutex); 1913 return pRet; 1914 } 1915 1916 #ifndef SQLITE_OMIT_WAL 1917 /* 1918 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint(). 1919 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file 1920 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by 1921 ** wal_autocheckpoint()). 1922 */ 1923 int sqlite3WalDefaultHook( 1924 void *pClientData, /* Argument */ 1925 sqlite3 *db, /* Connection */ 1926 const char *zDb, /* Database */ 1927 int nFrame /* Size of WAL */ 1928 ){ 1929 if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){ 1930 sqlite3BeginBenignMalloc(); 1931 sqlite3_wal_checkpoint(db, zDb); 1932 sqlite3EndBenignMalloc(); 1933 } 1934 return SQLITE_OK; 1935 } 1936 #endif /* SQLITE_OMIT_WAL */ 1937 1938 /* 1939 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint 1940 ** a database after committing a transaction if there are nFrame or 1941 ** more frames in the log file. Passing zero or a negative value as the 1942 ** nFrame parameter disables automatic checkpoints entirely. 1943 ** 1944 ** The callback registered by this function replaces any existing callback 1945 ** registered using sqlite3_wal_hook(). Likewise, registering a callback 1946 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism 1947 ** configured by this function. 1948 */ 1949 int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){ 1950 #ifdef SQLITE_OMIT_WAL 1951 UNUSED_PARAMETER(db); 1952 UNUSED_PARAMETER(nFrame); 1953 #else 1954 #ifdef SQLITE_ENABLE_API_ARMOR 1955 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; 1956 #endif 1957 if( nFrame>0 ){ 1958 sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame)); 1959 }else{ 1960 sqlite3_wal_hook(db, 0, 0); 1961 } 1962 #endif 1963 return SQLITE_OK; 1964 } 1965 1966 /* 1967 ** Register a callback to be invoked each time a transaction is written 1968 ** into the write-ahead-log by this database connection. 1969 */ 1970 void *sqlite3_wal_hook( 1971 sqlite3 *db, /* Attach the hook to this db handle */ 1972 int(*xCallback)(void *, sqlite3*, const char*, int), 1973 void *pArg /* First argument passed to xCallback() */ 1974 ){ 1975 #ifndef SQLITE_OMIT_WAL 1976 void *pRet; 1977 #ifdef SQLITE_ENABLE_API_ARMOR 1978 if( !sqlite3SafetyCheckOk(db) ){ 1979 (void)SQLITE_MISUSE_BKPT; 1980 return 0; 1981 } 1982 #endif 1983 sqlite3_mutex_enter(db->mutex); 1984 pRet = db->pWalArg; 1985 db->xWalCallback = xCallback; 1986 db->pWalArg = pArg; 1987 sqlite3_mutex_leave(db->mutex); 1988 return pRet; 1989 #else 1990 return 0; 1991 #endif 1992 } 1993 1994 /* 1995 ** Checkpoint database zDb. 1996 */ 1997 int sqlite3_wal_checkpoint_v2( 1998 sqlite3 *db, /* Database handle */ 1999 const char *zDb, /* Name of attached database (or NULL) */ 2000 int eMode, /* SQLITE_CHECKPOINT_* value */ 2001 int *pnLog, /* OUT: Size of WAL log in frames */ 2002 int *pnCkpt /* OUT: Total number of frames checkpointed */ 2003 ){ 2004 #ifdef SQLITE_OMIT_WAL 2005 return SQLITE_OK; 2006 #else 2007 int rc; /* Return code */ 2008 int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */ 2009 2010 #ifdef SQLITE_ENABLE_API_ARMOR 2011 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; 2012 #endif 2013 2014 /* Initialize the output variables to -1 in case an error occurs. */ 2015 if( pnLog ) *pnLog = -1; 2016 if( pnCkpt ) *pnCkpt = -1; 2017 2018 assert( SQLITE_CHECKPOINT_PASSIVE==0 ); 2019 assert( SQLITE_CHECKPOINT_FULL==1 ); 2020 assert( SQLITE_CHECKPOINT_RESTART==2 ); 2021 assert( SQLITE_CHECKPOINT_TRUNCATE==3 ); 2022 if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){ 2023 /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint 2024 ** mode: */ 2025 return SQLITE_MISUSE; 2026 } 2027 2028 sqlite3_mutex_enter(db->mutex); 2029 if( zDb && zDb[0] ){ 2030 iDb = sqlite3FindDbName(db, zDb); 2031 } 2032 if( iDb<0 ){ 2033 rc = SQLITE_ERROR; 2034 sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb); 2035 }else{ 2036 db->busyHandler.nBusy = 0; 2037 rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt); 2038 sqlite3Error(db, rc); 2039 } 2040 rc = sqlite3ApiExit(db, rc); 2041 sqlite3_mutex_leave(db->mutex); 2042 return rc; 2043 #endif 2044 } 2045 2046 2047 /* 2048 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points 2049 ** to contains a zero-length string, all attached databases are 2050 ** checkpointed. 2051 */ 2052 int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){ 2053 /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to 2054 ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */ 2055 return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0); 2056 } 2057 2058 #ifndef SQLITE_OMIT_WAL 2059 /* 2060 ** Run a checkpoint on database iDb. This is a no-op if database iDb is 2061 ** not currently open in WAL mode. 2062 ** 2063 ** If a transaction is open on the database being checkpointed, this 2064 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 2065 ** an error occurs while running the checkpoint, an SQLite error code is 2066 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK. 2067 ** 2068 ** The mutex on database handle db should be held by the caller. The mutex 2069 ** associated with the specific b-tree being checkpointed is taken by 2070 ** this function while the checkpoint is running. 2071 ** 2072 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are 2073 ** checkpointed. If an error is encountered it is returned immediately - 2074 ** no attempt is made to checkpoint any remaining databases. 2075 ** 2076 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. 2077 */ 2078 int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){ 2079 int rc = SQLITE_OK; /* Return code */ 2080 int i; /* Used to iterate through attached dbs */ 2081 int bBusy = 0; /* True if SQLITE_BUSY has been encountered */ 2082 2083 assert( sqlite3_mutex_held(db->mutex) ); 2084 assert( !pnLog || *pnLog==-1 ); 2085 assert( !pnCkpt || *pnCkpt==-1 ); 2086 2087 for(i=0; i<db->nDb && rc==SQLITE_OK; i++){ 2088 if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){ 2089 rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt); 2090 pnLog = 0; 2091 pnCkpt = 0; 2092 if( rc==SQLITE_BUSY ){ 2093 bBusy = 1; 2094 rc = SQLITE_OK; 2095 } 2096 } 2097 } 2098 2099 return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc; 2100 } 2101 #endif /* SQLITE_OMIT_WAL */ 2102 2103 /* 2104 ** This function returns true if main-memory should be used instead of 2105 ** a temporary file for transient pager files and statement journals. 2106 ** The value returned depends on the value of db->temp_store (runtime 2107 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The 2108 ** following table describes the relationship between these two values 2109 ** and this functions return value. 2110 ** 2111 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database 2112 ** ----------------- -------------- ------------------------------ 2113 ** 0 any file (return 0) 2114 ** 1 1 file (return 0) 2115 ** 1 2 memory (return 1) 2116 ** 1 0 file (return 0) 2117 ** 2 1 file (return 0) 2118 ** 2 2 memory (return 1) 2119 ** 2 0 memory (return 1) 2120 ** 3 any memory (return 1) 2121 */ 2122 int sqlite3TempInMemory(const sqlite3 *db){ 2123 #if SQLITE_TEMP_STORE==1 2124 return ( db->temp_store==2 ); 2125 #endif 2126 #if SQLITE_TEMP_STORE==2 2127 return ( db->temp_store!=1 ); 2128 #endif 2129 #if SQLITE_TEMP_STORE==3 2130 UNUSED_PARAMETER(db); 2131 return 1; 2132 #endif 2133 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3 2134 UNUSED_PARAMETER(db); 2135 return 0; 2136 #endif 2137 } 2138 2139 /* 2140 ** Return UTF-8 encoded English language explanation of the most recent 2141 ** error. 2142 */ 2143 const char *sqlite3_errmsg(sqlite3 *db){ 2144 const char *z; 2145 if( !db ){ 2146 return sqlite3ErrStr(SQLITE_NOMEM); 2147 } 2148 if( !sqlite3SafetyCheckSickOrOk(db) ){ 2149 return sqlite3ErrStr(SQLITE_MISUSE_BKPT); 2150 } 2151 sqlite3_mutex_enter(db->mutex); 2152 if( db->mallocFailed ){ 2153 z = sqlite3ErrStr(SQLITE_NOMEM); 2154 }else{ 2155 testcase( db->pErr==0 ); 2156 z = (char*)sqlite3_value_text(db->pErr); 2157 assert( !db->mallocFailed ); 2158 if( z==0 ){ 2159 z = sqlite3ErrStr(db->errCode); 2160 } 2161 } 2162 sqlite3_mutex_leave(db->mutex); 2163 return z; 2164 } 2165 2166 #ifndef SQLITE_OMIT_UTF16 2167 /* 2168 ** Return UTF-16 encoded English language explanation of the most recent 2169 ** error. 2170 */ 2171 const void *sqlite3_errmsg16(sqlite3 *db){ 2172 static const u16 outOfMem[] = { 2173 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0 2174 }; 2175 static const u16 misuse[] = { 2176 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 2177 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 2178 'c', 'a', 'l', 'l', 'e', 'd', ' ', 2179 'o', 'u', 't', ' ', 2180 'o', 'f', ' ', 2181 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0 2182 }; 2183 2184 const void *z; 2185 if( !db ){ 2186 return (void *)outOfMem; 2187 } 2188 if( !sqlite3SafetyCheckSickOrOk(db) ){ 2189 return (void *)misuse; 2190 } 2191 sqlite3_mutex_enter(db->mutex); 2192 if( db->mallocFailed ){ 2193 z = (void *)outOfMem; 2194 }else{ 2195 z = sqlite3_value_text16(db->pErr); 2196 if( z==0 ){ 2197 sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode)); 2198 z = sqlite3_value_text16(db->pErr); 2199 } 2200 /* A malloc() may have failed within the call to sqlite3_value_text16() 2201 ** above. If this is the case, then the db->mallocFailed flag needs to 2202 ** be cleared before returning. Do this directly, instead of via 2203 ** sqlite3ApiExit(), to avoid setting the database handle error message. 2204 */ 2205 db->mallocFailed = 0; 2206 } 2207 sqlite3_mutex_leave(db->mutex); 2208 return z; 2209 } 2210 #endif /* SQLITE_OMIT_UTF16 */ 2211 2212 /* 2213 ** Return the most recent error code generated by an SQLite routine. If NULL is 2214 ** passed to this function, we assume a malloc() failed during sqlite3_open(). 2215 */ 2216 int sqlite3_errcode(sqlite3 *db){ 2217 if( db && !sqlite3SafetyCheckSickOrOk(db) ){ 2218 return SQLITE_MISUSE_BKPT; 2219 } 2220 if( !db || db->mallocFailed ){ 2221 return SQLITE_NOMEM; 2222 } 2223 return db->errCode & db->errMask; 2224 } 2225 int sqlite3_extended_errcode(sqlite3 *db){ 2226 if( db && !sqlite3SafetyCheckSickOrOk(db) ){ 2227 return SQLITE_MISUSE_BKPT; 2228 } 2229 if( !db || db->mallocFailed ){ 2230 return SQLITE_NOMEM; 2231 } 2232 return db->errCode; 2233 } 2234 2235 /* 2236 ** Return a string that describes the kind of error specified in the 2237 ** argument. For now, this simply calls the internal sqlite3ErrStr() 2238 ** function. 2239 */ 2240 const char *sqlite3_errstr(int rc){ 2241 return sqlite3ErrStr(rc); 2242 } 2243 2244 /* 2245 ** Create a new collating function for database "db". The name is zName 2246 ** and the encoding is enc. 2247 */ 2248 static int createCollation( 2249 sqlite3* db, 2250 const char *zName, 2251 u8 enc, 2252 void* pCtx, 2253 int(*xCompare)(void*,int,const void*,int,const void*), 2254 void(*xDel)(void*) 2255 ){ 2256 CollSeq *pColl; 2257 int enc2; 2258 2259 assert( sqlite3_mutex_held(db->mutex) ); 2260 2261 /* If SQLITE_UTF16 is specified as the encoding type, transform this 2262 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the 2263 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. 2264 */ 2265 enc2 = enc; 2266 testcase( enc2==SQLITE_UTF16 ); 2267 testcase( enc2==SQLITE_UTF16_ALIGNED ); 2268 if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){ 2269 enc2 = SQLITE_UTF16NATIVE; 2270 } 2271 if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){ 2272 return SQLITE_MISUSE_BKPT; 2273 } 2274 2275 /* Check if this call is removing or replacing an existing collation 2276 ** sequence. If so, and there are active VMs, return busy. If there 2277 ** are no active VMs, invalidate any pre-compiled statements. 2278 */ 2279 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0); 2280 if( pColl && pColl->xCmp ){ 2281 if( db->nVdbeActive ){ 2282 sqlite3ErrorWithMsg(db, SQLITE_BUSY, 2283 "unable to delete/modify collation sequence due to active statements"); 2284 return SQLITE_BUSY; 2285 } 2286 sqlite3ExpirePreparedStatements(db); 2287 2288 /* If collation sequence pColl was created directly by a call to 2289 ** sqlite3_create_collation, and not generated by synthCollSeq(), 2290 ** then any copies made by synthCollSeq() need to be invalidated. 2291 ** Also, collation destructor - CollSeq.xDel() - function may need 2292 ** to be called. 2293 */ 2294 if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){ 2295 CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName); 2296 int j; 2297 for(j=0; j<3; j++){ 2298 CollSeq *p = &aColl[j]; 2299 if( p->enc==pColl->enc ){ 2300 if( p->xDel ){ 2301 p->xDel(p->pUser); 2302 } 2303 p->xCmp = 0; 2304 } 2305 } 2306 } 2307 } 2308 2309 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1); 2310 if( pColl==0 ) return SQLITE_NOMEM; 2311 pColl->xCmp = xCompare; 2312 pColl->pUser = pCtx; 2313 pColl->xDel = xDel; 2314 pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED)); 2315 sqlite3Error(db, SQLITE_OK); 2316 return SQLITE_OK; 2317 } 2318 2319 2320 /* 2321 ** This array defines hard upper bounds on limit values. The 2322 ** initializer must be kept in sync with the SQLITE_LIMIT_* 2323 ** #defines in sqlite3.h. 2324 */ 2325 static const int aHardLimit[] = { 2326 SQLITE_MAX_LENGTH, 2327 SQLITE_MAX_SQL_LENGTH, 2328 SQLITE_MAX_COLUMN, 2329 SQLITE_MAX_EXPR_DEPTH, 2330 SQLITE_MAX_COMPOUND_SELECT, 2331 SQLITE_MAX_VDBE_OP, 2332 SQLITE_MAX_FUNCTION_ARG, 2333 SQLITE_MAX_ATTACHED, 2334 SQLITE_MAX_LIKE_PATTERN_LENGTH, 2335 SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */ 2336 SQLITE_MAX_TRIGGER_DEPTH, 2337 SQLITE_MAX_WORKER_THREADS, 2338 }; 2339 2340 /* 2341 ** Make sure the hard limits are set to reasonable values 2342 */ 2343 #if SQLITE_MAX_LENGTH<100 2344 # error SQLITE_MAX_LENGTH must be at least 100 2345 #endif 2346 #if SQLITE_MAX_SQL_LENGTH<100 2347 # error SQLITE_MAX_SQL_LENGTH must be at least 100 2348 #endif 2349 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH 2350 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH 2351 #endif 2352 #if SQLITE_MAX_COMPOUND_SELECT<2 2353 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2 2354 #endif 2355 #if SQLITE_MAX_VDBE_OP<40 2356 # error SQLITE_MAX_VDBE_OP must be at least 40 2357 #endif 2358 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000 2359 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000 2360 #endif 2361 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125 2362 # error SQLITE_MAX_ATTACHED must be between 0 and 125 2363 #endif 2364 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1 2365 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1 2366 #endif 2367 #if SQLITE_MAX_COLUMN>32767 2368 # error SQLITE_MAX_COLUMN must not exceed 32767 2369 #endif 2370 #if SQLITE_MAX_TRIGGER_DEPTH<1 2371 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1 2372 #endif 2373 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50 2374 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50 2375 #endif 2376 2377 2378 /* 2379 ** Change the value of a limit. Report the old value. 2380 ** If an invalid limit index is supplied, report -1. 2381 ** Make no changes but still report the old value if the 2382 ** new limit is negative. 2383 ** 2384 ** A new lower limit does not shrink existing constructs. 2385 ** It merely prevents new constructs that exceed the limit 2386 ** from forming. 2387 */ 2388 int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){ 2389 int oldLimit; 2390 2391 #ifdef SQLITE_ENABLE_API_ARMOR 2392 if( !sqlite3SafetyCheckOk(db) ){ 2393 (void)SQLITE_MISUSE_BKPT; 2394 return -1; 2395 } 2396 #endif 2397 2398 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME 2399 ** there is a hard upper bound set at compile-time by a C preprocessor 2400 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to 2401 ** "_MAX_".) 2402 */ 2403 assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH ); 2404 assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH ); 2405 assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN ); 2406 assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH ); 2407 assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT); 2408 assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP ); 2409 assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG ); 2410 assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED ); 2411 assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]== 2412 SQLITE_MAX_LIKE_PATTERN_LENGTH ); 2413 assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER); 2414 assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH ); 2415 assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS ); 2416 assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) ); 2417 2418 2419 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){ 2420 return -1; 2421 } 2422 oldLimit = db->aLimit[limitId]; 2423 if( newLimit>=0 ){ /* IMP: R-52476-28732 */ 2424 if( newLimit>aHardLimit[limitId] ){ 2425 newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */ 2426 } 2427 db->aLimit[limitId] = newLimit; 2428 } 2429 return oldLimit; /* IMP: R-53341-35419 */ 2430 } 2431 2432 /* 2433 ** This function is used to parse both URIs and non-URI filenames passed by the 2434 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database 2435 ** URIs specified as part of ATTACH statements. 2436 ** 2437 ** The first argument to this function is the name of the VFS to use (or 2438 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx" 2439 ** query parameter. The second argument contains the URI (or non-URI filename) 2440 ** itself. When this function is called the *pFlags variable should contain 2441 ** the default flags to open the database handle with. The value stored in 2442 ** *pFlags may be updated before returning if the URI filename contains 2443 ** "cache=xxx" or "mode=xxx" query parameters. 2444 ** 2445 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to 2446 ** the VFS that should be used to open the database file. *pzFile is set to 2447 ** point to a buffer containing the name of the file to open. It is the 2448 ** responsibility of the caller to eventually call sqlite3_free() to release 2449 ** this buffer. 2450 ** 2451 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg 2452 ** may be set to point to a buffer containing an English language error 2453 ** message. It is the responsibility of the caller to eventually release 2454 ** this buffer by calling sqlite3_free(). 2455 */ 2456 int sqlite3ParseUri( 2457 const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */ 2458 const char *zUri, /* Nul-terminated URI to parse */ 2459 unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */ 2460 sqlite3_vfs **ppVfs, /* OUT: VFS to use */ 2461 char **pzFile, /* OUT: Filename component of URI */ 2462 char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */ 2463 ){ 2464 int rc = SQLITE_OK; 2465 unsigned int flags = *pFlags; 2466 const char *zVfs = zDefaultVfs; 2467 char *zFile; 2468 char c; 2469 int nUri = sqlite3Strlen30(zUri); 2470 2471 assert( *pzErrMsg==0 ); 2472 2473 if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */ 2474 || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */ 2475 && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */ 2476 ){ 2477 char *zOpt; 2478 int eState; /* Parser state when parsing URI */ 2479 int iIn; /* Input character index */ 2480 int iOut = 0; /* Output character index */ 2481 u64 nByte = nUri+2; /* Bytes of space to allocate */ 2482 2483 /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen 2484 ** method that there may be extra parameters following the file-name. */ 2485 flags |= SQLITE_OPEN_URI; 2486 2487 for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&'); 2488 zFile = sqlite3_malloc64(nByte); 2489 if( !zFile ) return SQLITE_NOMEM; 2490 2491 iIn = 5; 2492 #ifdef SQLITE_ALLOW_URI_AUTHORITY 2493 if( strncmp(zUri+5, "///", 3)==0 ){ 2494 iIn = 7; 2495 /* The following condition causes URIs with five leading / characters 2496 ** like file://///host/path to be converted into UNCs like //host/path. 2497 ** The correct URI for that UNC has only two or four leading / characters 2498 ** file://host/path or file:////host/path. But 5 leading slashes is a 2499 ** common error, we are told, so we handle it as a special case. */ 2500 if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; } 2501 }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){ 2502 iIn = 16; 2503 } 2504 #else 2505 /* Discard the scheme and authority segments of the URI. */ 2506 if( zUri[5]=='/' && zUri[6]=='/' ){ 2507 iIn = 7; 2508 while( zUri[iIn] && zUri[iIn]!='/' ) iIn++; 2509 if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){ 2510 *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", 2511 iIn-7, &zUri[7]); 2512 rc = SQLITE_ERROR; 2513 goto parse_uri_out; 2514 } 2515 } 2516 #endif 2517 2518 /* Copy the filename and any query parameters into the zFile buffer. 2519 ** Decode %HH escape codes along the way. 2520 ** 2521 ** Within this loop, variable eState may be set to 0, 1 or 2, depending 2522 ** on the parsing context. As follows: 2523 ** 2524 ** 0: Parsing file-name. 2525 ** 1: Parsing name section of a name=value query parameter. 2526 ** 2: Parsing value section of a name=value query parameter. 2527 */ 2528 eState = 0; 2529 while( (c = zUri[iIn])!=0 && c!='#' ){ 2530 iIn++; 2531 if( c=='%' 2532 && sqlite3Isxdigit(zUri[iIn]) 2533 && sqlite3Isxdigit(zUri[iIn+1]) 2534 ){ 2535 int octet = (sqlite3HexToInt(zUri[iIn++]) << 4); 2536 octet += sqlite3HexToInt(zUri[iIn++]); 2537 2538 assert( octet>=0 && octet<256 ); 2539 if( octet==0 ){ 2540 /* This branch is taken when "%00" appears within the URI. In this 2541 ** case we ignore all text in the remainder of the path, name or 2542 ** value currently being parsed. So ignore the current character 2543 ** and skip to the next "?", "=" or "&", as appropriate. */ 2544 while( (c = zUri[iIn])!=0 && c!='#' 2545 && (eState!=0 || c!='?') 2546 && (eState!=1 || (c!='=' && c!='&')) 2547 && (eState!=2 || c!='&') 2548 ){ 2549 iIn++; 2550 } 2551 continue; 2552 } 2553 c = octet; 2554 }else if( eState==1 && (c=='&' || c=='=') ){ 2555 if( zFile[iOut-1]==0 ){ 2556 /* An empty option name. Ignore this option altogether. */ 2557 while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++; 2558 continue; 2559 } 2560 if( c=='&' ){ 2561 zFile[iOut++] = '\0'; 2562 }else{ 2563 eState = 2; 2564 } 2565 c = 0; 2566 }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){ 2567 c = 0; 2568 eState = 1; 2569 } 2570 zFile[iOut++] = c; 2571 } 2572 if( eState==1 ) zFile[iOut++] = '\0'; 2573 zFile[iOut++] = '\0'; 2574 zFile[iOut++] = '\0'; 2575 2576 /* Check if there were any options specified that should be interpreted 2577 ** here. Options that are interpreted here include "vfs" and those that 2578 ** correspond to flags that may be passed to the sqlite3_open_v2() 2579 ** method. */ 2580 zOpt = &zFile[sqlite3Strlen30(zFile)+1]; 2581 while( zOpt[0] ){ 2582 int nOpt = sqlite3Strlen30(zOpt); 2583 char *zVal = &zOpt[nOpt+1]; 2584 int nVal = sqlite3Strlen30(zVal); 2585 2586 if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){ 2587 zVfs = zVal; 2588 }else{ 2589 struct OpenMode { 2590 const char *z; 2591 int mode; 2592 } *aMode = 0; 2593 char *zModeType = 0; 2594 int mask = 0; 2595 int limit = 0; 2596 2597 if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){ 2598 static struct OpenMode aCacheMode[] = { 2599 { "shared", SQLITE_OPEN_SHAREDCACHE }, 2600 { "private", SQLITE_OPEN_PRIVATECACHE }, 2601 { 0, 0 } 2602 }; 2603 2604 mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE; 2605 aMode = aCacheMode; 2606 limit = mask; 2607 zModeType = "cache"; 2608 } 2609 if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){ 2610 static struct OpenMode aOpenMode[] = { 2611 { "ro", SQLITE_OPEN_READONLY }, 2612 { "rw", SQLITE_OPEN_READWRITE }, 2613 { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE }, 2614 { "memory", SQLITE_OPEN_MEMORY }, 2615 { 0, 0 } 2616 }; 2617 2618 mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE 2619 | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY; 2620 aMode = aOpenMode; 2621 limit = mask & flags; 2622 zModeType = "access"; 2623 } 2624 2625 if( aMode ){ 2626 int i; 2627 int mode = 0; 2628 for(i=0; aMode[i].z; i++){ 2629 const char *z = aMode[i].z; 2630 if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){ 2631 mode = aMode[i].mode; 2632 break; 2633 } 2634 } 2635 if( mode==0 ){ 2636 *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal); 2637 rc = SQLITE_ERROR; 2638 goto parse_uri_out; 2639 } 2640 if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){ 2641 *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s", 2642 zModeType, zVal); 2643 rc = SQLITE_PERM; 2644 goto parse_uri_out; 2645 } 2646 flags = (flags & ~mask) | mode; 2647 } 2648 } 2649 2650 zOpt = &zVal[nVal+1]; 2651 } 2652 2653 }else{ 2654 zFile = sqlite3_malloc64(nUri+2); 2655 if( !zFile ) return SQLITE_NOMEM; 2656 memcpy(zFile, zUri, nUri); 2657 zFile[nUri] = '\0'; 2658 zFile[nUri+1] = '\0'; 2659 flags &= ~SQLITE_OPEN_URI; 2660 } 2661 2662 *ppVfs = sqlite3_vfs_find(zVfs); 2663 if( *ppVfs==0 ){ 2664 *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs); 2665 rc = SQLITE_ERROR; 2666 } 2667 parse_uri_out: 2668 if( rc!=SQLITE_OK ){ 2669 sqlite3_free(zFile); 2670 zFile = 0; 2671 } 2672 *pFlags = flags; 2673 *pzFile = zFile; 2674 return rc; 2675 } 2676 2677 2678 /* 2679 ** This routine does the work of opening a database on behalf of 2680 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename" 2681 ** is UTF-8 encoded. 2682 */ 2683 static int openDatabase( 2684 const char *zFilename, /* Database filename UTF-8 encoded */ 2685 sqlite3 **ppDb, /* OUT: Returned database handle */ 2686 unsigned int flags, /* Operational flags */ 2687 const char *zVfs /* Name of the VFS to use */ 2688 ){ 2689 sqlite3 *db; /* Store allocated handle here */ 2690 int rc; /* Return code */ 2691 int isThreadsafe; /* True for threadsafe connections */ 2692 char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */ 2693 char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */ 2694 2695 #ifdef SQLITE_ENABLE_API_ARMOR 2696 if( ppDb==0 ) return SQLITE_MISUSE_BKPT; 2697 #endif 2698 *ppDb = 0; 2699 #ifndef SQLITE_OMIT_AUTOINIT 2700 rc = sqlite3_initialize(); 2701 if( rc ) return rc; 2702 #endif 2703 2704 /* Only allow sensible combinations of bits in the flags argument. 2705 ** Throw an error if any non-sense combination is used. If we 2706 ** do not block illegal combinations here, it could trigger 2707 ** assert() statements in deeper layers. Sensible combinations 2708 ** are: 2709 ** 2710 ** 1: SQLITE_OPEN_READONLY 2711 ** 2: SQLITE_OPEN_READWRITE 2712 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE 2713 */ 2714 assert( SQLITE_OPEN_READONLY == 0x01 ); 2715 assert( SQLITE_OPEN_READWRITE == 0x02 ); 2716 assert( SQLITE_OPEN_CREATE == 0x04 ); 2717 testcase( (1<<(flags&7))==0x02 ); /* READONLY */ 2718 testcase( (1<<(flags&7))==0x04 ); /* READWRITE */ 2719 testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */ 2720 if( ((1<<(flags&7)) & 0x46)==0 ){ 2721 return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */ 2722 } 2723 2724 if( sqlite3GlobalConfig.bCoreMutex==0 ){ 2725 isThreadsafe = 0; 2726 }else if( flags & SQLITE_OPEN_NOMUTEX ){ 2727 isThreadsafe = 0; 2728 }else if( flags & SQLITE_OPEN_FULLMUTEX ){ 2729 isThreadsafe = 1; 2730 }else{ 2731 isThreadsafe = sqlite3GlobalConfig.bFullMutex; 2732 } 2733 if( flags & SQLITE_OPEN_PRIVATECACHE ){ 2734 flags &= ~SQLITE_OPEN_SHAREDCACHE; 2735 }else if( sqlite3GlobalConfig.sharedCacheEnabled ){ 2736 flags |= SQLITE_OPEN_SHAREDCACHE; 2737 } 2738 2739 /* Remove harmful bits from the flags parameter 2740 ** 2741 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were 2742 ** dealt with in the previous code block. Besides these, the only 2743 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY, 2744 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE, 2745 ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask 2746 ** off all other flags. 2747 */ 2748 flags &= ~( SQLITE_OPEN_DELETEONCLOSE | 2749 SQLITE_OPEN_EXCLUSIVE | 2750 SQLITE_OPEN_MAIN_DB | 2751 SQLITE_OPEN_TEMP_DB | 2752 SQLITE_OPEN_TRANSIENT_DB | 2753 SQLITE_OPEN_MAIN_JOURNAL | 2754 SQLITE_OPEN_TEMP_JOURNAL | 2755 SQLITE_OPEN_SUBJOURNAL | 2756 SQLITE_OPEN_MASTER_JOURNAL | 2757 SQLITE_OPEN_NOMUTEX | 2758 SQLITE_OPEN_FULLMUTEX | 2759 SQLITE_OPEN_WAL 2760 ); 2761 2762 /* Allocate the sqlite data structure */ 2763 db = sqlite3MallocZero( sizeof(sqlite3) ); 2764 if( db==0 ) goto opendb_out; 2765 if( isThreadsafe ){ 2766 db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); 2767 if( db->mutex==0 ){ 2768 sqlite3_free(db); 2769 db = 0; 2770 goto opendb_out; 2771 } 2772 } 2773 sqlite3_mutex_enter(db->mutex); 2774 db->errMask = 0xff; 2775 db->nDb = 2; 2776 db->magic = SQLITE_MAGIC_BUSY; 2777 db->aDb = db->aDbStatic; 2778 2779 assert( sizeof(db->aLimit)==sizeof(aHardLimit) ); 2780 memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit)); 2781 db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS; 2782 db->autoCommit = 1; 2783 db->nextAutovac = -1; 2784 db->szMmap = sqlite3GlobalConfig.szMmap; 2785 db->nextPagesize = 0; 2786 db->nMaxSorterMmap = 0x7FFFFFFF; 2787 db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill 2788 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX 2789 | SQLITE_AutoIndex 2790 #endif 2791 #if SQLITE_DEFAULT_CKPTFULLFSYNC 2792 | SQLITE_CkptFullFSync 2793 #endif 2794 #if SQLITE_DEFAULT_FILE_FORMAT<4 2795 | SQLITE_LegacyFileFmt 2796 #endif 2797 #ifdef SQLITE_ENABLE_LOAD_EXTENSION 2798 | SQLITE_LoadExtension 2799 #endif 2800 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS 2801 | SQLITE_RecTriggers 2802 #endif 2803 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS 2804 | SQLITE_ForeignKeys 2805 #endif 2806 #if defined(SQLITE_REVERSE_UNORDERED_SELECTS) 2807 | SQLITE_ReverseOrder 2808 #endif 2809 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK) 2810 | SQLITE_CellSizeCk 2811 #endif 2812 ; 2813 sqlite3HashInit(&db->aCollSeq); 2814 #ifndef SQLITE_OMIT_VIRTUALTABLE 2815 sqlite3HashInit(&db->aModule); 2816 #endif 2817 2818 /* Add the default collation sequence BINARY. BINARY works for both UTF-8 2819 ** and UTF-16, so add a version for each to avoid any unnecessary 2820 ** conversions. The only error that can occur here is a malloc() failure. 2821 ** 2822 ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating 2823 ** functions: 2824 */ 2825 createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0); 2826 createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0); 2827 createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0); 2828 createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0); 2829 createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0); 2830 if( db->mallocFailed ){ 2831 goto opendb_out; 2832 } 2833 /* EVIDENCE-OF: R-08308-17224 The default collating function for all 2834 ** strings is BINARY. 2835 */ 2836 db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0); 2837 assert( db->pDfltColl!=0 ); 2838 2839 /* Parse the filename/URI argument. */ 2840 db->openFlags = flags; 2841 rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg); 2842 if( rc!=SQLITE_OK ){ 2843 if( rc==SQLITE_NOMEM ) db->mallocFailed = 1; 2844 sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg); 2845 sqlite3_free(zErrMsg); 2846 goto opendb_out; 2847 } 2848 2849 /* Open the backend database driver */ 2850 rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0, 2851 flags | SQLITE_OPEN_MAIN_DB); 2852 if( rc!=SQLITE_OK ){ 2853 if( rc==SQLITE_IOERR_NOMEM ){ 2854 rc = SQLITE_NOMEM; 2855 } 2856 sqlite3Error(db, rc); 2857 goto opendb_out; 2858 } 2859 sqlite3BtreeEnter(db->aDb[0].pBt); 2860 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt); 2861 if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db); 2862 sqlite3BtreeLeave(db->aDb[0].pBt); 2863 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0); 2864 2865 /* The default safety_level for the main database is 'full'; for the temp 2866 ** database it is 'NONE'. This matches the pager layer defaults. 2867 */ 2868 db->aDb[0].zName = "main"; 2869 db->aDb[0].safety_level = 3; 2870 db->aDb[1].zName = "temp"; 2871 db->aDb[1].safety_level = 1; 2872 2873 db->magic = SQLITE_MAGIC_OPEN; 2874 if( db->mallocFailed ){ 2875 goto opendb_out; 2876 } 2877 2878 /* Register all built-in functions, but do not attempt to read the 2879 ** database schema yet. This is delayed until the first time the database 2880 ** is accessed. 2881 */ 2882 sqlite3Error(db, SQLITE_OK); 2883 sqlite3RegisterBuiltinFunctions(db); 2884 2885 /* Load automatic extensions - extensions that have been registered 2886 ** using the sqlite3_automatic_extension() API. 2887 */ 2888 rc = sqlite3_errcode(db); 2889 if( rc==SQLITE_OK ){ 2890 sqlite3AutoLoadExtensions(db); 2891 rc = sqlite3_errcode(db); 2892 if( rc!=SQLITE_OK ){ 2893 goto opendb_out; 2894 } 2895 } 2896 2897 #ifdef SQLITE_ENABLE_FTS1 2898 if( !db->mallocFailed ){ 2899 extern int sqlite3Fts1Init(sqlite3*); 2900 rc = sqlite3Fts1Init(db); 2901 } 2902 #endif 2903 2904 #ifdef SQLITE_ENABLE_FTS2 2905 if( !db->mallocFailed && rc==SQLITE_OK ){ 2906 extern int sqlite3Fts2Init(sqlite3*); 2907 rc = sqlite3Fts2Init(db); 2908 } 2909 #endif 2910 2911 #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */ 2912 if( !db->mallocFailed && rc==SQLITE_OK ){ 2913 rc = sqlite3Fts3Init(db); 2914 } 2915 #endif 2916 2917 #ifdef SQLITE_ENABLE_FTS5 2918 if( !db->mallocFailed && rc==SQLITE_OK ){ 2919 rc = sqlite3Fts5Init(db); 2920 } 2921 #endif 2922 2923 #ifdef SQLITE_ENABLE_ICU 2924 if( !db->mallocFailed && rc==SQLITE_OK ){ 2925 rc = sqlite3IcuInit(db); 2926 } 2927 #endif 2928 2929 #ifdef SQLITE_ENABLE_RTREE 2930 if( !db->mallocFailed && rc==SQLITE_OK){ 2931 rc = sqlite3RtreeInit(db); 2932 } 2933 #endif 2934 2935 #ifdef SQLITE_ENABLE_DBSTAT_VTAB 2936 if( !db->mallocFailed && rc==SQLITE_OK){ 2937 rc = sqlite3DbstatRegister(db); 2938 } 2939 #endif 2940 2941 #ifdef SQLITE_ENABLE_JSON1 2942 if( !db->mallocFailed && rc==SQLITE_OK){ 2943 rc = sqlite3Json1Init(db); 2944 } 2945 #endif 2946 2947 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking 2948 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking 2949 ** mode. Doing nothing at all also makes NORMAL the default. 2950 */ 2951 #ifdef SQLITE_DEFAULT_LOCKING_MODE 2952 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE; 2953 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt), 2954 SQLITE_DEFAULT_LOCKING_MODE); 2955 #endif 2956 2957 if( rc ) sqlite3Error(db, rc); 2958 2959 /* Enable the lookaside-malloc subsystem */ 2960 setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside, 2961 sqlite3GlobalConfig.nLookaside); 2962 2963 sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT); 2964 2965 opendb_out: 2966 sqlite3_free(zOpen); 2967 if( db ){ 2968 assert( db->mutex!=0 || isThreadsafe==0 2969 || sqlite3GlobalConfig.bFullMutex==0 ); 2970 sqlite3_mutex_leave(db->mutex); 2971 } 2972 rc = sqlite3_errcode(db); 2973 assert( db!=0 || rc==SQLITE_NOMEM ); 2974 if( rc==SQLITE_NOMEM ){ 2975 sqlite3_close(db); 2976 db = 0; 2977 }else if( rc!=SQLITE_OK ){ 2978 db->magic = SQLITE_MAGIC_SICK; 2979 } 2980 *ppDb = db; 2981 #ifdef SQLITE_ENABLE_SQLLOG 2982 if( sqlite3GlobalConfig.xSqllog ){ 2983 /* Opening a db handle. Fourth parameter is passed 0. */ 2984 void *pArg = sqlite3GlobalConfig.pSqllogArg; 2985 sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0); 2986 } 2987 #endif 2988 #if defined(SQLITE_HAS_CODEC) 2989 if( rc==SQLITE_OK ){ 2990 const char *zHexKey = sqlite3_uri_parameter(zOpen, "hexkey"); 2991 if( zHexKey && zHexKey[0] ){ 2992 u8 iByte; 2993 int i; 2994 char zKey[40]; 2995 for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zHexKey[i]); i++){ 2996 iByte = (iByte<<4) + sqlite3HexToInt(zHexKey[i]); 2997 if( (i&1)!=0 ) zKey[i/2] = iByte; 2998 } 2999 sqlite3_key_v2(db, 0, zKey, i/2); 3000 } 3001 } 3002 #endif 3003 return rc & 0xff; 3004 } 3005 3006 /* 3007 ** Open a new database handle. 3008 */ 3009 int sqlite3_open( 3010 const char *zFilename, 3011 sqlite3 **ppDb 3012 ){ 3013 return openDatabase(zFilename, ppDb, 3014 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); 3015 } 3016 int sqlite3_open_v2( 3017 const char *filename, /* Database filename (UTF-8) */ 3018 sqlite3 **ppDb, /* OUT: SQLite db handle */ 3019 int flags, /* Flags */ 3020 const char *zVfs /* Name of VFS module to use */ 3021 ){ 3022 return openDatabase(filename, ppDb, (unsigned int)flags, zVfs); 3023 } 3024 3025 #ifndef SQLITE_OMIT_UTF16 3026 /* 3027 ** Open a new database handle. 3028 */ 3029 int sqlite3_open16( 3030 const void *zFilename, 3031 sqlite3 **ppDb 3032 ){ 3033 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */ 3034 sqlite3_value *pVal; 3035 int rc; 3036 3037 #ifdef SQLITE_ENABLE_API_ARMOR 3038 if( ppDb==0 ) return SQLITE_MISUSE_BKPT; 3039 #endif 3040 *ppDb = 0; 3041 #ifndef SQLITE_OMIT_AUTOINIT 3042 rc = sqlite3_initialize(); 3043 if( rc ) return rc; 3044 #endif 3045 if( zFilename==0 ) zFilename = "\000\000"; 3046 pVal = sqlite3ValueNew(0); 3047 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC); 3048 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8); 3049 if( zFilename8 ){ 3050 rc = openDatabase(zFilename8, ppDb, 3051 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); 3052 assert( *ppDb || rc==SQLITE_NOMEM ); 3053 if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){ 3054 SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE; 3055 } 3056 }else{ 3057 rc = SQLITE_NOMEM; 3058 } 3059 sqlite3ValueFree(pVal); 3060 3061 return rc & 0xff; 3062 } 3063 #endif /* SQLITE_OMIT_UTF16 */ 3064 3065 /* 3066 ** Register a new collation sequence with the database handle db. 3067 */ 3068 int sqlite3_create_collation( 3069 sqlite3* db, 3070 const char *zName, 3071 int enc, 3072 void* pCtx, 3073 int(*xCompare)(void*,int,const void*,int,const void*) 3074 ){ 3075 return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0); 3076 } 3077 3078 /* 3079 ** Register a new collation sequence with the database handle db. 3080 */ 3081 int sqlite3_create_collation_v2( 3082 sqlite3* db, 3083 const char *zName, 3084 int enc, 3085 void* pCtx, 3086 int(*xCompare)(void*,int,const void*,int,const void*), 3087 void(*xDel)(void*) 3088 ){ 3089 int rc; 3090 3091 #ifdef SQLITE_ENABLE_API_ARMOR 3092 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; 3093 #endif 3094 sqlite3_mutex_enter(db->mutex); 3095 assert( !db->mallocFailed ); 3096 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel); 3097 rc = sqlite3ApiExit(db, rc); 3098 sqlite3_mutex_leave(db->mutex); 3099 return rc; 3100 } 3101 3102 #ifndef SQLITE_OMIT_UTF16 3103 /* 3104 ** Register a new collation sequence with the database handle db. 3105 */ 3106 int sqlite3_create_collation16( 3107 sqlite3* db, 3108 const void *zName, 3109 int enc, 3110 void* pCtx, 3111 int(*xCompare)(void*,int,const void*,int,const void*) 3112 ){ 3113 int rc = SQLITE_OK; 3114 char *zName8; 3115 3116 #ifdef SQLITE_ENABLE_API_ARMOR 3117 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; 3118 #endif 3119 sqlite3_mutex_enter(db->mutex); 3120 assert( !db->mallocFailed ); 3121 zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE); 3122 if( zName8 ){ 3123 rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0); 3124 sqlite3DbFree(db, zName8); 3125 } 3126 rc = sqlite3ApiExit(db, rc); 3127 sqlite3_mutex_leave(db->mutex); 3128 return rc; 3129 } 3130 #endif /* SQLITE_OMIT_UTF16 */ 3131 3132 /* 3133 ** Register a collation sequence factory callback with the database handle 3134 ** db. Replace any previously installed collation sequence factory. 3135 */ 3136 int sqlite3_collation_needed( 3137 sqlite3 *db, 3138 void *pCollNeededArg, 3139 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*) 3140 ){ 3141 #ifdef SQLITE_ENABLE_API_ARMOR 3142 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; 3143 #endif 3144 sqlite3_mutex_enter(db->mutex); 3145 db->xCollNeeded = xCollNeeded; 3146 db->xCollNeeded16 = 0; 3147 db->pCollNeededArg = pCollNeededArg; 3148 sqlite3_mutex_leave(db->mutex); 3149 return SQLITE_OK; 3150 } 3151 3152 #ifndef SQLITE_OMIT_UTF16 3153 /* 3154 ** Register a collation sequence factory callback with the database handle 3155 ** db. Replace any previously installed collation sequence factory. 3156 */ 3157 int sqlite3_collation_needed16( 3158 sqlite3 *db, 3159 void *pCollNeededArg, 3160 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*) 3161 ){ 3162 #ifdef SQLITE_ENABLE_API_ARMOR 3163 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; 3164 #endif 3165 sqlite3_mutex_enter(db->mutex); 3166 db->xCollNeeded = 0; 3167 db->xCollNeeded16 = xCollNeeded16; 3168 db->pCollNeededArg = pCollNeededArg; 3169 sqlite3_mutex_leave(db->mutex); 3170 return SQLITE_OK; 3171 } 3172 #endif /* SQLITE_OMIT_UTF16 */ 3173 3174 #ifndef SQLITE_OMIT_DEPRECATED 3175 /* 3176 ** This function is now an anachronism. It used to be used to recover from a 3177 ** malloc() failure, but SQLite now does this automatically. 3178 */ 3179 int sqlite3_global_recover(void){ 3180 return SQLITE_OK; 3181 } 3182 #endif 3183 3184 /* 3185 ** Test to see whether or not the database connection is in autocommit 3186 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on 3187 ** by default. Autocommit is disabled by a BEGIN statement and reenabled 3188 ** by the next COMMIT or ROLLBACK. 3189 */ 3190 int sqlite3_get_autocommit(sqlite3 *db){ 3191 #ifdef SQLITE_ENABLE_API_ARMOR 3192 if( !sqlite3SafetyCheckOk(db) ){ 3193 (void)SQLITE_MISUSE_BKPT; 3194 return 0; 3195 } 3196 #endif 3197 return db->autoCommit; 3198 } 3199 3200 /* 3201 ** The following routines are substitutes for constants SQLITE_CORRUPT, 3202 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error 3203 ** constants. They serve two purposes: 3204 ** 3205 ** 1. Serve as a convenient place to set a breakpoint in a debugger 3206 ** to detect when version error conditions occurs. 3207 ** 3208 ** 2. Invoke sqlite3_log() to provide the source code location where 3209 ** a low-level error is first detected. 3210 */ 3211 int sqlite3CorruptError(int lineno){ 3212 testcase( sqlite3GlobalConfig.xLog!=0 ); 3213 sqlite3_log(SQLITE_CORRUPT, 3214 "database corruption at line %d of [%.10s]", 3215 lineno, 20+sqlite3_sourceid()); 3216 return SQLITE_CORRUPT; 3217 } 3218 int sqlite3MisuseError(int lineno){ 3219 testcase( sqlite3GlobalConfig.xLog!=0 ); 3220 sqlite3_log(SQLITE_MISUSE, 3221 "misuse at line %d of [%.10s]", 3222 lineno, 20+sqlite3_sourceid()); 3223 return SQLITE_MISUSE; 3224 } 3225 int sqlite3CantopenError(int lineno){ 3226 testcase( sqlite3GlobalConfig.xLog!=0 ); 3227 sqlite3_log(SQLITE_CANTOPEN, 3228 "cannot open file at line %d of [%.10s]", 3229 lineno, 20+sqlite3_sourceid()); 3230 return SQLITE_CANTOPEN; 3231 } 3232 3233 3234 #ifndef SQLITE_OMIT_DEPRECATED 3235 /* 3236 ** This is a convenience routine that makes sure that all thread-specific 3237 ** data for this thread has been deallocated. 3238 ** 3239 ** SQLite no longer uses thread-specific data so this routine is now a 3240 ** no-op. It is retained for historical compatibility. 3241 */ 3242 void sqlite3_thread_cleanup(void){ 3243 } 3244 #endif 3245 3246 /* 3247 ** Return meta information about a specific column of a database table. 3248 ** See comment in sqlite3.h (sqlite.h.in) for details. 3249 */ 3250 int sqlite3_table_column_metadata( 3251 sqlite3 *db, /* Connection handle */ 3252 const char *zDbName, /* Database name or NULL */ 3253 const char *zTableName, /* Table name */ 3254 const char *zColumnName, /* Column name */ 3255 char const **pzDataType, /* OUTPUT: Declared data type */ 3256 char const **pzCollSeq, /* OUTPUT: Collation sequence name */ 3257 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ 3258 int *pPrimaryKey, /* OUTPUT: True if column part of PK */ 3259 int *pAutoinc /* OUTPUT: True if column is auto-increment */ 3260 ){ 3261 int rc; 3262 char *zErrMsg = 0; 3263 Table *pTab = 0; 3264 Column *pCol = 0; 3265 int iCol = 0; 3266 char const *zDataType = 0; 3267 char const *zCollSeq = 0; 3268 int notnull = 0; 3269 int primarykey = 0; 3270 int autoinc = 0; 3271 3272 3273 #ifdef SQLITE_ENABLE_API_ARMOR 3274 if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){ 3275 return SQLITE_MISUSE_BKPT; 3276 } 3277 #endif 3278 3279 /* Ensure the database schema has been loaded */ 3280 sqlite3_mutex_enter(db->mutex); 3281 sqlite3BtreeEnterAll(db); 3282 rc = sqlite3Init(db, &zErrMsg); 3283 if( SQLITE_OK!=rc ){ 3284 goto error_out; 3285 } 3286 3287 /* Locate the table in question */ 3288 pTab = sqlite3FindTable(db, zTableName, zDbName); 3289 if( !pTab || pTab->pSelect ){ 3290 pTab = 0; 3291 goto error_out; 3292 } 3293 3294 /* Find the column for which info is requested */ 3295 if( zColumnName==0 ){ 3296 /* Query for existance of table only */ 3297 }else{ 3298 for(iCol=0; iCol<pTab->nCol; iCol++){ 3299 pCol = &pTab->aCol[iCol]; 3300 if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){ 3301 break; 3302 } 3303 } 3304 if( iCol==pTab->nCol ){ 3305 if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){ 3306 iCol = pTab->iPKey; 3307 pCol = iCol>=0 ? &pTab->aCol[iCol] : 0; 3308 }else{ 3309 pTab = 0; 3310 goto error_out; 3311 } 3312 } 3313 } 3314 3315 /* The following block stores the meta information that will be returned 3316 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey 3317 ** and autoinc. At this point there are two possibilities: 3318 ** 3319 ** 1. The specified column name was rowid", "oid" or "_rowid_" 3320 ** and there is no explicitly declared IPK column. 3321 ** 3322 ** 2. The table is not a view and the column name identified an 3323 ** explicitly declared column. Copy meta information from *pCol. 3324 */ 3325 if( pCol ){ 3326 zDataType = pCol->zType; 3327 zCollSeq = pCol->zColl; 3328 notnull = pCol->notNull!=0; 3329 primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0; 3330 autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0; 3331 }else{ 3332 zDataType = "INTEGER"; 3333 primarykey = 1; 3334 } 3335 if( !zCollSeq ){ 3336 zCollSeq = "BINARY"; 3337 } 3338 3339 error_out: 3340 sqlite3BtreeLeaveAll(db); 3341 3342 /* Whether the function call succeeded or failed, set the output parameters 3343 ** to whatever their local counterparts contain. If an error did occur, 3344 ** this has the effect of zeroing all output parameters. 3345 */ 3346 if( pzDataType ) *pzDataType = zDataType; 3347 if( pzCollSeq ) *pzCollSeq = zCollSeq; 3348 if( pNotNull ) *pNotNull = notnull; 3349 if( pPrimaryKey ) *pPrimaryKey = primarykey; 3350 if( pAutoinc ) *pAutoinc = autoinc; 3351 3352 if( SQLITE_OK==rc && !pTab ){ 3353 sqlite3DbFree(db, zErrMsg); 3354 zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName, 3355 zColumnName); 3356 rc = SQLITE_ERROR; 3357 } 3358 sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg); 3359 sqlite3DbFree(db, zErrMsg); 3360 rc = sqlite3ApiExit(db, rc); 3361 sqlite3_mutex_leave(db->mutex); 3362 return rc; 3363 } 3364 3365 /* 3366 ** Sleep for a little while. Return the amount of time slept. 3367 */ 3368 int sqlite3_sleep(int ms){ 3369 sqlite3_vfs *pVfs; 3370 int rc; 3371 pVfs = sqlite3_vfs_find(0); 3372 if( pVfs==0 ) return 0; 3373 3374 /* This function works in milliseconds, but the underlying OsSleep() 3375 ** API uses microseconds. Hence the 1000's. 3376 */ 3377 rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000); 3378 return rc; 3379 } 3380 3381 /* 3382 ** Enable or disable the extended result codes. 3383 */ 3384 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){ 3385 #ifdef SQLITE_ENABLE_API_ARMOR 3386 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; 3387 #endif 3388 sqlite3_mutex_enter(db->mutex); 3389 db->errMask = onoff ? 0xffffffff : 0xff; 3390 sqlite3_mutex_leave(db->mutex); 3391 return SQLITE_OK; 3392 } 3393 3394 /* 3395 ** Invoke the xFileControl method on a particular database. 3396 */ 3397 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){ 3398 int rc = SQLITE_ERROR; 3399 Btree *pBtree; 3400 3401 #ifdef SQLITE_ENABLE_API_ARMOR 3402 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; 3403 #endif 3404 sqlite3_mutex_enter(db->mutex); 3405 pBtree = sqlite3DbNameToBtree(db, zDbName); 3406 if( pBtree ){ 3407 Pager *pPager; 3408 sqlite3_file *fd; 3409 sqlite3BtreeEnter(pBtree); 3410 pPager = sqlite3BtreePager(pBtree); 3411 assert( pPager!=0 ); 3412 fd = sqlite3PagerFile(pPager); 3413 assert( fd!=0 ); 3414 if( op==SQLITE_FCNTL_FILE_POINTER ){ 3415 *(sqlite3_file**)pArg = fd; 3416 rc = SQLITE_OK; 3417 }else if( fd->pMethods ){ 3418 rc = sqlite3OsFileControl(fd, op, pArg); 3419 }else{ 3420 rc = SQLITE_NOTFOUND; 3421 } 3422 sqlite3BtreeLeave(pBtree); 3423 } 3424 sqlite3_mutex_leave(db->mutex); 3425 return rc; 3426 } 3427 3428 /* 3429 ** Interface to the testing logic. 3430 */ 3431 int sqlite3_test_control(int op, ...){ 3432 int rc = 0; 3433 #ifdef SQLITE_OMIT_BUILTIN_TEST 3434 UNUSED_PARAMETER(op); 3435 #else 3436 va_list ap; 3437 va_start(ap, op); 3438 switch( op ){ 3439 3440 /* 3441 ** Save the current state of the PRNG. 3442 */ 3443 case SQLITE_TESTCTRL_PRNG_SAVE: { 3444 sqlite3PrngSaveState(); 3445 break; 3446 } 3447 3448 /* 3449 ** Restore the state of the PRNG to the last state saved using 3450 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then 3451 ** this verb acts like PRNG_RESET. 3452 */ 3453 case SQLITE_TESTCTRL_PRNG_RESTORE: { 3454 sqlite3PrngRestoreState(); 3455 break; 3456 } 3457 3458 /* 3459 ** Reset the PRNG back to its uninitialized state. The next call 3460 ** to sqlite3_randomness() will reseed the PRNG using a single call 3461 ** to the xRandomness method of the default VFS. 3462 */ 3463 case SQLITE_TESTCTRL_PRNG_RESET: { 3464 sqlite3_randomness(0,0); 3465 break; 3466 } 3467 3468 /* 3469 ** sqlite3_test_control(BITVEC_TEST, size, program) 3470 ** 3471 ** Run a test against a Bitvec object of size. The program argument 3472 ** is an array of integers that defines the test. Return -1 on a 3473 ** memory allocation error, 0 on success, or non-zero for an error. 3474 ** See the sqlite3BitvecBuiltinTest() for additional information. 3475 */ 3476 case SQLITE_TESTCTRL_BITVEC_TEST: { 3477 int sz = va_arg(ap, int); 3478 int *aProg = va_arg(ap, int*); 3479 rc = sqlite3BitvecBuiltinTest(sz, aProg); 3480 break; 3481 } 3482 3483 /* 3484 ** sqlite3_test_control(FAULT_INSTALL, xCallback) 3485 ** 3486 ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called, 3487 ** if xCallback is not NULL. 3488 ** 3489 ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0) 3490 ** is called immediately after installing the new callback and the return 3491 ** value from sqlite3FaultSim(0) becomes the return from 3492 ** sqlite3_test_control(). 3493 */ 3494 case SQLITE_TESTCTRL_FAULT_INSTALL: { 3495 /* MSVC is picky about pulling func ptrs from va lists. 3496 ** http://support.microsoft.com/kb/47961 3497 ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int)); 3498 */ 3499 typedef int(*TESTCALLBACKFUNC_t)(int); 3500 sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t); 3501 rc = sqlite3FaultSim(0); 3502 break; 3503 } 3504 3505 /* 3506 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd) 3507 ** 3508 ** Register hooks to call to indicate which malloc() failures 3509 ** are benign. 3510 */ 3511 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: { 3512 typedef void (*void_function)(void); 3513 void_function xBenignBegin; 3514 void_function xBenignEnd; 3515 xBenignBegin = va_arg(ap, void_function); 3516 xBenignEnd = va_arg(ap, void_function); 3517 sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd); 3518 break; 3519 } 3520 3521 /* 3522 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X) 3523 ** 3524 ** Set the PENDING byte to the value in the argument, if X>0. 3525 ** Make no changes if X==0. Return the value of the pending byte 3526 ** as it existing before this routine was called. 3527 ** 3528 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in 3529 ** an incompatible database file format. Changing the PENDING byte 3530 ** while any database connection is open results in undefined and 3531 ** deleterious behavior. 3532 */ 3533 case SQLITE_TESTCTRL_PENDING_BYTE: { 3534 rc = PENDING_BYTE; 3535 #ifndef SQLITE_OMIT_WSD 3536 { 3537 unsigned int newVal = va_arg(ap, unsigned int); 3538 if( newVal ) sqlite3PendingByte = newVal; 3539 } 3540 #endif 3541 break; 3542 } 3543 3544 /* 3545 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X) 3546 ** 3547 ** This action provides a run-time test to see whether or not 3548 ** assert() was enabled at compile-time. If X is true and assert() 3549 ** is enabled, then the return value is true. If X is true and 3550 ** assert() is disabled, then the return value is zero. If X is 3551 ** false and assert() is enabled, then the assertion fires and the 3552 ** process aborts. If X is false and assert() is disabled, then the 3553 ** return value is zero. 3554 */ 3555 case SQLITE_TESTCTRL_ASSERT: { 3556 volatile int x = 0; 3557 assert( (x = va_arg(ap,int))!=0 ); 3558 rc = x; 3559 break; 3560 } 3561 3562 3563 /* 3564 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X) 3565 ** 3566 ** This action provides a run-time test to see how the ALWAYS and 3567 ** NEVER macros were defined at compile-time. 3568 ** 3569 ** The return value is ALWAYS(X). 3570 ** 3571 ** The recommended test is X==2. If the return value is 2, that means 3572 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the 3573 ** default setting. If the return value is 1, then ALWAYS() is either 3574 ** hard-coded to true or else it asserts if its argument is false. 3575 ** The first behavior (hard-coded to true) is the case if 3576 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second 3577 ** behavior (assert if the argument to ALWAYS() is false) is the case if 3578 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled. 3579 ** 3580 ** The run-time test procedure might look something like this: 3581 ** 3582 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){ 3583 ** // ALWAYS() and NEVER() are no-op pass-through macros 3584 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){ 3585 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false. 3586 ** }else{ 3587 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0. 3588 ** } 3589 */ 3590 case SQLITE_TESTCTRL_ALWAYS: { 3591 int x = va_arg(ap,int); 3592 rc = ALWAYS(x); 3593 break; 3594 } 3595 3596 /* 3597 ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER); 3598 ** 3599 ** The integer returned reveals the byte-order of the computer on which 3600 ** SQLite is running: 3601 ** 3602 ** 1 big-endian, determined at run-time 3603 ** 10 little-endian, determined at run-time 3604 ** 432101 big-endian, determined at compile-time 3605 ** 123410 little-endian, determined at compile-time 3606 */ 3607 case SQLITE_TESTCTRL_BYTEORDER: { 3608 rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN; 3609 break; 3610 } 3611 3612 /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N) 3613 ** 3614 ** Set the nReserve size to N for the main database on the database 3615 ** connection db. 3616 */ 3617 case SQLITE_TESTCTRL_RESERVE: { 3618 sqlite3 *db = va_arg(ap, sqlite3*); 3619 int x = va_arg(ap,int); 3620 sqlite3_mutex_enter(db->mutex); 3621 sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0); 3622 sqlite3_mutex_leave(db->mutex); 3623 break; 3624 } 3625 3626 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N) 3627 ** 3628 ** Enable or disable various optimizations for testing purposes. The 3629 ** argument N is a bitmask of optimizations to be disabled. For normal 3630 ** operation N should be 0. The idea is that a test program (like the 3631 ** SQL Logic Test or SLT test module) can run the same SQL multiple times 3632 ** with various optimizations disabled to verify that the same answer 3633 ** is obtained in every case. 3634 */ 3635 case SQLITE_TESTCTRL_OPTIMIZATIONS: { 3636 sqlite3 *db = va_arg(ap, sqlite3*); 3637 db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff); 3638 break; 3639 } 3640 3641 #ifdef SQLITE_N_KEYWORD 3642 /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord) 3643 ** 3644 ** If zWord is a keyword recognized by the parser, then return the 3645 ** number of keywords. Or if zWord is not a keyword, return 0. 3646 ** 3647 ** This test feature is only available in the amalgamation since 3648 ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite 3649 ** is built using separate source files. 3650 */ 3651 case SQLITE_TESTCTRL_ISKEYWORD: { 3652 const char *zWord = va_arg(ap, const char*); 3653 int n = sqlite3Strlen30(zWord); 3654 rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0; 3655 break; 3656 } 3657 #endif 3658 3659 /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree); 3660 ** 3661 ** Pass pFree into sqlite3ScratchFree(). 3662 ** If sz>0 then allocate a scratch buffer into pNew. 3663 */ 3664 case SQLITE_TESTCTRL_SCRATCHMALLOC: { 3665 void *pFree, **ppNew; 3666 int sz; 3667 sz = va_arg(ap, int); 3668 ppNew = va_arg(ap, void**); 3669 pFree = va_arg(ap, void*); 3670 if( sz ) *ppNew = sqlite3ScratchMalloc(sz); 3671 sqlite3ScratchFree(pFree); 3672 break; 3673 } 3674 3675 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff); 3676 ** 3677 ** If parameter onoff is non-zero, configure the wrappers so that all 3678 ** subsequent calls to localtime() and variants fail. If onoff is zero, 3679 ** undo this setting. 3680 */ 3681 case SQLITE_TESTCTRL_LOCALTIME_FAULT: { 3682 sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int); 3683 break; 3684 } 3685 3686 /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int); 3687 ** 3688 ** Set or clear a flag that indicates that the database file is always well- 3689 ** formed and never corrupt. This flag is clear by default, indicating that 3690 ** database files might have arbitrary corruption. Setting the flag during 3691 ** testing causes certain assert() statements in the code to be activated 3692 ** that demonstrat invariants on well-formed database files. 3693 */ 3694 case SQLITE_TESTCTRL_NEVER_CORRUPT: { 3695 sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int); 3696 break; 3697 } 3698 3699 3700 /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr); 3701 ** 3702 ** Set the VDBE coverage callback function to xCallback with context 3703 ** pointer ptr. 3704 */ 3705 case SQLITE_TESTCTRL_VDBE_COVERAGE: { 3706 #ifdef SQLITE_VDBE_COVERAGE 3707 typedef void (*branch_callback)(void*,int,u8,u8); 3708 sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback); 3709 sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*); 3710 #endif 3711 break; 3712 } 3713 3714 /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */ 3715 case SQLITE_TESTCTRL_SORTER_MMAP: { 3716 sqlite3 *db = va_arg(ap, sqlite3*); 3717 db->nMaxSorterMmap = va_arg(ap, int); 3718 break; 3719 } 3720 3721 /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT); 3722 ** 3723 ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if 3724 ** not. 3725 */ 3726 case SQLITE_TESTCTRL_ISINIT: { 3727 if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR; 3728 break; 3729 } 3730 3731 /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum); 3732 ** 3733 ** This test control is used to create imposter tables. "db" is a pointer 3734 ** to the database connection. dbName is the database name (ex: "main" or 3735 ** "temp") which will receive the imposter. "onOff" turns imposter mode on 3736 ** or off. "tnum" is the root page of the b-tree to which the imposter 3737 ** table should connect. 3738 ** 3739 ** Enable imposter mode only when the schema has already been parsed. Then 3740 ** run a single CREATE TABLE statement to construct the imposter table in 3741 ** the parsed schema. Then turn imposter mode back off again. 3742 ** 3743 ** If onOff==0 and tnum>0 then reset the schema for all databases, causing 3744 ** the schema to be reparsed the next time it is needed. This has the 3745 ** effect of erasing all imposter tables. 3746 */ 3747 case SQLITE_TESTCTRL_IMPOSTER: { 3748 sqlite3 *db = va_arg(ap, sqlite3*); 3749 sqlite3_mutex_enter(db->mutex); 3750 db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*)); 3751 db->init.busy = db->init.imposterTable = va_arg(ap,int); 3752 db->init.newTnum = va_arg(ap,int); 3753 if( db->init.busy==0 && db->init.newTnum>0 ){ 3754 sqlite3ResetAllSchemasOfConnection(db); 3755 } 3756 sqlite3_mutex_leave(db->mutex); 3757 break; 3758 } 3759 } 3760 va_end(ap); 3761 #endif /* SQLITE_OMIT_BUILTIN_TEST */ 3762 return rc; 3763 } 3764 3765 /* 3766 ** This is a utility routine, useful to VFS implementations, that checks 3767 ** to see if a database file was a URI that contained a specific query 3768 ** parameter, and if so obtains the value of the query parameter. 3769 ** 3770 ** The zFilename argument is the filename pointer passed into the xOpen() 3771 ** method of a VFS implementation. The zParam argument is the name of the 3772 ** query parameter we seek. This routine returns the value of the zParam 3773 ** parameter if it exists. If the parameter does not exist, this routine 3774 ** returns a NULL pointer. 3775 */ 3776 const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){ 3777 if( zFilename==0 || zParam==0 ) return 0; 3778 zFilename += sqlite3Strlen30(zFilename) + 1; 3779 while( zFilename[0] ){ 3780 int x = strcmp(zFilename, zParam); 3781 zFilename += sqlite3Strlen30(zFilename) + 1; 3782 if( x==0 ) return zFilename; 3783 zFilename += sqlite3Strlen30(zFilename) + 1; 3784 } 3785 return 0; 3786 } 3787 3788 /* 3789 ** Return a boolean value for a query parameter. 3790 */ 3791 int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){ 3792 const char *z = sqlite3_uri_parameter(zFilename, zParam); 3793 bDflt = bDflt!=0; 3794 return z ? sqlite3GetBoolean(z, bDflt) : bDflt; 3795 } 3796 3797 /* 3798 ** Return a 64-bit integer value for a query parameter. 3799 */ 3800 sqlite3_int64 sqlite3_uri_int64( 3801 const char *zFilename, /* Filename as passed to xOpen */ 3802 const char *zParam, /* URI parameter sought */ 3803 sqlite3_int64 bDflt /* return if parameter is missing */ 3804 ){ 3805 const char *z = sqlite3_uri_parameter(zFilename, zParam); 3806 sqlite3_int64 v; 3807 if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){ 3808 bDflt = v; 3809 } 3810 return bDflt; 3811 } 3812 3813 /* 3814 ** Return the Btree pointer identified by zDbName. Return NULL if not found. 3815 */ 3816 Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){ 3817 int i; 3818 for(i=0; i<db->nDb; i++){ 3819 if( db->aDb[i].pBt 3820 && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0) 3821 ){ 3822 return db->aDb[i].pBt; 3823 } 3824 } 3825 return 0; 3826 } 3827 3828 /* 3829 ** Return the filename of the database associated with a database 3830 ** connection. 3831 */ 3832 const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){ 3833 Btree *pBt; 3834 #ifdef SQLITE_ENABLE_API_ARMOR 3835 if( !sqlite3SafetyCheckOk(db) ){ 3836 (void)SQLITE_MISUSE_BKPT; 3837 return 0; 3838 } 3839 #endif 3840 pBt = sqlite3DbNameToBtree(db, zDbName); 3841 return pBt ? sqlite3BtreeGetFilename(pBt) : 0; 3842 } 3843 3844 /* 3845 ** Return 1 if database is read-only or 0 if read/write. Return -1 if 3846 ** no such database exists. 3847 */ 3848 int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){ 3849 Btree *pBt; 3850 #ifdef SQLITE_ENABLE_API_ARMOR 3851 if( !sqlite3SafetyCheckOk(db) ){ 3852 (void)SQLITE_MISUSE_BKPT; 3853 return -1; 3854 } 3855 #endif 3856 pBt = sqlite3DbNameToBtree(db, zDbName); 3857 return pBt ? sqlite3BtreeIsReadonly(pBt) : -1; 3858 } 3859