main.c

Go to the documentation of this file.
00001 /*
00002 ** 2001 September 15
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 ** Main file for the SQLite library.  The routines in this file
00013 ** implement the programmer interface to the library.  Routines in
00014 ** other files are for internal use by SQLite and should not be
00015 ** accessed by users of the library.
00016 **
00017 ** $Id: main.c,v 1.511 2008/11/10 18:05:36 shane Exp $
00018 */
00019 #include "sqliteInt.h"
00020 #include <ctype.h>
00021 
00022 #ifdef SQLITE_ENABLE_FTS3
00023 # include "fts3.h"
00024 #endif
00025 #ifdef SQLITE_ENABLE_RTREE
00026 # include "rtree.h"
00027 #endif
00028 #ifdef SQLITE_ENABLE_ICU
00029 # include "sqliteicu.h"
00030 #endif
00031 
00032 /*
00033 ** The version of the library
00034 */
00035 const char sqlite3_version[] = SQLITE_VERSION;
00036 const char *sqlite3_libversion(void){ return sqlite3_version; }
00037 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
00038 int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
00039 
00040 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
00041 /*
00042 ** If the following function pointer is not NULL and if
00043 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
00044 ** I/O active are written using this function.  These messages
00045 ** are intended for debugging activity only.
00046 */
00047 void (*sqlite3IoTrace)(const char*, ...) = 0;
00048 #endif
00049 
00050 /*
00051 ** If the following global variable points to a string which is the
00052 ** name of a directory, then that directory will be used to store
00053 ** temporary files.
00054 **
00055 ** See also the "PRAGMA temp_store_directory" SQL command.
00056 */
00057 char *sqlite3_temp_directory = 0;
00058 
00059 /*
00060 ** Initialize SQLite.  
00061 **
00062 ** This routine must be called to initialize the memory allocation,
00063 ** VFS, and mutex subsystems prior to doing any serious work with
00064 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
00065 ** this routine will be called automatically by key routines such as
00066 ** sqlite3_open().  
00067 **
00068 ** This routine is a no-op except on its very first call for the process,
00069 ** or for the first call after a call to sqlite3_shutdown.
00070 **
00071 ** The first thread to call this routine runs the initialization to
00072 ** completion.  If subsequent threads call this routine before the first
00073 ** thread has finished the initialization process, then the subsequent
00074 ** threads must block until the first thread finishes with the initialization.
00075 **
00076 ** The first thread might call this routine recursively.  Recursive
00077 ** calls to this routine should not block, of course.  Otherwise the
00078 ** initialization process would never complete.
00079 **
00080 ** Let X be the first thread to enter this routine.  Let Y be some other
00081 ** thread.  Then while the initial invocation of this routine by X is
00082 ** incomplete, it is required that:
00083 **
00084 **    *  Calls to this routine from Y must block until the outer-most
00085 **       call by X completes.
00086 **
00087 **    *  Recursive calls to this routine from thread X return immediately
00088 **       without blocking.
00089 */
00090 int sqlite3_initialize(void){
00091   sqlite3_mutex *pMaster;                      /* The main static mutex */
00092   int rc;                                      /* Result code */
00093 
00094 #ifdef SQLITE_OMIT_WSD
00095   rc = sqlite3_wsd_init(4096, 24);
00096   if( rc!=SQLITE_OK ){
00097     return rc;
00098   }
00099 #endif
00100 
00101   /* If SQLite is already completely initialized, then this call
00102   ** to sqlite3_initialize() should be a no-op.  But the initialization
00103   ** must be complete.  So isInit must not be set until the very end
00104   ** of this routine.
00105   */
00106   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
00107 
00108   /* Make sure the mutex subsystem is initialized.  If unable to 
00109   ** initialize the mutex subsystem, return early with the error.
00110   ** If the system is so sick that we are unable to allocate a mutex,
00111   ** there is not much SQLite is going to be able to do.
00112   **
00113   ** The mutex subsystem must take care of serializing its own
00114   ** initialization.
00115   */
00116   rc = sqlite3MutexInit();
00117   if( rc ) return rc;
00118 
00119   /* Initialize the malloc() system and the recursive pInitMutex mutex.
00120   ** This operation is protected by the STATIC_MASTER mutex.  Note that
00121   ** MutexAlloc() is called for a static mutex prior to initializing the
00122   ** malloc subsystem - this implies that the allocation of a static
00123   ** mutex must not require support from the malloc subsystem.
00124   */
00125   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
00126   sqlite3_mutex_enter(pMaster);
00127   if( !sqlite3GlobalConfig.isMallocInit ){
00128     rc = sqlite3MallocInit();
00129   }
00130   if( rc==SQLITE_OK ){
00131     sqlite3GlobalConfig.isMallocInit = 1;
00132     if( !sqlite3GlobalConfig.pInitMutex ){
00133       sqlite3GlobalConfig.pInitMutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
00134       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
00135         rc = SQLITE_NOMEM;
00136       }
00137     }
00138   }
00139   if( rc==SQLITE_OK ){
00140     sqlite3GlobalConfig.nRefInitMutex++;
00141   }
00142   sqlite3_mutex_leave(pMaster);
00143 
00144   /* If unable to initialize the malloc subsystem, then return early.
00145   ** There is little hope of getting SQLite to run if the malloc
00146   ** subsystem cannot be initialized.
00147   */
00148   if( rc!=SQLITE_OK ){
00149     return rc;
00150   }
00151 
00152   /* Do the rest of the initialization under the recursive mutex so
00153   ** that we will be able to handle recursive calls into
00154   ** sqlite3_initialize().  The recursive calls normally come through
00155   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
00156   ** recursive calls might also be possible.
00157   */
00158   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
00159   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
00160     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
00161     sqlite3GlobalConfig.inProgress = 1;
00162     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
00163     sqlite3RegisterGlobalFunctions();
00164     rc = sqlite3_os_init();
00165     if( rc==SQLITE_OK ){
00166       rc = sqlite3PcacheInitialize();
00167       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
00168           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
00169     }
00170     sqlite3GlobalConfig.inProgress = 0;
00171     sqlite3GlobalConfig.isInit = (rc==SQLITE_OK ? 1 : 0);
00172   }
00173   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
00174 
00175   /* Go back under the static mutex and clean up the recursive
00176   ** mutex to prevent a resource leak.
00177   */
00178   sqlite3_mutex_enter(pMaster);
00179   sqlite3GlobalConfig.nRefInitMutex--;
00180   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
00181     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
00182     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
00183     sqlite3GlobalConfig.pInitMutex = 0;
00184   }
00185   sqlite3_mutex_leave(pMaster);
00186 
00187   /* The following is just a sanity check to make sure SQLite has
00188   ** been compiled correctly.  It is important to run this code, but
00189   ** we don't want to run it too often and soak up CPU cycles for no
00190   ** reason.  So we run it once during initialization.
00191   */
00192 #ifndef NDEBUG
00193   /* This section of code's only "output" is via assert() statements. */
00194   if ( rc==SQLITE_OK ){
00195     u64 x = (((u64)1)<<63)-1;
00196     double y;
00197     assert(sizeof(x)==8);
00198     assert(sizeof(x)==sizeof(y));
00199     memcpy(&y, &x, 8);
00200     assert( sqlite3IsNaN(y) );
00201   }
00202 #endif
00203 
00204   return rc;
00205 }
00206 
00207 /*
00208 ** Undo the effects of sqlite3_initialize().  Must not be called while
00209 ** there are outstanding database connections or memory allocations or
00210 ** while any part of SQLite is otherwise in use in any thread.  This
00211 ** routine is not threadsafe.  Not by a long shot.
00212 */
00213 int sqlite3_shutdown(void){
00214   sqlite3GlobalConfig.isMallocInit = 0;
00215   sqlite3PcacheShutdown();
00216   if( sqlite3GlobalConfig.isInit ){
00217     sqlite3_os_end();
00218   }
00219   sqlite3MallocEnd();
00220   sqlite3MutexEnd();
00221   sqlite3GlobalConfig.isInit = 0;
00222   return SQLITE_OK;
00223 }
00224 
00225 /*
00226 ** This API allows applications to modify the global configuration of
00227 ** the SQLite library at run-time.
00228 **
00229 ** This routine should only be called when there are no outstanding
00230 ** database connections or memory allocations.  This routine is not
00231 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
00232 ** behavior.
00233 */
00234 int sqlite3_config(int op, ...){
00235   va_list ap;
00236   int rc = SQLITE_OK;
00237 
00238   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
00239   ** the SQLite library is in use. */
00240   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE;
00241 
00242   va_start(ap, op);
00243   switch( op ){
00244 
00245     /* Mutex configuration options are only available in a threadsafe
00246     ** compile. 
00247     */
00248 #if SQLITE_THREADSAFE
00249     case SQLITE_CONFIG_SINGLETHREAD: {
00250       /* Disable all mutexing */
00251       sqlite3GlobalConfig.bCoreMutex = 0;
00252       sqlite3GlobalConfig.bFullMutex = 0;
00253       break;
00254     }
00255     case SQLITE_CONFIG_MULTITHREAD: {
00256       /* Disable mutexing of database connections */
00257       /* Enable mutexing of core data structures */
00258       sqlite3GlobalConfig.bCoreMutex = 1;
00259       sqlite3GlobalConfig.bFullMutex = 0;
00260       break;
00261     }
00262     case SQLITE_CONFIG_SERIALIZED: {
00263       /* Enable all mutexing */
00264       sqlite3GlobalConfig.bCoreMutex = 1;
00265       sqlite3GlobalConfig.bFullMutex = 1;
00266       break;
00267     }
00268     case SQLITE_CONFIG_MUTEX: {
00269       /* Specify an alternative mutex implementation */
00270       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
00271       break;
00272     }
00273     case SQLITE_CONFIG_GETMUTEX: {
00274       /* Retrieve the current mutex implementation */
00275       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
00276       break;
00277     }
00278 #endif
00279 
00280 
00281     case SQLITE_CONFIG_MALLOC: {
00282       /* Specify an alternative malloc implementation */
00283       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
00284       break;
00285     }
00286     case SQLITE_CONFIG_GETMALLOC: {
00287       /* Retrieve the current malloc() implementation */
00288       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
00289       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
00290       break;
00291     }
00292     case SQLITE_CONFIG_MEMSTATUS: {
00293       /* Enable or disable the malloc status collection */
00294       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
00295       break;
00296     }
00297     case SQLITE_CONFIG_SCRATCH: {
00298       /* Designate a buffer for scratch memory space */
00299       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
00300       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
00301       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
00302       break;
00303     }
00304     case SQLITE_CONFIG_PAGECACHE: {
00305       /* Designate a buffer for scratch memory space */
00306       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
00307       sqlite3GlobalConfig.szPage = va_arg(ap, int);
00308       sqlite3GlobalConfig.nPage = va_arg(ap, int);
00309       break;
00310     }
00311 
00312 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
00313     case SQLITE_CONFIG_HEAP: {
00314       /* Designate a buffer for heap memory space */
00315       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
00316       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
00317       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
00318 
00319       if( sqlite3GlobalConfig.pHeap==0 ){
00320         /* If the heap pointer is NULL, then restore the malloc implementation
00321         ** back to NULL pointers too.  This will cause the malloc to go
00322         ** back to its default implementation when sqlite3_initialize() is
00323         ** run.
00324         */
00325         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
00326       }else{
00327         /* The heap pointer is not NULL, then install one of the
00328         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
00329         ** ENABLE_MEMSYS5 is defined, return an error.
00330         ** the default case and return an error.
00331         */
00332 #ifdef SQLITE_ENABLE_MEMSYS3
00333         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
00334 #endif
00335 #ifdef SQLITE_ENABLE_MEMSYS5
00336         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
00337 #endif
00338       }
00339       break;
00340     }
00341 #endif
00342 
00343     case SQLITE_CONFIG_LOOKASIDE: {
00344       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
00345       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
00346       break;
00347     }
00348 
00349     default: {
00350       rc = SQLITE_ERROR;
00351       break;
00352     }
00353   }
00354   va_end(ap);
00355   return rc;
00356 }
00357 
00358 /*
00359 ** Set up the lookaside buffers for a database connection.
00360 ** Return SQLITE_OK on success.  
00361 ** If lookaside is already active, return SQLITE_BUSY.
00362 **
00363 ** The sz parameter is the number of bytes in each lookaside slot.
00364 ** The cnt parameter is the number of slots.  If pStart is NULL the
00365 ** space for the lookaside memory is obtained from sqlite3_malloc().
00366 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
00367 ** the lookaside memory.
00368 */
00369 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
00370   void *pStart;
00371   if( db->lookaside.nOut ){
00372     return SQLITE_BUSY;
00373   }
00374   if( sz<0 ) sz = 0;
00375   if( cnt<0 ) cnt = 0;
00376   if( pBuf==0 ){
00377     sz = (sz + 7)&~7;
00378     sqlite3BeginBenignMalloc();
00379     pStart = sqlite3Malloc( sz*cnt );
00380     sqlite3EndBenignMalloc();
00381   }else{
00382     sz = sz&~7;
00383     pStart = pBuf;
00384   }
00385   if( db->lookaside.bMalloced ){
00386     sqlite3_free(db->lookaside.pStart);
00387   }
00388   db->lookaside.pStart = pStart;
00389   db->lookaside.pFree = 0;
00390   db->lookaside.sz = sz;
00391   db->lookaside.bMalloced = pBuf==0;
00392   if( pStart ){
00393     int i;
00394     LookasideSlot *p;
00395     p = (LookasideSlot*)pStart;
00396     for(i=cnt-1; i>=0; i--){
00397       p->pNext = db->lookaside.pFree;
00398       db->lookaside.pFree = p;
00399       p = (LookasideSlot*)&((u8*)p)[sz];
00400     }
00401     db->lookaside.pEnd = p;
00402     db->lookaside.bEnabled = 1;
00403   }else{
00404     db->lookaside.pEnd = 0;
00405     db->lookaside.bEnabled = 0;
00406   }
00407   return SQLITE_OK;
00408 }
00409 
00410 /*
00411 ** Return the mutex associated with a database connection.
00412 */
00413 sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
00414   return db->mutex;
00415 }
00416 
00417 /*
00418 ** Configuration settings for an individual database connection
00419 */
00420 int sqlite3_db_config(sqlite3 *db, int op, ...){
00421   va_list ap;
00422   int rc;
00423   va_start(ap, op);
00424   switch( op ){
00425     case SQLITE_DBCONFIG_LOOKASIDE: {
00426       void *pBuf = va_arg(ap, void*);
00427       int sz = va_arg(ap, int);
00428       int cnt = va_arg(ap, int);
00429       rc = setupLookaside(db, pBuf, sz, cnt);
00430       break;
00431     }
00432     default: {
00433       rc = SQLITE_ERROR;
00434       break;
00435     }
00436   }
00437   va_end(ap);
00438   return rc;
00439 }
00440 
00441 /*
00442 ** Routine needed to support the testcase() macro.
00443 */
00444 #ifdef SQLITE_COVERAGE_TEST
00445 void sqlite3Coverage(int x){
00446   static int dummy = 0;
00447   dummy += x;
00448 }
00449 #endif
00450 
00451 
00452 /*
00453 ** Return true if the buffer z[0..n-1] contains all spaces.
00454 */
00455 static int allSpaces(const char *z, int n){
00456   while( n>0 && z[n-1]==' ' ){ n--; }
00457   return n==0;
00458 }
00459 
00460 /*
00461 ** This is the default collating function named "BINARY" which is always
00462 ** available.
00463 **
00464 ** If the padFlag argument is not NULL then space padding at the end
00465 ** of strings is ignored.  This implements the RTRIM collation.
00466 */
00467 static int binCollFunc(
00468   void *padFlag,
00469   int nKey1, const void *pKey1,
00470   int nKey2, const void *pKey2
00471 ){
00472   int rc, n;
00473   n = nKey1<nKey2 ? nKey1 : nKey2;
00474   rc = memcmp(pKey1, pKey2, n);
00475   if( rc==0 ){
00476     if( padFlag
00477      && allSpaces(((char*)pKey1)+n, nKey1-n)
00478      && allSpaces(((char*)pKey2)+n, nKey2-n)
00479     ){
00480       /* Leave rc unchanged at 0 */
00481     }else{
00482       rc = nKey1 - nKey2;
00483     }
00484   }
00485   return rc;
00486 }
00487 
00488 /*
00489 ** Another built-in collating sequence: NOCASE. 
00490 **
00491 ** This collating sequence is intended to be used for "case independant
00492 ** comparison". SQLite's knowledge of upper and lower case equivalents
00493 ** extends only to the 26 characters used in the English language.
00494 **
00495 ** At the moment there is only a UTF-8 implementation.
00496 */
00497 static int nocaseCollatingFunc(
00498   void *NotUsed,
00499   int nKey1, const void *pKey1,
00500   int nKey2, const void *pKey2
00501 ){
00502   int r = sqlite3StrNICmp(
00503       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
00504   if( 0==r ){
00505     r = nKey1-nKey2;
00506   }
00507   return r;
00508 }
00509 
00510 /*
00511 ** Return the ROWID of the most recent insert
00512 */
00513 sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
00514   return db->lastRowid;
00515 }
00516 
00517 /*
00518 ** Return the number of changes in the most recent call to sqlite3_exec().
00519 */
00520 int sqlite3_changes(sqlite3 *db){
00521   return db->nChange;
00522 }
00523 
00524 /*
00525 ** Return the number of changes since the database handle was opened.
00526 */
00527 int sqlite3_total_changes(sqlite3 *db){
00528   return db->nTotalChange;
00529 }
00530 
00531 /*
00532 ** Close an existing SQLite database
00533 */
00534 EXPORT_C int sqlite3_close(sqlite3 *db){
00535   HashElem *i;
00536   int j;
00537 
00538   if( !db ){
00539     return SQLITE_OK;
00540   }
00541   if( !sqlite3SafetyCheckSickOrOk(db) ){
00542     return SQLITE_MISUSE;
00543   }
00544   sqlite3_mutex_enter(db->mutex);
00545 
00546 #ifdef SQLITE_SSE
00547   {
00548     extern void sqlite3SseCleanup(sqlite3*);
00549     sqlite3SseCleanup(db);
00550   }
00551 #endif 
00552 
00553   sqlite3ResetInternalSchema(db, 0);
00554 
00555   /* If a transaction is open, the ResetInternalSchema() call above
00556   ** will not have called the xDisconnect() method on any virtual
00557   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
00558   ** call will do so. We need to do this before the check for active
00559   ** SQL statements below, as the v-table implementation may be storing
00560   ** some prepared statements internally.
00561   */
00562   sqlite3VtabRollback(db);
00563 
00564   /* If there are any outstanding VMs, return SQLITE_BUSY. */
00565   if( db->pVdbe ){
00566     sqlite3Error(db, SQLITE_BUSY, 
00567         "Unable to close due to unfinalised statements");
00568     sqlite3_mutex_leave(db->mutex);
00569     return SQLITE_BUSY;
00570   }
00571   assert( sqlite3SafetyCheckSickOrOk(db) );
00572 
00573   for(j=0; j<db->nDb; j++){
00574     struct Db *pDb = &db->aDb[j];
00575     if( pDb->pBt ){
00576       sqlite3BtreeClose(pDb->pBt);
00577       pDb->pBt = 0;
00578       if( j!=1 ){
00579         pDb->pSchema = 0;
00580       }
00581     }
00582   }
00583   sqlite3ResetInternalSchema(db, 0);
00584   assert( db->nDb<=2 );
00585   assert( db->aDb==db->aDbStatic );
00586   for(j=0; j<ArraySize(db->aFunc.a); j++){
00587     FuncDef *pNext, *pHash, *p;
00588     for(p=db->aFunc.a[j]; p; p=pHash){
00589       pHash = p->pHash;
00590       while( p ){
00591         pNext = p->pNext;
00592         sqlite3DbFree(db, p);
00593         p = pNext;
00594       }
00595     }
00596   }
00597   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
00598     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
00599     /* Invoke any destructors registered for collation sequence user data. */
00600     for(j=0; j<3; j++){
00601       if( pColl[j].xDel ){
00602         pColl[j].xDel(pColl[j].pUser);
00603       }
00604     }
00605     sqlite3DbFree(db, pColl);
00606   }
00607   sqlite3HashClear(&db->aCollSeq);
00608 #ifndef SQLITE_OMIT_VIRTUALTABLE
00609   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
00610     Module *pMod = (Module *)sqliteHashData(i);
00611     if( pMod->xDestroy ){
00612       pMod->xDestroy(pMod->pAux);
00613     }
00614     sqlite3DbFree(db, pMod);
00615   }
00616   sqlite3HashClear(&db->aModule);
00617 #endif
00618 
00619   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
00620   if( db->pErr ){
00621     sqlite3ValueFree(db->pErr);
00622   }
00623   sqlite3CloseExtensions(db);
00624 
00625   db->magic = SQLITE_MAGIC_ERROR;
00626 
00627   /* The temp-database schema is allocated differently from the other schema
00628   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
00629   ** So it needs to be freed here. Todo: Why not roll the temp schema into
00630   ** the same sqliteMalloc() as the one that allocates the database 
00631   ** structure?
00632   */
00633   sqlite3DbFree(db, db->aDb[1].pSchema);
00634   sqlite3_mutex_leave(db->mutex);
00635   db->magic = SQLITE_MAGIC_CLOSED;
00636   sqlite3_mutex_free(db->mutex);
00637   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
00638   if( db->lookaside.bMalloced ){
00639     sqlite3_free(db->lookaside.pStart);
00640   }
00641   sqlite3_free(db);
00642   return SQLITE_OK;
00643 }
00644 
00645 /*
00646 ** Rollback all database files.
00647 */
00648 void sqlite3RollbackAll(sqlite3 *db){
00649   int i;
00650   int inTrans = 0;
00651   assert( sqlite3_mutex_held(db->mutex) );
00652   sqlite3BeginBenignMalloc();
00653   for(i=0; i<db->nDb; i++){
00654     if( db->aDb[i].pBt ){
00655       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
00656         inTrans = 1;
00657       }
00658       sqlite3BtreeRollback(db->aDb[i].pBt);
00659       db->aDb[i].inTrans = 0;
00660     }
00661   }
00662   sqlite3VtabRollback(db);
00663   sqlite3EndBenignMalloc();
00664 
00665   if( db->flags&SQLITE_InternChanges ){
00666     sqlite3ExpirePreparedStatements(db);
00667     sqlite3ResetInternalSchema(db, 0);
00668   }
00669 
00670   /* If one has been configured, invoke the rollback-hook callback */
00671   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
00672     db->xRollbackCallback(db->pRollbackArg);
00673   }
00674 }
00675 
00676 /*
00677 ** Return a static string that describes the kind of error specified in the
00678 ** argument.
00679 */
00680 const char *sqlite3ErrStr(int rc){
00681   const char *z;
00682   switch( rc & 0xff ){
00683     case SQLITE_ROW:
00684     case SQLITE_DONE:
00685     case SQLITE_OK:         z = "not an error";                          break;
00686     case SQLITE_ERROR:      z = "SQL logic error or missing database";   break;
00687     case SQLITE_PERM:       z = "access permission denied";              break;
00688     case SQLITE_ABORT:      z = "callback requested query abort";        break;
00689     case SQLITE_BUSY:       z = "database is locked";                    break;
00690     case SQLITE_LOCKED:     z = "database table is locked";              break;
00691     case SQLITE_NOMEM:      z = "out of memory";                         break;
00692     case SQLITE_READONLY:   z = "attempt to write a readonly database";  break;
00693     case SQLITE_INTERRUPT:  z = "interrupted";                           break;
00694     case SQLITE_IOERR:      z = "disk I/O error";                        break;
00695     case SQLITE_CORRUPT:    z = "database disk image is malformed";      break;
00696     case SQLITE_FULL:       z = "database or disk is full";              break;
00697     case SQLITE_CANTOPEN:   z = "unable to open database file";          break;
00698     case SQLITE_EMPTY:      z = "table contains no data";                break;
00699     case SQLITE_SCHEMA:     z = "database schema has changed";           break;
00700     case SQLITE_TOOBIG:     z = "String or BLOB exceeded size limit";    break;
00701     case SQLITE_CONSTRAINT: z = "constraint failed";                     break;
00702     case SQLITE_MISMATCH:   z = "datatype mismatch";                     break;
00703     case SQLITE_MISUSE:     z = "library routine called out of sequence";break;
00704     case SQLITE_NOLFS:      z = "large file support is disabled";        break;
00705     case SQLITE_AUTH:       z = "authorization denied";                  break;
00706     case SQLITE_FORMAT:     z = "auxiliary database format error";       break;
00707     case SQLITE_RANGE:      z = "bind or column index out of range";     break;
00708     case SQLITE_NOTADB:     z = "file is encrypted or is not a database";break;
00709     default:                z = "unknown error";                         break;
00710   }
00711   return z;
00712 }
00713 
00714 /*
00715 ** This routine implements a busy callback that sleeps and tries
00716 ** again until a timeout value is reached.  The timeout value is
00717 ** an integer number of milliseconds passed in as the first
00718 ** argument.
00719 */
00720 static int sqliteDefaultBusyCallback(
00721  void *ptr,               /* Database connection */
00722  int count                /* Number of times table has been busy */
00723 ){
00724 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
00725   static const u8 delays[] =
00726      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
00727   static const u8 totals[] =
00728      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
00729 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
00730   sqlite3 *db = (sqlite3 *)ptr;
00731   int timeout = db->busyTimeout;
00732   int delay, prior;
00733 
00734   assert( count>=0 );
00735   if( count < NDELAY ){
00736     delay = delays[count];
00737     prior = totals[count];
00738   }else{
00739     delay = delays[NDELAY-1];
00740     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
00741   }
00742   if( prior + delay > timeout ){
00743     delay = timeout - prior;
00744     if( delay<=0 ) return 0;
00745   }
00746   sqlite3OsSleep(db->pVfs, delay*1000);
00747   return 1;
00748 #else
00749   sqlite3 *db = (sqlite3 *)ptr;
00750   int timeout = ((sqlite3 *)ptr)->busyTimeout;
00751   if( (count+1)*1000 > timeout ){
00752     return 0;
00753   }
00754   sqlite3OsSleep(db->pVfs, 1000000);
00755   return 1;
00756 #endif
00757 }
00758 
00759 /*
00760 ** Invoke the given busy handler.
00761 **
00762 ** This routine is called when an operation failed with a lock.
00763 ** If this routine returns non-zero, the lock is retried.  If it
00764 ** returns 0, the operation aborts with an SQLITE_BUSY error.
00765 */
00766 int sqlite3InvokeBusyHandler(BusyHandler *p){
00767   int rc;
00768   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
00769   rc = p->xFunc(p->pArg, p->nBusy);
00770   if( rc==0 ){
00771     p->nBusy = -1;
00772   }else{
00773     p->nBusy++;
00774   }
00775   return rc; 
00776 }
00777 
00778 /*
00779 ** This routine sets the busy callback for an Sqlite database to the
00780 ** given callback function with the given argument.
00781 */
00782 int sqlite3_busy_handler(
00783   sqlite3 *db,
00784   int (*xBusy)(void*,int),
00785   void *pArg
00786 ){
00787   sqlite3_mutex_enter(db->mutex);
00788   db->busyHandler.xFunc = xBusy;
00789   db->busyHandler.pArg = pArg;
00790   db->busyHandler.nBusy = 0;
00791   sqlite3_mutex_leave(db->mutex);
00792   return SQLITE_OK;
00793 }
00794 
00795 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
00796 /*
00797 ** This routine sets the progress callback for an Sqlite database to the
00798 ** given callback function with the given argument. The progress callback will
00799 ** be invoked every nOps opcodes.
00800 */
00801 void sqlite3_progress_handler(
00802   sqlite3 *db, 
00803   int nOps,
00804   int (*xProgress)(void*), 
00805   void *pArg
00806 ){
00807   sqlite3_mutex_enter(db->mutex);
00808   if( nOps>0 ){
00809     db->xProgress = xProgress;
00810     db->nProgressOps = nOps;
00811     db->pProgressArg = pArg;
00812   }else{
00813     db->xProgress = 0;
00814     db->nProgressOps = 0;
00815     db->pProgressArg = 0;
00816   }
00817   sqlite3_mutex_leave(db->mutex);
00818 }
00819 #endif
00820 
00821 
00822 /*
00823 ** This routine installs a default busy handler that waits for the
00824 ** specified number of milliseconds before returning 0.
00825 */
00826 int sqlite3_busy_timeout(sqlite3 *db, int ms){
00827   if( ms>0 ){
00828     db->busyTimeout = ms;
00829     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
00830   }else{
00831     sqlite3_busy_handler(db, 0, 0);
00832   }
00833   return SQLITE_OK;
00834 }
00835 
00836 /*
00837 ** Cause any pending operation to stop at its earliest opportunity.
00838 */
00839 void sqlite3_interrupt(sqlite3 *db){
00840   db->u1.isInterrupted = 1;
00841 }
00842 
00843 
00844 /*
00845 ** This function is exactly the same as sqlite3_create_function(), except
00846 ** that it is designed to be called by internal code. The difference is
00847 ** that if a malloc() fails in sqlite3_create_function(), an error code
00848 ** is returned and the mallocFailed flag cleared. 
00849 */
00850 int sqlite3CreateFunc(
00851   sqlite3 *db,
00852   const char *zFunctionName,
00853   int nArg,
00854   int enc,
00855   void *pUserData,
00856   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
00857   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
00858   void (*xFinal)(sqlite3_context*)
00859 ){
00860   FuncDef *p;
00861   int nName;
00862 
00863   assert( sqlite3_mutex_held(db->mutex) );
00864   if( zFunctionName==0 ||
00865       (xFunc && (xFinal || xStep)) || 
00866       (!xFunc && (xFinal && !xStep)) ||
00867       (!xFunc && (!xFinal && xStep)) ||
00868       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
00869       (255<(nName = sqlite3Strlen(db, zFunctionName))) ){
00870     sqlite3Error(db, SQLITE_ERROR, "bad parameters");
00871     return SQLITE_ERROR;
00872   }
00873   
00874 #ifndef SQLITE_OMIT_UTF16
00875   /* If SQLITE_UTF16 is specified as the encoding type, transform this
00876   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
00877   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
00878   **
00879   ** If SQLITE_ANY is specified, add three versions of the function
00880   ** to the hash table.
00881   */
00882   if( enc==SQLITE_UTF16 ){
00883     enc = SQLITE_UTF16NATIVE;
00884   }else if( enc==SQLITE_ANY ){
00885     int rc;
00886     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
00887          pUserData, xFunc, xStep, xFinal);
00888     if( rc==SQLITE_OK ){
00889       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
00890           pUserData, xFunc, xStep, xFinal);
00891     }
00892     if( rc!=SQLITE_OK ){
00893       return rc;
00894     }
00895     enc = SQLITE_UTF16BE;
00896   }
00897 #else
00898   enc = SQLITE_UTF8;
00899 #endif
00900   
00901   /* Check if an existing function is being overridden or deleted. If so,
00902   ** and there are active VMs, then return SQLITE_BUSY. If a function
00903   ** is being overridden/deleted but there are no active VMs, allow the
00904   ** operation to continue but invalidate all precompiled statements.
00905   */
00906   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 0);
00907   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
00908     if( db->activeVdbeCnt ){
00909       sqlite3Error(db, SQLITE_BUSY, 
00910         "Unable to delete/modify user-function due to active statements");
00911       assert( !db->mallocFailed );
00912       return SQLITE_BUSY;
00913     }else{
00914       sqlite3ExpirePreparedStatements(db);
00915     }
00916   }
00917 
00918   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 1);
00919   assert(p || db->mallocFailed);
00920   if( !p ){
00921     return SQLITE_NOMEM;
00922   }
00923   p->flags = 0;
00924   p->xFunc = xFunc;
00925   p->xStep = xStep;
00926   p->xFinalize = xFinal;
00927   p->pUserData = pUserData;
00928   p->nArg = nArg;
00929   return SQLITE_OK;
00930 }
00931 
00932 /*
00933 ** Create new user functions.
00934 */
00935 int sqlite3_create_function(
00936   sqlite3 *db,
00937   const char *zFunctionName,
00938   int nArg,
00939   int enc,
00940   void *p,
00941   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
00942   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
00943   void (*xFinal)(sqlite3_context*)
00944 ){
00945   int rc;
00946   sqlite3_mutex_enter(db->mutex);
00947   rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
00948   rc = sqlite3ApiExit(db, rc);
00949   sqlite3_mutex_leave(db->mutex);
00950   return rc;
00951 }
00952 
00953 #ifndef SQLITE_OMIT_UTF16
00954 int sqlite3_create_function16(
00955   sqlite3 *db,
00956   const void *zFunctionName,
00957   int nArg,
00958   int eTextRep,
00959   void *p,
00960   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
00961   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
00962   void (*xFinal)(sqlite3_context*)
00963 ){
00964   int rc;
00965   char *zFunc8;
00966   sqlite3_mutex_enter(db->mutex);
00967   assert( !db->mallocFailed );
00968   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
00969   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
00970   sqlite3DbFree(db, zFunc8);
00971   rc = sqlite3ApiExit(db, rc);
00972   sqlite3_mutex_leave(db->mutex);
00973   return rc;
00974 }
00975 #endif
00976 
00977 
00978 /*
00979 ** Declare that a function has been overloaded by a virtual table.
00980 **
00981 ** If the function already exists as a regular global function, then
00982 ** this routine is a no-op.  If the function does not exist, then create
00983 ** a new one that always throws a run-time error.  
00984 **
00985 ** When virtual tables intend to provide an overloaded function, they
00986 ** should call this routine to make sure the global function exists.
00987 ** A global function must exist in order for name resolution to work
00988 ** properly.
00989 */
00990 int sqlite3_overload_function(
00991   sqlite3 *db,
00992   const char *zName,
00993   int nArg
00994 ){
00995   int nName = sqlite3Strlen(db, zName);
00996   int rc;
00997   sqlite3_mutex_enter(db->mutex);
00998   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
00999     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
01000                       0, sqlite3InvalidFunction, 0, 0);
01001   }
01002   rc = sqlite3ApiExit(db, SQLITE_OK);
01003   sqlite3_mutex_leave(db->mutex);
01004   return rc;
01005 }
01006 
01007 #ifndef SQLITE_OMIT_TRACE
01008 /*
01009 ** Register a trace function.  The pArg from the previously registered trace
01010 ** is returned.  
01011 **
01012 ** A NULL trace function means that no tracing is executes.  A non-NULL
01013 ** trace is a pointer to a function that is invoked at the start of each
01014 ** SQL statement.
01015 */
01016 void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
01017   void *pOld;
01018   sqlite3_mutex_enter(db->mutex);
01019   pOld = db->pTraceArg;
01020   db->xTrace = xTrace;
01021   db->pTraceArg = pArg;
01022   sqlite3_mutex_leave(db->mutex);
01023   return pOld;
01024 }
01025 /*
01026 ** Register a profile function.  The pArg from the previously registered 
01027 ** profile function is returned.  
01028 **
01029 ** A NULL profile function means that no profiling is executes.  A non-NULL
01030 ** profile is a pointer to a function that is invoked at the conclusion of
01031 ** each SQL statement that is run.
01032 */
01033 void *sqlite3_profile(
01034   sqlite3 *db,
01035   void (*xProfile)(void*,const char*,sqlite_uint64),
01036   void *pArg
01037 ){
01038   void *pOld;
01039   sqlite3_mutex_enter(db->mutex);
01040   pOld = db->pProfileArg;
01041   db->xProfile = xProfile;
01042   db->pProfileArg = pArg;
01043   sqlite3_mutex_leave(db->mutex);
01044   return pOld;
01045 }
01046 #endif /* SQLITE_OMIT_TRACE */
01047 
01048 /*** EXPERIMENTAL ***
01049 **
01050 ** Register a function to be invoked when a transaction comments.
01051 ** If the invoked function returns non-zero, then the commit becomes a
01052 ** rollback.
01053 */
01054 void *sqlite3_commit_hook(
01055   sqlite3 *db,              /* Attach the hook to this database */
01056   int (*xCallback)(void*),  /* Function to invoke on each commit */
01057   void *pArg                /* Argument to the function */
01058 ){
01059   void *pOld;
01060   sqlite3_mutex_enter(db->mutex);
01061   pOld = db->pCommitArg;
01062   db->xCommitCallback = xCallback;
01063   db->pCommitArg = pArg;
01064   sqlite3_mutex_leave(db->mutex);
01065   return pOld;
01066 }
01067 
01068 /*
01069 ** Register a callback to be invoked each time a row is updated,
01070 ** inserted or deleted using this database connection.
01071 */
01072 void *sqlite3_update_hook(
01073   sqlite3 *db,              /* Attach the hook to this database */
01074   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
01075   void *pArg                /* Argument to the function */
01076 ){
01077   void *pRet;
01078   sqlite3_mutex_enter(db->mutex);
01079   pRet = db->pUpdateArg;
01080   db->xUpdateCallback = xCallback;
01081   db->pUpdateArg = pArg;
01082   sqlite3_mutex_leave(db->mutex);
01083   return pRet;
01084 }
01085 
01086 /*
01087 ** Register a callback to be invoked each time a transaction is rolled
01088 ** back by this database connection.
01089 */
01090 void *sqlite3_rollback_hook(
01091   sqlite3 *db,              /* Attach the hook to this database */
01092   void (*xCallback)(void*), /* Callback function */
01093   void *pArg                /* Argument to the function */
01094 ){
01095   void *pRet;
01096   sqlite3_mutex_enter(db->mutex);
01097   pRet = db->pRollbackArg;
01098   db->xRollbackCallback = xCallback;
01099   db->pRollbackArg = pArg;
01100   sqlite3_mutex_leave(db->mutex);
01101   return pRet;
01102 }
01103 
01104 /*
01105 ** This routine is called to create a connection to a database BTree
01106 ** driver.  If zFilename is the name of a file, then that file is
01107 ** opened and used.  If zFilename is the magic name ":memory:" then
01108 ** the database is stored in memory (and is thus forgotten as soon as
01109 ** the connection is closed.)  If zFilename is NULL then the database
01110 ** is a "virtual" database for transient use only and is deleted as
01111 ** soon as the connection is closed.
01112 **
01113 ** A virtual database can be either a disk file (that is automatically
01114 ** deleted when the file is closed) or it an be held entirely in memory,
01115 ** depending on the values of the SQLITE_TEMP_STORE compile-time macro and the
01116 ** db->temp_store variable, according to the following chart:
01117 **
01118 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
01119 **   -----------------     --------------     ------------------------------
01120 **   0                     any                file
01121 **   1                     1                  file
01122 **   1                     2                  memory
01123 **   1                     0                  file
01124 **   2                     1                  file
01125 **   2                     2                  memory
01126 **   2                     0                  memory
01127 **   3                     any                memory
01128 */
01129 int sqlite3BtreeFactory(
01130   const sqlite3 *db,        /* Main database when opening aux otherwise 0 */
01131   const char *zFilename,    /* Name of the file containing the BTree database */
01132   int omitJournal,          /* if TRUE then do not journal this file */
01133   int nCache,               /* How many pages in the page cache */
01134   int vfsFlags,             /* Flags passed through to vfsOpen */
01135   Btree **ppBtree           /* Pointer to new Btree object written here */
01136 ){
01137   int btFlags = 0;
01138   int rc;
01139   
01140   assert( sqlite3_mutex_held(db->mutex) );
01141   assert( ppBtree != 0);
01142   if( omitJournal ){
01143     btFlags |= BTREE_OMIT_JOURNAL;
01144   }
01145   if( db->flags & SQLITE_NoReadlock ){
01146     btFlags |= BTREE_NO_READLOCK;
01147   }
01148   if( zFilename==0 ){
01149 #if SQLITE_TEMP_STORE==0
01150     /* Do nothing */
01151 #endif
01152 #ifndef SQLITE_OMIT_MEMORYDB
01153 #if SQLITE_TEMP_STORE==1
01154     if( db->temp_store==2 ) zFilename = ":memory:";
01155 #endif
01156 #if SQLITE_TEMP_STORE==2
01157     if( db->temp_store!=1 ) zFilename = ":memory:";
01158 #endif
01159 #if SQLITE_TEMP_STORE==3
01160     zFilename = ":memory:";
01161 #endif
01162 #endif /* SQLITE_OMIT_MEMORYDB */
01163   }
01164 
01165   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
01166     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
01167   }
01168   rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
01169 
01170   /* If the B-Tree was successfully opened, set the pager-cache size to the
01171   ** default value. Except, if the call to BtreeOpen() returned a handle
01172   ** open on an existing shared pager-cache, do not change the pager-cache 
01173   ** size.
01174   */
01175   if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
01176     sqlite3BtreeSetCacheSize(*ppBtree, nCache);
01177   }
01178   return rc;
01179 }
01180 
01181 /*
01182 ** Return UTF-8 encoded English language explanation of the most recent
01183 ** error.
01184 */
01185 EXPORT_C const char *sqlite3_errmsg(sqlite3 *db){
01186   const char *z;
01187   if( !db ){
01188     return sqlite3ErrStr(SQLITE_NOMEM);
01189   }
01190   if( !sqlite3SafetyCheckSickOrOk(db) ){
01191     return sqlite3ErrStr(SQLITE_MISUSE);
01192   }
01193   sqlite3_mutex_enter(db->mutex);
01194   assert( !db->mallocFailed );
01195   z = (char*)sqlite3_value_text(db->pErr);
01196   assert( !db->mallocFailed );
01197   if( z==0 ){
01198     z = sqlite3ErrStr(db->errCode);
01199   }
01200   sqlite3_mutex_leave(db->mutex);
01201   return z;
01202 }
01203 
01204 #ifndef SQLITE_OMIT_UTF16
01205 /*
01206 ** Return UTF-16 encoded English language explanation of the most recent
01207 ** error.
01208 */
01209 const void *sqlite3_errmsg16(sqlite3 *db){
01210   /* Because all the characters in the string are in the unicode
01211   ** range 0x00-0xFF, if we pad the big-endian string with a 
01212   ** zero byte, we can obtain the little-endian string with
01213   ** &big_endian[1].
01214   */
01215   static const char outOfMemBe[] = {
01216     0, 'o', 0, 'u', 0, 't', 0, ' ', 
01217     0, 'o', 0, 'f', 0, ' ', 
01218     0, 'm', 0, 'e', 0, 'm', 0, 'o', 0, 'r', 0, 'y', 0, 0, 0
01219   };
01220   static const char misuseBe [] = {
01221     0, 'l', 0, 'i', 0, 'b', 0, 'r', 0, 'a', 0, 'r', 0, 'y', 0, ' ', 
01222     0, 'r', 0, 'o', 0, 'u', 0, 't', 0, 'i', 0, 'n', 0, 'e', 0, ' ', 
01223     0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ', 
01224     0, 'o', 0, 'u', 0, 't', 0, ' ', 
01225     0, 'o', 0, 'f', 0, ' ', 
01226     0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
01227   };
01228 
01229   const void *z;
01230   if( !db ){
01231     return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
01232   }
01233   if( !sqlite3SafetyCheckSickOrOk(db) ){
01234     return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
01235   }
01236   sqlite3_mutex_enter(db->mutex);
01237   assert( !db->mallocFailed );
01238   z = sqlite3_value_text16(db->pErr);
01239   if( z==0 ){
01240     sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
01241          SQLITE_UTF8, SQLITE_STATIC);
01242     z = sqlite3_value_text16(db->pErr);
01243   }
01244   /* A malloc() may have failed within the call to sqlite3_value_text16()
01245   ** above. If this is the case, then the db->mallocFailed flag needs to
01246   ** be cleared before returning. Do this directly, instead of via
01247   ** sqlite3ApiExit(), to avoid setting the database handle error message.
01248   */
01249   db->mallocFailed = 0;
01250   sqlite3_mutex_leave(db->mutex);
01251   return z;
01252 }
01253 #endif /* SQLITE_OMIT_UTF16 */
01254 
01255 /*
01256 ** Return the most recent error code generated by an SQLite routine. If NULL is
01257 ** passed to this function, we assume a malloc() failed during sqlite3_open().
01258 */
01259 int sqlite3_errcode(sqlite3 *db){
01260   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
01261     return SQLITE_MISUSE;
01262   }
01263   if( !db || db->mallocFailed ){
01264     return SQLITE_NOMEM;
01265   }
01266   return db->errCode & db->errMask;
01267 }
01268 int sqlite3_extended_errcode(sqlite3 *db){
01269   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
01270     return SQLITE_MISUSE;
01271   }
01272   if( !db || db->mallocFailed ){
01273     return SQLITE_NOMEM;
01274   }
01275   return db->errCode;
01276 }
01277 
01278 /*
01279 ** Create a new collating function for database "db".  The name is zName
01280 ** and the encoding is enc.
01281 */
01282 static int createCollation(
01283   sqlite3* db, 
01284   const char *zName, 
01285   int enc, 
01286   void* pCtx,
01287   int(*xCompare)(void*,int,const void*,int,const void*),
01288   void(*xDel)(void*)
01289 ){
01290   CollSeq *pColl;
01291   int enc2;
01292   int nName;
01293   
01294   assert( sqlite3_mutex_held(db->mutex) );
01295 
01296   /* If SQLITE_UTF16 is specified as the encoding type, transform this
01297   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
01298   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
01299   */
01300   enc2 = enc & ~SQLITE_UTF16_ALIGNED;
01301   if( enc2==SQLITE_UTF16 ){
01302     enc2 = SQLITE_UTF16NATIVE;
01303   }
01304   if( (enc2&~3)!=0 ){
01305     return SQLITE_MISUSE;
01306   }
01307 
01308   /* Check if this call is removing or replacing an existing collation 
01309   ** sequence. If so, and there are active VMs, return busy. If there
01310   ** are no active VMs, invalidate any pre-compiled statements.
01311   */
01312   nName = sqlite3Strlen(db, zName);
01313   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 0);
01314   if( pColl && pColl->xCmp ){
01315     if( db->activeVdbeCnt ){
01316       sqlite3Error(db, SQLITE_BUSY, 
01317         "Unable to delete/modify collation sequence due to active statements");
01318       return SQLITE_BUSY;
01319     }
01320     sqlite3ExpirePreparedStatements(db);
01321 
01322     /* If collation sequence pColl was created directly by a call to
01323     ** sqlite3_create_collation, and not generated by synthCollSeq(),
01324     ** then any copies made by synthCollSeq() need to be invalidated.
01325     ** Also, collation destructor - CollSeq.xDel() - function may need
01326     ** to be called.
01327     */ 
01328     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
01329       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
01330       int j;
01331       for(j=0; j<3; j++){
01332         CollSeq *p = &aColl[j];
01333         if( p->enc==pColl->enc ){
01334           if( p->xDel ){
01335             p->xDel(p->pUser);
01336           }
01337           p->xCmp = 0;
01338         }
01339       }
01340     }
01341   }
01342 
01343   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 1);
01344   if( pColl ){
01345     pColl->xCmp = xCompare;
01346     pColl->pUser = pCtx;
01347     pColl->xDel = xDel;
01348     pColl->enc = enc2 | (enc & SQLITE_UTF16_ALIGNED);
01349   }
01350   sqlite3Error(db, SQLITE_OK, 0);
01351   return SQLITE_OK;
01352 }
01353 
01354 
01355 /*
01356 ** This array defines hard upper bounds on limit values.  The
01357 ** initializer must be kept in sync with the SQLITE_LIMIT_*
01358 ** #defines in sqlite3.h.
01359 */
01360 static const int aHardLimit[] = {
01361   SQLITE_MAX_LENGTH,
01362   SQLITE_MAX_SQL_LENGTH,
01363   SQLITE_MAX_COLUMN,
01364   SQLITE_MAX_EXPR_DEPTH,
01365   SQLITE_MAX_COMPOUND_SELECT,
01366   SQLITE_MAX_VDBE_OP,
01367   SQLITE_MAX_FUNCTION_ARG,
01368   SQLITE_MAX_ATTACHED,
01369   SQLITE_MAX_LIKE_PATTERN_LENGTH,
01370   SQLITE_MAX_VARIABLE_NUMBER,
01371 };
01372 
01373 /*
01374 ** Make sure the hard limits are set to reasonable values
01375 */
01376 #if SQLITE_MAX_LENGTH<100
01377 # error SQLITE_MAX_LENGTH must be at least 100
01378 #endif
01379 #if SQLITE_MAX_SQL_LENGTH<100
01380 # error SQLITE_MAX_SQL_LENGTH must be at least 100
01381 #endif
01382 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
01383 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
01384 #endif
01385 #if SQLITE_MAX_COMPOUND_SELECT<2
01386 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
01387 #endif
01388 #if SQLITE_MAX_VDBE_OP<40
01389 # error SQLITE_MAX_VDBE_OP must be at least 40
01390 #endif
01391 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
01392 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
01393 #endif
01394 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
01395 # error SQLITE_MAX_ATTACHED must be between 0 and 30
01396 #endif
01397 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
01398 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
01399 #endif
01400 #if SQLITE_MAX_VARIABLE_NUMBER<1
01401 # error SQLITE_MAX_VARIABLE_NUMBER must be at least 1
01402 #endif
01403 #if SQLITE_MAX_COLUMN>32767
01404 # error SQLITE_MAX_COLUMN must not exceed 32767
01405 #endif
01406 
01407 
01408 /*
01409 ** Change the value of a limit.  Report the old value.
01410 ** If an invalid limit index is supplied, report -1.
01411 ** Make no changes but still report the old value if the
01412 ** new limit is negative.
01413 **
01414 ** A new lower limit does not shrink existing constructs.
01415 ** It merely prevents new constructs that exceed the limit
01416 ** from forming.
01417 */
01418 int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
01419   int oldLimit;
01420   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
01421     return -1;
01422   }
01423   oldLimit = db->aLimit[limitId];
01424   if( newLimit>=0 ){
01425     if( newLimit>aHardLimit[limitId] ){
01426       newLimit = aHardLimit[limitId];
01427     }
01428     db->aLimit[limitId] = newLimit;
01429   }
01430   return oldLimit;
01431 }
01432 
01433 /*
01434 ** This routine does the work of opening a database on behalf of
01435 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
01436 ** is UTF-8 encoded.
01437 */
01438 static int openDatabase(
01439   const char *zFilename, /* Database filename UTF-8 encoded */
01440   sqlite3 **ppDb,        /* OUT: Returned database handle */
01441   unsigned flags,        /* Operational flags */
01442   const char *zVfs       /* Name of the VFS to use */
01443 ){
01444   sqlite3 *db;
01445   int rc;
01446   CollSeq *pColl;
01447   int isThreadsafe;
01448 
01449 #ifndef SQLITE_OMIT_AUTOINIT
01450   rc = sqlite3_initialize();
01451   if( rc ) return rc;
01452 #endif
01453 
01454   if( sqlite3GlobalConfig.bCoreMutex==0 ){
01455     isThreadsafe = 0;
01456   }else if( flags & SQLITE_OPEN_NOMUTEX ){
01457     isThreadsafe = 0;
01458   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
01459     isThreadsafe = 1;
01460   }else{
01461     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
01462   }
01463 
01464   /* Remove harmful bits from the flags parameter */
01465   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
01466                SQLITE_OPEN_MAIN_DB |
01467                SQLITE_OPEN_TEMP_DB | 
01468                SQLITE_OPEN_TRANSIENT_DB | 
01469                SQLITE_OPEN_MAIN_JOURNAL | 
01470                SQLITE_OPEN_TEMP_JOURNAL | 
01471                SQLITE_OPEN_SUBJOURNAL | 
01472                SQLITE_OPEN_MASTER_JOURNAL |
01473                SQLITE_OPEN_NOMUTEX |
01474                SQLITE_OPEN_FULLMUTEX
01475              );
01476 
01477   /* Allocate the sqlite data structure */
01478   db = sqlite3MallocZero( sizeof(sqlite3) );
01479   if( db==0 ) goto opendb_out;
01480   if( isThreadsafe ){
01481     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
01482     if( db->mutex==0 ){
01483       sqlite3_free(db);
01484       db = 0;
01485       goto opendb_out;
01486     }
01487   }
01488   sqlite3_mutex_enter(db->mutex);
01489   db->errMask = 0xff;
01490   db->priorNewRowid = 0;
01491   db->nDb = 2;
01492   db->magic = SQLITE_MAGIC_BUSY;
01493   db->aDb = db->aDbStatic;
01494 
01495   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
01496   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
01497   db->autoCommit = 1;
01498   db->nextAutovac = -1;
01499   db->nextPagesize = 0;
01500   db->flags |= SQLITE_ShortColNames
01501 #if SQLITE_DEFAULT_FILE_FORMAT<4
01502                  | SQLITE_LegacyFileFmt
01503 #endif
01504 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
01505                  | SQLITE_LoadExtension
01506 #endif
01507       ;
01508   sqlite3HashInit(&db->aCollSeq, 0);
01509 #ifndef SQLITE_OMIT_VIRTUALTABLE
01510   sqlite3HashInit(&db->aModule, 0);
01511 #endif
01512 
01513   db->pVfs = sqlite3_vfs_find(zVfs);
01514   if( !db->pVfs ){
01515     rc = SQLITE_ERROR;
01516     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
01517     goto opendb_out;
01518   }
01519 
01520   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
01521   ** and UTF-16, so add a version for each to avoid any unnecessary
01522   ** conversions. The only error that can occur here is a malloc() failure.
01523   */
01524   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
01525   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
01526   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
01527   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
01528   if( db->mallocFailed ){
01529     goto opendb_out;
01530   }
01531   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
01532   assert( db->pDfltColl!=0 );
01533 
01534   /* Also add a UTF-8 case-insensitive collation sequence. */
01535   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
01536 
01537   /* Set flags on the built-in collating sequences */
01538   db->pDfltColl->type = SQLITE_COLL_BINARY;
01539   pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "NOCASE", 6, 0);
01540   if( pColl ){
01541     pColl->type = SQLITE_COLL_NOCASE;
01542   }
01543 
01544   /* Open the backend database driver */
01545   db->openFlags = flags;
01546   rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE, 
01547                            flags | SQLITE_OPEN_MAIN_DB,
01548                            &db->aDb[0].pBt);
01549   if( rc!=SQLITE_OK ){
01550     if( rc==SQLITE_IOERR_NOMEM ){
01551       rc = SQLITE_NOMEM;
01552     }
01553     sqlite3Error(db, rc, 0);
01554     goto opendb_out;
01555   }
01556   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
01557   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
01558 
01559 
01560   /* The default safety_level for the main database is 'full'; for the temp
01561   ** database it is 'NONE'. This matches the pager layer defaults.  
01562   */
01563   db->aDb[0].zName = "main";
01564   db->aDb[0].safety_level = 3;
01565 #ifndef SQLITE_OMIT_TEMPDB
01566   db->aDb[1].zName = "temp";
01567   db->aDb[1].safety_level = 1;
01568 #endif
01569 
01570   db->magic = SQLITE_MAGIC_OPEN;
01571   if( db->mallocFailed ){
01572     goto opendb_out;
01573   }
01574 
01575   /* Register all built-in functions, but do not attempt to read the
01576   ** database schema yet. This is delayed until the first time the database
01577   ** is accessed.
01578   */
01579   sqlite3Error(db, SQLITE_OK, 0);
01580   sqlite3RegisterBuiltinFunctions(db);
01581 
01582   /* Load automatic extensions - extensions that have been registered
01583   ** using the sqlite3_automatic_extension() API.
01584   */
01585   (void)sqlite3AutoLoadExtensions(db);
01586   if( sqlite3_errcode(db)!=SQLITE_OK ){
01587     goto opendb_out;
01588   }
01589 
01590 #ifdef SQLITE_ENABLE_FTS1
01591   if( !db->mallocFailed ){
01592     extern int sqlite3Fts1Init(sqlite3*);
01593     rc = sqlite3Fts1Init(db);
01594   }
01595 #endif
01596 
01597 #ifdef SQLITE_ENABLE_FTS2
01598   if( !db->mallocFailed && rc==SQLITE_OK ){
01599     extern int sqlite3Fts2Init(sqlite3*);
01600     rc = sqlite3Fts2Init(db);
01601   }
01602 #endif
01603 
01604 #ifdef SQLITE_ENABLE_FTS3
01605   if( !db->mallocFailed && rc==SQLITE_OK ){
01606     rc = sqlite3Fts3Init(db);
01607   }
01608 #endif
01609 
01610 #ifdef SQLITE_ENABLE_ICU
01611   if( !db->mallocFailed && rc==SQLITE_OK ){
01612     rc = sqlite3IcuInit(db);
01613   }
01614 #endif
01615 
01616 #ifdef SQLITE_ENABLE_RTREE
01617   if( !db->mallocFailed && rc==SQLITE_OK){
01618     rc = sqlite3RtreeInit(db);
01619   }
01620 #endif
01621 
01622   sqlite3Error(db, rc, 0);
01623 
01624   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
01625   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
01626   ** mode.  Doing nothing at all also makes NORMAL the default.
01627   */
01628 #ifdef SQLITE_DEFAULT_LOCKING_MODE
01629   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
01630   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
01631                           SQLITE_DEFAULT_LOCKING_MODE);
01632 #endif
01633 
01634   /* Enable the lookaside-malloc subsystem */
01635   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
01636                         sqlite3GlobalConfig.nLookaside);
01637 
01638 opendb_out:
01639   if( db ){
01640     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
01641     sqlite3_mutex_leave(db->mutex);
01642   }
01643   rc = sqlite3_errcode(db);
01644   if( rc==SQLITE_NOMEM ){
01645     sqlite3_close(db);
01646     db = 0;
01647   }else if( rc!=SQLITE_OK ){
01648     db->magic = SQLITE_MAGIC_SICK;
01649   }
01650   *ppDb = db;
01651   return sqlite3ApiExit(0, rc);
01652 }
01653 
01654 /*
01655 ** Open a new database handle.
01656 */
01657 EXPORT_C int sqlite3_open(
01658   const char *zFilename, 
01659   sqlite3 **ppDb 
01660 ){
01661   return openDatabase(zFilename, ppDb,
01662                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
01663 }
01664 int sqlite3_open_v2(
01665   const char *filename,   /* Database filename (UTF-8) */
01666   sqlite3 **ppDb,         /* OUT: SQLite db handle */
01667   int flags,              /* Flags */
01668   const char *zVfs        /* Name of VFS module to use */
01669 ){
01670   return openDatabase(filename, ppDb, flags, zVfs);
01671 }
01672 
01673 #ifndef SQLITE_OMIT_UTF16
01674 /*
01675 ** Open a new database handle.
01676 */
01677 int sqlite3_open16(
01678   const void *zFilename, 
01679   sqlite3 **ppDb
01680 ){
01681   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
01682   sqlite3_value *pVal;
01683   int rc;
01684 
01685   assert( zFilename );
01686   assert( ppDb );
01687   *ppDb = 0;
01688 #ifndef SQLITE_OMIT_AUTOINIT
01689   rc = sqlite3_initialize();
01690   if( rc ) return rc;
01691 #endif
01692   pVal = sqlite3ValueNew(0);
01693   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
01694   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
01695   if( zFilename8 ){
01696     rc = openDatabase(zFilename8, ppDb,
01697                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
01698     assert( *ppDb || rc==SQLITE_NOMEM );
01699     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
01700       ENC(*ppDb) = SQLITE_UTF16NATIVE;
01701     }
01702   }else{
01703     rc = SQLITE_NOMEM;
01704   }
01705   sqlite3ValueFree(pVal);
01706 
01707   return sqlite3ApiExit(0, rc);
01708 }
01709 #endif /* SQLITE_OMIT_UTF16 */
01710 
01711 /*
01712 ** Register a new collation sequence with the database handle db.
01713 */
01714 int sqlite3_create_collation(
01715   sqlite3* db, 
01716   const char *zName, 
01717   int enc, 
01718   void* pCtx,
01719   int(*xCompare)(void*,int,const void*,int,const void*)
01720 ){
01721   int rc;
01722   sqlite3_mutex_enter(db->mutex);
01723   assert( !db->mallocFailed );
01724   rc = createCollation(db, zName, enc, pCtx, xCompare, 0);
01725   rc = sqlite3ApiExit(db, rc);
01726   sqlite3_mutex_leave(db->mutex);
01727   return rc;
01728 }
01729 
01730 /*
01731 ** Register a new collation sequence with the database handle db.
01732 */
01733 int sqlite3_create_collation_v2(
01734   sqlite3* db, 
01735   const char *zName, 
01736   int enc, 
01737   void* pCtx,
01738   int(*xCompare)(void*,int,const void*,int,const void*),
01739   void(*xDel)(void*)
01740 ){
01741   int rc;
01742   sqlite3_mutex_enter(db->mutex);
01743   assert( !db->mallocFailed );
01744   rc = createCollation(db, zName, enc, pCtx, xCompare, xDel);
01745   rc = sqlite3ApiExit(db, rc);
01746   sqlite3_mutex_leave(db->mutex);
01747   return rc;
01748 }
01749 
01750 #ifndef SQLITE_OMIT_UTF16
01751 /*
01752 ** Register a new collation sequence with the database handle db.
01753 */
01754 int sqlite3_create_collation16(
01755   sqlite3* db, 
01756   const void *zName,
01757   int enc, 
01758   void* pCtx,
01759   int(*xCompare)(void*,int,const void*,int,const void*)
01760 ){
01761   int rc = SQLITE_OK;
01762   char *zName8;
01763   sqlite3_mutex_enter(db->mutex);
01764   assert( !db->mallocFailed );
01765   zName8 = sqlite3Utf16to8(db, zName, -1);
01766   if( zName8 ){
01767     rc = createCollation(db, zName8, enc, pCtx, xCompare, 0);
01768     sqlite3DbFree(db, zName8);
01769   }
01770   rc = sqlite3ApiExit(db, rc);
01771   sqlite3_mutex_leave(db->mutex);
01772   return rc;
01773 }
01774 #endif /* SQLITE_OMIT_UTF16 */
01775 
01776 /*
01777 ** Register a collation sequence factory callback with the database handle
01778 ** db. Replace any previously installed collation sequence factory.
01779 */
01780 int sqlite3_collation_needed(
01781   sqlite3 *db, 
01782   void *pCollNeededArg, 
01783   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
01784 ){
01785   sqlite3_mutex_enter(db->mutex);
01786   db->xCollNeeded = xCollNeeded;
01787   db->xCollNeeded16 = 0;
01788   db->pCollNeededArg = pCollNeededArg;
01789   sqlite3_mutex_leave(db->mutex);
01790   return SQLITE_OK;
01791 }
01792 
01793 #ifndef SQLITE_OMIT_UTF16
01794 /*
01795 ** Register a collation sequence factory callback with the database handle
01796 ** db. Replace any previously installed collation sequence factory.
01797 */
01798 int sqlite3_collation_needed16(
01799   sqlite3 *db, 
01800   void *pCollNeededArg, 
01801   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
01802 ){
01803   sqlite3_mutex_enter(db->mutex);
01804   db->xCollNeeded = 0;
01805   db->xCollNeeded16 = xCollNeeded16;
01806   db->pCollNeededArg = pCollNeededArg;
01807   sqlite3_mutex_leave(db->mutex);
01808   return SQLITE_OK;
01809 }
01810 #endif /* SQLITE_OMIT_UTF16 */
01811 
01812 #ifndef SQLITE_OMIT_GLOBALRECOVER
01813 #ifndef SQLITE_OMIT_DEPRECATED
01814 /*
01815 ** This function is now an anachronism. It used to be used to recover from a
01816 ** malloc() failure, but SQLite now does this automatically.
01817 */
01818 int sqlite3_global_recover(void){
01819   return SQLITE_OK;
01820 }
01821 #endif
01822 #endif
01823 
01824 /*
01825 ** Test to see whether or not the database connection is in autocommit
01826 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
01827 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
01828 ** by the next COMMIT or ROLLBACK.
01829 **
01830 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
01831 */
01832 int sqlite3_get_autocommit(sqlite3 *db){
01833   return db->autoCommit;
01834 }
01835 
01836 #ifdef SQLITE_DEBUG
01837 /*
01838 ** The following routine is subtituted for constant SQLITE_CORRUPT in
01839 ** debugging builds.  This provides a way to set a breakpoint for when
01840 ** corruption is first detected.
01841 */
01842 int sqlite3Corrupt(void){
01843   return SQLITE_CORRUPT;
01844 }
01845 #endif
01846 
01847 #ifndef SQLITE_OMIT_DEPRECATED
01848 /*
01849 ** This is a convenience routine that makes sure that all thread-specific
01850 ** data for this thread has been deallocated.
01851 **
01852 ** SQLite no longer uses thread-specific data so this routine is now a
01853 ** no-op.  It is retained for historical compatibility.
01854 */
01855 void sqlite3_thread_cleanup(void){
01856 }
01857 #endif
01858 
01859 /*
01860 ** Return meta information about a specific column of a database table.
01861 ** See comment in sqlite3.h (sqlite.h.in) for details.
01862 */
01863 #ifdef SQLITE_ENABLE_COLUMN_METADATA
01864 int sqlite3_table_column_metadata(
01865   sqlite3 *db,                /* Connection handle */
01866   const char *zDbName,        /* Database name or NULL */
01867   const char *zTableName,     /* Table name */
01868   const char *zColumnName,    /* Column name */
01869   char const **pzDataType,    /* OUTPUT: Declared data type */
01870   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
01871   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
01872   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
01873   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
01874 ){
01875   int rc;
01876   char *zErrMsg = 0;
01877   Table *pTab = 0;
01878   Column *pCol = 0;
01879   int iCol;
01880 
01881   char const *zDataType = 0;
01882   char const *zCollSeq = 0;
01883   int notnull = 0;
01884   int primarykey = 0;
01885   int autoinc = 0;
01886 
01887   /* Ensure the database schema has been loaded */
01888   sqlite3_mutex_enter(db->mutex);
01889   (void)sqlite3SafetyOn(db);
01890   sqlite3BtreeEnterAll(db);
01891   rc = sqlite3Init(db, &zErrMsg);
01892   sqlite3BtreeLeaveAll(db);
01893   if( SQLITE_OK!=rc ){
01894     goto error_out;
01895   }
01896 
01897   /* Locate the table in question */
01898   pTab = sqlite3FindTable(db, zTableName, zDbName);
01899   if( !pTab || pTab->pSelect ){
01900     pTab = 0;
01901     goto error_out;
01902   }
01903 
01904   /* Find the column for which info is requested */
01905   if( sqlite3IsRowid(zColumnName) ){
01906     iCol = pTab->iPKey;
01907     if( iCol>=0 ){
01908       pCol = &pTab->aCol[iCol];
01909     }
01910   }else{
01911     for(iCol=0; iCol<pTab->nCol; iCol++){
01912       pCol = &pTab->aCol[iCol];
01913       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
01914         break;
01915       }
01916     }
01917     if( iCol==pTab->nCol ){
01918       pTab = 0;
01919       goto error_out;
01920     }
01921   }
01922 
01923   /* The following block stores the meta information that will be returned
01924   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
01925   ** and autoinc. At this point there are two possibilities:
01926   ** 
01927   **     1. The specified column name was rowid", "oid" or "_rowid_" 
01928   **        and there is no explicitly declared IPK column. 
01929   **
01930   **     2. The table is not a view and the column name identified an 
01931   **        explicitly declared column. Copy meta information from *pCol.
01932   */ 
01933   if( pCol ){
01934     zDataType = pCol->zType;
01935     zCollSeq = pCol->zColl;
01936     notnull = pCol->notNull!=0;
01937     primarykey  = pCol->isPrimKey!=0;
01938     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
01939   }else{
01940     zDataType = "INTEGER";
01941     primarykey = 1;
01942   }
01943   if( !zCollSeq ){
01944     zCollSeq = "BINARY";
01945   }
01946 
01947 error_out:
01948   (void)sqlite3SafetyOff(db);
01949 
01950   /* Whether the function call succeeded or failed, set the output parameters
01951   ** to whatever their local counterparts contain. If an error did occur,
01952   ** this has the effect of zeroing all output parameters.
01953   */
01954   if( pzDataType ) *pzDataType = zDataType;
01955   if( pzCollSeq ) *pzCollSeq = zCollSeq;
01956   if( pNotNull ) *pNotNull = notnull;
01957   if( pPrimaryKey ) *pPrimaryKey = primarykey;
01958   if( pAutoinc ) *pAutoinc = autoinc;
01959 
01960   if( SQLITE_OK==rc && !pTab ){
01961     sqlite3DbFree(db, zErrMsg);
01962     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
01963         zColumnName);
01964     rc = SQLITE_ERROR;
01965   }
01966   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
01967   sqlite3DbFree(db, zErrMsg);
01968   rc = sqlite3ApiExit(db, rc);
01969   sqlite3_mutex_leave(db->mutex);
01970   return rc;
01971 }
01972 #endif
01973 
01974 /*
01975 ** Sleep for a little while.  Return the amount of time slept.
01976 */
01977 int sqlite3_sleep(int ms){
01978   sqlite3_vfs *pVfs;
01979   int rc;
01980   pVfs = sqlite3_vfs_find(0);
01981   if( pVfs==0 ) return 0;
01982 
01983   /* This function works in milliseconds, but the underlying OsSleep() 
01984   ** API uses microseconds. Hence the 1000's.
01985   */
01986   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
01987   return rc;
01988 }
01989 
01990 /*
01991 ** Enable or disable the extended result codes.
01992 */
01993 EXPORT_C int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
01994   sqlite3_mutex_enter(db->mutex);
01995   db->errMask = onoff ? 0xffffffff : 0xff;
01996   sqlite3_mutex_leave(db->mutex);
01997   return SQLITE_OK;
01998 }
01999 
02000 /*
02001 ** Invoke the xFileControl method on a particular database.
02002 */
02003 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
02004   int rc = SQLITE_ERROR;
02005   int iDb;
02006   sqlite3_mutex_enter(db->mutex);
02007   if( zDbName==0 ){
02008     iDb = 0;
02009   }else{
02010     for(iDb=0; iDb<db->nDb; iDb++){
02011       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
02012     }
02013   }
02014   if( iDb<db->nDb ){
02015     Btree *pBtree = db->aDb[iDb].pBt;
02016     if( pBtree ){
02017       Pager *pPager;
02018       sqlite3_file *fd;
02019       sqlite3BtreeEnter(pBtree);
02020       pPager = sqlite3BtreePager(pBtree);
02021       assert( pPager!=0 );
02022       fd = sqlite3PagerFile(pPager);
02023       assert( fd!=0 );
02024       if( fd->pMethods ){
02025         rc = sqlite3OsFileControl(fd, op, pArg);
02026       }
02027       sqlite3BtreeLeave(pBtree);
02028     }
02029   }
02030   sqlite3_mutex_leave(db->mutex);
02031   return rc;   
02032 }
02033 
02034 /*
02035 ** Interface to the testing logic.
02036 */
02037 int sqlite3_test_control(int op, ...){
02038   int rc = 0;
02039 #ifndef SQLITE_OMIT_BUILTIN_TEST
02040   va_list ap;
02041   va_start(ap, op);
02042   switch( op ){
02043 
02044     /*
02045     ** Save the current state of the PRNG.
02046     */
02047     case SQLITE_TESTCTRL_PRNG_SAVE: {
02048       sqlite3PrngSaveState();
02049       break;
02050     }
02051 
02052     /*
02053     ** Restore the state of the PRNG to the last state saved using
02054     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
02055     ** this verb acts like PRNG_RESET.
02056     */
02057     case SQLITE_TESTCTRL_PRNG_RESTORE: {
02058       sqlite3PrngRestoreState();
02059       break;
02060     }
02061 
02062     /*
02063     ** Reset the PRNG back to its uninitialized state.  The next call
02064     ** to sqlite3_randomness() will reseed the PRNG using a single call
02065     ** to the xRandomness method of the default VFS.
02066     */
02067     case SQLITE_TESTCTRL_PRNG_RESET: {
02068       sqlite3PrngResetState();
02069       break;
02070     }
02071 
02072     /*
02073     **  sqlite3_test_control(BITVEC_TEST, size, program)
02074     **
02075     ** Run a test against a Bitvec object of size.  The program argument
02076     ** is an array of integers that defines the test.  Return -1 on a
02077     ** memory allocation error, 0 on success, or non-zero for an error.
02078     ** See the sqlite3BitvecBuiltinTest() for additional information.
02079     */
02080     case SQLITE_TESTCTRL_BITVEC_TEST: {
02081       int sz = va_arg(ap, int);
02082       int *aProg = va_arg(ap, int*);
02083       rc = sqlite3BitvecBuiltinTest(sz, aProg);
02084       break;
02085     }
02086 
02087     /*
02088     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
02089     **
02090     ** Register hooks to call to indicate which malloc() failures 
02091     ** are benign.
02092     */
02093     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
02094       typedef void (*void_function)(void);
02095       void_function xBenignBegin;
02096       void_function xBenignEnd;
02097       xBenignBegin = va_arg(ap, void_function);
02098       xBenignEnd = va_arg(ap, void_function);
02099       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
02100       break;
02101     }
02102   }
02103   va_end(ap);
02104 #endif /* SQLITE_OMIT_BUILTIN_TEST */
02105   return rc;
02106 }

ContextLogger2—ContextLogger2 Logger Daemon Internals—Generated on Mon May 2 13:49:55 2011 by Doxygen 1.6.1