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