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