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