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