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 ** Disconnect all sqlite3_vtab objects that belong to database connection 725 ** db. This is called when db is being closed. 726 */ 727 static void disconnectAllVtab(sqlite3 *db){ 728 #ifndef SQLITE_OMIT_VIRTUALTABLE 729 int i; 730 sqlite3BtreeEnterAll(db); 731 for(i=0; i<db->nDb; i++){ 732 Schema *pSchema = db->aDb[i].pSchema; 733 if( db->aDb[i].pSchema ){ 734 HashElem *p; 735 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){ 736 Table *pTab = (Table *)sqliteHashData(p); 737 if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab); 738 } 739 } 740 } 741 sqlite3BtreeLeaveAll(db); 742 #else 743 UNUSED_PARAMETER(db); 744 #endif 745 } 746 747 /* 748 ** Close an existing SQLite database 749 */ 750 int sqlite3_close(sqlite3 *db){ 751 HashElem *i; /* Hash table iterator */ 752 int j; 753 754 if( !db ){ 755 return SQLITE_OK; 756 } 757 if( !sqlite3SafetyCheckSickOrOk(db) ){ 758 return SQLITE_MISUSE_BKPT; 759 } 760 sqlite3_mutex_enter(db->mutex); 761 762 /* Force xDisconnect calls on all virtual tables */ 763 disconnectAllVtab(db); 764 765 /* If a transaction is open, the disconnectAllVtab() call above 766 ** will not have called the xDisconnect() method on any virtual 767 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback() 768 ** call will do so. We need to do this before the check for active 769 ** SQL statements below, as the v-table implementation may be storing 770 ** some prepared statements internally. 771 */ 772 sqlite3VtabRollback(db); 773 774 /* If there are any outstanding VMs, return SQLITE_BUSY. */ 775 if( db->pVdbe ){ 776 sqlite3Error(db, SQLITE_BUSY, 777 "unable to close due to unfinalised statements"); 778 sqlite3_mutex_leave(db->mutex); 779 return SQLITE_BUSY; 780 } 781 assert( sqlite3SafetyCheckSickOrOk(db) ); 782 783 for(j=0; j<db->nDb; j++){ 784 Btree *pBt = db->aDb[j].pBt; 785 if( pBt && sqlite3BtreeIsInBackup(pBt) ){ 786 sqlite3Error(db, SQLITE_BUSY, 787 "unable to close due to unfinished backup operation"); 788 sqlite3_mutex_leave(db->mutex); 789 return SQLITE_BUSY; 790 } 791 } 792 793 /* Free any outstanding Savepoint structures. */ 794 sqlite3CloseSavepoints(db); 795 796 /* Close all database connections */ 797 for(j=0; j<db->nDb; j++){ 798 struct Db *pDb = &db->aDb[j]; 799 if( pDb->pBt ){ 800 sqlite3BtreeClose(pDb->pBt); 801 pDb->pBt = 0; 802 if( j!=1 ){ 803 pDb->pSchema = 0; 804 } 805 } 806 } 807 /* Clear the TEMP schema separately and last */ 808 if( db->aDb[1].pSchema ){ 809 sqlite3SchemaClear(db->aDb[1].pSchema); 810 } 811 sqlite3VtabUnlockList(db); 812 813 /* Free up the array of auxiliary databases */ 814 sqlite3CollapseDatabaseArray(db); 815 assert( db->nDb<=2 ); 816 assert( db->aDb==db->aDbStatic ); 817 818 /* Tell the code in notify.c that the connection no longer holds any 819 ** locks and does not require any further unlock-notify callbacks. 820 */ 821 sqlite3ConnectionClosed(db); 822 823 for(j=0; j<ArraySize(db->aFunc.a); j++){ 824 FuncDef *pNext, *pHash, *p; 825 for(p=db->aFunc.a[j]; p; p=pHash){ 826 pHash = p->pHash; 827 while( p ){ 828 functionDestroy(db, p); 829 pNext = p->pNext; 830 sqlite3DbFree(db, p); 831 p = pNext; 832 } 833 } 834 } 835 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){ 836 CollSeq *pColl = (CollSeq *)sqliteHashData(i); 837 /* Invoke any destructors registered for collation sequence user data. */ 838 for(j=0; j<3; j++){ 839 if( pColl[j].xDel ){ 840 pColl[j].xDel(pColl[j].pUser); 841 } 842 } 843 sqlite3DbFree(db, pColl); 844 } 845 sqlite3HashClear(&db->aCollSeq); 846 #ifndef SQLITE_OMIT_VIRTUALTABLE 847 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){ 848 Module *pMod = (Module *)sqliteHashData(i); 849 if( pMod->xDestroy ){ 850 pMod->xDestroy(pMod->pAux); 851 } 852 sqlite3DbFree(db, pMod); 853 } 854 sqlite3HashClear(&db->aModule); 855 #endif 856 857 sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */ 858 if( db->pErr ){ 859 sqlite3ValueFree(db->pErr); 860 } 861 sqlite3CloseExtensions(db); 862 863 db->magic = SQLITE_MAGIC_ERROR; 864 865 /* The temp-database schema is allocated differently from the other schema 866 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()). 867 ** So it needs to be freed here. Todo: Why not roll the temp schema into 868 ** the same sqliteMalloc() as the one that allocates the database 869 ** structure? 870 */ 871 sqlite3DbFree(db, db->aDb[1].pSchema); 872 sqlite3_mutex_leave(db->mutex); 873 db->magic = SQLITE_MAGIC_CLOSED; 874 sqlite3_mutex_free(db->mutex); 875 assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */ 876 if( db->lookaside.bMalloced ){ 877 sqlite3_free(db->lookaside.pStart); 878 } 879 sqlite3_free(db); 880 return SQLITE_OK; 881 } 882 883 /* 884 ** Rollback all database files. If tripCode is not SQLITE_OK, then 885 ** any open cursors are invalidated ("tripped" - as in "tripping a circuit 886 ** breaker") and made to return tripCode if there are any further 887 ** attempts to use that cursor. 888 */ 889 void sqlite3RollbackAll(sqlite3 *db, int tripCode){ 890 int i; 891 int inTrans = 0; 892 assert( sqlite3_mutex_held(db->mutex) ); 893 sqlite3BeginBenignMalloc(); 894 for(i=0; i<db->nDb; i++){ 895 Btree *p = db->aDb[i].pBt; 896 if( p ){ 897 if( sqlite3BtreeIsInTrans(p) ){ 898 inTrans = 1; 899 } 900 sqlite3BtreeRollback(p, tripCode); 901 db->aDb[i].inTrans = 0; 902 } 903 } 904 sqlite3VtabRollback(db); 905 sqlite3EndBenignMalloc(); 906 907 if( db->flags&SQLITE_InternChanges ){ 908 sqlite3ExpirePreparedStatements(db); 909 sqlite3ResetAllSchemasOfConnection(db); 910 } 911 912 /* Any deferred constraint violations have now been resolved. */ 913 db->nDeferredCons = 0; 914 915 /* If one has been configured, invoke the rollback-hook callback */ 916 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){ 917 db->xRollbackCallback(db->pRollbackArg); 918 } 919 } 920 921 /* 922 ** Return a static string that describes the kind of error specified in the 923 ** argument. 924 */ 925 const char *sqlite3ErrStr(int rc){ 926 static const char* const aMsg[] = { 927 /* SQLITE_OK */ "not an error", 928 /* SQLITE_ERROR */ "SQL logic error or missing database", 929 /* SQLITE_INTERNAL */ 0, 930 /* SQLITE_PERM */ "access permission denied", 931 /* SQLITE_ABORT */ "callback requested query abort", 932 /* SQLITE_BUSY */ "database is locked", 933 /* SQLITE_LOCKED */ "database table is locked", 934 /* SQLITE_NOMEM */ "out of memory", 935 /* SQLITE_READONLY */ "attempt to write a readonly database", 936 /* SQLITE_INTERRUPT */ "interrupted", 937 /* SQLITE_IOERR */ "disk I/O error", 938 /* SQLITE_CORRUPT */ "database disk image is malformed", 939 /* SQLITE_NOTFOUND */ "unknown operation", 940 /* SQLITE_FULL */ "database or disk is full", 941 /* SQLITE_CANTOPEN */ "unable to open database file", 942 /* SQLITE_PROTOCOL */ "locking protocol", 943 /* SQLITE_EMPTY */ "table contains no data", 944 /* SQLITE_SCHEMA */ "database schema has changed", 945 /* SQLITE_TOOBIG */ "string or blob too big", 946 /* SQLITE_CONSTRAINT */ "constraint failed", 947 /* SQLITE_MISMATCH */ "datatype mismatch", 948 /* SQLITE_MISUSE */ "library routine called out of sequence", 949 /* SQLITE_NOLFS */ "large file support is disabled", 950 /* SQLITE_AUTH */ "authorization denied", 951 /* SQLITE_FORMAT */ "auxiliary database format error", 952 /* SQLITE_RANGE */ "bind or column index out of range", 953 /* SQLITE_NOTADB */ "file is encrypted or is not a database", 954 }; 955 const char *zErr = "unknown error"; 956 switch( rc ){ 957 case SQLITE_ABORT_ROLLBACK: { 958 zErr = "abort due to ROLLBACK"; 959 break; 960 } 961 default: { 962 rc &= 0xff; 963 if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){ 964 zErr = aMsg[rc]; 965 } 966 break; 967 } 968 } 969 return zErr; 970 } 971 972 /* 973 ** This routine implements a busy callback that sleeps and tries 974 ** again until a timeout value is reached. The timeout value is 975 ** an integer number of milliseconds passed in as the first 976 ** argument. 977 */ 978 static int sqliteDefaultBusyCallback( 979 void *ptr, /* Database connection */ 980 int count /* Number of times table has been busy */ 981 ){ 982 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP) 983 static const u8 delays[] = 984 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 }; 985 static const u8 totals[] = 986 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 }; 987 # define NDELAY ArraySize(delays) 988 sqlite3 *db = (sqlite3 *)ptr; 989 int timeout = db->busyTimeout; 990 int delay, prior; 991 992 assert( count>=0 ); 993 if( count < NDELAY ){ 994 delay = delays[count]; 995 prior = totals[count]; 996 }else{ 997 delay = delays[NDELAY-1]; 998 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1)); 999 } 1000 if( prior + delay > timeout ){ 1001 delay = timeout - prior; 1002 if( delay<=0 ) return 0; 1003 } 1004 sqlite3OsSleep(db->pVfs, delay*1000); 1005 return 1; 1006 #else 1007 sqlite3 *db = (sqlite3 *)ptr; 1008 int timeout = ((sqlite3 *)ptr)->busyTimeout; 1009 if( (count+1)*1000 > timeout ){ 1010 return 0; 1011 } 1012 sqlite3OsSleep(db->pVfs, 1000000); 1013 return 1; 1014 #endif 1015 } 1016 1017 /* 1018 ** Invoke the given busy handler. 1019 ** 1020 ** This routine is called when an operation failed with a lock. 1021 ** If this routine returns non-zero, the lock is retried. If it 1022 ** returns 0, the operation aborts with an SQLITE_BUSY error. 1023 */ 1024 int sqlite3InvokeBusyHandler(BusyHandler *p){ 1025 int rc; 1026 if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0; 1027 rc = p->xFunc(p->pArg, p->nBusy); 1028 if( rc==0 ){ 1029 p->nBusy = -1; 1030 }else{ 1031 p->nBusy++; 1032 } 1033 return rc; 1034 } 1035 1036 /* 1037 ** This routine sets the busy callback for an Sqlite database to the 1038 ** given callback function with the given argument. 1039 */ 1040 int sqlite3_busy_handler( 1041 sqlite3 *db, 1042 int (*xBusy)(void*,int), 1043 void *pArg 1044 ){ 1045 sqlite3_mutex_enter(db->mutex); 1046 db->busyHandler.xFunc = xBusy; 1047 db->busyHandler.pArg = pArg; 1048 db->busyHandler.nBusy = 0; 1049 sqlite3_mutex_leave(db->mutex); 1050 return SQLITE_OK; 1051 } 1052 1053 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 1054 /* 1055 ** This routine sets the progress callback for an Sqlite database to the 1056 ** given callback function with the given argument. The progress callback will 1057 ** be invoked every nOps opcodes. 1058 */ 1059 void sqlite3_progress_handler( 1060 sqlite3 *db, 1061 int nOps, 1062 int (*xProgress)(void*), 1063 void *pArg 1064 ){ 1065 sqlite3_mutex_enter(db->mutex); 1066 if( nOps>0 ){ 1067 db->xProgress = xProgress; 1068 db->nProgressOps = nOps; 1069 db->pProgressArg = pArg; 1070 }else{ 1071 db->xProgress = 0; 1072 db->nProgressOps = 0; 1073 db->pProgressArg = 0; 1074 } 1075 sqlite3_mutex_leave(db->mutex); 1076 } 1077 #endif 1078 1079 1080 /* 1081 ** This routine installs a default busy handler that waits for the 1082 ** specified number of milliseconds before returning 0. 1083 */ 1084 int sqlite3_busy_timeout(sqlite3 *db, int ms){ 1085 if( ms>0 ){ 1086 db->busyTimeout = ms; 1087 sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db); 1088 }else{ 1089 sqlite3_busy_handler(db, 0, 0); 1090 } 1091 return SQLITE_OK; 1092 } 1093 1094 /* 1095 ** Cause any pending operation to stop at its earliest opportunity. 1096 */ 1097 void sqlite3_interrupt(sqlite3 *db){ 1098 db->u1.isInterrupted = 1; 1099 } 1100 1101 1102 /* 1103 ** This function is exactly the same as sqlite3_create_function(), except 1104 ** that it is designed to be called by internal code. The difference is 1105 ** that if a malloc() fails in sqlite3_create_function(), an error code 1106 ** is returned and the mallocFailed flag cleared. 1107 */ 1108 int sqlite3CreateFunc( 1109 sqlite3 *db, 1110 const char *zFunctionName, 1111 int nArg, 1112 int enc, 1113 void *pUserData, 1114 void (*xFunc)(sqlite3_context*,int,sqlite3_value **), 1115 void (*xStep)(sqlite3_context*,int,sqlite3_value **), 1116 void (*xFinal)(sqlite3_context*), 1117 FuncDestructor *pDestructor 1118 ){ 1119 FuncDef *p; 1120 int nName; 1121 1122 assert( sqlite3_mutex_held(db->mutex) ); 1123 if( zFunctionName==0 || 1124 (xFunc && (xFinal || xStep)) || 1125 (!xFunc && (xFinal && !xStep)) || 1126 (!xFunc && (!xFinal && xStep)) || 1127 (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) || 1128 (255<(nName = sqlite3Strlen30( zFunctionName))) ){ 1129 return SQLITE_MISUSE_BKPT; 1130 } 1131 1132 #ifndef SQLITE_OMIT_UTF16 1133 /* If SQLITE_UTF16 is specified as the encoding type, transform this 1134 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the 1135 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. 1136 ** 1137 ** If SQLITE_ANY is specified, add three versions of the function 1138 ** to the hash table. 1139 */ 1140 if( enc==SQLITE_UTF16 ){ 1141 enc = SQLITE_UTF16NATIVE; 1142 }else if( enc==SQLITE_ANY ){ 1143 int rc; 1144 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8, 1145 pUserData, xFunc, xStep, xFinal, pDestructor); 1146 if( rc==SQLITE_OK ){ 1147 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE, 1148 pUserData, xFunc, xStep, xFinal, pDestructor); 1149 } 1150 if( rc!=SQLITE_OK ){ 1151 return rc; 1152 } 1153 enc = SQLITE_UTF16BE; 1154 } 1155 #else 1156 enc = SQLITE_UTF8; 1157 #endif 1158 1159 /* Check if an existing function is being overridden or deleted. If so, 1160 ** and there are active VMs, then return SQLITE_BUSY. If a function 1161 ** is being overridden/deleted but there are no active VMs, allow the 1162 ** operation to continue but invalidate all precompiled statements. 1163 */ 1164 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0); 1165 if( p && p->iPrefEnc==enc && p->nArg==nArg ){ 1166 if( db->activeVdbeCnt ){ 1167 sqlite3Error(db, SQLITE_BUSY, 1168 "unable to delete/modify user-function due to active statements"); 1169 assert( !db->mallocFailed ); 1170 return SQLITE_BUSY; 1171 }else{ 1172 sqlite3ExpirePreparedStatements(db); 1173 } 1174 } 1175 1176 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1); 1177 assert(p || db->mallocFailed); 1178 if( !p ){ 1179 return SQLITE_NOMEM; 1180 } 1181 1182 /* If an older version of the function with a configured destructor is 1183 ** being replaced invoke the destructor function here. */ 1184 functionDestroy(db, p); 1185 1186 if( pDestructor ){ 1187 pDestructor->nRef++; 1188 } 1189 p->pDestructor = pDestructor; 1190 p->flags = 0; 1191 p->xFunc = xFunc; 1192 p->xStep = xStep; 1193 p->xFinalize = xFinal; 1194 p->pUserData = pUserData; 1195 p->nArg = (u16)nArg; 1196 return SQLITE_OK; 1197 } 1198 1199 /* 1200 ** Create new user functions. 1201 */ 1202 int sqlite3_create_function( 1203 sqlite3 *db, 1204 const char *zFunc, 1205 int nArg, 1206 int enc, 1207 void *p, 1208 void (*xFunc)(sqlite3_context*,int,sqlite3_value **), 1209 void (*xStep)(sqlite3_context*,int,sqlite3_value **), 1210 void (*xFinal)(sqlite3_context*) 1211 ){ 1212 return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep, 1213 xFinal, 0); 1214 } 1215 1216 int sqlite3_create_function_v2( 1217 sqlite3 *db, 1218 const char *zFunc, 1219 int nArg, 1220 int enc, 1221 void *p, 1222 void (*xFunc)(sqlite3_context*,int,sqlite3_value **), 1223 void (*xStep)(sqlite3_context*,int,sqlite3_value **), 1224 void (*xFinal)(sqlite3_context*), 1225 void (*xDestroy)(void *) 1226 ){ 1227 int rc = SQLITE_ERROR; 1228 FuncDestructor *pArg = 0; 1229 sqlite3_mutex_enter(db->mutex); 1230 if( xDestroy ){ 1231 pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor)); 1232 if( !pArg ){ 1233 xDestroy(p); 1234 goto out; 1235 } 1236 pArg->xDestroy = xDestroy; 1237 pArg->pUserData = p; 1238 } 1239 rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg); 1240 if( pArg && pArg->nRef==0 ){ 1241 assert( rc!=SQLITE_OK ); 1242 xDestroy(p); 1243 sqlite3DbFree(db, pArg); 1244 } 1245 1246 out: 1247 rc = sqlite3ApiExit(db, rc); 1248 sqlite3_mutex_leave(db->mutex); 1249 return rc; 1250 } 1251 1252 #ifndef SQLITE_OMIT_UTF16 1253 int sqlite3_create_function16( 1254 sqlite3 *db, 1255 const void *zFunctionName, 1256 int nArg, 1257 int eTextRep, 1258 void *p, 1259 void (*xFunc)(sqlite3_context*,int,sqlite3_value**), 1260 void (*xStep)(sqlite3_context*,int,sqlite3_value**), 1261 void (*xFinal)(sqlite3_context*) 1262 ){ 1263 int rc; 1264 char *zFunc8; 1265 sqlite3_mutex_enter(db->mutex); 1266 assert( !db->mallocFailed ); 1267 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE); 1268 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0); 1269 sqlite3DbFree(db, zFunc8); 1270 rc = sqlite3ApiExit(db, rc); 1271 sqlite3_mutex_leave(db->mutex); 1272 return rc; 1273 } 1274 #endif 1275 1276 1277 /* 1278 ** Declare that a function has been overloaded by a virtual table. 1279 ** 1280 ** If the function already exists as a regular global function, then 1281 ** this routine is a no-op. If the function does not exist, then create 1282 ** a new one that always throws a run-time error. 1283 ** 1284 ** When virtual tables intend to provide an overloaded function, they 1285 ** should call this routine to make sure the global function exists. 1286 ** A global function must exist in order for name resolution to work 1287 ** properly. 1288 */ 1289 int sqlite3_overload_function( 1290 sqlite3 *db, 1291 const char *zName, 1292 int nArg 1293 ){ 1294 int nName = sqlite3Strlen30(zName); 1295 int rc = SQLITE_OK; 1296 sqlite3_mutex_enter(db->mutex); 1297 if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){ 1298 rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8, 1299 0, sqlite3InvalidFunction, 0, 0, 0); 1300 } 1301 rc = sqlite3ApiExit(db, rc); 1302 sqlite3_mutex_leave(db->mutex); 1303 return rc; 1304 } 1305 1306 #ifndef SQLITE_OMIT_TRACE 1307 /* 1308 ** Register a trace function. The pArg from the previously registered trace 1309 ** is returned. 1310 ** 1311 ** A NULL trace function means that no tracing is executes. A non-NULL 1312 ** trace is a pointer to a function that is invoked at the start of each 1313 ** SQL statement. 1314 */ 1315 void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){ 1316 void *pOld; 1317 sqlite3_mutex_enter(db->mutex); 1318 pOld = db->pTraceArg; 1319 db->xTrace = xTrace; 1320 db->pTraceArg = pArg; 1321 sqlite3_mutex_leave(db->mutex); 1322 return pOld; 1323 } 1324 /* 1325 ** Register a profile function. The pArg from the previously registered 1326 ** profile function is returned. 1327 ** 1328 ** A NULL profile function means that no profiling is executes. A non-NULL 1329 ** profile is a pointer to a function that is invoked at the conclusion of 1330 ** each SQL statement that is run. 1331 */ 1332 void *sqlite3_profile( 1333 sqlite3 *db, 1334 void (*xProfile)(void*,const char*,sqlite_uint64), 1335 void *pArg 1336 ){ 1337 void *pOld; 1338 sqlite3_mutex_enter(db->mutex); 1339 pOld = db->pProfileArg; 1340 db->xProfile = xProfile; 1341 db->pProfileArg = pArg; 1342 sqlite3_mutex_leave(db->mutex); 1343 return pOld; 1344 } 1345 #endif /* SQLITE_OMIT_TRACE */ 1346 1347 /* 1348 ** Register a function to be invoked when a transaction commits. 1349 ** If the invoked function returns non-zero, then the commit becomes a 1350 ** rollback. 1351 */ 1352 void *sqlite3_commit_hook( 1353 sqlite3 *db, /* Attach the hook to this database */ 1354 int (*xCallback)(void*), /* Function to invoke on each commit */ 1355 void *pArg /* Argument to the function */ 1356 ){ 1357 void *pOld; 1358 sqlite3_mutex_enter(db->mutex); 1359 pOld = db->pCommitArg; 1360 db->xCommitCallback = xCallback; 1361 db->pCommitArg = pArg; 1362 sqlite3_mutex_leave(db->mutex); 1363 return pOld; 1364 } 1365 1366 /* 1367 ** Register a callback to be invoked each time a row is updated, 1368 ** inserted or deleted using this database connection. 1369 */ 1370 void *sqlite3_update_hook( 1371 sqlite3 *db, /* Attach the hook to this database */ 1372 void (*xCallback)(void*,int,char const *,char const *,sqlite_int64), 1373 void *pArg /* Argument to the function */ 1374 ){ 1375 void *pRet; 1376 sqlite3_mutex_enter(db->mutex); 1377 pRet = db->pUpdateArg; 1378 db->xUpdateCallback = xCallback; 1379 db->pUpdateArg = pArg; 1380 sqlite3_mutex_leave(db->mutex); 1381 return pRet; 1382 } 1383 1384 /* 1385 ** Register a callback to be invoked each time a transaction is rolled 1386 ** back by this database connection. 1387 */ 1388 void *sqlite3_rollback_hook( 1389 sqlite3 *db, /* Attach the hook to this database */ 1390 void (*xCallback)(void*), /* Callback function */ 1391 void *pArg /* Argument to the function */ 1392 ){ 1393 void *pRet; 1394 sqlite3_mutex_enter(db->mutex); 1395 pRet = db->pRollbackArg; 1396 db->xRollbackCallback = xCallback; 1397 db->pRollbackArg = pArg; 1398 sqlite3_mutex_leave(db->mutex); 1399 return pRet; 1400 } 1401 1402 #ifndef SQLITE_OMIT_WAL 1403 /* 1404 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint(). 1405 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file 1406 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by 1407 ** wal_autocheckpoint()). 1408 */ 1409 int sqlite3WalDefaultHook( 1410 void *pClientData, /* Argument */ 1411 sqlite3 *db, /* Connection */ 1412 const char *zDb, /* Database */ 1413 int nFrame /* Size of WAL */ 1414 ){ 1415 if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){ 1416 sqlite3BeginBenignMalloc(); 1417 sqlite3_wal_checkpoint(db, zDb); 1418 sqlite3EndBenignMalloc(); 1419 } 1420 return SQLITE_OK; 1421 } 1422 #endif /* SQLITE_OMIT_WAL */ 1423 1424 /* 1425 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint 1426 ** a database after committing a transaction if there are nFrame or 1427 ** more frames in the log file. Passing zero or a negative value as the 1428 ** nFrame parameter disables automatic checkpoints entirely. 1429 ** 1430 ** The callback registered by this function replaces any existing callback 1431 ** registered using sqlite3_wal_hook(). Likewise, registering a callback 1432 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism 1433 ** configured by this function. 1434 */ 1435 int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){ 1436 #ifdef SQLITE_OMIT_WAL 1437 UNUSED_PARAMETER(db); 1438 UNUSED_PARAMETER(nFrame); 1439 #else 1440 if( nFrame>0 ){ 1441 sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame)); 1442 }else{ 1443 sqlite3_wal_hook(db, 0, 0); 1444 } 1445 #endif 1446 return SQLITE_OK; 1447 } 1448 1449 /* 1450 ** Register a callback to be invoked each time a transaction is written 1451 ** into the write-ahead-log by this database connection. 1452 */ 1453 void *sqlite3_wal_hook( 1454 sqlite3 *db, /* Attach the hook to this db handle */ 1455 int(*xCallback)(void *, sqlite3*, const char*, int), 1456 void *pArg /* First argument passed to xCallback() */ 1457 ){ 1458 #ifndef SQLITE_OMIT_WAL 1459 void *pRet; 1460 sqlite3_mutex_enter(db->mutex); 1461 pRet = db->pWalArg; 1462 db->xWalCallback = xCallback; 1463 db->pWalArg = pArg; 1464 sqlite3_mutex_leave(db->mutex); 1465 return pRet; 1466 #else 1467 return 0; 1468 #endif 1469 } 1470 1471 /* 1472 ** Checkpoint database zDb. 1473 */ 1474 int sqlite3_wal_checkpoint_v2( 1475 sqlite3 *db, /* Database handle */ 1476 const char *zDb, /* Name of attached database (or NULL) */ 1477 int eMode, /* SQLITE_CHECKPOINT_* value */ 1478 int *pnLog, /* OUT: Size of WAL log in frames */ 1479 int *pnCkpt /* OUT: Total number of frames checkpointed */ 1480 ){ 1481 #ifdef SQLITE_OMIT_WAL 1482 return SQLITE_OK; 1483 #else 1484 int rc; /* Return code */ 1485 int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */ 1486 1487 /* Initialize the output variables to -1 in case an error occurs. */ 1488 if( pnLog ) *pnLog = -1; 1489 if( pnCkpt ) *pnCkpt = -1; 1490 1491 assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE ); 1492 assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART ); 1493 assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART ); 1494 if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){ 1495 return SQLITE_MISUSE; 1496 } 1497 1498 sqlite3_mutex_enter(db->mutex); 1499 if( zDb && zDb[0] ){ 1500 iDb = sqlite3FindDbName(db, zDb); 1501 } 1502 if( iDb<0 ){ 1503 rc = SQLITE_ERROR; 1504 sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb); 1505 }else{ 1506 rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt); 1507 sqlite3Error(db, rc, 0); 1508 } 1509 rc = sqlite3ApiExit(db, rc); 1510 sqlite3_mutex_leave(db->mutex); 1511 return rc; 1512 #endif 1513 } 1514 1515 1516 /* 1517 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points 1518 ** to contains a zero-length string, all attached databases are 1519 ** checkpointed. 1520 */ 1521 int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){ 1522 return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0); 1523 } 1524 1525 #ifndef SQLITE_OMIT_WAL 1526 /* 1527 ** Run a checkpoint on database iDb. This is a no-op if database iDb is 1528 ** not currently open in WAL mode. 1529 ** 1530 ** If a transaction is open on the database being checkpointed, this 1531 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 1532 ** an error occurs while running the checkpoint, an SQLite error code is 1533 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK. 1534 ** 1535 ** The mutex on database handle db should be held by the caller. The mutex 1536 ** associated with the specific b-tree being checkpointed is taken by 1537 ** this function while the checkpoint is running. 1538 ** 1539 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are 1540 ** checkpointed. If an error is encountered it is returned immediately - 1541 ** no attempt is made to checkpoint any remaining databases. 1542 ** 1543 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. 1544 */ 1545 int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){ 1546 int rc = SQLITE_OK; /* Return code */ 1547 int i; /* Used to iterate through attached dbs */ 1548 int bBusy = 0; /* True if SQLITE_BUSY has been encountered */ 1549 1550 assert( sqlite3_mutex_held(db->mutex) ); 1551 assert( !pnLog || *pnLog==-1 ); 1552 assert( !pnCkpt || *pnCkpt==-1 ); 1553 1554 for(i=0; i<db->nDb && rc==SQLITE_OK; i++){ 1555 if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){ 1556 rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt); 1557 pnLog = 0; 1558 pnCkpt = 0; 1559 if( rc==SQLITE_BUSY ){ 1560 bBusy = 1; 1561 rc = SQLITE_OK; 1562 } 1563 } 1564 } 1565 1566 return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc; 1567 } 1568 #endif /* SQLITE_OMIT_WAL */ 1569 1570 /* 1571 ** This function returns true if main-memory should be used instead of 1572 ** a temporary file for transient pager files and statement journals. 1573 ** The value returned depends on the value of db->temp_store (runtime 1574 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The 1575 ** following table describes the relationship between these two values 1576 ** and this functions return value. 1577 ** 1578 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database 1579 ** ----------------- -------------- ------------------------------ 1580 ** 0 any file (return 0) 1581 ** 1 1 file (return 0) 1582 ** 1 2 memory (return 1) 1583 ** 1 0 file (return 0) 1584 ** 2 1 file (return 0) 1585 ** 2 2 memory (return 1) 1586 ** 2 0 memory (return 1) 1587 ** 3 any memory (return 1) 1588 */ 1589 int sqlite3TempInMemory(const sqlite3 *db){ 1590 #if SQLITE_TEMP_STORE==1 1591 return ( db->temp_store==2 ); 1592 #endif 1593 #if SQLITE_TEMP_STORE==2 1594 return ( db->temp_store!=1 ); 1595 #endif 1596 #if SQLITE_TEMP_STORE==3 1597 return 1; 1598 #endif 1599 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3 1600 return 0; 1601 #endif 1602 } 1603 1604 /* 1605 ** Return UTF-8 encoded English language explanation of the most recent 1606 ** error. 1607 */ 1608 const char *sqlite3_errmsg(sqlite3 *db){ 1609 const char *z; 1610 if( !db ){ 1611 return sqlite3ErrStr(SQLITE_NOMEM); 1612 } 1613 if( !sqlite3SafetyCheckSickOrOk(db) ){ 1614 return sqlite3ErrStr(SQLITE_MISUSE_BKPT); 1615 } 1616 sqlite3_mutex_enter(db->mutex); 1617 if( db->mallocFailed ){ 1618 z = sqlite3ErrStr(SQLITE_NOMEM); 1619 }else{ 1620 z = (char*)sqlite3_value_text(db->pErr); 1621 assert( !db->mallocFailed ); 1622 if( z==0 ){ 1623 z = sqlite3ErrStr(db->errCode); 1624 } 1625 } 1626 sqlite3_mutex_leave(db->mutex); 1627 return z; 1628 } 1629 1630 #ifndef SQLITE_OMIT_UTF16 1631 /* 1632 ** Return UTF-16 encoded English language explanation of the most recent 1633 ** error. 1634 */ 1635 const void *sqlite3_errmsg16(sqlite3 *db){ 1636 static const u16 outOfMem[] = { 1637 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0 1638 }; 1639 static const u16 misuse[] = { 1640 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 1641 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 1642 'c', 'a', 'l', 'l', 'e', 'd', ' ', 1643 'o', 'u', 't', ' ', 1644 'o', 'f', ' ', 1645 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0 1646 }; 1647 1648 const void *z; 1649 if( !db ){ 1650 return (void *)outOfMem; 1651 } 1652 if( !sqlite3SafetyCheckSickOrOk(db) ){ 1653 return (void *)misuse; 1654 } 1655 sqlite3_mutex_enter(db->mutex); 1656 if( db->mallocFailed ){ 1657 z = (void *)outOfMem; 1658 }else{ 1659 z = sqlite3_value_text16(db->pErr); 1660 if( z==0 ){ 1661 sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode), 1662 SQLITE_UTF8, SQLITE_STATIC); 1663 z = sqlite3_value_text16(db->pErr); 1664 } 1665 /* A malloc() may have failed within the call to sqlite3_value_text16() 1666 ** above. If this is the case, then the db->mallocFailed flag needs to 1667 ** be cleared before returning. Do this directly, instead of via 1668 ** sqlite3ApiExit(), to avoid setting the database handle error message. 1669 */ 1670 db->mallocFailed = 0; 1671 } 1672 sqlite3_mutex_leave(db->mutex); 1673 return z; 1674 } 1675 #endif /* SQLITE_OMIT_UTF16 */ 1676 1677 /* 1678 ** Return the most recent error code generated by an SQLite routine. If NULL is 1679 ** passed to this function, we assume a malloc() failed during sqlite3_open(). 1680 */ 1681 int sqlite3_errcode(sqlite3 *db){ 1682 if( db && !sqlite3SafetyCheckSickOrOk(db) ){ 1683 return SQLITE_MISUSE_BKPT; 1684 } 1685 if( !db || db->mallocFailed ){ 1686 return SQLITE_NOMEM; 1687 } 1688 return db->errCode & db->errMask; 1689 } 1690 int sqlite3_extended_errcode(sqlite3 *db){ 1691 if( db && !sqlite3SafetyCheckSickOrOk(db) ){ 1692 return SQLITE_MISUSE_BKPT; 1693 } 1694 if( !db || db->mallocFailed ){ 1695 return SQLITE_NOMEM; 1696 } 1697 return db->errCode; 1698 } 1699 1700 /* 1701 ** Create a new collating function for database "db". The name is zName 1702 ** and the encoding is enc. 1703 */ 1704 static int createCollation( 1705 sqlite3* db, 1706 const char *zName, 1707 u8 enc, 1708 void* pCtx, 1709 int(*xCompare)(void*,int,const void*,int,const void*), 1710 void(*xDel)(void*) 1711 ){ 1712 CollSeq *pColl; 1713 int enc2; 1714 int nName = sqlite3Strlen30(zName); 1715 1716 assert( sqlite3_mutex_held(db->mutex) ); 1717 1718 /* If SQLITE_UTF16 is specified as the encoding type, transform this 1719 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the 1720 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. 1721 */ 1722 enc2 = enc; 1723 testcase( enc2==SQLITE_UTF16 ); 1724 testcase( enc2==SQLITE_UTF16_ALIGNED ); 1725 if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){ 1726 enc2 = SQLITE_UTF16NATIVE; 1727 } 1728 if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){ 1729 return SQLITE_MISUSE_BKPT; 1730 } 1731 1732 /* Check if this call is removing or replacing an existing collation 1733 ** sequence. If so, and there are active VMs, return busy. If there 1734 ** are no active VMs, invalidate any pre-compiled statements. 1735 */ 1736 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0); 1737 if( pColl && pColl->xCmp ){ 1738 if( db->activeVdbeCnt ){ 1739 sqlite3Error(db, SQLITE_BUSY, 1740 "unable to delete/modify collation sequence due to active statements"); 1741 return SQLITE_BUSY; 1742 } 1743 sqlite3ExpirePreparedStatements(db); 1744 1745 /* If collation sequence pColl was created directly by a call to 1746 ** sqlite3_create_collation, and not generated by synthCollSeq(), 1747 ** then any copies made by synthCollSeq() need to be invalidated. 1748 ** Also, collation destructor - CollSeq.xDel() - function may need 1749 ** to be called. 1750 */ 1751 if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){ 1752 CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName); 1753 int j; 1754 for(j=0; j<3; j++){ 1755 CollSeq *p = &aColl[j]; 1756 if( p->enc==pColl->enc ){ 1757 if( p->xDel ){ 1758 p->xDel(p->pUser); 1759 } 1760 p->xCmp = 0; 1761 } 1762 } 1763 } 1764 } 1765 1766 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1); 1767 if( pColl==0 ) return SQLITE_NOMEM; 1768 pColl->xCmp = xCompare; 1769 pColl->pUser = pCtx; 1770 pColl->xDel = xDel; 1771 pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED)); 1772 sqlite3Error(db, SQLITE_OK, 0); 1773 return SQLITE_OK; 1774 } 1775 1776 1777 /* 1778 ** This array defines hard upper bounds on limit values. The 1779 ** initializer must be kept in sync with the SQLITE_LIMIT_* 1780 ** #defines in sqlite3.h. 1781 */ 1782 static const int aHardLimit[] = { 1783 SQLITE_MAX_LENGTH, 1784 SQLITE_MAX_SQL_LENGTH, 1785 SQLITE_MAX_COLUMN, 1786 SQLITE_MAX_EXPR_DEPTH, 1787 SQLITE_MAX_COMPOUND_SELECT, 1788 SQLITE_MAX_VDBE_OP, 1789 SQLITE_MAX_FUNCTION_ARG, 1790 SQLITE_MAX_ATTACHED, 1791 SQLITE_MAX_LIKE_PATTERN_LENGTH, 1792 SQLITE_MAX_VARIABLE_NUMBER, 1793 SQLITE_MAX_TRIGGER_DEPTH, 1794 }; 1795 1796 /* 1797 ** Make sure the hard limits are set to reasonable values 1798 */ 1799 #if SQLITE_MAX_LENGTH<100 1800 # error SQLITE_MAX_LENGTH must be at least 100 1801 #endif 1802 #if SQLITE_MAX_SQL_LENGTH<100 1803 # error SQLITE_MAX_SQL_LENGTH must be at least 100 1804 #endif 1805 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH 1806 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH 1807 #endif 1808 #if SQLITE_MAX_COMPOUND_SELECT<2 1809 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2 1810 #endif 1811 #if SQLITE_MAX_VDBE_OP<40 1812 # error SQLITE_MAX_VDBE_OP must be at least 40 1813 #endif 1814 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000 1815 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000 1816 #endif 1817 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62 1818 # error SQLITE_MAX_ATTACHED must be between 0 and 62 1819 #endif 1820 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1 1821 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1 1822 #endif 1823 #if SQLITE_MAX_COLUMN>32767 1824 # error SQLITE_MAX_COLUMN must not exceed 32767 1825 #endif 1826 #if SQLITE_MAX_TRIGGER_DEPTH<1 1827 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1 1828 #endif 1829 1830 1831 /* 1832 ** Change the value of a limit. Report the old value. 1833 ** If an invalid limit index is supplied, report -1. 1834 ** Make no changes but still report the old value if the 1835 ** new limit is negative. 1836 ** 1837 ** A new lower limit does not shrink existing constructs. 1838 ** It merely prevents new constructs that exceed the limit 1839 ** from forming. 1840 */ 1841 int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){ 1842 int oldLimit; 1843 1844 1845 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME 1846 ** there is a hard upper bound set at compile-time by a C preprocessor 1847 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to 1848 ** "_MAX_".) 1849 */ 1850 assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH ); 1851 assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH ); 1852 assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN ); 1853 assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH ); 1854 assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT); 1855 assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP ); 1856 assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG ); 1857 assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED ); 1858 assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]== 1859 SQLITE_MAX_LIKE_PATTERN_LENGTH ); 1860 assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER); 1861 assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH ); 1862 assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) ); 1863 1864 1865 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){ 1866 return -1; 1867 } 1868 oldLimit = db->aLimit[limitId]; 1869 if( newLimit>=0 ){ /* IMP: R-52476-28732 */ 1870 if( newLimit>aHardLimit[limitId] ){ 1871 newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */ 1872 } 1873 db->aLimit[limitId] = newLimit; 1874 } 1875 return oldLimit; /* IMP: R-53341-35419 */ 1876 } 1877 1878 /* 1879 ** This function is used to parse both URIs and non-URI filenames passed by the 1880 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database 1881 ** URIs specified as part of ATTACH statements. 1882 ** 1883 ** The first argument to this function is the name of the VFS to use (or 1884 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx" 1885 ** query parameter. The second argument contains the URI (or non-URI filename) 1886 ** itself. When this function is called the *pFlags variable should contain 1887 ** the default flags to open the database handle with. The value stored in 1888 ** *pFlags may be updated before returning if the URI filename contains 1889 ** "cache=xxx" or "mode=xxx" query parameters. 1890 ** 1891 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to 1892 ** the VFS that should be used to open the database file. *pzFile is set to 1893 ** point to a buffer containing the name of the file to open. It is the 1894 ** responsibility of the caller to eventually call sqlite3_free() to release 1895 ** this buffer. 1896 ** 1897 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg 1898 ** may be set to point to a buffer containing an English language error 1899 ** message. It is the responsibility of the caller to eventually release 1900 ** this buffer by calling sqlite3_free(). 1901 */ 1902 int sqlite3ParseUri( 1903 const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */ 1904 const char *zUri, /* Nul-terminated URI to parse */ 1905 unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */ 1906 sqlite3_vfs **ppVfs, /* OUT: VFS to use */ 1907 char **pzFile, /* OUT: Filename component of URI */ 1908 char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */ 1909 ){ 1910 int rc = SQLITE_OK; 1911 unsigned int flags = *pFlags; 1912 const char *zVfs = zDefaultVfs; 1913 char *zFile; 1914 char c; 1915 int nUri = sqlite3Strlen30(zUri); 1916 1917 assert( *pzErrMsg==0 ); 1918 1919 if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri) 1920 && nUri>=5 && memcmp(zUri, "file:", 5)==0 1921 ){ 1922 char *zOpt; 1923 int eState; /* Parser state when parsing URI */ 1924 int iIn; /* Input character index */ 1925 int iOut = 0; /* Output character index */ 1926 int nByte = nUri+2; /* Bytes of space to allocate */ 1927 1928 /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen 1929 ** method that there may be extra parameters following the file-name. */ 1930 flags |= SQLITE_OPEN_URI; 1931 1932 for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&'); 1933 zFile = sqlite3_malloc(nByte); 1934 if( !zFile ) return SQLITE_NOMEM; 1935 1936 /* Discard the scheme and authority segments of the URI. */ 1937 if( zUri[5]=='/' && zUri[6]=='/' ){ 1938 iIn = 7; 1939 while( zUri[iIn] && zUri[iIn]!='/' ) iIn++; 1940 1941 if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){ 1942 *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", 1943 iIn-7, &zUri[7]); 1944 rc = SQLITE_ERROR; 1945 goto parse_uri_out; 1946 } 1947 }else{ 1948 iIn = 5; 1949 } 1950 1951 /* Copy the filename and any query parameters into the zFile buffer. 1952 ** Decode %HH escape codes along the way. 1953 ** 1954 ** Within this loop, variable eState may be set to 0, 1 or 2, depending 1955 ** on the parsing context. As follows: 1956 ** 1957 ** 0: Parsing file-name. 1958 ** 1: Parsing name section of a name=value query parameter. 1959 ** 2: Parsing value section of a name=value query parameter. 1960 */ 1961 eState = 0; 1962 while( (c = zUri[iIn])!=0 && c!='#' ){ 1963 iIn++; 1964 if( c=='%' 1965 && sqlite3Isxdigit(zUri[iIn]) 1966 && sqlite3Isxdigit(zUri[iIn+1]) 1967 ){ 1968 int octet = (sqlite3HexToInt(zUri[iIn++]) << 4); 1969 octet += sqlite3HexToInt(zUri[iIn++]); 1970 1971 assert( octet>=0 && octet<256 ); 1972 if( octet==0 ){ 1973 /* This branch is taken when "%00" appears within the URI. In this 1974 ** case we ignore all text in the remainder of the path, name or 1975 ** value currently being parsed. So ignore the current character 1976 ** and skip to the next "?", "=" or "&", as appropriate. */ 1977 while( (c = zUri[iIn])!=0 && c!='#' 1978 && (eState!=0 || c!='?') 1979 && (eState!=1 || (c!='=' && c!='&')) 1980 && (eState!=2 || c!='&') 1981 ){ 1982 iIn++; 1983 } 1984 continue; 1985 } 1986 c = octet; 1987 }else if( eState==1 && (c=='&' || c=='=') ){ 1988 if( zFile[iOut-1]==0 ){ 1989 /* An empty option name. Ignore this option altogether. */ 1990 while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++; 1991 continue; 1992 } 1993 if( c=='&' ){ 1994 zFile[iOut++] = '\0'; 1995 }else{ 1996 eState = 2; 1997 } 1998 c = 0; 1999 }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){ 2000 c = 0; 2001 eState = 1; 2002 } 2003 zFile[iOut++] = c; 2004 } 2005 if( eState==1 ) zFile[iOut++] = '\0'; 2006 zFile[iOut++] = '\0'; 2007 zFile[iOut++] = '\0'; 2008 2009 /* Check if there were any options specified that should be interpreted 2010 ** here. Options that are interpreted here include "vfs" and those that 2011 ** correspond to flags that may be passed to the sqlite3_open_v2() 2012 ** method. */ 2013 zOpt = &zFile[sqlite3Strlen30(zFile)+1]; 2014 while( zOpt[0] ){ 2015 int nOpt = sqlite3Strlen30(zOpt); 2016 char *zVal = &zOpt[nOpt+1]; 2017 int nVal = sqlite3Strlen30(zVal); 2018 2019 if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){ 2020 zVfs = zVal; 2021 }else{ 2022 struct OpenMode { 2023 const char *z; 2024 int mode; 2025 } *aMode = 0; 2026 char *zModeType = 0; 2027 int mask = 0; 2028 int limit = 0; 2029 2030 if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){ 2031 static struct OpenMode aCacheMode[] = { 2032 { "shared", SQLITE_OPEN_SHAREDCACHE }, 2033 { "private", SQLITE_OPEN_PRIVATECACHE }, 2034 { 0, 0 } 2035 }; 2036 2037 mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE; 2038 aMode = aCacheMode; 2039 limit = mask; 2040 zModeType = "cache"; 2041 } 2042 if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){ 2043 static struct OpenMode aOpenMode[] = { 2044 { "ro", SQLITE_OPEN_READONLY }, 2045 { "rw", SQLITE_OPEN_READWRITE }, 2046 { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE }, 2047 { "memory", 2048 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE 2049 | SQLITE_OPEN_MEMORY }, 2050 { 0, 0 } 2051 }; 2052 2053 mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE 2054 | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY; 2055 aMode = aOpenMode; 2056 limit = mask & flags; 2057 zModeType = "access"; 2058 } 2059 2060 if( aMode ){ 2061 int i; 2062 int mode = 0; 2063 for(i=0; aMode[i].z; i++){ 2064 const char *z = aMode[i].z; 2065 if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){ 2066 mode = aMode[i].mode; 2067 break; 2068 } 2069 } 2070 if( mode==0 ){ 2071 *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal); 2072 rc = SQLITE_ERROR; 2073 goto parse_uri_out; 2074 } 2075 if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){ 2076 *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s", 2077 zModeType, zVal); 2078 rc = SQLITE_PERM; 2079 goto parse_uri_out; 2080 } 2081 flags = (flags & ~mask) | mode; 2082 } 2083 } 2084 2085 zOpt = &zVal[nVal+1]; 2086 } 2087 2088 }else{ 2089 zFile = sqlite3_malloc(nUri+2); 2090 if( !zFile ) return SQLITE_NOMEM; 2091 memcpy(zFile, zUri, nUri); 2092 zFile[nUri] = '\0'; 2093 zFile[nUri+1] = '\0'; 2094 flags &= ~SQLITE_OPEN_URI; 2095 } 2096 2097 *ppVfs = sqlite3_vfs_find(zVfs); 2098 if( *ppVfs==0 ){ 2099 *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs); 2100 rc = SQLITE_ERROR; 2101 } 2102 parse_uri_out: 2103 if( rc!=SQLITE_OK ){ 2104 sqlite3_free(zFile); 2105 zFile = 0; 2106 } 2107 *pFlags = flags; 2108 *pzFile = zFile; 2109 return rc; 2110 } 2111 2112 2113 /* 2114 ** This routine does the work of opening a database on behalf of 2115 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename" 2116 ** is UTF-8 encoded. 2117 */ 2118 static int openDatabase( 2119 const char *zFilename, /* Database filename UTF-8 encoded */ 2120 sqlite3 **ppDb, /* OUT: Returned database handle */ 2121 unsigned int flags, /* Operational flags */ 2122 const char *zVfs /* Name of the VFS to use */ 2123 ){ 2124 sqlite3 *db; /* Store allocated handle here */ 2125 int rc; /* Return code */ 2126 int isThreadsafe; /* True for threadsafe connections */ 2127 char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */ 2128 char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */ 2129 2130 *ppDb = 0; 2131 #ifndef SQLITE_OMIT_AUTOINIT 2132 rc = sqlite3_initialize(); 2133 if( rc ) return rc; 2134 #endif 2135 2136 /* Only allow sensible combinations of bits in the flags argument. 2137 ** Throw an error if any non-sense combination is used. If we 2138 ** do not block illegal combinations here, it could trigger 2139 ** assert() statements in deeper layers. Sensible combinations 2140 ** are: 2141 ** 2142 ** 1: SQLITE_OPEN_READONLY 2143 ** 2: SQLITE_OPEN_READWRITE 2144 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE 2145 */ 2146 assert( SQLITE_OPEN_READONLY == 0x01 ); 2147 assert( SQLITE_OPEN_READWRITE == 0x02 ); 2148 assert( SQLITE_OPEN_CREATE == 0x04 ); 2149 testcase( (1<<(flags&7))==0x02 ); /* READONLY */ 2150 testcase( (1<<(flags&7))==0x04 ); /* READWRITE */ 2151 testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */ 2152 if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT; 2153 2154 if( sqlite3GlobalConfig.bCoreMutex==0 ){ 2155 isThreadsafe = 0; 2156 }else if( flags & SQLITE_OPEN_NOMUTEX ){ 2157 isThreadsafe = 0; 2158 }else if( flags & SQLITE_OPEN_FULLMUTEX ){ 2159 isThreadsafe = 1; 2160 }else{ 2161 isThreadsafe = sqlite3GlobalConfig.bFullMutex; 2162 } 2163 if( flags & SQLITE_OPEN_PRIVATECACHE ){ 2164 flags &= ~SQLITE_OPEN_SHAREDCACHE; 2165 }else if( sqlite3GlobalConfig.sharedCacheEnabled ){ 2166 flags |= SQLITE_OPEN_SHAREDCACHE; 2167 } 2168 2169 /* Remove harmful bits from the flags parameter 2170 ** 2171 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were 2172 ** dealt with in the previous code block. Besides these, the only 2173 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY, 2174 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE, 2175 ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask 2176 ** off all other flags. 2177 */ 2178 flags &= ~( SQLITE_OPEN_DELETEONCLOSE | 2179 SQLITE_OPEN_EXCLUSIVE | 2180 SQLITE_OPEN_MAIN_DB | 2181 SQLITE_OPEN_TEMP_DB | 2182 SQLITE_OPEN_TRANSIENT_DB | 2183 SQLITE_OPEN_MAIN_JOURNAL | 2184 SQLITE_OPEN_TEMP_JOURNAL | 2185 SQLITE_OPEN_SUBJOURNAL | 2186 SQLITE_OPEN_MASTER_JOURNAL | 2187 SQLITE_OPEN_NOMUTEX | 2188 SQLITE_OPEN_FULLMUTEX | 2189 SQLITE_OPEN_WAL 2190 ); 2191 2192 /* Allocate the sqlite data structure */ 2193 db = sqlite3MallocZero( sizeof(sqlite3) ); 2194 if( db==0 ) goto opendb_out; 2195 if( isThreadsafe ){ 2196 db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); 2197 if( db->mutex==0 ){ 2198 sqlite3_free(db); 2199 db = 0; 2200 goto opendb_out; 2201 } 2202 } 2203 sqlite3_mutex_enter(db->mutex); 2204 db->errMask = 0xff; 2205 db->nDb = 2; 2206 db->magic = SQLITE_MAGIC_BUSY; 2207 db->aDb = db->aDbStatic; 2208 2209 assert( sizeof(db->aLimit)==sizeof(aHardLimit) ); 2210 memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit)); 2211 db->autoCommit = 1; 2212 db->nextAutovac = -1; 2213 db->nextPagesize = 0; 2214 db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger 2215 #if SQLITE_DEFAULT_FILE_FORMAT<4 2216 | SQLITE_LegacyFileFmt 2217 #endif 2218 #ifdef SQLITE_ENABLE_LOAD_EXTENSION 2219 | SQLITE_LoadExtension 2220 #endif 2221 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS 2222 | SQLITE_RecTriggers 2223 #endif 2224 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS 2225 | SQLITE_ForeignKeys 2226 #endif 2227 ; 2228 sqlite3HashInit(&db->aCollSeq); 2229 #ifndef SQLITE_OMIT_VIRTUALTABLE 2230 sqlite3HashInit(&db->aModule); 2231 #endif 2232 2233 /* Add the default collation sequence BINARY. BINARY works for both UTF-8 2234 ** and UTF-16, so add a version for each to avoid any unnecessary 2235 ** conversions. The only error that can occur here is a malloc() failure. 2236 */ 2237 createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0); 2238 createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0); 2239 createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0); 2240 createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0); 2241 if( db->mallocFailed ){ 2242 goto opendb_out; 2243 } 2244 db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0); 2245 assert( db->pDfltColl!=0 ); 2246 2247 /* Also add a UTF-8 case-insensitive collation sequence. */ 2248 createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0); 2249 2250 /* Parse the filename/URI argument. */ 2251 db->openFlags = flags; 2252 rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg); 2253 if( rc!=SQLITE_OK ){ 2254 if( rc==SQLITE_NOMEM ) db->mallocFailed = 1; 2255 sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg); 2256 sqlite3_free(zErrMsg); 2257 goto opendb_out; 2258 } 2259 2260 /* Open the backend database driver */ 2261 rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0, 2262 flags | SQLITE_OPEN_MAIN_DB); 2263 if( rc!=SQLITE_OK ){ 2264 if( rc==SQLITE_IOERR_NOMEM ){ 2265 rc = SQLITE_NOMEM; 2266 } 2267 sqlite3Error(db, rc, 0); 2268 goto opendb_out; 2269 } 2270 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt); 2271 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0); 2272 2273 2274 /* The default safety_level for the main database is 'full'; for the temp 2275 ** database it is 'NONE'. This matches the pager layer defaults. 2276 */ 2277 db->aDb[0].zName = "main"; 2278 db->aDb[0].safety_level = 3; 2279 db->aDb[1].zName = "temp"; 2280 db->aDb[1].safety_level = 1; 2281 2282 db->magic = SQLITE_MAGIC_OPEN; 2283 if( db->mallocFailed ){ 2284 goto opendb_out; 2285 } 2286 2287 /* Register all built-in functions, but do not attempt to read the 2288 ** database schema yet. This is delayed until the first time the database 2289 ** is accessed. 2290 */ 2291 sqlite3Error(db, SQLITE_OK, 0); 2292 sqlite3RegisterBuiltinFunctions(db); 2293 2294 /* Load automatic extensions - extensions that have been registered 2295 ** using the sqlite3_automatic_extension() API. 2296 */ 2297 rc = sqlite3_errcode(db); 2298 if( rc==SQLITE_OK ){ 2299 sqlite3AutoLoadExtensions(db); 2300 rc = sqlite3_errcode(db); 2301 if( rc!=SQLITE_OK ){ 2302 goto opendb_out; 2303 } 2304 } 2305 2306 #ifdef SQLITE_ENABLE_FTS1 2307 if( !db->mallocFailed ){ 2308 extern int sqlite3Fts1Init(sqlite3*); 2309 rc = sqlite3Fts1Init(db); 2310 } 2311 #endif 2312 2313 #ifdef SQLITE_ENABLE_FTS2 2314 if( !db->mallocFailed && rc==SQLITE_OK ){ 2315 extern int sqlite3Fts2Init(sqlite3*); 2316 rc = sqlite3Fts2Init(db); 2317 } 2318 #endif 2319 2320 #ifdef SQLITE_ENABLE_FTS3 2321 if( !db->mallocFailed && rc==SQLITE_OK ){ 2322 rc = sqlite3Fts3Init(db); 2323 } 2324 #endif 2325 2326 #ifdef SQLITE_ENABLE_ICU 2327 if( !db->mallocFailed && rc==SQLITE_OK ){ 2328 rc = sqlite3IcuInit(db); 2329 } 2330 #endif 2331 2332 #ifdef SQLITE_ENABLE_RTREE 2333 if( !db->mallocFailed && rc==SQLITE_OK){ 2334 rc = sqlite3RtreeInit(db); 2335 } 2336 #endif 2337 2338 sqlite3Error(db, rc, 0); 2339 2340 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking 2341 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking 2342 ** mode. Doing nothing at all also makes NORMAL the default. 2343 */ 2344 #ifdef SQLITE_DEFAULT_LOCKING_MODE 2345 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE; 2346 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt), 2347 SQLITE_DEFAULT_LOCKING_MODE); 2348 #endif 2349 2350 /* Enable the lookaside-malloc subsystem */ 2351 setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside, 2352 sqlite3GlobalConfig.nLookaside); 2353 2354 sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT); 2355 2356 opendb_out: 2357 sqlite3_free(zOpen); 2358 if( db ){ 2359 assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 ); 2360 sqlite3_mutex_leave(db->mutex); 2361 } 2362 rc = sqlite3_errcode(db); 2363 assert( db!=0 || rc==SQLITE_NOMEM ); 2364 if( rc==SQLITE_NOMEM ){ 2365 sqlite3_close(db); 2366 db = 0; 2367 }else if( rc!=SQLITE_OK ){ 2368 db->magic = SQLITE_MAGIC_SICK; 2369 } 2370 *ppDb = db; 2371 return sqlite3ApiExit(0, rc); 2372 } 2373 2374 /* 2375 ** Open a new database handle. 2376 */ 2377 int sqlite3_open( 2378 const char *zFilename, 2379 sqlite3 **ppDb 2380 ){ 2381 return openDatabase(zFilename, ppDb, 2382 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); 2383 } 2384 int sqlite3_open_v2( 2385 const char *filename, /* Database filename (UTF-8) */ 2386 sqlite3 **ppDb, /* OUT: SQLite db handle */ 2387 int flags, /* Flags */ 2388 const char *zVfs /* Name of VFS module to use */ 2389 ){ 2390 return openDatabase(filename, ppDb, (unsigned int)flags, zVfs); 2391 } 2392 2393 #ifndef SQLITE_OMIT_UTF16 2394 /* 2395 ** Open a new database handle. 2396 */ 2397 int sqlite3_open16( 2398 const void *zFilename, 2399 sqlite3 **ppDb 2400 ){ 2401 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */ 2402 sqlite3_value *pVal; 2403 int rc; 2404 2405 assert( zFilename ); 2406 assert( ppDb ); 2407 *ppDb = 0; 2408 #ifndef SQLITE_OMIT_AUTOINIT 2409 rc = sqlite3_initialize(); 2410 if( rc ) return rc; 2411 #endif 2412 pVal = sqlite3ValueNew(0); 2413 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC); 2414 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8); 2415 if( zFilename8 ){ 2416 rc = openDatabase(zFilename8, ppDb, 2417 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); 2418 assert( *ppDb || rc==SQLITE_NOMEM ); 2419 if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){ 2420 ENC(*ppDb) = SQLITE_UTF16NATIVE; 2421 } 2422 }else{ 2423 rc = SQLITE_NOMEM; 2424 } 2425 sqlite3ValueFree(pVal); 2426 2427 return sqlite3ApiExit(0, rc); 2428 } 2429 #endif /* SQLITE_OMIT_UTF16 */ 2430 2431 /* 2432 ** Register a new collation sequence with the database handle db. 2433 */ 2434 int sqlite3_create_collation( 2435 sqlite3* db, 2436 const char *zName, 2437 int enc, 2438 void* pCtx, 2439 int(*xCompare)(void*,int,const void*,int,const void*) 2440 ){ 2441 int rc; 2442 sqlite3_mutex_enter(db->mutex); 2443 assert( !db->mallocFailed ); 2444 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0); 2445 rc = sqlite3ApiExit(db, rc); 2446 sqlite3_mutex_leave(db->mutex); 2447 return rc; 2448 } 2449 2450 /* 2451 ** Register a new collation sequence with the database handle db. 2452 */ 2453 int sqlite3_create_collation_v2( 2454 sqlite3* db, 2455 const char *zName, 2456 int enc, 2457 void* pCtx, 2458 int(*xCompare)(void*,int,const void*,int,const void*), 2459 void(*xDel)(void*) 2460 ){ 2461 int rc; 2462 sqlite3_mutex_enter(db->mutex); 2463 assert( !db->mallocFailed ); 2464 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel); 2465 rc = sqlite3ApiExit(db, rc); 2466 sqlite3_mutex_leave(db->mutex); 2467 return rc; 2468 } 2469 2470 #ifndef SQLITE_OMIT_UTF16 2471 /* 2472 ** Register a new collation sequence with the database handle db. 2473 */ 2474 int sqlite3_create_collation16( 2475 sqlite3* db, 2476 const void *zName, 2477 int enc, 2478 void* pCtx, 2479 int(*xCompare)(void*,int,const void*,int,const void*) 2480 ){ 2481 int rc = SQLITE_OK; 2482 char *zName8; 2483 sqlite3_mutex_enter(db->mutex); 2484 assert( !db->mallocFailed ); 2485 zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE); 2486 if( zName8 ){ 2487 rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0); 2488 sqlite3DbFree(db, zName8); 2489 } 2490 rc = sqlite3ApiExit(db, rc); 2491 sqlite3_mutex_leave(db->mutex); 2492 return rc; 2493 } 2494 #endif /* SQLITE_OMIT_UTF16 */ 2495 2496 /* 2497 ** Register a collation sequence factory callback with the database handle 2498 ** db. Replace any previously installed collation sequence factory. 2499 */ 2500 int sqlite3_collation_needed( 2501 sqlite3 *db, 2502 void *pCollNeededArg, 2503 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*) 2504 ){ 2505 sqlite3_mutex_enter(db->mutex); 2506 db->xCollNeeded = xCollNeeded; 2507 db->xCollNeeded16 = 0; 2508 db->pCollNeededArg = pCollNeededArg; 2509 sqlite3_mutex_leave(db->mutex); 2510 return SQLITE_OK; 2511 } 2512 2513 #ifndef SQLITE_OMIT_UTF16 2514 /* 2515 ** Register a collation sequence factory callback with the database handle 2516 ** db. Replace any previously installed collation sequence factory. 2517 */ 2518 int sqlite3_collation_needed16( 2519 sqlite3 *db, 2520 void *pCollNeededArg, 2521 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*) 2522 ){ 2523 sqlite3_mutex_enter(db->mutex); 2524 db->xCollNeeded = 0; 2525 db->xCollNeeded16 = xCollNeeded16; 2526 db->pCollNeededArg = pCollNeededArg; 2527 sqlite3_mutex_leave(db->mutex); 2528 return SQLITE_OK; 2529 } 2530 #endif /* SQLITE_OMIT_UTF16 */ 2531 2532 #ifndef SQLITE_OMIT_DEPRECATED 2533 /* 2534 ** This function is now an anachronism. It used to be used to recover from a 2535 ** malloc() failure, but SQLite now does this automatically. 2536 */ 2537 int sqlite3_global_recover(void){ 2538 return SQLITE_OK; 2539 } 2540 #endif 2541 2542 /* 2543 ** Test to see whether or not the database connection is in autocommit 2544 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on 2545 ** by default. Autocommit is disabled by a BEGIN statement and reenabled 2546 ** by the next COMMIT or ROLLBACK. 2547 ** 2548 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ****** 2549 */ 2550 int sqlite3_get_autocommit(sqlite3 *db){ 2551 return db->autoCommit; 2552 } 2553 2554 /* 2555 ** The following routines are subtitutes for constants SQLITE_CORRUPT, 2556 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error 2557 ** constants. They server two purposes: 2558 ** 2559 ** 1. Serve as a convenient place to set a breakpoint in a debugger 2560 ** to detect when version error conditions occurs. 2561 ** 2562 ** 2. Invoke sqlite3_log() to provide the source code location where 2563 ** a low-level error is first detected. 2564 */ 2565 int sqlite3CorruptError(int lineno){ 2566 testcase( sqlite3GlobalConfig.xLog!=0 ); 2567 sqlite3_log(SQLITE_CORRUPT, 2568 "database corruption at line %d of [%.10s]", 2569 lineno, 20+sqlite3_sourceid()); 2570 return SQLITE_CORRUPT; 2571 } 2572 int sqlite3MisuseError(int lineno){ 2573 testcase( sqlite3GlobalConfig.xLog!=0 ); 2574 sqlite3_log(SQLITE_MISUSE, 2575 "misuse at line %d of [%.10s]", 2576 lineno, 20+sqlite3_sourceid()); 2577 return SQLITE_MISUSE; 2578 } 2579 int sqlite3CantopenError(int lineno){ 2580 testcase( sqlite3GlobalConfig.xLog!=0 ); 2581 sqlite3_log(SQLITE_CANTOPEN, 2582 "cannot open file at line %d of [%.10s]", 2583 lineno, 20+sqlite3_sourceid()); 2584 return SQLITE_CANTOPEN; 2585 } 2586 2587 2588 #ifndef SQLITE_OMIT_DEPRECATED 2589 /* 2590 ** This is a convenience routine that makes sure that all thread-specific 2591 ** data for this thread has been deallocated. 2592 ** 2593 ** SQLite no longer uses thread-specific data so this routine is now a 2594 ** no-op. It is retained for historical compatibility. 2595 */ 2596 void sqlite3_thread_cleanup(void){ 2597 } 2598 #endif 2599 2600 /* 2601 ** Return meta information about a specific column of a database table. 2602 ** See comment in sqlite3.h (sqlite.h.in) for details. 2603 */ 2604 #ifdef SQLITE_ENABLE_COLUMN_METADATA 2605 int sqlite3_table_column_metadata( 2606 sqlite3 *db, /* Connection handle */ 2607 const char *zDbName, /* Database name or NULL */ 2608 const char *zTableName, /* Table name */ 2609 const char *zColumnName, /* Column name */ 2610 char const **pzDataType, /* OUTPUT: Declared data type */ 2611 char const **pzCollSeq, /* OUTPUT: Collation sequence name */ 2612 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ 2613 int *pPrimaryKey, /* OUTPUT: True if column part of PK */ 2614 int *pAutoinc /* OUTPUT: True if column is auto-increment */ 2615 ){ 2616 int rc; 2617 char *zErrMsg = 0; 2618 Table *pTab = 0; 2619 Column *pCol = 0; 2620 int iCol; 2621 2622 char const *zDataType = 0; 2623 char const *zCollSeq = 0; 2624 int notnull = 0; 2625 int primarykey = 0; 2626 int autoinc = 0; 2627 2628 /* Ensure the database schema has been loaded */ 2629 sqlite3_mutex_enter(db->mutex); 2630 sqlite3BtreeEnterAll(db); 2631 rc = sqlite3Init(db, &zErrMsg); 2632 if( SQLITE_OK!=rc ){ 2633 goto error_out; 2634 } 2635 2636 /* Locate the table in question */ 2637 pTab = sqlite3FindTable(db, zTableName, zDbName); 2638 if( !pTab || pTab->pSelect ){ 2639 pTab = 0; 2640 goto error_out; 2641 } 2642 2643 /* Find the column for which info is requested */ 2644 if( sqlite3IsRowid(zColumnName) ){ 2645 iCol = pTab->iPKey; 2646 if( iCol>=0 ){ 2647 pCol = &pTab->aCol[iCol]; 2648 } 2649 }else{ 2650 for(iCol=0; iCol<pTab->nCol; iCol++){ 2651 pCol = &pTab->aCol[iCol]; 2652 if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){ 2653 break; 2654 } 2655 } 2656 if( iCol==pTab->nCol ){ 2657 pTab = 0; 2658 goto error_out; 2659 } 2660 } 2661 2662 /* The following block stores the meta information that will be returned 2663 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey 2664 ** and autoinc. At this point there are two possibilities: 2665 ** 2666 ** 1. The specified column name was rowid", "oid" or "_rowid_" 2667 ** and there is no explicitly declared IPK column. 2668 ** 2669 ** 2. The table is not a view and the column name identified an 2670 ** explicitly declared column. Copy meta information from *pCol. 2671 */ 2672 if( pCol ){ 2673 zDataType = pCol->zType; 2674 zCollSeq = pCol->zColl; 2675 notnull = pCol->notNull!=0; 2676 primarykey = pCol->isPrimKey!=0; 2677 autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0; 2678 }else{ 2679 zDataType = "INTEGER"; 2680 primarykey = 1; 2681 } 2682 if( !zCollSeq ){ 2683 zCollSeq = "BINARY"; 2684 } 2685 2686 error_out: 2687 sqlite3BtreeLeaveAll(db); 2688 2689 /* Whether the function call succeeded or failed, set the output parameters 2690 ** to whatever their local counterparts contain. If an error did occur, 2691 ** this has the effect of zeroing all output parameters. 2692 */ 2693 if( pzDataType ) *pzDataType = zDataType; 2694 if( pzCollSeq ) *pzCollSeq = zCollSeq; 2695 if( pNotNull ) *pNotNull = notnull; 2696 if( pPrimaryKey ) *pPrimaryKey = primarykey; 2697 if( pAutoinc ) *pAutoinc = autoinc; 2698 2699 if( SQLITE_OK==rc && !pTab ){ 2700 sqlite3DbFree(db, zErrMsg); 2701 zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName, 2702 zColumnName); 2703 rc = SQLITE_ERROR; 2704 } 2705 sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg); 2706 sqlite3DbFree(db, zErrMsg); 2707 rc = sqlite3ApiExit(db, rc); 2708 sqlite3_mutex_leave(db->mutex); 2709 return rc; 2710 } 2711 #endif 2712 2713 /* 2714 ** Sleep for a little while. Return the amount of time slept. 2715 */ 2716 int sqlite3_sleep(int ms){ 2717 sqlite3_vfs *pVfs; 2718 int rc; 2719 pVfs = sqlite3_vfs_find(0); 2720 if( pVfs==0 ) return 0; 2721 2722 /* This function works in milliseconds, but the underlying OsSleep() 2723 ** API uses microseconds. Hence the 1000's. 2724 */ 2725 rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000); 2726 return rc; 2727 } 2728 2729 /* 2730 ** Enable or disable the extended result codes. 2731 */ 2732 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){ 2733 sqlite3_mutex_enter(db->mutex); 2734 db->errMask = onoff ? 0xffffffff : 0xff; 2735 sqlite3_mutex_leave(db->mutex); 2736 return SQLITE_OK; 2737 } 2738 2739 /* 2740 ** Invoke the xFileControl method on a particular database. 2741 */ 2742 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){ 2743 int rc = SQLITE_ERROR; 2744 Btree *pBtree; 2745 2746 sqlite3_mutex_enter(db->mutex); 2747 pBtree = sqlite3DbNameToBtree(db, zDbName); 2748 if( pBtree ){ 2749 Pager *pPager; 2750 sqlite3_file *fd; 2751 sqlite3BtreeEnter(pBtree); 2752 pPager = sqlite3BtreePager(pBtree); 2753 assert( pPager!=0 ); 2754 fd = sqlite3PagerFile(pPager); 2755 assert( fd!=0 ); 2756 if( op==SQLITE_FCNTL_FILE_POINTER ){ 2757 *(sqlite3_file**)pArg = fd; 2758 rc = SQLITE_OK; 2759 }else if( fd->pMethods ){ 2760 rc = sqlite3OsFileControl(fd, op, pArg); 2761 }else{ 2762 rc = SQLITE_NOTFOUND; 2763 } 2764 sqlite3BtreeLeave(pBtree); 2765 } 2766 sqlite3_mutex_leave(db->mutex); 2767 return rc; 2768 } 2769 2770 /* 2771 ** Interface to the testing logic. 2772 */ 2773 int sqlite3_test_control(int op, ...){ 2774 int rc = 0; 2775 #ifndef SQLITE_OMIT_BUILTIN_TEST 2776 va_list ap; 2777 va_start(ap, op); 2778 switch( op ){ 2779 2780 /* 2781 ** Save the current state of the PRNG. 2782 */ 2783 case SQLITE_TESTCTRL_PRNG_SAVE: { 2784 sqlite3PrngSaveState(); 2785 break; 2786 } 2787 2788 /* 2789 ** Restore the state of the PRNG to the last state saved using 2790 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then 2791 ** this verb acts like PRNG_RESET. 2792 */ 2793 case SQLITE_TESTCTRL_PRNG_RESTORE: { 2794 sqlite3PrngRestoreState(); 2795 break; 2796 } 2797 2798 /* 2799 ** Reset the PRNG back to its uninitialized state. The next call 2800 ** to sqlite3_randomness() will reseed the PRNG using a single call 2801 ** to the xRandomness method of the default VFS. 2802 */ 2803 case SQLITE_TESTCTRL_PRNG_RESET: { 2804 sqlite3PrngResetState(); 2805 break; 2806 } 2807 2808 /* 2809 ** sqlite3_test_control(BITVEC_TEST, size, program) 2810 ** 2811 ** Run a test against a Bitvec object of size. The program argument 2812 ** is an array of integers that defines the test. Return -1 on a 2813 ** memory allocation error, 0 on success, or non-zero for an error. 2814 ** See the sqlite3BitvecBuiltinTest() for additional information. 2815 */ 2816 case SQLITE_TESTCTRL_BITVEC_TEST: { 2817 int sz = va_arg(ap, int); 2818 int *aProg = va_arg(ap, int*); 2819 rc = sqlite3BitvecBuiltinTest(sz, aProg); 2820 break; 2821 } 2822 2823 /* 2824 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd) 2825 ** 2826 ** Register hooks to call to indicate which malloc() failures 2827 ** are benign. 2828 */ 2829 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: { 2830 typedef void (*void_function)(void); 2831 void_function xBenignBegin; 2832 void_function xBenignEnd; 2833 xBenignBegin = va_arg(ap, void_function); 2834 xBenignEnd = va_arg(ap, void_function); 2835 sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd); 2836 break; 2837 } 2838 2839 /* 2840 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X) 2841 ** 2842 ** Set the PENDING byte to the value in the argument, if X>0. 2843 ** Make no changes if X==0. Return the value of the pending byte 2844 ** as it existing before this routine was called. 2845 ** 2846 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in 2847 ** an incompatible database file format. Changing the PENDING byte 2848 ** while any database connection is open results in undefined and 2849 ** dileterious behavior. 2850 */ 2851 case SQLITE_TESTCTRL_PENDING_BYTE: { 2852 rc = PENDING_BYTE; 2853 #ifndef SQLITE_OMIT_WSD 2854 { 2855 unsigned int newVal = va_arg(ap, unsigned int); 2856 if( newVal ) sqlite3PendingByte = newVal; 2857 } 2858 #endif 2859 break; 2860 } 2861 2862 /* 2863 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X) 2864 ** 2865 ** This action provides a run-time test to see whether or not 2866 ** assert() was enabled at compile-time. If X is true and assert() 2867 ** is enabled, then the return value is true. If X is true and 2868 ** assert() is disabled, then the return value is zero. If X is 2869 ** false and assert() is enabled, then the assertion fires and the 2870 ** process aborts. If X is false and assert() is disabled, then the 2871 ** return value is zero. 2872 */ 2873 case SQLITE_TESTCTRL_ASSERT: { 2874 volatile int x = 0; 2875 assert( (x = va_arg(ap,int))!=0 ); 2876 rc = x; 2877 break; 2878 } 2879 2880 2881 /* 2882 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X) 2883 ** 2884 ** This action provides a run-time test to see how the ALWAYS and 2885 ** NEVER macros were defined at compile-time. 2886 ** 2887 ** The return value is ALWAYS(X). 2888 ** 2889 ** The recommended test is X==2. If the return value is 2, that means 2890 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the 2891 ** default setting. If the return value is 1, then ALWAYS() is either 2892 ** hard-coded to true or else it asserts if its argument is false. 2893 ** The first behavior (hard-coded to true) is the case if 2894 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second 2895 ** behavior (assert if the argument to ALWAYS() is false) is the case if 2896 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled. 2897 ** 2898 ** The run-time test procedure might look something like this: 2899 ** 2900 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){ 2901 ** // ALWAYS() and NEVER() are no-op pass-through macros 2902 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){ 2903 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false. 2904 ** }else{ 2905 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0. 2906 ** } 2907 */ 2908 case SQLITE_TESTCTRL_ALWAYS: { 2909 int x = va_arg(ap,int); 2910 rc = ALWAYS(x); 2911 break; 2912 } 2913 2914 /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N) 2915 ** 2916 ** Set the nReserve size to N for the main database on the database 2917 ** connection db. 2918 */ 2919 case SQLITE_TESTCTRL_RESERVE: { 2920 sqlite3 *db = va_arg(ap, sqlite3*); 2921 int x = va_arg(ap,int); 2922 sqlite3_mutex_enter(db->mutex); 2923 sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0); 2924 sqlite3_mutex_leave(db->mutex); 2925 break; 2926 } 2927 2928 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N) 2929 ** 2930 ** Enable or disable various optimizations for testing purposes. The 2931 ** argument N is a bitmask of optimizations to be disabled. For normal 2932 ** operation N should be 0. The idea is that a test program (like the 2933 ** SQL Logic Test or SLT test module) can run the same SQL multiple times 2934 ** with various optimizations disabled to verify that the same answer 2935 ** is obtained in every case. 2936 */ 2937 case SQLITE_TESTCTRL_OPTIMIZATIONS: { 2938 sqlite3 *db = va_arg(ap, sqlite3*); 2939 int x = va_arg(ap,int); 2940 db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask); 2941 break; 2942 } 2943 2944 #ifdef SQLITE_N_KEYWORD 2945 /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord) 2946 ** 2947 ** If zWord is a keyword recognized by the parser, then return the 2948 ** number of keywords. Or if zWord is not a keyword, return 0. 2949 ** 2950 ** This test feature is only available in the amalgamation since 2951 ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite 2952 ** is built using separate source files. 2953 */ 2954 case SQLITE_TESTCTRL_ISKEYWORD: { 2955 const char *zWord = va_arg(ap, const char*); 2956 int n = sqlite3Strlen30(zWord); 2957 rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0; 2958 break; 2959 } 2960 #endif 2961 2962 /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree); 2963 ** 2964 ** Pass pFree into sqlite3ScratchFree(). 2965 ** If sz>0 then allocate a scratch buffer into pNew. 2966 */ 2967 case SQLITE_TESTCTRL_SCRATCHMALLOC: { 2968 void *pFree, **ppNew; 2969 int sz; 2970 sz = va_arg(ap, int); 2971 ppNew = va_arg(ap, void**); 2972 pFree = va_arg(ap, void*); 2973 if( sz ) *ppNew = sqlite3ScratchMalloc(sz); 2974 sqlite3ScratchFree(pFree); 2975 break; 2976 } 2977 2978 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff); 2979 ** 2980 ** If parameter onoff is non-zero, configure the wrappers so that all 2981 ** subsequent calls to localtime() and variants fail. If onoff is zero, 2982 ** undo this setting. 2983 */ 2984 case SQLITE_TESTCTRL_LOCALTIME_FAULT: { 2985 sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int); 2986 break; 2987 } 2988 2989 #if defined(SQLITE_ENABLE_TREE_EXPLAIN) 2990 /* sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT, 2991 ** sqlite3_stmt*,const char**); 2992 ** 2993 ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds 2994 ** a string that describes the optimized parse tree. This test-control 2995 ** returns a pointer to that string. 2996 */ 2997 case SQLITE_TESTCTRL_EXPLAIN_STMT: { 2998 sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*); 2999 const char **pzRet = va_arg(ap, const char**); 3000 *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt); 3001 break; 3002 } 3003 #endif 3004 3005 } 3006 va_end(ap); 3007 #endif /* SQLITE_OMIT_BUILTIN_TEST */ 3008 return rc; 3009 } 3010 3011 /* 3012 ** This is a utility routine, useful to VFS implementations, that checks 3013 ** to see if a database file was a URI that contained a specific query 3014 ** parameter, and if so obtains the value of the query parameter. 3015 ** 3016 ** The zFilename argument is the filename pointer passed into the xOpen() 3017 ** method of a VFS implementation. The zParam argument is the name of the 3018 ** query parameter we seek. This routine returns the value of the zParam 3019 ** parameter if it exists. If the parameter does not exist, this routine 3020 ** returns a NULL pointer. 3021 */ 3022 const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){ 3023 if( zFilename==0 ) return 0; 3024 zFilename += sqlite3Strlen30(zFilename) + 1; 3025 while( zFilename[0] ){ 3026 int x = strcmp(zFilename, zParam); 3027 zFilename += sqlite3Strlen30(zFilename) + 1; 3028 if( x==0 ) return zFilename; 3029 zFilename += sqlite3Strlen30(zFilename) + 1; 3030 } 3031 return 0; 3032 } 3033 3034 /* 3035 ** Return a boolean value for a query parameter. 3036 */ 3037 int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){ 3038 const char *z = sqlite3_uri_parameter(zFilename, zParam); 3039 bDflt = bDflt!=0; 3040 return z ? sqlite3GetBoolean(z, bDflt) : bDflt; 3041 } 3042 3043 /* 3044 ** Return a 64-bit integer value for a query parameter. 3045 */ 3046 sqlite3_int64 sqlite3_uri_int64( 3047 const char *zFilename, /* Filename as passed to xOpen */ 3048 const char *zParam, /* URI parameter sought */ 3049 sqlite3_int64 bDflt /* return if parameter is missing */ 3050 ){ 3051 const char *z = sqlite3_uri_parameter(zFilename, zParam); 3052 sqlite3_int64 v; 3053 if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){ 3054 bDflt = v; 3055 } 3056 return bDflt; 3057 } 3058 3059 /* 3060 ** Return the Btree pointer identified by zDbName. Return NULL if not found. 3061 */ 3062 Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){ 3063 int i; 3064 for(i=0; i<db->nDb; i++){ 3065 if( db->aDb[i].pBt 3066 && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0) 3067 ){ 3068 return db->aDb[i].pBt; 3069 } 3070 } 3071 return 0; 3072 } 3073 3074 /* 3075 ** Return the filename of the database associated with a database 3076 ** connection. 3077 */ 3078 const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){ 3079 Btree *pBt = sqlite3DbNameToBtree(db, zDbName); 3080 return pBt ? sqlite3BtreeGetFilename(pBt) : 0; 3081 } 3082 3083 /* 3084 ** Return 1 if database is read-only or 0 if read/write. Return -1 if 3085 ** no such database exists. 3086 */ 3087 int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){ 3088 Btree *pBt = sqlite3DbNameToBtree(db, zDbName); 3089 return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1; 3090 } 3091