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