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