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