Back to index

lightning-sunbird  0.9+nobinonly
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.339 2006/03/16 16:19:56 drh Exp $
00018 */
00019 #include "sqliteInt.h"
00020 #include "os.h"
00021 #include <ctype.h>
00022 
00023 /*
00024 ** The following constant value is used by the SQLITE_BIGENDIAN and
00025 ** SQLITE_LITTLEENDIAN macros.
00026 */
00027 const int sqlite3one = 1;
00028 
00029 /*
00030 ** The version of the library
00031 */
00032 const char sqlite3_version[] = SQLITE_VERSION;
00033 const char *sqlite3_libversion(void){ return sqlite3_version; }
00034 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
00035 
00036 /*
00037 ** This is the default collating function named "BINARY" which is always
00038 ** available.
00039 */
00040 static int binCollFunc(
00041   void *NotUsed,
00042   int nKey1, const void *pKey1,
00043   int nKey2, const void *pKey2
00044 ){
00045   int rc, n;
00046   n = nKey1<nKey2 ? nKey1 : nKey2;
00047   rc = memcmp(pKey1, pKey2, n);
00048   if( rc==0 ){
00049     rc = nKey1 - nKey2;
00050   }
00051   return rc;
00052 }
00053 
00054 /*
00055 ** Another built-in collating sequence: NOCASE. 
00056 **
00057 ** This collating sequence is intended to be used for "case independant
00058 ** comparison". SQLite's knowledge of upper and lower case equivalents
00059 ** extends only to the 26 characters used in the English language.
00060 **
00061 ** At the moment there is only a UTF-8 implementation.
00062 */
00063 static int nocaseCollatingFunc(
00064   void *NotUsed,
00065   int nKey1, const void *pKey1,
00066   int nKey2, const void *pKey2
00067 ){
00068   int r = sqlite3StrNICmp(
00069       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
00070   if( 0==r ){
00071     r = nKey1-nKey2;
00072   }
00073   return r;
00074 }
00075 
00076 /*
00077 ** Return the ROWID of the most recent insert
00078 */
00079 sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
00080   return db->lastRowid;
00081 }
00082 
00083 /*
00084 ** Return the number of changes in the most recent call to sqlite3_exec().
00085 */
00086 int sqlite3_changes(sqlite3 *db){
00087   return db->nChange;
00088 }
00089 
00090 /*
00091 ** Return the number of changes since the database handle was opened.
00092 */
00093 int sqlite3_total_changes(sqlite3 *db){
00094   return db->nTotalChange;
00095 }
00096 
00097 /*
00098 ** Close an existing SQLite database
00099 */
00100 int sqlite3_close(sqlite3 *db){
00101   HashElem *i;
00102   int j;
00103 
00104   if( !db ){
00105     return SQLITE_OK;
00106   }
00107   if( sqlite3SafetyCheck(db) ){
00108     return SQLITE_MISUSE;
00109   }
00110 
00111 #ifdef SQLITE_SSE
00112   {
00113     extern void sqlite3SseCleanup(sqlite3*);
00114     sqlite3SseCleanup(db);
00115   }
00116 #endif 
00117 
00118   /* If there are any outstanding VMs, return SQLITE_BUSY. */
00119   if( db->pVdbe ){
00120     sqlite3Error(db, SQLITE_BUSY, 
00121         "Unable to close due to unfinalised statements");
00122     return SQLITE_BUSY;
00123   }
00124   assert( !sqlite3SafetyCheck(db) );
00125 
00126   /* FIX ME: db->magic may be set to SQLITE_MAGIC_CLOSED if the database
00127   ** cannot be opened for some reason. So this routine needs to run in
00128   ** that case. But maybe there should be an extra magic value for the
00129   ** "failed to open" state.
00130   */
00131   if( db->magic!=SQLITE_MAGIC_CLOSED && sqlite3SafetyOn(db) ){
00132     /* printf("DID NOT CLOSE\n"); fflush(stdout); */
00133     return SQLITE_ERROR;
00134   }
00135 
00136   for(j=0; j<db->nDb; j++){
00137     struct Db *pDb = &db->aDb[j];
00138     if( pDb->pBt ){
00139       sqlite3BtreeClose(pDb->pBt);
00140       pDb->pBt = 0;
00141       if( j!=1 ){
00142         pDb->pSchema = 0;
00143       }
00144     }
00145   }
00146   sqlite3ResetInternalSchema(db, 0);
00147   assert( db->nDb<=2 );
00148   assert( db->aDb==db->aDbStatic );
00149   for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
00150     FuncDef *pFunc, *pNext;
00151     for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext){
00152       pNext = pFunc->pNext;
00153       sqliteFree(pFunc);
00154     }
00155   }
00156 
00157   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
00158     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
00159     sqliteFree(pColl);
00160   }
00161   sqlite3HashClear(&db->aCollSeq);
00162 
00163   sqlite3HashClear(&db->aFunc);
00164   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
00165   if( db->pErr ){
00166     sqlite3ValueFree(db->pErr);
00167   }
00168 
00169   db->magic = SQLITE_MAGIC_ERROR;
00170 
00171   /* The temp-database schema is allocated differently from the other schema
00172   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
00173   ** So it needs to be freed here. Todo: Why not roll the temp schema into
00174   ** the same sqliteMalloc() as the one that allocates the database 
00175   ** structure?
00176   */
00177   sqliteFree(db->aDb[1].pSchema);
00178   sqliteFree(db);
00179   sqlite3ReleaseThreadData();
00180   return SQLITE_OK;
00181 }
00182 
00183 /*
00184 ** Rollback all database files.
00185 */
00186 void sqlite3RollbackAll(sqlite3 *db){
00187   int i;
00188   int inTrans = 0;
00189   for(i=0; i<db->nDb; i++){
00190     if( db->aDb[i].pBt ){
00191       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
00192         inTrans = 1;
00193       }
00194       sqlite3BtreeRollback(db->aDb[i].pBt);
00195       db->aDb[i].inTrans = 0;
00196     }
00197   }
00198   if( db->flags&SQLITE_InternChanges ){
00199     sqlite3ResetInternalSchema(db, 0);
00200   }
00201 
00202   /* If one has been configured, invoke the rollback-hook callback */
00203   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
00204     db->xRollbackCallback(db->pRollbackArg);
00205   }
00206 }
00207 
00208 /*
00209 ** Return a static string that describes the kind of error specified in the
00210 ** argument.
00211 */
00212 const char *sqlite3ErrStr(int rc){
00213   const char *z;
00214   switch( rc ){
00215     case SQLITE_ROW:
00216     case SQLITE_DONE:
00217     case SQLITE_OK:         z = "not an error";                          break;
00218     case SQLITE_ERROR:      z = "SQL logic error or missing database";   break;
00219     case SQLITE_PERM:       z = "access permission denied";              break;
00220     case SQLITE_ABORT:      z = "callback requested query abort";        break;
00221     case SQLITE_BUSY:       z = "database is locked";                    break;
00222     case SQLITE_LOCKED:     z = "database table is locked";              break;
00223     case SQLITE_NOMEM:      z = "out of memory";                         break;
00224     case SQLITE_READONLY:   z = "attempt to write a readonly database";  break;
00225     case SQLITE_INTERRUPT:  z = "interrupted";                           break;
00226     case SQLITE_IOERR:      z = "disk I/O error";                        break;
00227     case SQLITE_CORRUPT:    z = "database disk image is malformed";      break;
00228     case SQLITE_FULL:       z = "database or disk is full";              break;
00229     case SQLITE_CANTOPEN:   z = "unable to open database file";          break;
00230     case SQLITE_PROTOCOL:   z = "database locking protocol failure";     break;
00231     case SQLITE_EMPTY:      z = "table contains no data";                break;
00232     case SQLITE_SCHEMA:     z = "database schema has changed";           break;
00233     case SQLITE_CONSTRAINT: z = "constraint failed";                     break;
00234     case SQLITE_MISMATCH:   z = "datatype mismatch";                     break;
00235     case SQLITE_MISUSE:     z = "library routine called out of sequence";break;
00236     case SQLITE_NOLFS:      z = "kernel lacks large file support";       break;
00237     case SQLITE_AUTH:       z = "authorization denied";                  break;
00238     case SQLITE_FORMAT:     z = "auxiliary database format error";       break;
00239     case SQLITE_RANGE:      z = "bind or column index out of range";     break;
00240     case SQLITE_NOTADB:     z = "file is encrypted or is not a database";break;
00241     default:                z = "unknown error";                         break;
00242   }
00243   return z;
00244 }
00245 
00246 /*
00247 ** This routine implements a busy callback that sleeps and tries
00248 ** again until a timeout value is reached.  The timeout value is
00249 ** an integer number of milliseconds passed in as the first
00250 ** argument.
00251 */
00252 static int sqliteDefaultBusyCallback(
00253  void *ptr,               /* Database connection */
00254  int count                /* Number of times table has been busy */
00255 ){
00256 #if OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
00257   static const u8 delays[] =
00258      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
00259   static const u8 totals[] =
00260      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
00261 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
00262   int timeout = ((sqlite3 *)ptr)->busyTimeout;
00263   int delay, prior;
00264 
00265   assert( count>=0 );
00266   if( count < NDELAY ){
00267     delay = delays[count];
00268     prior = totals[count];
00269   }else{
00270     delay = delays[NDELAY-1];
00271     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
00272   }
00273   if( prior + delay > timeout ){
00274     delay = timeout - prior;
00275     if( delay<=0 ) return 0;
00276   }
00277   sqlite3OsSleep(delay);
00278   return 1;
00279 #else
00280   int timeout = ((sqlite3 *)ptr)->busyTimeout;
00281   if( (count+1)*1000 > timeout ){
00282     return 0;
00283   }
00284   sqlite3OsSleep(1000);
00285   return 1;
00286 #endif
00287 }
00288 
00289 /*
00290 ** Invoke the given busy handler.
00291 **
00292 ** This routine is called when an operation failed with a lock.
00293 ** If this routine returns non-zero, the lock is retried.  If it
00294 ** returns 0, the operation aborts with an SQLITE_BUSY error.
00295 */
00296 int sqlite3InvokeBusyHandler(BusyHandler *p){
00297   int rc;
00298   if( p==0 || p->xFunc==0 || p->nBusy<0 ) return 0;
00299   rc = p->xFunc(p->pArg, p->nBusy);
00300   if( rc==0 ){
00301     p->nBusy = -1;
00302   }else{
00303     p->nBusy++;
00304   }
00305   return rc; 
00306 }
00307 
00308 /*
00309 ** This routine sets the busy callback for an Sqlite database to the
00310 ** given callback function with the given argument.
00311 */
00312 int sqlite3_busy_handler(
00313   sqlite3 *db,
00314   int (*xBusy)(void*,int),
00315   void *pArg
00316 ){
00317   if( sqlite3SafetyCheck(db) ){
00318     return SQLITE_MISUSE;
00319   }
00320   db->busyHandler.xFunc = xBusy;
00321   db->busyHandler.pArg = pArg;
00322   db->busyHandler.nBusy = 0;
00323   return SQLITE_OK;
00324 }
00325 
00326 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
00327 /*
00328 ** This routine sets the progress callback for an Sqlite database to the
00329 ** given callback function with the given argument. The progress callback will
00330 ** be invoked every nOps opcodes.
00331 */
00332 void sqlite3_progress_handler(
00333   sqlite3 *db, 
00334   int nOps,
00335   int (*xProgress)(void*), 
00336   void *pArg
00337 ){
00338   if( !sqlite3SafetyCheck(db) ){
00339     if( nOps>0 ){
00340       db->xProgress = xProgress;
00341       db->nProgressOps = nOps;
00342       db->pProgressArg = pArg;
00343     }else{
00344       db->xProgress = 0;
00345       db->nProgressOps = 0;
00346       db->pProgressArg = 0;
00347     }
00348   }
00349 }
00350 #endif
00351 
00352 
00353 /*
00354 ** This routine installs a default busy handler that waits for the
00355 ** specified number of milliseconds before returning 0.
00356 */
00357 int sqlite3_busy_timeout(sqlite3 *db, int ms){
00358   if( ms>0 ){
00359     db->busyTimeout = ms;
00360     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
00361   }else{
00362     sqlite3_busy_handler(db, 0, 0);
00363   }
00364   return SQLITE_OK;
00365 }
00366 
00367 /*
00368 ** Cause any pending operation to stop at its earliest opportunity.
00369 */
00370 void sqlite3_interrupt(sqlite3 *db){
00371   if( !sqlite3SafetyCheck(db) ){
00372     db->flags |= SQLITE_Interrupt;
00373   }
00374 }
00375 
00376 /*
00377 ** Windows systems should call this routine to free memory that
00378 ** is returned in the in the errmsg parameter of sqlite3_open() when
00379 ** SQLite is a DLL.  For some reason, it does not work to call free()
00380 ** directly.
00381 **
00382 ** Note that we need to call free() not sqliteFree() here.
00383 */
00384 void sqlite3_free(char *p){ free(p); }
00385 
00386 /*
00387 ** This function is exactly the same as sqlite3_create_function(), except
00388 ** that it is designed to be called by internal code. The difference is
00389 ** that if a malloc() fails in sqlite3_create_function(), an error code
00390 ** is returned and the mallocFailed flag cleared. 
00391 */
00392 int sqlite3CreateFunc(
00393   sqlite3 *db,
00394   const char *zFunctionName,
00395   int nArg,
00396   int enc,
00397   void *pUserData,
00398   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
00399   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
00400   void (*xFinal)(sqlite3_context*)
00401 ){
00402   FuncDef *p;
00403   int nName;
00404 
00405   if( sqlite3SafetyCheck(db) ){
00406     return SQLITE_MISUSE;
00407   }
00408   if( zFunctionName==0 ||
00409       (xFunc && (xFinal || xStep)) || 
00410       (!xFunc && (xFinal && !xStep)) ||
00411       (!xFunc && (!xFinal && xStep)) ||
00412       (nArg<-1 || nArg>127) ||
00413       (255<(nName = strlen(zFunctionName))) ){
00414     return SQLITE_ERROR;
00415   }
00416   
00417 #ifndef SQLITE_OMIT_UTF16
00418   /* If SQLITE_UTF16 is specified as the encoding type, transform this
00419   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
00420   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
00421   **
00422   ** If SQLITE_ANY is specified, add three versions of the function
00423   ** to the hash table.
00424   */
00425   if( enc==SQLITE_UTF16 ){
00426     enc = SQLITE_UTF16NATIVE;
00427   }else if( enc==SQLITE_ANY ){
00428     int rc;
00429     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
00430          pUserData, xFunc, xStep, xFinal);
00431     if( rc!=SQLITE_OK ) return rc;
00432     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
00433         pUserData, xFunc, xStep, xFinal);
00434     if( rc!=SQLITE_OK ) return rc;
00435     enc = SQLITE_UTF16BE;
00436   }
00437 #else
00438   enc = SQLITE_UTF8;
00439 #endif
00440   
00441   /* Check if an existing function is being overridden or deleted. If so,
00442   ** and there are active VMs, then return SQLITE_BUSY. If a function
00443   ** is being overridden/deleted but there are no active VMs, allow the
00444   ** operation to continue but invalidate all precompiled statements.
00445   */
00446   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 0);
00447   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
00448     if( db->activeVdbeCnt ){
00449       sqlite3Error(db, SQLITE_BUSY, 
00450         "Unable to delete/modify user-function due to active statements");
00451       assert( !sqlite3MallocFailed() );
00452       return SQLITE_BUSY;
00453     }else{
00454       sqlite3ExpirePreparedStatements(db);
00455     }
00456   }
00457 
00458   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 1);
00459   if( p ){
00460     p->flags = 0;
00461     p->xFunc = xFunc;
00462     p->xStep = xStep;
00463     p->xFinalize = xFinal;
00464     p->pUserData = pUserData;
00465   }
00466   return SQLITE_OK;
00467 }
00468 
00469 /*
00470 ** Create new user functions.
00471 */
00472 int sqlite3_create_function(
00473   sqlite3 *db,
00474   const char *zFunctionName,
00475   int nArg,
00476   int enc,
00477   void *p,
00478   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
00479   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
00480   void (*xFinal)(sqlite3_context*)
00481 ){
00482   int rc;
00483   assert( !sqlite3MallocFailed() );
00484   rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
00485 
00486   return sqlite3ApiExit(db, rc);
00487 }
00488 
00489 #ifndef SQLITE_OMIT_UTF16
00490 int sqlite3_create_function16(
00491   sqlite3 *db,
00492   const void *zFunctionName,
00493   int nArg,
00494   int eTextRep,
00495   void *p,
00496   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
00497   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
00498   void (*xFinal)(sqlite3_context*)
00499 ){
00500   int rc;
00501   char *zFunc8;
00502   assert( !sqlite3MallocFailed() );
00503 
00504   zFunc8 = sqlite3utf16to8(zFunctionName, -1);
00505   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
00506   sqliteFree(zFunc8);
00507 
00508   return sqlite3ApiExit(db, rc);
00509 }
00510 #endif
00511 
00512 #ifndef SQLITE_OMIT_TRACE
00513 /*
00514 ** Register a trace function.  The pArg from the previously registered trace
00515 ** is returned.  
00516 **
00517 ** A NULL trace function means that no tracing is executes.  A non-NULL
00518 ** trace is a pointer to a function that is invoked at the start of each
00519 ** SQL statement.
00520 */
00521 void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
00522   void *pOld = db->pTraceArg;
00523   db->xTrace = xTrace;
00524   db->pTraceArg = pArg;
00525   return pOld;
00526 }
00527 /*
00528 ** Register a profile function.  The pArg from the previously registered 
00529 ** profile function is returned.  
00530 **
00531 ** A NULL profile function means that no profiling is executes.  A non-NULL
00532 ** profile is a pointer to a function that is invoked at the conclusion of
00533 ** each SQL statement that is run.
00534 */
00535 void *sqlite3_profile(
00536   sqlite3 *db,
00537   void (*xProfile)(void*,const char*,sqlite_uint64),
00538   void *pArg
00539 ){
00540   void *pOld = db->pProfileArg;
00541   db->xProfile = xProfile;
00542   db->pProfileArg = pArg;
00543   return pOld;
00544 }
00545 #endif /* SQLITE_OMIT_TRACE */
00546 
00547 /*** EXPERIMENTAL ***
00548 **
00549 ** Register a function to be invoked when a transaction comments.
00550 ** If the invoked function returns non-zero, then the commit becomes a
00551 ** rollback.
00552 */
00553 void *sqlite3_commit_hook(
00554   sqlite3 *db,              /* Attach the hook to this database */
00555   int (*xCallback)(void*),  /* Function to invoke on each commit */
00556   void *pArg                /* Argument to the function */
00557 ){
00558   void *pOld = db->pCommitArg;
00559   db->xCommitCallback = xCallback;
00560   db->pCommitArg = pArg;
00561   return pOld;
00562 }
00563 
00564 /*
00565 ** Register a callback to be invoked each time a row is updated,
00566 ** inserted or deleted using this database connection.
00567 */
00568 void *sqlite3_update_hook(
00569   sqlite3 *db,              /* Attach the hook to this database */
00570   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
00571   void *pArg                /* Argument to the function */
00572 ){
00573   void *pRet = db->pUpdateArg;
00574   db->xUpdateCallback = xCallback;
00575   db->pUpdateArg = pArg;
00576   return pRet;
00577 }
00578 
00579 /*
00580 ** Register a callback to be invoked each time a transaction is rolled
00581 ** back by this database connection.
00582 */
00583 void *sqlite3_rollback_hook(
00584   sqlite3 *db,              /* Attach the hook to this database */
00585   void (*xCallback)(void*), /* Callback function */
00586   void *pArg                /* Argument to the function */
00587 ){
00588   void *pRet = db->pRollbackArg;
00589   db->xRollbackCallback = xCallback;
00590   db->pRollbackArg = pArg;
00591   return pRet;
00592 }
00593 
00594 /*
00595 ** This routine is called to create a connection to a database BTree
00596 ** driver.  If zFilename is the name of a file, then that file is
00597 ** opened and used.  If zFilename is the magic name ":memory:" then
00598 ** the database is stored in memory (and is thus forgotten as soon as
00599 ** the connection is closed.)  If zFilename is NULL then the database
00600 ** is a "virtual" database for transient use only and is deleted as
00601 ** soon as the connection is closed.
00602 **
00603 ** A virtual database can be either a disk file (that is automatically
00604 ** deleted when the file is closed) or it an be held entirely in memory,
00605 ** depending on the values of the TEMP_STORE compile-time macro and the
00606 ** db->temp_store variable, according to the following chart:
00607 **
00608 **       TEMP_STORE     db->temp_store     Location of temporary database
00609 **       ----------     --------------     ------------------------------
00610 **           0               any             file
00611 **           1                1              file
00612 **           1                2              memory
00613 **           1                0              file
00614 **           2                1              file
00615 **           2                2              memory
00616 **           2                0              memory
00617 **           3               any             memory
00618 */
00619 int sqlite3BtreeFactory(
00620   const sqlite3 *db,        /* Main database when opening aux otherwise 0 */
00621   const char *zFilename,    /* Name of the file containing the BTree database */
00622   int omitJournal,          /* if TRUE then do not journal this file */
00623   int nCache,               /* How many pages in the page cache */
00624   Btree **ppBtree           /* Pointer to new Btree object written here */
00625 ){
00626   int btree_flags = 0;
00627   int rc;
00628   
00629   assert( ppBtree != 0);
00630   if( omitJournal ){
00631     btree_flags |= BTREE_OMIT_JOURNAL;
00632   }
00633   if( db->flags & SQLITE_NoReadlock ){
00634     btree_flags |= BTREE_NO_READLOCK;
00635   }
00636   if( zFilename==0 ){
00637 #if TEMP_STORE==0
00638     /* Do nothing */
00639 #endif
00640 #ifndef SQLITE_OMIT_MEMORYDB
00641 #if TEMP_STORE==1
00642     if( db->temp_store==2 ) zFilename = ":memory:";
00643 #endif
00644 #if TEMP_STORE==2
00645     if( db->temp_store!=1 ) zFilename = ":memory:";
00646 #endif
00647 #if TEMP_STORE==3
00648     zFilename = ":memory:";
00649 #endif
00650 #endif /* SQLITE_OMIT_MEMORYDB */
00651   }
00652 
00653   rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btree_flags);
00654   if( rc==SQLITE_OK ){
00655     sqlite3BtreeSetBusyHandler(*ppBtree, (void*)&db->busyHandler);
00656     sqlite3BtreeSetCacheSize(*ppBtree, nCache);
00657   }
00658   return rc;
00659 }
00660 
00661 /*
00662 ** Return UTF-8 encoded English language explanation of the most recent
00663 ** error.
00664 */
00665 const char *sqlite3_errmsg(sqlite3 *db){
00666   const char *z;
00667   if( !db || sqlite3MallocFailed() ){
00668     return sqlite3ErrStr(SQLITE_NOMEM);
00669   }
00670   if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
00671     return sqlite3ErrStr(SQLITE_MISUSE);
00672   }
00673   z = (char*)sqlite3_value_text(db->pErr);
00674   if( z==0 ){
00675     z = sqlite3ErrStr(db->errCode);
00676   }
00677   return z;
00678 }
00679 
00680 #ifndef SQLITE_OMIT_UTF16
00681 /*
00682 ** Return UTF-16 encoded English language explanation of the most recent
00683 ** error.
00684 */
00685 const void *sqlite3_errmsg16(sqlite3 *db){
00686   /* Because all the characters in the string are in the unicode
00687   ** range 0x00-0xFF, if we pad the big-endian string with a 
00688   ** zero byte, we can obtain the little-endian string with
00689   ** &big_endian[1].
00690   */
00691   static const char outOfMemBe[] = {
00692     0, 'o', 0, 'u', 0, 't', 0, ' ', 
00693     0, 'o', 0, 'f', 0, ' ', 
00694     0, 'm', 0, 'e', 0, 'm', 0, 'o', 0, 'r', 0, 'y', 0, 0, 0
00695   };
00696   static const char misuseBe [] = {
00697     0, 'l', 0, 'i', 0, 'b', 0, 'r', 0, 'a', 0, 'r', 0, 'y', 0, ' ', 
00698     0, 'r', 0, 'o', 0, 'u', 0, 't', 0, 'i', 0, 'n', 0, 'e', 0, ' ', 
00699     0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ', 
00700     0, 'o', 0, 'u', 0, 't', 0, ' ', 
00701     0, 'o', 0, 'f', 0, ' ', 
00702     0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
00703   };
00704 
00705   const void *z;
00706   if( sqlite3MallocFailed() ){
00707     return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
00708   }
00709   if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
00710     return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
00711   }
00712   z = sqlite3_value_text16(db->pErr);
00713   if( z==0 ){
00714     sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
00715          SQLITE_UTF8, SQLITE_STATIC);
00716     z = sqlite3_value_text16(db->pErr);
00717   }
00718   sqlite3ApiExit(0, 0);
00719   return z;
00720 }
00721 #endif /* SQLITE_OMIT_UTF16 */
00722 
00723 /*
00724 ** Return the most recent error code generated by an SQLite routine. If NULL is
00725 ** passed to this function, we assume a malloc() failed during sqlite3_open().
00726 */
00727 int sqlite3_errcode(sqlite3 *db){
00728   if( !db || sqlite3MallocFailed() ){
00729     return SQLITE_NOMEM;
00730   }
00731   if( sqlite3SafetyCheck(db) ){
00732     return SQLITE_MISUSE;
00733   }
00734   return db->errCode;
00735 }
00736 
00737 /*
00738 ** Create a new collating function for database "db".  The name is zName
00739 ** and the encoding is enc.
00740 */
00741 static int createCollation(
00742   sqlite3* db, 
00743   const char *zName, 
00744   int enc, 
00745   void* pCtx,
00746   int(*xCompare)(void*,int,const void*,int,const void*)
00747 ){
00748   CollSeq *pColl;
00749   int enc2;
00750   
00751   if( sqlite3SafetyCheck(db) ){
00752     return SQLITE_MISUSE;
00753   }
00754 
00755   /* If SQLITE_UTF16 is specified as the encoding type, transform this
00756   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
00757   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
00758   */
00759   enc2 = enc & ~SQLITE_UTF16_ALIGNED;
00760   if( enc2==SQLITE_UTF16 ){
00761     enc2 = SQLITE_UTF16NATIVE;
00762   }
00763 
00764   if( (enc2&~3)!=0 ){
00765     sqlite3Error(db, SQLITE_ERROR, "unknown encoding");
00766     return SQLITE_ERROR;
00767   }
00768 
00769   /* Check if this call is removing or replacing an existing collation 
00770   ** sequence. If so, and there are active VMs, return busy. If there
00771   ** are no active VMs, invalidate any pre-compiled statements.
00772   */
00773   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, strlen(zName), 0);
00774   if( pColl && pColl->xCmp ){
00775     if( db->activeVdbeCnt ){
00776       sqlite3Error(db, SQLITE_BUSY, 
00777         "Unable to delete/modify collation sequence due to active statements");
00778       return SQLITE_BUSY;
00779     }
00780     sqlite3ExpirePreparedStatements(db);
00781   }
00782 
00783   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, strlen(zName), 1);
00784   if( pColl ){
00785     pColl->xCmp = xCompare;
00786     pColl->pUser = pCtx;
00787     pColl->enc = enc2 | (enc & SQLITE_UTF16_ALIGNED);
00788   }
00789   sqlite3Error(db, SQLITE_OK, 0);
00790   return SQLITE_OK;
00791 }
00792 
00793 
00794 /*
00795 ** This routine does the work of opening a database on behalf of
00796 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
00797 ** is UTF-8 encoded.
00798 */
00799 static int openDatabase(
00800   const char *zFilename, /* Database filename UTF-8 encoded */
00801   sqlite3 **ppDb         /* OUT: Returned database handle */
00802 ){
00803   sqlite3 *db;
00804   int rc;
00805   CollSeq *pColl;
00806 
00807   assert( !sqlite3MallocFailed() );
00808 
00809   /* Allocate the sqlite data structure */
00810   db = sqliteMalloc( sizeof(sqlite3) );
00811   if( db==0 ) goto opendb_out;
00812   db->priorNewRowid = 0;
00813   db->magic = SQLITE_MAGIC_BUSY;
00814   db->nDb = 2;
00815   db->aDb = db->aDbStatic;
00816   db->autoCommit = 1;
00817   db->flags |= SQLITE_ShortColNames;
00818   sqlite3HashInit(&db->aFunc, SQLITE_HASH_STRING, 0);
00819   sqlite3HashInit(&db->aCollSeq, SQLITE_HASH_STRING, 0);
00820 
00821   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
00822   ** and UTF-16, so add a version for each to avoid any unnecessary
00823   ** conversions. The only error that can occur here is a malloc() failure.
00824   */
00825   if( createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc) ||
00826       createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc) ||
00827       createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc) ||
00828       (db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0))==0 
00829   ){
00830     assert( sqlite3MallocFailed() );
00831     db->magic = SQLITE_MAGIC_CLOSED;
00832     goto opendb_out;
00833   }
00834 
00835   /* Also add a UTF-8 case-insensitive collation sequence. */
00836   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc);
00837 
00838   /* Set flags on the built-in collating sequences */
00839   db->pDfltColl->type = SQLITE_COLL_BINARY;
00840   pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "NOCASE", 6, 0);
00841   if( pColl ){
00842     pColl->type = SQLITE_COLL_NOCASE;
00843   }
00844 
00845   /* Open the backend database driver */
00846   rc = sqlite3BtreeFactory(db, zFilename, 0, MAX_PAGES, &db->aDb[0].pBt);
00847   if( rc!=SQLITE_OK ){
00848     sqlite3Error(db, rc, 0);
00849     db->magic = SQLITE_MAGIC_CLOSED;
00850     goto opendb_out;
00851   }
00852   db->aDb[0].pSchema = sqlite3SchemaGet(db->aDb[0].pBt);
00853   db->aDb[1].pSchema = sqlite3SchemaGet(0);
00854   if( db->aDb[0].pSchema ){
00855     ENC(db) = SQLITE_UTF8;
00856   }
00857 
00858 
00859   /* The default safety_level for the main database is 'full'; for the temp
00860   ** database it is 'NONE'. This matches the pager layer defaults.  
00861   */
00862   db->aDb[0].zName = "main";
00863   db->aDb[0].safety_level = 3;
00864 #ifndef SQLITE_OMIT_TEMPDB
00865   db->aDb[1].zName = "temp";
00866   db->aDb[1].safety_level = 1;
00867 #endif
00868 
00869   /* Register all built-in functions, but do not attempt to read the
00870   ** database schema yet. This is delayed until the first time the database
00871   ** is accessed.
00872   */
00873   if( !sqlite3MallocFailed() ){
00874     sqlite3RegisterBuiltinFunctions(db);
00875     sqlite3Error(db, SQLITE_OK, 0);
00876   }
00877   db->magic = SQLITE_MAGIC_OPEN;
00878 
00879 opendb_out:
00880   if( SQLITE_NOMEM==(rc = sqlite3_errcode(db)) ){
00881     sqlite3_close(db);
00882     db = 0;
00883   }
00884   *ppDb = db;
00885   return sqlite3ApiExit(0, rc);
00886 }
00887 
00888 /*
00889 ** Open a new database handle.
00890 */
00891 int sqlite3_open(
00892   const char *zFilename, 
00893   sqlite3 **ppDb 
00894 ){
00895   return openDatabase(zFilename, ppDb);
00896 }
00897 
00898 #ifndef SQLITE_OMIT_UTF16
00899 /*
00900 ** Open a new database handle.
00901 */
00902 int sqlite3_open16(
00903   const void *zFilename, 
00904   sqlite3 **ppDb
00905 ){
00906   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
00907   int rc = SQLITE_OK;
00908   sqlite3_value *pVal;
00909 
00910   assert( zFilename );
00911   assert( ppDb );
00912   *ppDb = 0;
00913   pVal = sqlite3ValueNew();
00914   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
00915   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
00916   if( zFilename8 ){
00917     rc = openDatabase(zFilename8, ppDb);
00918     if( rc==SQLITE_OK && *ppDb ){
00919       rc = sqlite3_exec(*ppDb, "PRAGMA encoding = 'UTF-16'", 0, 0, 0);
00920       if( rc!=SQLITE_OK ){
00921         sqlite3_close(*ppDb);
00922         *ppDb = 0;
00923       }
00924     }
00925   }
00926   sqlite3ValueFree(pVal);
00927 
00928   return sqlite3ApiExit(0, rc);
00929 }
00930 #endif /* SQLITE_OMIT_UTF16 */
00931 
00932 /*
00933 ** The following routine destroys a virtual machine that is created by
00934 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
00935 ** success/failure code that describes the result of executing the virtual
00936 ** machine.
00937 **
00938 ** This routine sets the error code and string returned by
00939 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
00940 */
00941 int sqlite3_finalize(sqlite3_stmt *pStmt){
00942   int rc;
00943   if( pStmt==0 ){
00944     rc = SQLITE_OK;
00945   }else{
00946     rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
00947   }
00948   return rc;
00949 }
00950 
00951 /*
00952 ** Terminate the current execution of an SQL statement and reset it
00953 ** back to its starting state so that it can be reused. A success code from
00954 ** the prior execution is returned.
00955 **
00956 ** This routine sets the error code and string returned by
00957 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
00958 */
00959 int sqlite3_reset(sqlite3_stmt *pStmt){
00960   int rc;
00961   if( pStmt==0 ){
00962     rc = SQLITE_OK;
00963   }else{
00964     rc = sqlite3VdbeReset((Vdbe*)pStmt);
00965     sqlite3VdbeMakeReady((Vdbe*)pStmt, -1, 0, 0, 0);
00966   }
00967   return rc;
00968 }
00969 
00970 /*
00971 ** Register a new collation sequence with the database handle db.
00972 */
00973 int sqlite3_create_collation(
00974   sqlite3* db, 
00975   const char *zName, 
00976   int enc, 
00977   void* pCtx,
00978   int(*xCompare)(void*,int,const void*,int,const void*)
00979 ){
00980   int rc;
00981   assert( !sqlite3MallocFailed() );
00982   rc = createCollation(db, zName, enc, pCtx, xCompare);
00983   return sqlite3ApiExit(db, rc);
00984 }
00985 
00986 #ifndef SQLITE_OMIT_UTF16
00987 /*
00988 ** Register a new collation sequence with the database handle db.
00989 */
00990 int sqlite3_create_collation16(
00991   sqlite3* db, 
00992   const char *zName, 
00993   int enc, 
00994   void* pCtx,
00995   int(*xCompare)(void*,int,const void*,int,const void*)
00996 ){
00997   int rc = SQLITE_OK;
00998   char *zName8; 
00999   assert( !sqlite3MallocFailed() );
01000   zName8 = sqlite3utf16to8(zName, -1);
01001   if( zName8 ){
01002     rc = createCollation(db, zName8, enc, pCtx, xCompare);
01003     sqliteFree(zName8);
01004   }
01005   return sqlite3ApiExit(db, rc);
01006 }
01007 #endif /* SQLITE_OMIT_UTF16 */
01008 
01009 /*
01010 ** Register a collation sequence factory callback with the database handle
01011 ** db. Replace any previously installed collation sequence factory.
01012 */
01013 int sqlite3_collation_needed(
01014   sqlite3 *db, 
01015   void *pCollNeededArg, 
01016   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
01017 ){
01018   if( sqlite3SafetyCheck(db) ){
01019     return SQLITE_MISUSE;
01020   }
01021   db->xCollNeeded = xCollNeeded;
01022   db->xCollNeeded16 = 0;
01023   db->pCollNeededArg = pCollNeededArg;
01024   return SQLITE_OK;
01025 }
01026 
01027 #ifndef SQLITE_OMIT_UTF16
01028 /*
01029 ** Register a collation sequence factory callback with the database handle
01030 ** db. Replace any previously installed collation sequence factory.
01031 */
01032 int sqlite3_collation_needed16(
01033   sqlite3 *db, 
01034   void *pCollNeededArg, 
01035   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
01036 ){
01037   if( sqlite3SafetyCheck(db) ){
01038     return SQLITE_MISUSE;
01039   }
01040   db->xCollNeeded = 0;
01041   db->xCollNeeded16 = xCollNeeded16;
01042   db->pCollNeededArg = pCollNeededArg;
01043   return SQLITE_OK;
01044 }
01045 #endif /* SQLITE_OMIT_UTF16 */
01046 
01047 #ifndef SQLITE_OMIT_GLOBALRECOVER
01048 /*
01049 ** This function is now an anachronism. It used to be used to recover from a
01050 ** malloc() failure, but SQLite now does this automatically.
01051 */
01052 int sqlite3_global_recover(){
01053   return SQLITE_OK;
01054 }
01055 #endif
01056 
01057 /*
01058 ** Test to see whether or not the database connection is in autocommit
01059 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
01060 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
01061 ** by the next COMMIT or ROLLBACK.
01062 **
01063 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
01064 */
01065 int sqlite3_get_autocommit(sqlite3 *db){
01066   return db->autoCommit;
01067 }
01068 
01069 #ifdef SQLITE_DEBUG
01070 /*
01071 ** The following routine is subtituted for constant SQLITE_CORRUPT in
01072 ** debugging builds.  This provides a way to set a breakpoint for when
01073 ** corruption is first detected.
01074 */
01075 int sqlite3Corrupt(void){
01076   return SQLITE_CORRUPT;
01077 }
01078 #endif
01079 
01080 
01081 #ifndef SQLITE_OMIT_SHARED_CACHE
01082 /*
01083 ** Enable or disable the shared pager and schema features for the
01084 ** current thread.
01085 **
01086 ** This routine should only be called when there are no open
01087 ** database connections.
01088 */
01089 int sqlite3_enable_shared_cache(int enable){
01090   ThreadData *pTd = sqlite3ThreadData();
01091   if( pTd ){
01092     /* It is only legal to call sqlite3_enable_shared_cache() when there
01093     ** are no currently open b-trees that were opened by the calling thread.
01094     ** This condition is only easy to detect if the shared-cache were 
01095     ** previously enabled (and is being disabled). 
01096     */
01097     if( pTd->pBtree && !enable ){
01098       assert( pTd->useSharedData );
01099       return SQLITE_MISUSE;
01100     }
01101 
01102     pTd->useSharedData = enable;
01103     sqlite3ReleaseThreadData();
01104   }
01105   return sqlite3ApiExit(0, SQLITE_OK);
01106 }
01107 #endif
01108 
01109 /*
01110 ** This is a convenience routine that makes sure that all thread-specific
01111 ** data for this thread has been deallocated.
01112 */
01113 void sqlite3_thread_cleanup(void){
01114   ThreadData *pTd = sqlite3OsThreadSpecificData(0);
01115   if( pTd ){
01116     memset(pTd, 0, sizeof(*pTd));
01117     sqlite3OsThreadSpecificData(-1);
01118   }
01119 }
01120 
01121 /*
01122 ** Return meta information about a specific column of a database table.
01123 ** See comment in sqlite3.h (sqlite.h.in) for details.
01124 */
01125 #ifdef SQLITE_ENABLE_COLUMN_METADATA
01126 int sqlite3_table_column_metadata(
01127   sqlite3 *db,                /* Connection handle */
01128   const char *zDbName,        /* Database name or NULL */
01129   const char *zTableName,     /* Table name */
01130   const char *zColumnName,    /* Column name */
01131   char const **pzDataType,    /* OUTPUT: Declared data type */
01132   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
01133   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
01134   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
01135   int *pAutoinc               /* OUTPUT: True if colums is auto-increment */
01136 ){
01137   int rc;
01138   char *zErrMsg = 0;
01139   Table *pTab = 0;
01140   Column *pCol = 0;
01141   int iCol;
01142 
01143   char const *zDataType = 0;
01144   char const *zCollSeq = 0;
01145   int notnull = 0;
01146   int primarykey = 0;
01147   int autoinc = 0;
01148 
01149   /* Ensure the database schema has been loaded */
01150   if( sqlite3SafetyOn(db) ){
01151     return SQLITE_MISUSE;
01152   }
01153   rc = sqlite3Init(db, &zErrMsg);
01154   if( SQLITE_OK!=rc ){
01155     goto error_out;
01156   }
01157 
01158   /* Locate the table in question */
01159   pTab = sqlite3FindTable(db, zTableName, zDbName);
01160   if( !pTab || pTab->pSelect ){
01161     pTab = 0;
01162     goto error_out;
01163   }
01164 
01165   /* Find the column for which info is requested */
01166   if( sqlite3IsRowid(zColumnName) ){
01167     iCol = pTab->iPKey;
01168     if( iCol>=0 ){
01169       pCol = &pTab->aCol[iCol];
01170     }
01171   }else{
01172     for(iCol=0; iCol<pTab->nCol; iCol++){
01173       pCol = &pTab->aCol[iCol];
01174       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
01175         break;
01176       }
01177     }
01178     if( iCol==pTab->nCol ){
01179       pTab = 0;
01180       goto error_out;
01181     }
01182   }
01183 
01184   /* The following block stores the meta information that will be returned
01185   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
01186   ** and autoinc. At this point there are two possibilities:
01187   ** 
01188   **     1. The specified column name was rowid", "oid" or "_rowid_" 
01189   **        and there is no explicitly declared IPK column. 
01190   **
01191   **     2. The table is not a view and the column name identified an 
01192   **        explicitly declared column. Copy meta information from *pCol.
01193   */ 
01194   if( pCol ){
01195     zDataType = pCol->zType;
01196     zCollSeq = pCol->zColl;
01197     notnull = (pCol->notNull?1:0);
01198     primarykey  = (pCol->isPrimKey?1:0);
01199     autoinc = ((pTab->iPKey==iCol && pTab->autoInc)?1:0);
01200   }else{
01201     zDataType = "INTEGER";
01202     primarykey = 1;
01203   }
01204   if( !zCollSeq ){
01205     zCollSeq = "BINARY";
01206   }
01207 
01208 error_out:
01209   if( sqlite3SafetyOff(db) ){
01210     rc = SQLITE_MISUSE;
01211   }
01212 
01213   /* Whether the function call succeeded or failed, set the output parameters
01214   ** to whatever their local counterparts contain. If an error did occur,
01215   ** this has the effect of zeroing all output parameters.
01216   */
01217   if( pzDataType ) *pzDataType = zDataType;
01218   if( pzCollSeq ) *pzCollSeq = zCollSeq;
01219   if( pNotNull ) *pNotNull = notnull;
01220   if( pPrimaryKey ) *pPrimaryKey = primarykey;
01221   if( pAutoinc ) *pAutoinc = autoinc;
01222 
01223   if( SQLITE_OK==rc && !pTab ){
01224     sqlite3SetString(&zErrMsg, "no such table column: ", zTableName, ".", 
01225         zColumnName, 0);
01226     rc = SQLITE_ERROR;
01227   }
01228   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
01229   sqliteFree(zErrMsg);
01230   return sqlite3ApiExit(db, rc);
01231 }
01232 #endif