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; 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 SQLITE_THREADSAFE 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 default: { 383 rc = SQLITE_ERROR; 384 break; 385 } 386 } 387 va_end(ap); 388 return rc; 389 } 390 391 /* 392 ** Set up the lookaside buffers for a database connection. 393 ** Return SQLITE_OK on success. 394 ** If lookaside is already active, return SQLITE_BUSY. 395 ** 396 ** The sz parameter is the number of bytes in each lookaside slot. 397 ** The cnt parameter is the number of slots. If pStart is NULL the 398 ** space for the lookaside memory is obtained from sqlite3_malloc(). 399 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for 400 ** the lookaside memory. 401 */ 402 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){ 403 void *pStart; 404 if( db->lookaside.nOut ){ 405 return SQLITE_BUSY; 406 } 407 /* Free any existing lookaside buffer for this handle before 408 ** allocating a new one so we don't have to have space for 409 ** both at the same time. 410 */ 411 if( db->lookaside.bMalloced ){ 412 sqlite3_free(db->lookaside.pStart); 413 } 414 /* The size of a lookaside slot needs to be larger than a pointer 415 ** to be useful. 416 */ 417 if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0; 418 if( cnt<0 ) cnt = 0; 419 if( sz==0 || cnt==0 ){ 420 sz = 0; 421 pStart = 0; 422 }else if( pBuf==0 ){ 423 sz = ROUND8(sz); 424 sqlite3BeginBenignMalloc(); 425 pStart = sqlite3Malloc( sz*cnt ); 426 sqlite3EndBenignMalloc(); 427 }else{ 428 sz = ROUNDDOWN8(sz); 429 pStart = pBuf; 430 } 431 db->lookaside.pStart = pStart; 432 db->lookaside.pFree = 0; 433 db->lookaside.sz = (u16)sz; 434 if( pStart ){ 435 int i; 436 LookasideSlot *p; 437 assert( sz > (int)sizeof(LookasideSlot*) ); 438 p = (LookasideSlot*)pStart; 439 for(i=cnt-1; i>=0; i--){ 440 p->pNext = db->lookaside.pFree; 441 db->lookaside.pFree = p; 442 p = (LookasideSlot*)&((u8*)p)[sz]; 443 } 444 db->lookaside.pEnd = p; 445 db->lookaside.bEnabled = 1; 446 db->lookaside.bMalloced = pBuf==0 ?1:0; 447 }else{ 448 db->lookaside.pEnd = 0; 449 db->lookaside.bEnabled = 0; 450 db->lookaside.bMalloced = 0; 451 } 452 return SQLITE_OK; 453 } 454 455 /* 456 ** Return the mutex associated with a database connection. 457 */ 458 sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){ 459 return db->mutex; 460 } 461 462 /* 463 ** Configuration settings for an individual database connection 464 */ 465 int sqlite3_db_config(sqlite3 *db, int op, ...){ 466 va_list ap; 467 int rc; 468 va_start(ap, op); 469 switch( op ){ 470 case SQLITE_DBCONFIG_LOOKASIDE: { 471 void *pBuf = va_arg(ap, void*); 472 int sz = va_arg(ap, int); 473 int cnt = va_arg(ap, int); 474 rc = setupLookaside(db, pBuf, sz, cnt); 475 break; 476 } 477 default: { 478 rc = SQLITE_ERROR; 479 break; 480 } 481 } 482 va_end(ap); 483 return rc; 484 } 485 486 487 /* 488 ** Return true if the buffer z[0..n-1] contains all spaces. 489 */ 490 static int allSpaces(const char *z, int n){ 491 while( n>0 && z[n-1]==' ' ){ n--; } 492 return n==0; 493 } 494 495 /* 496 ** This is the default collating function named "BINARY" which is always 497 ** available. 498 ** 499 ** If the padFlag argument is not NULL then space padding at the end 500 ** of strings is ignored. This implements the RTRIM collation. 501 */ 502 static int binCollFunc( 503 void *padFlag, 504 int nKey1, const void *pKey1, 505 int nKey2, const void *pKey2 506 ){ 507 int rc, n; 508 n = nKey1<nKey2 ? nKey1 : nKey2; 509 rc = memcmp(pKey1, pKey2, n); 510 if( rc==0 ){ 511 if( padFlag 512 && allSpaces(((char*)pKey1)+n, nKey1-n) 513 && allSpaces(((char*)pKey2)+n, nKey2-n) 514 ){ 515 /* Leave rc unchanged at 0 */ 516 }else{ 517 rc = nKey1 - nKey2; 518 } 519 } 520 return rc; 521 } 522 523 /* 524 ** Another built-in collating sequence: NOCASE. 525 ** 526 ** This collating sequence is intended to be used for "case independant 527 ** comparison". SQLite's knowledge of upper and lower case equivalents 528 ** extends only to the 26 characters used in the English language. 529 ** 530 ** At the moment there is only a UTF-8 implementation. 531 */ 532 static int nocaseCollatingFunc( 533 void *NotUsed, 534 int nKey1, const void *pKey1, 535 int nKey2, const void *pKey2 536 ){ 537 int r = sqlite3StrNICmp( 538 (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2); 539 UNUSED_PARAMETER(NotUsed); 540 if( 0==r ){ 541 r = nKey1-nKey2; 542 } 543 return r; 544 } 545 546 /* 547 ** Return the ROWID of the most recent insert 548 */ 549 sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){ 550 return db->lastRowid; 551 } 552 553 /* 554 ** Return the number of changes in the most recent call to sqlite3_exec(). 555 */ 556 int sqlite3_changes(sqlite3 *db){ 557 return db->nChange; 558 } 559 560 /* 561 ** Return the number of changes since the database handle was opened. 562 */ 563 int sqlite3_total_changes(sqlite3 *db){ 564 return db->nTotalChange; 565 } 566 567 /* 568 ** Close all open savepoints. This function only manipulates fields of the 569 ** database handle object, it does not close any savepoints that may be open 570 ** at the b-tree/pager level. 571 */ 572 void sqlite3CloseSavepoints(sqlite3 *db){ 573 while( db->pSavepoint ){ 574 Savepoint *pTmp = db->pSavepoint; 575 db->pSavepoint = pTmp->pNext; 576 sqlite3DbFree(db, pTmp); 577 } 578 db->nSavepoint = 0; 579 db->nStatement = 0; 580 db->isTransactionSavepoint = 0; 581 } 582 583 /* 584 ** Close an existing SQLite database 585 */ 586 int sqlite3_close(sqlite3 *db){ 587 HashElem *i; 588 int j; 589 590 if( !db ){ 591 return SQLITE_OK; 592 } 593 if( !sqlite3SafetyCheckSickOrOk(db) ){ 594 return SQLITE_MISUSE; 595 } 596 sqlite3_mutex_enter(db->mutex); 597 598 sqlite3ResetInternalSchema(db, 0); 599 600 /* If a transaction is open, the ResetInternalSchema() call above 601 ** will not have called the xDisconnect() method on any virtual 602 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback() 603 ** call will do so. We need to do this before the check for active 604 ** SQL statements below, as the v-table implementation may be storing 605 ** some prepared statements internally. 606 */ 607 sqlite3VtabRollback(db); 608 609 /* If there are any outstanding VMs, return SQLITE_BUSY. */ 610 if( db->pVdbe ){ 611 sqlite3Error(db, SQLITE_BUSY, 612 "unable to close due to unfinalised statements"); 613 sqlite3_mutex_leave(db->mutex); 614 return SQLITE_BUSY; 615 } 616 assert( sqlite3SafetyCheckSickOrOk(db) ); 617 618 for(j=0; j<db->nDb; j++){ 619 Btree *pBt = db->aDb[j].pBt; 620 if( pBt && sqlite3BtreeIsInBackup(pBt) ){ 621 sqlite3Error(db, SQLITE_BUSY, 622 "unable to close due to unfinished backup operation"); 623 sqlite3_mutex_leave(db->mutex); 624 return SQLITE_BUSY; 625 } 626 } 627 628 /* Free any outstanding Savepoint structures. */ 629 sqlite3CloseSavepoints(db); 630 631 for(j=0; j<db->nDb; j++){ 632 struct Db *pDb = &db->aDb[j]; 633 if( pDb->pBt ){ 634 sqlite3BtreeClose(pDb->pBt); 635 pDb->pBt = 0; 636 if( j!=1 ){ 637 pDb->pSchema = 0; 638 } 639 } 640 } 641 sqlite3ResetInternalSchema(db, 0); 642 643 /* Tell the code in notify.c that the connection no longer holds any 644 ** locks and does not require any further unlock-notify callbacks. 645 */ 646 sqlite3ConnectionClosed(db); 647 648 assert( db->nDb<=2 ); 649 assert( db->aDb==db->aDbStatic ); 650 for(j=0; j<ArraySize(db->aFunc.a); j++){ 651 FuncDef *pNext, *pHash, *p; 652 for(p=db->aFunc.a[j]; p; p=pHash){ 653 pHash = p->pHash; 654 while( p ){ 655 pNext = p->pNext; 656 sqlite3DbFree(db, p); 657 p = pNext; 658 } 659 } 660 } 661 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){ 662 CollSeq *pColl = (CollSeq *)sqliteHashData(i); 663 /* Invoke any destructors registered for collation sequence user data. */ 664 for(j=0; j<3; j++){ 665 if( pColl[j].xDel ){ 666 pColl[j].xDel(pColl[j].pUser); 667 } 668 } 669 sqlite3DbFree(db, pColl); 670 } 671 sqlite3HashClear(&db->aCollSeq); 672 #ifndef SQLITE_OMIT_VIRTUALTABLE 673 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){ 674 Module *pMod = (Module *)sqliteHashData(i); 675 if( pMod->xDestroy ){ 676 pMod->xDestroy(pMod->pAux); 677 } 678 sqlite3DbFree(db, pMod); 679 } 680 sqlite3HashClear(&db->aModule); 681 #endif 682 683 sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */ 684 if( db->pErr ){ 685 sqlite3ValueFree(db->pErr); 686 } 687 sqlite3CloseExtensions(db); 688 689 db->magic = SQLITE_MAGIC_ERROR; 690 691 /* The temp-database schema is allocated differently from the other schema 692 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()). 693 ** So it needs to be freed here. Todo: Why not roll the temp schema into 694 ** the same sqliteMalloc() as the one that allocates the database 695 ** structure? 696 */ 697 sqlite3DbFree(db, db->aDb[1].pSchema); 698 sqlite3_mutex_leave(db->mutex); 699 db->magic = SQLITE_MAGIC_CLOSED; 700 sqlite3_mutex_free(db->mutex); 701 assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */ 702 if( db->lookaside.bMalloced ){ 703 sqlite3_free(db->lookaside.pStart); 704 } 705 sqlite3_free(db); 706 return SQLITE_OK; 707 } 708 709 /* 710 ** Rollback all database files. 711 */ 712 void sqlite3RollbackAll(sqlite3 *db){ 713 int i; 714 int inTrans = 0; 715 assert( sqlite3_mutex_held(db->mutex) ); 716 sqlite3BeginBenignMalloc(); 717 for(i=0; i<db->nDb; i++){ 718 if( db->aDb[i].pBt ){ 719 if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){ 720 inTrans = 1; 721 } 722 sqlite3BtreeRollback(db->aDb[i].pBt); 723 db->aDb[i].inTrans = 0; 724 } 725 } 726 sqlite3VtabRollback(db); 727 sqlite3EndBenignMalloc(); 728 729 if( db->flags&SQLITE_InternChanges ){ 730 sqlite3ExpirePreparedStatements(db); 731 sqlite3ResetInternalSchema(db, 0); 732 } 733 734 /* If one has been configured, invoke the rollback-hook callback */ 735 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){ 736 db->xRollbackCallback(db->pRollbackArg); 737 } 738 } 739 740 /* 741 ** Return a static string that describes the kind of error specified in the 742 ** argument. 743 */ 744 const char *sqlite3ErrStr(int rc){ 745 static const char* const aMsg[] = { 746 /* SQLITE_OK */ "not an error", 747 /* SQLITE_ERROR */ "SQL logic error or missing database", 748 /* SQLITE_INTERNAL */ 0, 749 /* SQLITE_PERM */ "access permission denied", 750 /* SQLITE_ABORT */ "callback requested query abort", 751 /* SQLITE_BUSY */ "database is locked", 752 /* SQLITE_LOCKED */ "database table is locked", 753 /* SQLITE_NOMEM */ "out of memory", 754 /* SQLITE_READONLY */ "attempt to write a readonly database", 755 /* SQLITE_INTERRUPT */ "interrupted", 756 /* SQLITE_IOERR */ "disk I/O error", 757 /* SQLITE_CORRUPT */ "database disk image is malformed", 758 /* SQLITE_NOTFOUND */ 0, 759 /* SQLITE_FULL */ "database or disk is full", 760 /* SQLITE_CANTOPEN */ "unable to open database file", 761 /* SQLITE_PROTOCOL */ 0, 762 /* SQLITE_EMPTY */ "table contains no data", 763 /* SQLITE_SCHEMA */ "database schema has changed", 764 /* SQLITE_TOOBIG */ "string or blob too big", 765 /* SQLITE_CONSTRAINT */ "constraint failed", 766 /* SQLITE_MISMATCH */ "datatype mismatch", 767 /* SQLITE_MISUSE */ "library routine called out of sequence", 768 /* SQLITE_NOLFS */ "large file support is disabled", 769 /* SQLITE_AUTH */ "authorization denied", 770 /* SQLITE_FORMAT */ "auxiliary database format error", 771 /* SQLITE_RANGE */ "bind or column index out of range", 772 /* SQLITE_NOTADB */ "file is encrypted or is not a database", 773 }; 774 rc &= 0xff; 775 if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){ 776 return aMsg[rc]; 777 }else{ 778 return "unknown error"; 779 } 780 } 781 782 /* 783 ** This routine implements a busy callback that sleeps and tries 784 ** again until a timeout value is reached. The timeout value is 785 ** an integer number of milliseconds passed in as the first 786 ** argument. 787 */ 788 static int sqliteDefaultBusyCallback( 789 void *ptr, /* Database connection */ 790 int count /* Number of times table has been busy */ 791 ){ 792 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP) 793 static const u8 delays[] = 794 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 }; 795 static const u8 totals[] = 796 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 }; 797 # define NDELAY (sizeof(delays)/sizeof(delays[0])) 798 sqlite3 *db = (sqlite3 *)ptr; 799 int timeout = db->busyTimeout; 800 int delay, prior; 801 802 assert( count>=0 ); 803 if( count < NDELAY ){ 804 delay = delays[count]; 805 prior = totals[count]; 806 }else{ 807 delay = delays[NDELAY-1]; 808 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1)); 809 } 810 if( prior + delay > timeout ){ 811 delay = timeout - prior; 812 if( delay<=0 ) return 0; 813 } 814 sqlite3OsSleep(db->pVfs, delay*1000); 815 return 1; 816 #else 817 sqlite3 *db = (sqlite3 *)ptr; 818 int timeout = ((sqlite3 *)ptr)->busyTimeout; 819 if( (count+1)*1000 > timeout ){ 820 return 0; 821 } 822 sqlite3OsSleep(db->pVfs, 1000000); 823 return 1; 824 #endif 825 } 826 827 /* 828 ** Invoke the given busy handler. 829 ** 830 ** This routine is called when an operation failed with a lock. 831 ** If this routine returns non-zero, the lock is retried. If it 832 ** returns 0, the operation aborts with an SQLITE_BUSY error. 833 */ 834 int sqlite3InvokeBusyHandler(BusyHandler *p){ 835 int rc; 836 if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0; 837 rc = p->xFunc(p->pArg, p->nBusy); 838 if( rc==0 ){ 839 p->nBusy = -1; 840 }else{ 841 p->nBusy++; 842 } 843 return rc; 844 } 845 846 /* 847 ** This routine sets the busy callback for an Sqlite database to the 848 ** given callback function with the given argument. 849 */ 850 int sqlite3_busy_handler( 851 sqlite3 *db, 852 int (*xBusy)(void*,int), 853 void *pArg 854 ){ 855 sqlite3_mutex_enter(db->mutex); 856 db->busyHandler.xFunc = xBusy; 857 db->busyHandler.pArg = pArg; 858 db->busyHandler.nBusy = 0; 859 sqlite3_mutex_leave(db->mutex); 860 return SQLITE_OK; 861 } 862 863 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 864 /* 865 ** This routine sets the progress callback for an Sqlite database to the 866 ** given callback function with the given argument. The progress callback will 867 ** be invoked every nOps opcodes. 868 */ 869 void sqlite3_progress_handler( 870 sqlite3 *db, 871 int nOps, 872 int (*xProgress)(void*), 873 void *pArg 874 ){ 875 sqlite3_mutex_enter(db->mutex); 876 if( nOps>0 ){ 877 db->xProgress = xProgress; 878 db->nProgressOps = nOps; 879 db->pProgressArg = pArg; 880 }else{ 881 db->xProgress = 0; 882 db->nProgressOps = 0; 883 db->pProgressArg = 0; 884 } 885 sqlite3_mutex_leave(db->mutex); 886 } 887 #endif 888 889 890 /* 891 ** This routine installs a default busy handler that waits for the 892 ** specified number of milliseconds before returning 0. 893 */ 894 int sqlite3_busy_timeout(sqlite3 *db, int ms){ 895 if( ms>0 ){ 896 db->busyTimeout = ms; 897 sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db); 898 }else{ 899 sqlite3_busy_handler(db, 0, 0); 900 } 901 return SQLITE_OK; 902 } 903 904 /* 905 ** Cause any pending operation to stop at its earliest opportunity. 906 */ 907 void sqlite3_interrupt(sqlite3 *db){ 908 db->u1.isInterrupted = 1; 909 } 910 911 912 /* 913 ** This function is exactly the same as sqlite3_create_function(), except 914 ** that it is designed to be called by internal code. The difference is 915 ** that if a malloc() fails in sqlite3_create_function(), an error code 916 ** is returned and the mallocFailed flag cleared. 917 */ 918 int sqlite3CreateFunc( 919 sqlite3 *db, 920 const char *zFunctionName, 921 int nArg, 922 int enc, 923 void *pUserData, 924 void (*xFunc)(sqlite3_context*,int,sqlite3_value **), 925 void (*xStep)(sqlite3_context*,int,sqlite3_value **), 926 void (*xFinal)(sqlite3_context*) 927 ){ 928 FuncDef *p; 929 int nName; 930 931 assert( sqlite3_mutex_held(db->mutex) ); 932 if( zFunctionName==0 || 933 (xFunc && (xFinal || xStep)) || 934 (!xFunc && (xFinal && !xStep)) || 935 (!xFunc && (!xFinal && xStep)) || 936 (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) || 937 (255<(nName = sqlite3Strlen30( zFunctionName))) ){ 938 return SQLITE_MISUSE; 939 } 940 941 #ifndef SQLITE_OMIT_UTF16 942 /* If SQLITE_UTF16 is specified as the encoding type, transform this 943 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the 944 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. 945 ** 946 ** If SQLITE_ANY is specified, add three versions of the function 947 ** to the hash table. 948 */ 949 if( enc==SQLITE_UTF16 ){ 950 enc = SQLITE_UTF16NATIVE; 951 }else if( enc==SQLITE_ANY ){ 952 int rc; 953 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8, 954 pUserData, xFunc, xStep, xFinal); 955 if( rc==SQLITE_OK ){ 956 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE, 957 pUserData, xFunc, xStep, xFinal); 958 } 959 if( rc!=SQLITE_OK ){ 960 return rc; 961 } 962 enc = SQLITE_UTF16BE; 963 } 964 #else 965 enc = SQLITE_UTF8; 966 #endif 967 968 /* Check if an existing function is being overridden or deleted. If so, 969 ** and there are active VMs, then return SQLITE_BUSY. If a function 970 ** is being overridden/deleted but there are no active VMs, allow the 971 ** operation to continue but invalidate all precompiled statements. 972 */ 973 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0); 974 if( p && p->iPrefEnc==enc && p->nArg==nArg ){ 975 if( db->activeVdbeCnt ){ 976 sqlite3Error(db, SQLITE_BUSY, 977 "unable to delete/modify user-function due to active statements"); 978 assert( !db->mallocFailed ); 979 return SQLITE_BUSY; 980 }else{ 981 sqlite3ExpirePreparedStatements(db); 982 } 983 } 984 985 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1); 986 assert(p || db->mallocFailed); 987 if( !p ){ 988 return SQLITE_NOMEM; 989 } 990 p->flags = 0; 991 p->xFunc = xFunc; 992 p->xStep = xStep; 993 p->xFinalize = xFinal; 994 p->pUserData = pUserData; 995 p->nArg = (u16)nArg; 996 return SQLITE_OK; 997 } 998 999 /* 1000 ** Create new user functions. 1001 */ 1002 int sqlite3_create_function( 1003 sqlite3 *db, 1004 const char *zFunctionName, 1005 int nArg, 1006 int enc, 1007 void *p, 1008 void (*xFunc)(sqlite3_context*,int,sqlite3_value **), 1009 void (*xStep)(sqlite3_context*,int,sqlite3_value **), 1010 void (*xFinal)(sqlite3_context*) 1011 ){ 1012 int rc; 1013 sqlite3_mutex_enter(db->mutex); 1014 rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal); 1015 rc = sqlite3ApiExit(db, rc); 1016 sqlite3_mutex_leave(db->mutex); 1017 return rc; 1018 } 1019 1020 #ifndef SQLITE_OMIT_UTF16 1021 int sqlite3_create_function16( 1022 sqlite3 *db, 1023 const void *zFunctionName, 1024 int nArg, 1025 int eTextRep, 1026 void *p, 1027 void (*xFunc)(sqlite3_context*,int,sqlite3_value**), 1028 void (*xStep)(sqlite3_context*,int,sqlite3_value**), 1029 void (*xFinal)(sqlite3_context*) 1030 ){ 1031 int rc; 1032 char *zFunc8; 1033 sqlite3_mutex_enter(db->mutex); 1034 assert( !db->mallocFailed ); 1035 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1); 1036 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal); 1037 sqlite3DbFree(db, zFunc8); 1038 rc = sqlite3ApiExit(db, rc); 1039 sqlite3_mutex_leave(db->mutex); 1040 return rc; 1041 } 1042 #endif 1043 1044 1045 /* 1046 ** Declare that a function has been overloaded by a virtual table. 1047 ** 1048 ** If the function already exists as a regular global function, then 1049 ** this routine is a no-op. If the function does not exist, then create 1050 ** a new one that always throws a run-time error. 1051 ** 1052 ** When virtual tables intend to provide an overloaded function, they 1053 ** should call this routine to make sure the global function exists. 1054 ** A global function must exist in order for name resolution to work 1055 ** properly. 1056 */ 1057 int sqlite3_overload_function( 1058 sqlite3 *db, 1059 const char *zName, 1060 int nArg 1061 ){ 1062 int nName = sqlite3Strlen30(zName); 1063 int rc; 1064 sqlite3_mutex_enter(db->mutex); 1065 if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){ 1066 sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8, 1067 0, sqlite3InvalidFunction, 0, 0); 1068 } 1069 rc = sqlite3ApiExit(db, SQLITE_OK); 1070 sqlite3_mutex_leave(db->mutex); 1071 return rc; 1072 } 1073 1074 #ifndef SQLITE_OMIT_TRACE 1075 /* 1076 ** Register a trace function. The pArg from the previously registered trace 1077 ** is returned. 1078 ** 1079 ** A NULL trace function means that no tracing is executes. A non-NULL 1080 ** trace is a pointer to a function that is invoked at the start of each 1081 ** SQL statement. 1082 */ 1083 void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){ 1084 void *pOld; 1085 sqlite3_mutex_enter(db->mutex); 1086 pOld = db->pTraceArg; 1087 db->xTrace = xTrace; 1088 db->pTraceArg = pArg; 1089 sqlite3_mutex_leave(db->mutex); 1090 return pOld; 1091 } 1092 /* 1093 ** Register a profile function. The pArg from the previously registered 1094 ** profile function is returned. 1095 ** 1096 ** A NULL profile function means that no profiling is executes. A non-NULL 1097 ** profile is a pointer to a function that is invoked at the conclusion of 1098 ** each SQL statement that is run. 1099 */ 1100 void *sqlite3_profile( 1101 sqlite3 *db, 1102 void (*xProfile)(void*,const char*,sqlite_uint64), 1103 void *pArg 1104 ){ 1105 void *pOld; 1106 sqlite3_mutex_enter(db->mutex); 1107 pOld = db->pProfileArg; 1108 db->xProfile = xProfile; 1109 db->pProfileArg = pArg; 1110 sqlite3_mutex_leave(db->mutex); 1111 return pOld; 1112 } 1113 #endif /* SQLITE_OMIT_TRACE */ 1114 1115 /*** EXPERIMENTAL *** 1116 ** 1117 ** Register a function to be invoked when a transaction comments. 1118 ** If the invoked function returns non-zero, then the commit becomes a 1119 ** rollback. 1120 */ 1121 void *sqlite3_commit_hook( 1122 sqlite3 *db, /* Attach the hook to this database */ 1123 int (*xCallback)(void*), /* Function to invoke on each commit */ 1124 void *pArg /* Argument to the function */ 1125 ){ 1126 void *pOld; 1127 sqlite3_mutex_enter(db->mutex); 1128 pOld = db->pCommitArg; 1129 db->xCommitCallback = xCallback; 1130 db->pCommitArg = pArg; 1131 sqlite3_mutex_leave(db->mutex); 1132 return pOld; 1133 } 1134 1135 /* 1136 ** Register a callback to be invoked each time a row is updated, 1137 ** inserted or deleted using this database connection. 1138 */ 1139 void *sqlite3_update_hook( 1140 sqlite3 *db, /* Attach the hook to this database */ 1141 void (*xCallback)(void*,int,char const *,char const *,sqlite_int64), 1142 void *pArg /* Argument to the function */ 1143 ){ 1144 void *pRet; 1145 sqlite3_mutex_enter(db->mutex); 1146 pRet = db->pUpdateArg; 1147 db->xUpdateCallback = xCallback; 1148 db->pUpdateArg = pArg; 1149 sqlite3_mutex_leave(db->mutex); 1150 return pRet; 1151 } 1152 1153 /* 1154 ** Register a callback to be invoked each time a transaction is rolled 1155 ** back by this database connection. 1156 */ 1157 void *sqlite3_rollback_hook( 1158 sqlite3 *db, /* Attach the hook to this database */ 1159 void (*xCallback)(void*), /* Callback function */ 1160 void *pArg /* Argument to the function */ 1161 ){ 1162 void *pRet; 1163 sqlite3_mutex_enter(db->mutex); 1164 pRet = db->pRollbackArg; 1165 db->xRollbackCallback = xCallback; 1166 db->pRollbackArg = pArg; 1167 sqlite3_mutex_leave(db->mutex); 1168 return pRet; 1169 } 1170 1171 /* 1172 ** This function returns true if main-memory should be used instead of 1173 ** a temporary file for transient pager files and statement journals. 1174 ** The value returned depends on the value of db->temp_store (runtime 1175 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The 1176 ** following table describes the relationship between these two values 1177 ** and this functions return value. 1178 ** 1179 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database 1180 ** ----------------- -------------- ------------------------------ 1181 ** 0 any file (return 0) 1182 ** 1 1 file (return 0) 1183 ** 1 2 memory (return 1) 1184 ** 1 0 file (return 0) 1185 ** 2 1 file (return 0) 1186 ** 2 2 memory (return 1) 1187 ** 2 0 memory (return 1) 1188 ** 3 any memory (return 1) 1189 */ 1190 int sqlite3TempInMemory(const sqlite3 *db){ 1191 #if SQLITE_TEMP_STORE==1 1192 return ( db->temp_store==2 ); 1193 #endif 1194 #if SQLITE_TEMP_STORE==2 1195 return ( db->temp_store!=1 ); 1196 #endif 1197 #if SQLITE_TEMP_STORE==3 1198 return 1; 1199 #endif 1200 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3 1201 return 0; 1202 #endif 1203 } 1204 1205 /* 1206 ** This routine is called to create a connection to a database BTree 1207 ** driver. If zFilename is the name of a file, then that file is 1208 ** opened and used. If zFilename is the magic name ":memory:" then 1209 ** the database is stored in memory (and is thus forgotten as soon as 1210 ** the connection is closed.) If zFilename is NULL then the database 1211 ** is a "virtual" database for transient use only and is deleted as 1212 ** soon as the connection is closed. 1213 ** 1214 ** A virtual database can be either a disk file (that is automatically 1215 ** deleted when the file is closed) or it an be held entirely in memory. 1216 ** The sqlite3TempInMemory() function is used to determine which. 1217 */ 1218 int sqlite3BtreeFactory( 1219 const sqlite3 *db, /* Main database when opening aux otherwise 0 */ 1220 const char *zFilename, /* Name of the file containing the BTree database */ 1221 int omitJournal, /* if TRUE then do not journal this file */ 1222 int nCache, /* How many pages in the page cache */ 1223 int vfsFlags, /* Flags passed through to vfsOpen */ 1224 Btree **ppBtree /* Pointer to new Btree object written here */ 1225 ){ 1226 int btFlags = 0; 1227 int rc; 1228 1229 assert( sqlite3_mutex_held(db->mutex) ); 1230 assert( ppBtree != 0); 1231 if( omitJournal ){ 1232 btFlags |= BTREE_OMIT_JOURNAL; 1233 } 1234 if( db->flags & SQLITE_NoReadlock ){ 1235 btFlags |= BTREE_NO_READLOCK; 1236 } 1237 #ifndef SQLITE_OMIT_MEMORYDB 1238 if( zFilename==0 && sqlite3TempInMemory(db) ){ 1239 zFilename = ":memory:"; 1240 } 1241 #endif 1242 1243 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){ 1244 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB; 1245 } 1246 rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags); 1247 1248 /* If the B-Tree was successfully opened, set the pager-cache size to the 1249 ** default value. Except, if the call to BtreeOpen() returned a handle 1250 ** open on an existing shared pager-cache, do not change the pager-cache 1251 ** size. 1252 */ 1253 if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){ 1254 sqlite3BtreeSetCacheSize(*ppBtree, nCache); 1255 } 1256 return rc; 1257 } 1258 1259 /* 1260 ** Return UTF-8 encoded English language explanation of the most recent 1261 ** error. 1262 */ 1263 const char *sqlite3_errmsg(sqlite3 *db){ 1264 const char *z; 1265 if( !db ){ 1266 return sqlite3ErrStr(SQLITE_NOMEM); 1267 } 1268 if( !sqlite3SafetyCheckSickOrOk(db) ){ 1269 return sqlite3ErrStr(SQLITE_MISUSE); 1270 } 1271 sqlite3_mutex_enter(db->mutex); 1272 if( db->mallocFailed ){ 1273 z = sqlite3ErrStr(SQLITE_NOMEM); 1274 }else{ 1275 z = (char*)sqlite3_value_text(db->pErr); 1276 assert( !db->mallocFailed ); 1277 if( z==0 ){ 1278 z = sqlite3ErrStr(db->errCode); 1279 } 1280 } 1281 sqlite3_mutex_leave(db->mutex); 1282 return z; 1283 } 1284 1285 #ifndef SQLITE_OMIT_UTF16 1286 /* 1287 ** Return UTF-16 encoded English language explanation of the most recent 1288 ** error. 1289 */ 1290 const void *sqlite3_errmsg16(sqlite3 *db){ 1291 static const u16 outOfMem[] = { 1292 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0 1293 }; 1294 static const u16 misuse[] = { 1295 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 1296 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 1297 'c', 'a', 'l', 'l', 'e', 'd', ' ', 1298 'o', 'u', 't', ' ', 1299 'o', 'f', ' ', 1300 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0 1301 }; 1302 1303 const void *z; 1304 if( !db ){ 1305 return (void *)outOfMem; 1306 } 1307 if( !sqlite3SafetyCheckSickOrOk(db) ){ 1308 return (void *)misuse; 1309 } 1310 sqlite3_mutex_enter(db->mutex); 1311 if( db->mallocFailed ){ 1312 z = (void *)outOfMem; 1313 }else{ 1314 z = sqlite3_value_text16(db->pErr); 1315 if( z==0 ){ 1316 sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode), 1317 SQLITE_UTF8, SQLITE_STATIC); 1318 z = sqlite3_value_text16(db->pErr); 1319 } 1320 /* A malloc() may have failed within the call to sqlite3_value_text16() 1321 ** above. If this is the case, then the db->mallocFailed flag needs to 1322 ** be cleared before returning. Do this directly, instead of via 1323 ** sqlite3ApiExit(), to avoid setting the database handle error message. 1324 */ 1325 db->mallocFailed = 0; 1326 } 1327 sqlite3_mutex_leave(db->mutex); 1328 return z; 1329 } 1330 #endif /* SQLITE_OMIT_UTF16 */ 1331 1332 /* 1333 ** Return the most recent error code generated by an SQLite routine. If NULL is 1334 ** passed to this function, we assume a malloc() failed during sqlite3_open(). 1335 */ 1336 int sqlite3_errcode(sqlite3 *db){ 1337 if( db && !sqlite3SafetyCheckSickOrOk(db) ){ 1338 return SQLITE_MISUSE; 1339 } 1340 if( !db || db->mallocFailed ){ 1341 return SQLITE_NOMEM; 1342 } 1343 return db->errCode & db->errMask; 1344 } 1345 int sqlite3_extended_errcode(sqlite3 *db){ 1346 if( db && !sqlite3SafetyCheckSickOrOk(db) ){ 1347 return SQLITE_MISUSE; 1348 } 1349 if( !db || db->mallocFailed ){ 1350 return SQLITE_NOMEM; 1351 } 1352 return db->errCode; 1353 } 1354 1355 /* 1356 ** Create a new collating function for database "db". The name is zName 1357 ** and the encoding is enc. 1358 */ 1359 static int createCollation( 1360 sqlite3* db, 1361 const char *zName, 1362 int enc, 1363 int collType, 1364 void* pCtx, 1365 int(*xCompare)(void*,int,const void*,int,const void*), 1366 void(*xDel)(void*) 1367 ){ 1368 CollSeq *pColl; 1369 int enc2; 1370 int nName = sqlite3Strlen30(zName); 1371 1372 assert( sqlite3_mutex_held(db->mutex) ); 1373 1374 /* If SQLITE_UTF16 is specified as the encoding type, transform this 1375 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the 1376 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. 1377 */ 1378 enc2 = enc; 1379 testcase( enc2==SQLITE_UTF16 ); 1380 testcase( enc2==SQLITE_UTF16_ALIGNED ); 1381 if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){ 1382 enc2 = SQLITE_UTF16NATIVE; 1383 } 1384 if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){ 1385 return SQLITE_MISUSE; 1386 } 1387 1388 /* Check if this call is removing or replacing an existing collation 1389 ** sequence. If so, and there are active VMs, return busy. If there 1390 ** are no active VMs, invalidate any pre-compiled statements. 1391 */ 1392 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0); 1393 if( pColl && pColl->xCmp ){ 1394 if( db->activeVdbeCnt ){ 1395 sqlite3Error(db, SQLITE_BUSY, 1396 "unable to delete/modify collation sequence due to active statements"); 1397 return SQLITE_BUSY; 1398 } 1399 sqlite3ExpirePreparedStatements(db); 1400 1401 /* If collation sequence pColl was created directly by a call to 1402 ** sqlite3_create_collation, and not generated by synthCollSeq(), 1403 ** then any copies made by synthCollSeq() need to be invalidated. 1404 ** Also, collation destructor - CollSeq.xDel() - function may need 1405 ** to be called. 1406 */ 1407 if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){ 1408 CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName); 1409 int j; 1410 for(j=0; j<3; j++){ 1411 CollSeq *p = &aColl[j]; 1412 if( p->enc==pColl->enc ){ 1413 if( p->xDel ){ 1414 p->xDel(p->pUser); 1415 } 1416 p->xCmp = 0; 1417 } 1418 } 1419 } 1420 } 1421 1422 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1); 1423 if( pColl ){ 1424 pColl->xCmp = xCompare; 1425 pColl->pUser = pCtx; 1426 pColl->xDel = xDel; 1427 pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED)); 1428 pColl->type = collType; 1429 } 1430 sqlite3Error(db, SQLITE_OK, 0); 1431 return SQLITE_OK; 1432 } 1433 1434 1435 /* 1436 ** This array defines hard upper bounds on limit values. The 1437 ** initializer must be kept in sync with the SQLITE_LIMIT_* 1438 ** #defines in sqlite3.h. 1439 */ 1440 static const int aHardLimit[] = { 1441 SQLITE_MAX_LENGTH, 1442 SQLITE_MAX_SQL_LENGTH, 1443 SQLITE_MAX_COLUMN, 1444 SQLITE_MAX_EXPR_DEPTH, 1445 SQLITE_MAX_COMPOUND_SELECT, 1446 SQLITE_MAX_VDBE_OP, 1447 SQLITE_MAX_FUNCTION_ARG, 1448 SQLITE_MAX_ATTACHED, 1449 SQLITE_MAX_LIKE_PATTERN_LENGTH, 1450 SQLITE_MAX_VARIABLE_NUMBER, 1451 }; 1452 1453 /* 1454 ** Make sure the hard limits are set to reasonable values 1455 */ 1456 #if SQLITE_MAX_LENGTH<100 1457 # error SQLITE_MAX_LENGTH must be at least 100 1458 #endif 1459 #if SQLITE_MAX_SQL_LENGTH<100 1460 # error SQLITE_MAX_SQL_LENGTH must be at least 100 1461 #endif 1462 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH 1463 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH 1464 #endif 1465 #if SQLITE_MAX_COMPOUND_SELECT<2 1466 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2 1467 #endif 1468 #if SQLITE_MAX_VDBE_OP<40 1469 # error SQLITE_MAX_VDBE_OP must be at least 40 1470 #endif 1471 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000 1472 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000 1473 #endif 1474 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30 1475 # error SQLITE_MAX_ATTACHED must be between 0 and 30 1476 #endif 1477 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1 1478 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1 1479 #endif 1480 #if SQLITE_MAX_VARIABLE_NUMBER<1 1481 # error SQLITE_MAX_VARIABLE_NUMBER must be at least 1 1482 #endif 1483 #if SQLITE_MAX_COLUMN>32767 1484 # error SQLITE_MAX_COLUMN must not exceed 32767 1485 #endif 1486 1487 1488 /* 1489 ** Change the value of a limit. Report the old value. 1490 ** If an invalid limit index is supplied, report -1. 1491 ** Make no changes but still report the old value if the 1492 ** new limit is negative. 1493 ** 1494 ** A new lower limit does not shrink existing constructs. 1495 ** It merely prevents new constructs that exceed the limit 1496 ** from forming. 1497 */ 1498 int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){ 1499 int oldLimit; 1500 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){ 1501 return -1; 1502 } 1503 oldLimit = db->aLimit[limitId]; 1504 if( newLimit>=0 ){ 1505 if( newLimit>aHardLimit[limitId] ){ 1506 newLimit = aHardLimit[limitId]; 1507 } 1508 db->aLimit[limitId] = newLimit; 1509 } 1510 return oldLimit; 1511 } 1512 1513 /* 1514 ** This routine does the work of opening a database on behalf of 1515 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename" 1516 ** is UTF-8 encoded. 1517 */ 1518 static int openDatabase( 1519 const char *zFilename, /* Database filename UTF-8 encoded */ 1520 sqlite3 **ppDb, /* OUT: Returned database handle */ 1521 unsigned flags, /* Operational flags */ 1522 const char *zVfs /* Name of the VFS to use */ 1523 ){ 1524 sqlite3 *db; 1525 int rc; 1526 int isThreadsafe; 1527 1528 *ppDb = 0; 1529 #ifndef SQLITE_OMIT_AUTOINIT 1530 rc = sqlite3_initialize(); 1531 if( rc ) return rc; 1532 #endif 1533 1534 if( sqlite3GlobalConfig.bCoreMutex==0 ){ 1535 isThreadsafe = 0; 1536 }else if( flags & SQLITE_OPEN_NOMUTEX ){ 1537 isThreadsafe = 0; 1538 }else if( flags & SQLITE_OPEN_FULLMUTEX ){ 1539 isThreadsafe = 1; 1540 }else{ 1541 isThreadsafe = sqlite3GlobalConfig.bFullMutex; 1542 } 1543 1544 /* Remove harmful bits from the flags parameter 1545 ** 1546 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were 1547 ** dealt with in the previous code block. Besides these, the only 1548 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY, 1549 ** SQLITE_OPEN_READWRITE, and SQLITE_OPEN_CREATE. Silently mask 1550 ** off all other flags. 1551 */ 1552 flags &= ~( SQLITE_OPEN_DELETEONCLOSE | 1553 SQLITE_OPEN_EXCLUSIVE | 1554 SQLITE_OPEN_MAIN_DB | 1555 SQLITE_OPEN_TEMP_DB | 1556 SQLITE_OPEN_TRANSIENT_DB | 1557 SQLITE_OPEN_MAIN_JOURNAL | 1558 SQLITE_OPEN_TEMP_JOURNAL | 1559 SQLITE_OPEN_SUBJOURNAL | 1560 SQLITE_OPEN_MASTER_JOURNAL | 1561 SQLITE_OPEN_NOMUTEX | 1562 SQLITE_OPEN_FULLMUTEX 1563 ); 1564 1565 /* Allocate the sqlite data structure */ 1566 db = sqlite3MallocZero( sizeof(sqlite3) ); 1567 if( db==0 ) goto opendb_out; 1568 if( isThreadsafe ){ 1569 db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); 1570 if( db->mutex==0 ){ 1571 sqlite3_free(db); 1572 db = 0; 1573 goto opendb_out; 1574 } 1575 } 1576 sqlite3_mutex_enter(db->mutex); 1577 db->errMask = 0xff; 1578 db->nDb = 2; 1579 db->magic = SQLITE_MAGIC_BUSY; 1580 db->aDb = db->aDbStatic; 1581 1582 assert( sizeof(db->aLimit)==sizeof(aHardLimit) ); 1583 memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit)); 1584 db->autoCommit = 1; 1585 db->nextAutovac = -1; 1586 db->nextPagesize = 0; 1587 db->flags |= SQLITE_ShortColNames 1588 #if SQLITE_DEFAULT_FILE_FORMAT<4 1589 | SQLITE_LegacyFileFmt 1590 #endif 1591 #ifdef SQLITE_ENABLE_LOAD_EXTENSION 1592 | SQLITE_LoadExtension 1593 #endif 1594 ; 1595 sqlite3HashInit(&db->aCollSeq); 1596 #ifndef SQLITE_OMIT_VIRTUALTABLE 1597 sqlite3HashInit(&db->aModule); 1598 #endif 1599 1600 db->pVfs = sqlite3_vfs_find(zVfs); 1601 if( !db->pVfs ){ 1602 rc = SQLITE_ERROR; 1603 sqlite3Error(db, rc, "no such vfs: %s", zVfs); 1604 goto opendb_out; 1605 } 1606 1607 /* Add the default collation sequence BINARY. BINARY works for both UTF-8 1608 ** and UTF-16, so add a version for each to avoid any unnecessary 1609 ** conversions. The only error that can occur here is a malloc() failure. 1610 */ 1611 createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0, 1612 binCollFunc, 0); 1613 createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0, 1614 binCollFunc, 0); 1615 createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0, 1616 binCollFunc, 0); 1617 createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1, 1618 binCollFunc, 0); 1619 if( db->mallocFailed ){ 1620 goto opendb_out; 1621 } 1622 db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0); 1623 assert( db->pDfltColl!=0 ); 1624 1625 /* Also add a UTF-8 case-insensitive collation sequence. */ 1626 createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0, 1627 nocaseCollatingFunc, 0); 1628 1629 /* Open the backend database driver */ 1630 db->openFlags = flags; 1631 rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE, 1632 flags | SQLITE_OPEN_MAIN_DB, 1633 &db->aDb[0].pBt); 1634 if( rc!=SQLITE_OK ){ 1635 if( rc==SQLITE_IOERR_NOMEM ){ 1636 rc = SQLITE_NOMEM; 1637 } 1638 sqlite3Error(db, rc, 0); 1639 goto opendb_out; 1640 } 1641 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt); 1642 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0); 1643 1644 1645 /* The default safety_level for the main database is 'full'; for the temp 1646 ** database it is 'NONE'. This matches the pager layer defaults. 1647 */ 1648 db->aDb[0].zName = "main"; 1649 db->aDb[0].safety_level = 3; 1650 db->aDb[1].zName = "temp"; 1651 db->aDb[1].safety_level = 1; 1652 1653 db->magic = SQLITE_MAGIC_OPEN; 1654 if( db->mallocFailed ){ 1655 goto opendb_out; 1656 } 1657 1658 /* Register all built-in functions, but do not attempt to read the 1659 ** database schema yet. This is delayed until the first time the database 1660 ** is accessed. 1661 */ 1662 sqlite3Error(db, SQLITE_OK, 0); 1663 sqlite3RegisterBuiltinFunctions(db); 1664 1665 /* Load automatic extensions - extensions that have been registered 1666 ** using the sqlite3_automatic_extension() API. 1667 */ 1668 sqlite3AutoLoadExtensions(db); 1669 rc = sqlite3_errcode(db); 1670 if( rc!=SQLITE_OK ){ 1671 goto opendb_out; 1672 } 1673 1674 #ifdef SQLITE_ENABLE_FTS1 1675 if( !db->mallocFailed ){ 1676 extern int sqlite3Fts1Init(sqlite3*); 1677 rc = sqlite3Fts1Init(db); 1678 } 1679 #endif 1680 1681 #ifdef SQLITE_ENABLE_FTS2 1682 if( !db->mallocFailed && rc==SQLITE_OK ){ 1683 extern int sqlite3Fts2Init(sqlite3*); 1684 rc = sqlite3Fts2Init(db); 1685 } 1686 #endif 1687 1688 #ifdef SQLITE_ENABLE_FTS3 1689 if( !db->mallocFailed && rc==SQLITE_OK ){ 1690 rc = sqlite3Fts3Init(db); 1691 } 1692 #endif 1693 1694 #ifdef SQLITE_ENABLE_ICU 1695 if( !db->mallocFailed && rc==SQLITE_OK ){ 1696 rc = sqlite3IcuInit(db); 1697 } 1698 #endif 1699 1700 #ifdef SQLITE_ENABLE_RTREE 1701 if( !db->mallocFailed && rc==SQLITE_OK){ 1702 rc = sqlite3RtreeInit(db); 1703 } 1704 #endif 1705 1706 sqlite3Error(db, rc, 0); 1707 1708 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking 1709 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking 1710 ** mode. Doing nothing at all also makes NORMAL the default. 1711 */ 1712 #ifdef SQLITE_DEFAULT_LOCKING_MODE 1713 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE; 1714 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt), 1715 SQLITE_DEFAULT_LOCKING_MODE); 1716 #endif 1717 1718 /* Enable the lookaside-malloc subsystem */ 1719 setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside, 1720 sqlite3GlobalConfig.nLookaside); 1721 1722 opendb_out: 1723 if( db ){ 1724 assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 ); 1725 sqlite3_mutex_leave(db->mutex); 1726 } 1727 rc = sqlite3_errcode(db); 1728 if( rc==SQLITE_NOMEM ){ 1729 sqlite3_close(db); 1730 db = 0; 1731 }else if( rc!=SQLITE_OK ){ 1732 db->magic = SQLITE_MAGIC_SICK; 1733 } 1734 *ppDb = db; 1735 return sqlite3ApiExit(0, rc); 1736 } 1737 1738 /* 1739 ** Open a new database handle. 1740 */ 1741 int sqlite3_open( 1742 const char *zFilename, 1743 sqlite3 **ppDb 1744 ){ 1745 return openDatabase(zFilename, ppDb, 1746 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); 1747 } 1748 int sqlite3_open_v2( 1749 const char *filename, /* Database filename (UTF-8) */ 1750 sqlite3 **ppDb, /* OUT: SQLite db handle */ 1751 int flags, /* Flags */ 1752 const char *zVfs /* Name of VFS module to use */ 1753 ){ 1754 return openDatabase(filename, ppDb, flags, zVfs); 1755 } 1756 1757 #ifndef SQLITE_OMIT_UTF16 1758 /* 1759 ** Open a new database handle. 1760 */ 1761 int sqlite3_open16( 1762 const void *zFilename, 1763 sqlite3 **ppDb 1764 ){ 1765 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */ 1766 sqlite3_value *pVal; 1767 int rc; 1768 1769 assert( zFilename ); 1770 assert( ppDb ); 1771 *ppDb = 0; 1772 #ifndef SQLITE_OMIT_AUTOINIT 1773 rc = sqlite3_initialize(); 1774 if( rc ) return rc; 1775 #endif 1776 pVal = sqlite3ValueNew(0); 1777 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC); 1778 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8); 1779 if( zFilename8 ){ 1780 rc = openDatabase(zFilename8, ppDb, 1781 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); 1782 assert( *ppDb || rc==SQLITE_NOMEM ); 1783 if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){ 1784 ENC(*ppDb) = SQLITE_UTF16NATIVE; 1785 } 1786 }else{ 1787 rc = SQLITE_NOMEM; 1788 } 1789 sqlite3ValueFree(pVal); 1790 1791 return sqlite3ApiExit(0, rc); 1792 } 1793 #endif /* SQLITE_OMIT_UTF16 */ 1794 1795 /* 1796 ** Register a new collation sequence with the database handle db. 1797 */ 1798 int sqlite3_create_collation( 1799 sqlite3* db, 1800 const char *zName, 1801 int enc, 1802 void* pCtx, 1803 int(*xCompare)(void*,int,const void*,int,const void*) 1804 ){ 1805 int rc; 1806 sqlite3_mutex_enter(db->mutex); 1807 assert( !db->mallocFailed ); 1808 rc = createCollation(db, zName, enc, SQLITE_COLL_USER, pCtx, xCompare, 0); 1809 rc = sqlite3ApiExit(db, rc); 1810 sqlite3_mutex_leave(db->mutex); 1811 return rc; 1812 } 1813 1814 /* 1815 ** Register a new collation sequence with the database handle db. 1816 */ 1817 int sqlite3_create_collation_v2( 1818 sqlite3* db, 1819 const char *zName, 1820 int enc, 1821 void* pCtx, 1822 int(*xCompare)(void*,int,const void*,int,const void*), 1823 void(*xDel)(void*) 1824 ){ 1825 int rc; 1826 sqlite3_mutex_enter(db->mutex); 1827 assert( !db->mallocFailed ); 1828 rc = createCollation(db, zName, enc, SQLITE_COLL_USER, pCtx, xCompare, xDel); 1829 rc = sqlite3ApiExit(db, rc); 1830 sqlite3_mutex_leave(db->mutex); 1831 return rc; 1832 } 1833 1834 #ifndef SQLITE_OMIT_UTF16 1835 /* 1836 ** Register a new collation sequence with the database handle db. 1837 */ 1838 int sqlite3_create_collation16( 1839 sqlite3* db, 1840 const void *zName, 1841 int enc, 1842 void* pCtx, 1843 int(*xCompare)(void*,int,const void*,int,const void*) 1844 ){ 1845 int rc = SQLITE_OK; 1846 char *zName8; 1847 sqlite3_mutex_enter(db->mutex); 1848 assert( !db->mallocFailed ); 1849 zName8 = sqlite3Utf16to8(db, zName, -1); 1850 if( zName8 ){ 1851 rc = createCollation(db, zName8, enc, SQLITE_COLL_USER, pCtx, xCompare, 0); 1852 sqlite3DbFree(db, zName8); 1853 } 1854 rc = sqlite3ApiExit(db, rc); 1855 sqlite3_mutex_leave(db->mutex); 1856 return rc; 1857 } 1858 #endif /* SQLITE_OMIT_UTF16 */ 1859 1860 /* 1861 ** Register a collation sequence factory callback with the database handle 1862 ** db. Replace any previously installed collation sequence factory. 1863 */ 1864 int sqlite3_collation_needed( 1865 sqlite3 *db, 1866 void *pCollNeededArg, 1867 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*) 1868 ){ 1869 sqlite3_mutex_enter(db->mutex); 1870 db->xCollNeeded = xCollNeeded; 1871 db->xCollNeeded16 = 0; 1872 db->pCollNeededArg = pCollNeededArg; 1873 sqlite3_mutex_leave(db->mutex); 1874 return SQLITE_OK; 1875 } 1876 1877 #ifndef SQLITE_OMIT_UTF16 1878 /* 1879 ** Register a collation sequence factory callback with the database handle 1880 ** db. Replace any previously installed collation sequence factory. 1881 */ 1882 int sqlite3_collation_needed16( 1883 sqlite3 *db, 1884 void *pCollNeededArg, 1885 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*) 1886 ){ 1887 sqlite3_mutex_enter(db->mutex); 1888 db->xCollNeeded = 0; 1889 db->xCollNeeded16 = xCollNeeded16; 1890 db->pCollNeededArg = pCollNeededArg; 1891 sqlite3_mutex_leave(db->mutex); 1892 return SQLITE_OK; 1893 } 1894 #endif /* SQLITE_OMIT_UTF16 */ 1895 1896 #ifndef SQLITE_OMIT_GLOBALRECOVER 1897 #ifndef SQLITE_OMIT_DEPRECATED 1898 /* 1899 ** This function is now an anachronism. It used to be used to recover from a 1900 ** malloc() failure, but SQLite now does this automatically. 1901 */ 1902 int sqlite3_global_recover(void){ 1903 return SQLITE_OK; 1904 } 1905 #endif 1906 #endif 1907 1908 /* 1909 ** Test to see whether or not the database connection is in autocommit 1910 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on 1911 ** by default. Autocommit is disabled by a BEGIN statement and reenabled 1912 ** by the next COMMIT or ROLLBACK. 1913 ** 1914 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ****** 1915 */ 1916 int sqlite3_get_autocommit(sqlite3 *db){ 1917 return db->autoCommit; 1918 } 1919 1920 #ifdef SQLITE_DEBUG 1921 /* 1922 ** The following routine is subtituted for constant SQLITE_CORRUPT in 1923 ** debugging builds. This provides a way to set a breakpoint for when 1924 ** corruption is first detected. 1925 */ 1926 int sqlite3Corrupt(void){ 1927 return SQLITE_CORRUPT; 1928 } 1929 #endif 1930 1931 #ifndef SQLITE_OMIT_DEPRECATED 1932 /* 1933 ** This is a convenience routine that makes sure that all thread-specific 1934 ** data for this thread has been deallocated. 1935 ** 1936 ** SQLite no longer uses thread-specific data so this routine is now a 1937 ** no-op. It is retained for historical compatibility. 1938 */ 1939 void sqlite3_thread_cleanup(void){ 1940 } 1941 #endif 1942 1943 /* 1944 ** Return meta information about a specific column of a database table. 1945 ** See comment in sqlite3.h (sqlite.h.in) for details. 1946 */ 1947 #ifdef SQLITE_ENABLE_COLUMN_METADATA 1948 int sqlite3_table_column_metadata( 1949 sqlite3 *db, /* Connection handle */ 1950 const char *zDbName, /* Database name or NULL */ 1951 const char *zTableName, /* Table name */ 1952 const char *zColumnName, /* Column name */ 1953 char const **pzDataType, /* OUTPUT: Declared data type */ 1954 char const **pzCollSeq, /* OUTPUT: Collation sequence name */ 1955 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ 1956 int *pPrimaryKey, /* OUTPUT: True if column part of PK */ 1957 int *pAutoinc /* OUTPUT: True if column is auto-increment */ 1958 ){ 1959 int rc; 1960 char *zErrMsg = 0; 1961 Table *pTab = 0; 1962 Column *pCol = 0; 1963 int iCol; 1964 1965 char const *zDataType = 0; 1966 char const *zCollSeq = 0; 1967 int notnull = 0; 1968 int primarykey = 0; 1969 int autoinc = 0; 1970 1971 /* Ensure the database schema has been loaded */ 1972 sqlite3_mutex_enter(db->mutex); 1973 (void)sqlite3SafetyOn(db); 1974 sqlite3BtreeEnterAll(db); 1975 rc = sqlite3Init(db, &zErrMsg); 1976 if( SQLITE_OK!=rc ){ 1977 goto error_out; 1978 } 1979 1980 /* Locate the table in question */ 1981 pTab = sqlite3FindTable(db, zTableName, zDbName); 1982 if( !pTab || pTab->pSelect ){ 1983 pTab = 0; 1984 goto error_out; 1985 } 1986 1987 /* Find the column for which info is requested */ 1988 if( sqlite3IsRowid(zColumnName) ){ 1989 iCol = pTab->iPKey; 1990 if( iCol>=0 ){ 1991 pCol = &pTab->aCol[iCol]; 1992 } 1993 }else{ 1994 for(iCol=0; iCol<pTab->nCol; iCol++){ 1995 pCol = &pTab->aCol[iCol]; 1996 if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){ 1997 break; 1998 } 1999 } 2000 if( iCol==pTab->nCol ){ 2001 pTab = 0; 2002 goto error_out; 2003 } 2004 } 2005 2006 /* The following block stores the meta information that will be returned 2007 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey 2008 ** and autoinc. At this point there are two possibilities: 2009 ** 2010 ** 1. The specified column name was rowid", "oid" or "_rowid_" 2011 ** and there is no explicitly declared IPK column. 2012 ** 2013 ** 2. The table is not a view and the column name identified an 2014 ** explicitly declared column. Copy meta information from *pCol. 2015 */ 2016 if( pCol ){ 2017 zDataType = pCol->zType; 2018 zCollSeq = pCol->zColl; 2019 notnull = pCol->notNull!=0; 2020 primarykey = pCol->isPrimKey!=0; 2021 autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0; 2022 }else{ 2023 zDataType = "INTEGER"; 2024 primarykey = 1; 2025 } 2026 if( !zCollSeq ){ 2027 zCollSeq = "BINARY"; 2028 } 2029 2030 error_out: 2031 sqlite3BtreeLeaveAll(db); 2032 (void)sqlite3SafetyOff(db); 2033 2034 /* Whether the function call succeeded or failed, set the output parameters 2035 ** to whatever their local counterparts contain. If an error did occur, 2036 ** this has the effect of zeroing all output parameters. 2037 */ 2038 if( pzDataType ) *pzDataType = zDataType; 2039 if( pzCollSeq ) *pzCollSeq = zCollSeq; 2040 if( pNotNull ) *pNotNull = notnull; 2041 if( pPrimaryKey ) *pPrimaryKey = primarykey; 2042 if( pAutoinc ) *pAutoinc = autoinc; 2043 2044 if( SQLITE_OK==rc && !pTab ){ 2045 sqlite3DbFree(db, zErrMsg); 2046 zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName, 2047 zColumnName); 2048 rc = SQLITE_ERROR; 2049 } 2050 sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg); 2051 sqlite3DbFree(db, zErrMsg); 2052 rc = sqlite3ApiExit(db, rc); 2053 sqlite3_mutex_leave(db->mutex); 2054 return rc; 2055 } 2056 #endif 2057 2058 /* 2059 ** Sleep for a little while. Return the amount of time slept. 2060 */ 2061 int sqlite3_sleep(int ms){ 2062 sqlite3_vfs *pVfs; 2063 int rc; 2064 pVfs = sqlite3_vfs_find(0); 2065 if( pVfs==0 ) return 0; 2066 2067 /* This function works in milliseconds, but the underlying OsSleep() 2068 ** API uses microseconds. Hence the 1000's. 2069 */ 2070 rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000); 2071 return rc; 2072 } 2073 2074 /* 2075 ** Enable or disable the extended result codes. 2076 */ 2077 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){ 2078 sqlite3_mutex_enter(db->mutex); 2079 db->errMask = onoff ? 0xffffffff : 0xff; 2080 sqlite3_mutex_leave(db->mutex); 2081 return SQLITE_OK; 2082 } 2083 2084 /* 2085 ** Invoke the xFileControl method on a particular database. 2086 */ 2087 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){ 2088 int rc = SQLITE_ERROR; 2089 int iDb; 2090 sqlite3_mutex_enter(db->mutex); 2091 if( zDbName==0 ){ 2092 iDb = 0; 2093 }else{ 2094 for(iDb=0; iDb<db->nDb; iDb++){ 2095 if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break; 2096 } 2097 } 2098 if( iDb<db->nDb ){ 2099 Btree *pBtree = db->aDb[iDb].pBt; 2100 if( pBtree ){ 2101 Pager *pPager; 2102 sqlite3_file *fd; 2103 sqlite3BtreeEnter(pBtree); 2104 pPager = sqlite3BtreePager(pBtree); 2105 assert( pPager!=0 ); 2106 fd = sqlite3PagerFile(pPager); 2107 assert( fd!=0 ); 2108 if( fd->pMethods ){ 2109 rc = sqlite3OsFileControl(fd, op, pArg); 2110 } 2111 sqlite3BtreeLeave(pBtree); 2112 } 2113 } 2114 sqlite3_mutex_leave(db->mutex); 2115 return rc; 2116 } 2117 2118 /* 2119 ** Interface to the testing logic. 2120 */ 2121 int sqlite3_test_control(int op, ...){ 2122 int rc = 0; 2123 #ifndef SQLITE_OMIT_BUILTIN_TEST 2124 va_list ap; 2125 va_start(ap, op); 2126 switch( op ){ 2127 2128 /* 2129 ** Save the current state of the PRNG. 2130 */ 2131 case SQLITE_TESTCTRL_PRNG_SAVE: { 2132 sqlite3PrngSaveState(); 2133 break; 2134 } 2135 2136 /* 2137 ** Restore the state of the PRNG to the last state saved using 2138 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then 2139 ** this verb acts like PRNG_RESET. 2140 */ 2141 case SQLITE_TESTCTRL_PRNG_RESTORE: { 2142 sqlite3PrngRestoreState(); 2143 break; 2144 } 2145 2146 /* 2147 ** Reset the PRNG back to its uninitialized state. The next call 2148 ** to sqlite3_randomness() will reseed the PRNG using a single call 2149 ** to the xRandomness method of the default VFS. 2150 */ 2151 case SQLITE_TESTCTRL_PRNG_RESET: { 2152 sqlite3PrngResetState(); 2153 break; 2154 } 2155 2156 /* 2157 ** sqlite3_test_control(BITVEC_TEST, size, program) 2158 ** 2159 ** Run a test against a Bitvec object of size. The program argument 2160 ** is an array of integers that defines the test. Return -1 on a 2161 ** memory allocation error, 0 on success, or non-zero for an error. 2162 ** See the sqlite3BitvecBuiltinTest() for additional information. 2163 */ 2164 case SQLITE_TESTCTRL_BITVEC_TEST: { 2165 int sz = va_arg(ap, int); 2166 int *aProg = va_arg(ap, int*); 2167 rc = sqlite3BitvecBuiltinTest(sz, aProg); 2168 break; 2169 } 2170 2171 /* 2172 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd) 2173 ** 2174 ** Register hooks to call to indicate which malloc() failures 2175 ** are benign. 2176 */ 2177 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: { 2178 typedef void (*void_function)(void); 2179 void_function xBenignBegin; 2180 void_function xBenignEnd; 2181 xBenignBegin = va_arg(ap, void_function); 2182 xBenignEnd = va_arg(ap, void_function); 2183 sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd); 2184 break; 2185 } 2186 2187 /* 2188 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X) 2189 ** 2190 ** Set the PENDING byte to the value in the argument, if X>0. 2191 ** Make no changes if X==0. Return the value of the pending byte 2192 ** as it existing before this routine was called. 2193 ** 2194 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in 2195 ** an incompatible database file format. Changing the PENDING byte 2196 ** while any database connection is open results in undefined and 2197 ** dileterious behavior. 2198 */ 2199 case SQLITE_TESTCTRL_PENDING_BYTE: { 2200 unsigned int newVal = va_arg(ap, unsigned int); 2201 rc = sqlite3PendingByte; 2202 if( newVal ) sqlite3PendingByte = newVal; 2203 break; 2204 } 2205 2206 /* 2207 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X) 2208 ** 2209 ** This action provides a run-time test to see whether or not 2210 ** assert() was enabled at compile-time. If X is true and assert() 2211 ** is enabled, then the return value is true. If X is true and 2212 ** assert() is disabled, then the return value is zero. If X is 2213 ** false and assert() is enabled, then the assertion fires and the 2214 ** process aborts. If X is false and assert() is disabled, then the 2215 ** return value is zero. 2216 */ 2217 case SQLITE_TESTCTRL_ASSERT: { 2218 volatile int x = 0; 2219 assert( (x = va_arg(ap,int))!=0 ); 2220 rc = x; 2221 break; 2222 } 2223 2224 2225 /* 2226 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X) 2227 ** 2228 ** This action provides a run-time test to see how the ALWAYS and 2229 ** NEVER macros were defined at compile-time. 2230 ** 2231 ** The return value is ALWAYS(X). 2232 ** 2233 ** The recommended test is X==2. If the return value is 2, that means 2234 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the 2235 ** default setting. If the return value is 1, then ALWAYS() is either 2236 ** hard-coded to true or else it asserts if its argument is false. 2237 ** The first behavior (hard-coded to true) is the case if 2238 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second 2239 ** behavior (assert if the argument to ALWAYS() is false) is the case if 2240 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled. 2241 ** 2242 ** The run-time test procedure might look something like this: 2243 ** 2244 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){ 2245 ** // ALWAYS() and NEVER() are no-op pass-through macros 2246 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){ 2247 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false. 2248 ** }else{ 2249 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0. 2250 ** } 2251 */ 2252 case SQLITE_TESTCTRL_ALWAYS: { 2253 int x = va_arg(ap,int); 2254 rc = ALWAYS(x); 2255 break; 2256 } 2257 2258 /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N) 2259 ** 2260 ** Set the nReserve size to N for the main database on the database 2261 ** connection db. 2262 */ 2263 case SQLITE_TESTCTRL_RESERVE: { 2264 sqlite3 *db = va_arg(ap, sqlite3*); 2265 int x = va_arg(ap,int); 2266 sqlite3_mutex_enter(db->mutex); 2267 sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0); 2268 sqlite3_mutex_leave(db->mutex); 2269 break; 2270 } 2271 2272 } 2273 va_end(ap); 2274 #endif /* SQLITE_OMIT_BUILTIN_TEST */ 2275 return rc; 2276 } 2277