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