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