⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 main.c

📁 sqlite 嵌入式数据库的源码
💻 C
📖 第 1 页 / 共 2 页
字号:
/*** 2001 September 15**** The author disclaims copyright to this source code.  In place of** a legal notice, here is a blessing:****    May you do good and not evil.**    May you find forgiveness for yourself and forgive others.**    May you share freely, never taking more than you give.***************************************************************************** Main file for the SQLite library.  The routines in this file** implement the programmer interface to the library.  Routines in** other files are for internal use by SQLite and should not be** accessed by users of the library.**** $Id: main.c,v 1.293 2005/05/26 16:23:34 drh Exp $*/#include "sqliteInt.h"#include "os.h"#include <ctype.h>/*** The following constant value is used by the SQLITE_BIGENDIAN and** SQLITE_LITTLEENDIAN macros.*/const int sqlite3one = 1;#ifndef SQLITE_OMIT_GLOBALRECOVER/*** Linked list of all open database handles. This is used by the ** sqlite3_global_recover() function. Entries are added to the list** by openDatabase() and removed by sqlite3_close().*/static sqlite3 *pDbList = 0;#endif#ifndef SQLITE_OMIT_UTF16/* ** Return the transient sqlite3_value object used for encoding conversions** during SQL compilation.*/sqlite3_value *sqlite3GetTransientValue(sqlite3 *db){  if( !db->pValue ){    db->pValue = sqlite3ValueNew();  }  return db->pValue;}#endif/*** The version of the library*/const char rcsid3[] = "@(#) \044Id: SQLite version " SQLITE_VERSION " $";const char sqlite3_version[] = SQLITE_VERSION;const char *sqlite3_libversion(void){ return sqlite3_version; }int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }/*** This is the default collating function named "BINARY" which is always** available.*/static int binCollFunc(  void *NotUsed,  int nKey1, const void *pKey1,  int nKey2, const void *pKey2){  int rc, n;  n = nKey1<nKey2 ? nKey1 : nKey2;  rc = memcmp(pKey1, pKey2, n);  if( rc==0 ){    rc = nKey1 - nKey2;  }  return rc;}/*** Another built-in collating sequence: NOCASE. **** This collating sequence is intended to be used for "case independant** comparison". SQLite's knowledge of upper and lower case equivalents** extends only to the 26 characters used in the English language.**** At the moment there is only a UTF-8 implementation.*/static int nocaseCollatingFunc(  void *NotUsed,  int nKey1, const void *pKey1,  int nKey2, const void *pKey2){  int r = sqlite3StrNICmp(      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);  if( 0==r ){    r = nKey1-nKey2;  }  return r;}/*** Return the ROWID of the most recent insert*/sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){  return db->lastRowid;}/*** Return the number of changes in the most recent call to sqlite3_exec().*/int sqlite3_changes(sqlite3 *db){  return db->nChange;}/*** Return the number of changes since the database handle was opened.*/int sqlite3_total_changes(sqlite3 *db){  return db->nTotalChange;}/*** Close an existing SQLite database*/int sqlite3_close(sqlite3 *db){  HashElem *i;  int j;  if( !db ){    return SQLITE_OK;  }  if( sqlite3SafetyCheck(db) ){    return SQLITE_MISUSE;  }#ifdef SQLITE_SSE  sqlite3_finalize(db->pFetch);#endif   /* If there are any outstanding VMs, return SQLITE_BUSY. */  if( db->pVdbe ){    sqlite3Error(db, SQLITE_BUSY,         "Unable to close due to unfinalised statements");    return SQLITE_BUSY;  }  assert( !sqlite3SafetyCheck(db) );  /* FIX ME: db->magic may be set to SQLITE_MAGIC_CLOSED if the database  ** cannot be opened for some reason. So this routine needs to run in  ** that case. But maybe there should be an extra magic value for the  ** "failed to open" state.  */  if( db->magic!=SQLITE_MAGIC_CLOSED && sqlite3SafetyOn(db) ){    /* printf("DID NOT CLOSE\n"); fflush(stdout); */    return SQLITE_ERROR;  }  for(j=0; j<db->nDb; j++){    struct Db *pDb = &db->aDb[j];    if( pDb->pBt ){      sqlite3BtreeClose(pDb->pBt);      pDb->pBt = 0;    }  }  sqlite3ResetInternalSchema(db, 0);  assert( db->nDb<=2 );  assert( db->aDb==db->aDbStatic );  for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){    FuncDef *pFunc, *pNext;    for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext){      pNext = pFunc->pNext;      sqliteFree(pFunc);    }  }  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){    CollSeq *pColl = (CollSeq *)sqliteHashData(i);    sqliteFree(pColl);  }  sqlite3HashClear(&db->aCollSeq);  sqlite3HashClear(&db->aFunc);  sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */  if( db->pValue ){    sqlite3ValueFree(db->pValue);  }  if( db->pErr ){    sqlite3ValueFree(db->pErr);  }#ifndef SQLITE_OMIT_GLOBALRECOVER  {    sqlite3 *pPrev;    sqlite3OsEnterMutex();    pPrev = pDbList;    while( pPrev && pPrev->pNext!=db ){      pPrev = pPrev->pNext;    }    if( pPrev ){      pPrev->pNext = db->pNext;    }else{      assert( pDbList==db );      pDbList = db->pNext;    }    sqlite3OsLeaveMutex();  }#endif  db->magic = SQLITE_MAGIC_ERROR;  sqliteFree(db);  return SQLITE_OK;}/*** Rollback all database files.*/void sqlite3RollbackAll(sqlite3 *db){  int i;  for(i=0; i<db->nDb; i++){    if( db->aDb[i].pBt ){      sqlite3BtreeRollback(db->aDb[i].pBt);      db->aDb[i].inTrans = 0;    }  }  sqlite3ResetInternalSchema(db, 0);}/*** Return a static string that describes the kind of error specified in the** argument.*/const char *sqlite3ErrStr(int rc){  const char *z;  switch( rc ){    case SQLITE_ROW:    case SQLITE_DONE:    case SQLITE_OK:         z = "not an error";                          break;    case SQLITE_ERROR:      z = "SQL logic error or missing database";   break;    case SQLITE_INTERNAL:   z = "internal SQLite implementation flaw";   break;    case SQLITE_PERM:       z = "access permission denied";              break;    case SQLITE_ABORT:      z = "callback requested query abort";        break;    case SQLITE_BUSY:       z = "database is locked";                    break;    case SQLITE_LOCKED:     z = "database table is locked";              break;    case SQLITE_NOMEM:      z = "out of memory";                         break;    case SQLITE_READONLY:   z = "attempt to write a readonly database";  break;    case SQLITE_INTERRUPT:  z = "interrupted";                           break;    case SQLITE_IOERR:      z = "disk I/O error";                        break;    case SQLITE_CORRUPT:    z = "database disk image is malformed";      break;    case SQLITE_NOTFOUND:   z = "table or record not found";             break;    case SQLITE_FULL:       z = "database is full";                      break;    case SQLITE_CANTOPEN:   z = "unable to open database file";          break;    case SQLITE_PROTOCOL:   z = "database locking protocol failure";     break;    case SQLITE_EMPTY:      z = "table contains no data";                break;    case SQLITE_SCHEMA:     z = "database schema has changed";           break;    case SQLITE_TOOBIG:     z = "too much data for one table row";       break;    case SQLITE_CONSTRAINT: z = "constraint failed";                     break;    case SQLITE_MISMATCH:   z = "datatype mismatch";                     break;    case SQLITE_MISUSE:     z = "library routine called out of sequence";break;    case SQLITE_NOLFS:      z = "kernel lacks large file support";       break;    case SQLITE_AUTH:       z = "authorization denied";                  break;    case SQLITE_FORMAT:     z = "auxiliary database format error";       break;    case SQLITE_RANGE:      z = "bind or column index out of range";     break;    case SQLITE_NOTADB:     z = "file is encrypted or is not a database";break;    default:                z = "unknown error";                         break;  }  return z;}/*** This routine implements a busy callback that sleeps and tries** again until a timeout value is reached.  The timeout value is** an integer number of milliseconds passed in as the first** argument.*/static int sqliteDefaultBusyCallback( void *ptr,               /* Database connection */ int count                /* Number of times table has been busy */){#if SQLITE_MIN_SLEEP_MS==1  static const u8 delays[] =     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };  static const u8 totals[] =     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };# define NDELAY (sizeof(delays)/sizeof(delays[0]))  int timeout = ((sqlite3 *)ptr)->busyTimeout;  int delay, prior;  assert( count>=0 );  if( count < NDELAY ){    delay = delays[count];    prior = totals[count];  }else{    delay = delays[NDELAY-1];    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));  }  if( prior + delay > timeout ){    delay = timeout - prior;    if( delay<=0 ) return 0;  }  sqlite3OsSleep(delay);  return 1;#else  int timeout = (int)Timeout;  if( (count+1)*1000 > timeout ){    return 0;  }  sqlite3OsSleep(1000);  return 1;#endif}/*** This routine sets the busy callback for an Sqlite database to the** given callback function with the given argument.*/int sqlite3_busy_handler(  sqlite3 *db,  int (*xBusy)(void*,int),  void *pArg){  if( sqlite3SafetyCheck(db) ){    return SQLITE_MISUSE;  }  db->busyHandler.xFunc = xBusy;  db->busyHandler.pArg = pArg;  return SQLITE_OK;}#ifndef SQLITE_OMIT_PROGRESS_CALLBACK/*** This routine sets the progress callback for an Sqlite database to the** given callback function with the given argument. The progress callback will** be invoked every nOps opcodes.*/void sqlite3_progress_handler(  sqlite3 *db,   int nOps,  int (*xProgress)(void*),   void *pArg){  if( !sqlite3SafetyCheck(db) ){    if( nOps>0 ){      db->xProgress = xProgress;      db->nProgressOps = nOps;      db->pProgressArg = pArg;    }else{      db->xProgress = 0;      db->nProgressOps = 0;      db->pProgressArg = 0;    }  }}#endif/*** This routine installs a default busy handler that waits for the** specified number of milliseconds before returning 0.*/int sqlite3_busy_timeout(sqlite3 *db, int ms){  if( ms>0 ){    db->busyTimeout = ms;    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);  }else{    sqlite3_busy_handler(db, 0, 0);  }  return SQLITE_OK;}/*** Cause any pending operation to stop at its earliest opportunity.*/void sqlite3_interrupt(sqlite3 *db){  if( !sqlite3SafetyCheck(db) ){    db->flags |= SQLITE_Interrupt;  }}/*** Windows systems should call this routine to free memory that** is returned in the in the errmsg parameter of sqlite3_open() when** SQLite is a DLL.  For some reason, it does not work to call free()** directly.**** Note that we need to call free() not sqliteFree() here.*/void sqlite3_free(char *p){ free(p); }/*** Create new user functions.*/int sqlite3_create_function(  sqlite3 *db,  const char *zFunctionName,  int nArg,  int enc,  void *pUserData,  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),  void (*xStep)(sqlite3_context*,int,sqlite3_value **),  void (*xFinal)(sqlite3_context*)){  FuncDef *p;  int nName;  if( sqlite3SafetyCheck(db) ){    return SQLITE_MISUSE;  }  if( zFunctionName==0 ||      (xFunc && (xFinal || xStep)) ||       (!xFunc && (xFinal && !xStep)) ||      (!xFunc && (!xFinal && xStep)) ||      (nArg<-1 || nArg>127) ||      (255<(nName = strlen(zFunctionName))) ){    return SQLITE_ERROR;  }  #ifndef SQLITE_OMIT_UTF16  /* If SQLITE_UTF16 is specified as the encoding type, transform this  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.  **  ** If SQLITE_ANY is specified, add three versions of the function  ** to the hash table.  */  if( enc==SQLITE_UTF16 ){    enc = SQLITE_UTF16NATIVE;  }else if( enc==SQLITE_ANY ){    int rc;    rc = sqlite3_create_function(db, zFunctionName, nArg, SQLITE_UTF8,         pUserData, xFunc, xStep, xFinal);    if( rc!=SQLITE_OK ) return rc;    rc = sqlite3_create_function(db, zFunctionName, nArg, SQLITE_UTF16LE,        pUserData, xFunc, xStep, xFinal);    if( rc!=SQLITE_OK ) return rc;    enc = SQLITE_UTF16BE;  }#else  enc = SQLITE_UTF8;#endif    /* Check if an existing function is being overridden or deleted. If so,  ** and there are active VMs, then return SQLITE_BUSY. If a function  ** is being overridden/deleted but there are no active VMs, allow the  ** operation to continue but invalidate all precompiled statements.  */  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 0);  if( p && p->iPrefEnc==enc && p->nArg==nArg ){    if( db->activeVdbeCnt ){      sqlite3Error(db, SQLITE_BUSY,         "Unable to delete/modify user-function due to active statements");      return SQLITE_BUSY;    }else{      sqlite3ExpirePreparedStatements(db);    }  }  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 1);  if( p==0 ) return SQLITE_NOMEM;  p->xFunc = xFunc;  p->xStep = xStep;  p->xFinalize = xFinal;  p->pUserData = pUserData;  return SQLITE_OK;}#ifndef SQLITE_OMIT_UTF16int sqlite3_create_function16(  sqlite3 *db,  const void *zFunctionName,  int nArg,  int eTextRep,  void *pUserData,  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),  void (*xStep)(sqlite3_context*,int,sqlite3_value**),  void (*xFinal)(sqlite3_context*)){  int rc;  char const *zFunc8;  sqlite3_value *pTmp;  if( sqlite3SafetyCheck(db) ){    return SQLITE_MISUSE;  }  pTmp = sqlite3GetTransientValue(db);  sqlite3ValueSetStr(pTmp, -1, zFunctionName, SQLITE_UTF16NATIVE,SQLITE_STATIC);  zFunc8 = sqlite3ValueText(pTmp, SQLITE_UTF8);  if( !zFunc8 ){    return SQLITE_NOMEM;  }  rc = sqlite3_create_function(db, zFunc8, nArg, eTextRep,       pUserData, xFunc, xStep, xFinal);  return rc;}#endif/*** Register a trace function.  The pArg from the previously registered trace** is returned.  **** A NULL trace function means that no tracing is executes.  A non-NULL** trace is a pointer to a function that is invoked at the start of each** sqlite3_exec().*/void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -