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