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