engine/sqlite/src/main.cpp
changeset 2 29cda98b007e
equal deleted inserted replaced
1:5f8e5adbbed9 2:29cda98b007e
       
     1 /*
       
     2 ** 2001 September 15
       
     3 **
       
     4 ** The author disclaims copyright to this source code.  In place of
       
     5 ** a legal notice, here is a blessing:
       
     6 **
       
     7 **    May you do good and not evil.
       
     8 **    May you find forgiveness for yourself and forgive others.
       
     9 **    May you share freely, never taking more than you give.
       
    10 **
       
    11 *************************************************************************
       
    12 ** Main file for the SQLite library.  The routines in this file
       
    13 ** implement the programmer interface to the library.  Routines in
       
    14 ** other files are for internal use by SQLite and should not be
       
    15 ** accessed by users of the library.
       
    16 **
       
    17 ** $Id: main.cpp 1282 2008-11-13 09:31:33Z LarsPson $
       
    18 */
       
    19 #include "sqliteInt.h"
       
    20 #include <ctype.h>
       
    21 #include <stdio.h>
       
    22 #include <string.h>
       
    23 
       
    24 /*
       
    25 ** The version of the library
       
    26 */
       
    27 EXPORT_C const char *sqlite3_libversion(void){ return sqlite3_version; }
       
    28 EXPORT_C int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
       
    29 EXPORT_C int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
       
    30 
       
    31 /*
       
    32 ** If the following function pointer is not NULL and if
       
    33 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
       
    34 ** I/O active are written using this function.  These messages
       
    35 ** are intended for debugging activity only.
       
    36 */
       
    37 void (*sqlite3_io_trace)(const char*, ...) = 0;
       
    38 
       
    39 /*
       
    40 ** If the following global variable points to a string which is the
       
    41 ** name of a directory, then that directory will be used to store
       
    42 ** temporary files.
       
    43 **
       
    44 ** See also the "PRAGMA temp_store_directory" SQL command.
       
    45 */
       
    46 char *sqlite3_temp_directory = 0;
       
    47 
       
    48 
       
    49 /*
       
    50 ** This is the default collating function named "BINARY" which is always
       
    51 ** available.
       
    52 */
       
    53 static int binCollFunc(
       
    54   void *NotUsed,
       
    55   int nKey1, const void *pKey1,
       
    56   int nKey2, const void *pKey2
       
    57 ){
       
    58   int rc, n;
       
    59   n = nKey1<nKey2 ? nKey1 : nKey2;
       
    60   rc = memcmp(pKey1, pKey2, n);
       
    61   if( rc==0 ){
       
    62     rc = nKey1 - nKey2;
       
    63   }
       
    64   return rc;
       
    65 }
       
    66 
       
    67 /*
       
    68 ** Another built-in collating sequence: NOCASE. 
       
    69 **
       
    70 ** This collating sequence is intended to be used for "case independant
       
    71 ** comparison". SQLite's knowledge of upper and lower case equivalents
       
    72 ** extends only to the 26 characters used in the English language.
       
    73 **
       
    74 ** At the moment there is only a UTF-8 implementation.
       
    75 */
       
    76 static int nocaseCollatingFunc(
       
    77   void *NotUsed,
       
    78   int nKey1, const void *pKey1,
       
    79   int nKey2, const void *pKey2
       
    80 ){
       
    81   int r = sqlite3StrNICmp(
       
    82       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
       
    83   if( 0==r ){
       
    84     r = nKey1-nKey2;
       
    85   }
       
    86   return r;
       
    87 }
       
    88 
       
    89 /*
       
    90 ** Return the ROWID of the most recent insert
       
    91 */
       
    92 EXPORT_C sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
       
    93   return db->lastRowid;
       
    94 }
       
    95 
       
    96 /*
       
    97 ** Return the number of changes in the most recent call to sqlite3_exec().
       
    98 */
       
    99 EXPORT_C int sqlite3_changes(sqlite3 *db){
       
   100   return db->nChange;
       
   101 }
       
   102 
       
   103 /*
       
   104 ** Return the number of changes since the database handle was opened.
       
   105 */
       
   106 EXPORT_C int sqlite3_total_changes(sqlite3 *db){
       
   107   return db->nTotalChange;
       
   108 }
       
   109 
       
   110 /*
       
   111 ** Close an existing SQLite database
       
   112 */
       
   113 EXPORT_C int sqlite3_close(sqlite3 *db){
       
   114   HashElem *i;
       
   115   int j;
       
   116 
       
   117   if( !db ){
       
   118     return SQLITE_OK;
       
   119   }
       
   120   if( sqlite3SafetyCheck(db) ){
       
   121     return SQLITE_MISUSE;
       
   122   }
       
   123   sqlite3_mutex_enter(db->mutex);
       
   124 
       
   125 #ifdef SQLITE_SSE
       
   126   {
       
   127     extern void sqlite3SseCleanup(sqlite3*);
       
   128     sqlite3SseCleanup(db);
       
   129   }
       
   130 #endif 
       
   131 
       
   132   sqlite3ResetInternalSchema(db, 0);
       
   133 
       
   134   /* If a transaction is open, the ResetInternalSchema() call above
       
   135   ** will not have called the xDisconnect() method on any virtual
       
   136   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
       
   137   ** call will do so. We need to do this before the check for active
       
   138   ** SQL statements below, as the v-table implementation may be storing
       
   139   ** some prepared statements internally.
       
   140   */
       
   141   sqlite3VtabRollback(db);
       
   142 
       
   143   /* If there are any outstanding VMs, return SQLITE_BUSY. */
       
   144   if( db->pVdbe ){
       
   145     sqlite3Error(db, SQLITE_BUSY, 
       
   146         "Unable to close due to unfinalised statements");
       
   147     sqlite3_mutex_leave(db->mutex);
       
   148     return SQLITE_BUSY;
       
   149   }
       
   150   assert( !sqlite3SafetyCheck(db) );
       
   151 
       
   152   /* FIX ME: db->magic may be set to SQLITE_MAGIC_CLOSED if the database
       
   153   ** cannot be opened for some reason. So this routine needs to run in
       
   154   ** that case. But maybe there should be an extra magic value for the
       
   155   ** "failed to open" state.
       
   156   **
       
   157   ** TODO: Coverage tests do not test the case where this condition is
       
   158   ** true. It's hard to see how to cause it without messing with threads.
       
   159   */
       
   160   if( db->magic!=SQLITE_MAGIC_CLOSED && sqlite3SafetyOn(db) ){
       
   161     /* printf("DID NOT CLOSE\n"); fflush(stdout); */
       
   162     sqlite3_mutex_leave(db->mutex);
       
   163     return SQLITE_ERROR;
       
   164   }
       
   165 
       
   166   for(j=0; j<db->nDb; j++){
       
   167     struct Db *pDb = &db->aDb[j];
       
   168     if( pDb->pBt ){
       
   169       sqlite3BtreeClose(pDb->pBt);
       
   170       pDb->pBt = 0;
       
   171       if( j!=1 ){
       
   172         pDb->pSchema = 0;
       
   173       }
       
   174     }
       
   175   }
       
   176   sqlite3ResetInternalSchema(db, 0);
       
   177   assert( db->nDb<=2 );
       
   178   assert( db->aDb==db->aDbStatic );
       
   179   for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
       
   180     FuncDef *pFunc, *pNext;
       
   181     for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext){
       
   182       pNext = pFunc->pNext;
       
   183       sqlite3_free(pFunc);
       
   184     }
       
   185   }
       
   186 
       
   187   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
       
   188     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
       
   189     /* Invoke any destructors registered for collation sequence user data. */
       
   190     for(j=0; j<3; j++){
       
   191       if( pColl[j].xDel ){
       
   192         pColl[j].xDel(pColl[j].pUser);
       
   193       }
       
   194     }
       
   195     sqlite3_free(pColl);
       
   196   }
       
   197   sqlite3HashClear(&db->aCollSeq);
       
   198 #ifndef SQLITE_OMIT_VIRTUALTABLE
       
   199   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
       
   200     Module *pMod = (Module *)sqliteHashData(i);
       
   201     if( pMod->xDestroy ){
       
   202       pMod->xDestroy(pMod->pAux);
       
   203     }
       
   204     sqlite3_free(pMod);
       
   205   }
       
   206   sqlite3HashClear(&db->aModule);
       
   207 #endif
       
   208 
       
   209   sqlite3HashClear(&db->aFunc);
       
   210   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
       
   211   if( db->pErr ){
       
   212     sqlite3ValueFree(db->pErr);
       
   213   }
       
   214   sqlite3CloseExtensions(db);
       
   215 
       
   216   db->magic = SQLITE_MAGIC_ERROR;
       
   217 
       
   218   /* The temp-database schema is allocated differently from the other schema
       
   219   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
       
   220   ** So it needs to be freed here. Todo: Why not roll the temp schema into
       
   221   ** the same sqliteMalloc() as the one that allocates the database 
       
   222   ** structure?
       
   223   */
       
   224   sqlite3_free(db->aDb[1].pSchema);
       
   225   sqlite3_mutex_leave(db->mutex);
       
   226   sqlite3_mutex_free(db->mutex);
       
   227   sqlite3_free(db);
       
   228   return SQLITE_OK;
       
   229 }
       
   230 
       
   231 /*
       
   232 ** Rollback all database files.
       
   233 */
       
   234 void sqlite3RollbackAll(sqlite3 *db){
       
   235   int i;
       
   236   int inTrans = 0;
       
   237   assert( sqlite3_mutex_held(db->mutex) );
       
   238   sqlite3MallocEnterBenignBlock(1);                 /* Enter benign region */
       
   239   for(i=0; i<db->nDb; i++){
       
   240     if( db->aDb[i].pBt ){
       
   241       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
       
   242         inTrans = 1;
       
   243       }
       
   244       sqlite3BtreeRollback(db->aDb[i].pBt);
       
   245       db->aDb[i].inTrans = 0;
       
   246     }
       
   247   }
       
   248   sqlite3VtabRollback(db);
       
   249   sqlite3MallocLeaveBenignBlock();                 /* Leave benign region */
       
   250 
       
   251   if( db->flags&SQLITE_InternChanges ){
       
   252     sqlite3ExpirePreparedStatements(db);
       
   253     sqlite3ResetInternalSchema(db, 0);
       
   254   }
       
   255 
       
   256   /* If one has been configured, invoke the rollback-hook callback */
       
   257   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
       
   258     db->xRollbackCallback(db->pRollbackArg);
       
   259   }
       
   260 }
       
   261 
       
   262 /*
       
   263 ** Return a static string that describes the kind of error specified in the
       
   264 ** argument.
       
   265 */
       
   266 const char *sqlite3ErrStr(int rc){
       
   267   const char *z;
       
   268   switch( rc & 0xff ){
       
   269     case SQLITE_ROW:
       
   270     case SQLITE_DONE:
       
   271     case SQLITE_OK:         z = "not an error";                          break;
       
   272     case SQLITE_ERROR:      z = "SQL logic error or missing database";   break;
       
   273     case SQLITE_PERM:       z = "access permission denied";              break;
       
   274     case SQLITE_ABORT:      z = "callback requested query abort";        break;
       
   275     case SQLITE_BUSY:       z = "database is locked";                    break;
       
   276     case SQLITE_LOCKED:     z = "database table is locked";              break;
       
   277     case SQLITE_NOMEM:      z = "out of memory";                         break;
       
   278     case SQLITE_READONLY:   z = "attempt to write a readonly database";  break;
       
   279     case SQLITE_INTERRUPT:  z = "interrupted";                           break;
       
   280     case SQLITE_IOERR:      z = "disk I/O error";                        break;
       
   281     case SQLITE_CORRUPT:    z = "database disk image is malformed";      break;
       
   282     case SQLITE_FULL:       z = "database or disk is full";              break;
       
   283     case SQLITE_CANTOPEN:   z = "unable to open database file";          break;
       
   284     case SQLITE_EMPTY:      z = "table contains no data";                break;
       
   285     case SQLITE_SCHEMA:     z = "database schema has changed";           break;
       
   286     case SQLITE_TOOBIG:     z = "String or BLOB exceeded size limit";    break;
       
   287     case SQLITE_CONSTRAINT: z = "constraint failed";                     break;
       
   288     case SQLITE_MISMATCH:   z = "datatype mismatch";                     break;
       
   289     case SQLITE_MISUSE:     z = "library routine called out of sequence";break;
       
   290     case SQLITE_NOLFS:      z = "kernel lacks large file support";       break;
       
   291     case SQLITE_AUTH:       z = "authorization denied";                  break;
       
   292     case SQLITE_FORMAT:     z = "auxiliary database format error";       break;
       
   293     case SQLITE_RANGE:      z = "bind or column index out of range";     break;
       
   294     case SQLITE_NOTADB:     z = "file is encrypted or is not a database";break;
       
   295     default:                z = "unknown error";                         break;
       
   296   }
       
   297   return z;
       
   298 }
       
   299 
       
   300 /*
       
   301 ** This routine implements a busy callback that sleeps and tries
       
   302 ** again until a timeout value is reached.  The timeout value is
       
   303 ** an integer number of milliseconds passed in as the first
       
   304 ** argument.
       
   305 */
       
   306 static int sqliteDefaultBusyCallback(
       
   307  void *ptr,               /* Database connection */
       
   308  int count                /* Number of times table has been busy */
       
   309 ){
       
   310 #if OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
       
   311   static const u8 delays[] =
       
   312      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
       
   313   static const u8 totals[] =
       
   314      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
       
   315 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
       
   316   sqlite3 *db = (sqlite3 *)ptr;
       
   317   int timeout = db->busyTimeout;
       
   318   int delay, prior;
       
   319 
       
   320   assert( count>=0 );
       
   321   if( count < NDELAY ){
       
   322     delay = delays[count];
       
   323     prior = totals[count];
       
   324   }else{
       
   325     delay = delays[NDELAY-1];
       
   326     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
       
   327   }
       
   328   if( prior + delay > timeout ){
       
   329     delay = timeout - prior;
       
   330     if( delay<=0 ) return 0;
       
   331   }
       
   332   sqlite3OsSleep(db->pVfs, delay*1000);
       
   333   return 1;
       
   334 #else
       
   335   sqlite3 *db = (sqlite3 *)ptr;
       
   336   int timeout = ((sqlite3 *)ptr)->busyTimeout;
       
   337   if( (count+1)*1000 > timeout ){
       
   338     return 0;
       
   339   }
       
   340   sqlite3OsSleep(db->pVfs, 1000000);
       
   341   return 1;
       
   342 #endif
       
   343 }
       
   344 
       
   345 /*
       
   346 ** Invoke the given busy handler.
       
   347 **
       
   348 ** This routine is called when an operation failed with a lock.
       
   349 ** If this routine returns non-zero, the lock is retried.  If it
       
   350 ** returns 0, the operation aborts with an SQLITE_BUSY error.
       
   351 */
       
   352 int sqlite3InvokeBusyHandler(BusyHandler *p){
       
   353   int rc;
       
   354   if( p==0 || p->xFunc==0 || p->nBusy<0 ) return 0;
       
   355   rc = p->xFunc(p->pArg, p->nBusy);
       
   356   if( rc==0 ){
       
   357     p->nBusy = -1;
       
   358   }else{
       
   359     p->nBusy++;
       
   360   }
       
   361   return rc; 
       
   362 }
       
   363 
       
   364 /*
       
   365 ** This routine sets the busy callback for an Sqlite database to the
       
   366 ** given callback function with the given argument.
       
   367 */
       
   368 EXPORT_C int sqlite3_busy_handler(
       
   369   sqlite3 *db,
       
   370   int (*xBusy)(void*,int),
       
   371   void *pArg
       
   372 ){
       
   373   if( sqlite3SafetyCheck(db) ){
       
   374     return SQLITE_MISUSE;
       
   375   }
       
   376   sqlite3_mutex_enter(db->mutex);
       
   377   db->busyHandler.xFunc = xBusy;
       
   378   db->busyHandler.pArg = pArg;
       
   379   db->busyHandler.nBusy = 0;
       
   380   sqlite3_mutex_leave(db->mutex);
       
   381   return SQLITE_OK;
       
   382 }
       
   383 
       
   384 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
       
   385 /*
       
   386 ** This routine sets the progress callback for an Sqlite database to the
       
   387 ** given callback function with the given argument. The progress callback will
       
   388 ** be invoked every nOps opcodes.
       
   389 */
       
   390 EXPORT_C void sqlite3_progress_handler(
       
   391   sqlite3 *db, 
       
   392   int nOps,
       
   393   int (*xProgress)(void*), 
       
   394   void *pArg
       
   395 ){
       
   396   if( !sqlite3SafetyCheck(db) ){
       
   397     sqlite3_mutex_enter(db->mutex);
       
   398     if( nOps>0 ){
       
   399       db->xProgress = xProgress;
       
   400       db->nProgressOps = nOps;
       
   401       db->pProgressArg = pArg;
       
   402     }else{
       
   403       db->xProgress = 0;
       
   404       db->nProgressOps = 0;
       
   405       db->pProgressArg = 0;
       
   406     }
       
   407     sqlite3_mutex_leave(db->mutex);
       
   408   }
       
   409 }
       
   410 #endif
       
   411 
       
   412 
       
   413 /*
       
   414 ** This routine installs a default busy handler that waits for the
       
   415 ** specified number of milliseconds before returning 0.
       
   416 */
       
   417 EXPORT_C int sqlite3_busy_timeout(sqlite3 *db, int ms){
       
   418   if( sqlite3SafetyCheck(db) ){
       
   419     return SQLITE_MISUSE;
       
   420   }
       
   421   if( ms>0 ){
       
   422     db->busyTimeout = ms;
       
   423     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
       
   424   }else{
       
   425     sqlite3_busy_handler(db, NULL, NULL);
       
   426   }
       
   427   return SQLITE_OK;
       
   428 }
       
   429 
       
   430 /*
       
   431 ** Cause any pending operation to stop at its earliest opportunity.
       
   432 */
       
   433 EXPORT_C void sqlite3_interrupt(sqlite3 *db){
       
   434   if( db && (db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_BUSY) ){
       
   435     db->u1.isInterrupted = 1;
       
   436   }
       
   437 }
       
   438 
       
   439 
       
   440 /*
       
   441 ** This function is exactly the same as sqlite3_create_function(), except
       
   442 ** that it is designed to be called by internal code. The difference is
       
   443 ** that if a malloc() fails in sqlite3_create_function(), an error code
       
   444 ** is returned and the mallocFailed flag cleared. 
       
   445 */
       
   446 int sqlite3CreateFunc(
       
   447   sqlite3 *db,
       
   448   const char *zFunctionName,
       
   449   int nArg,
       
   450   int enc,
       
   451   void *pUserData,
       
   452   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
       
   453   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
       
   454   void (*xFinal)(sqlite3_context*)
       
   455 ){
       
   456   FuncDef *p;
       
   457   int nName;
       
   458 
       
   459   assert( sqlite3_mutex_held(db->mutex) );
       
   460   if( sqlite3SafetyCheck(db) ){
       
   461     return SQLITE_MISUSE;
       
   462   }
       
   463   if( zFunctionName==0 ||
       
   464       (xFunc && (xFinal || xStep)) || 
       
   465       (!xFunc && (xFinal && !xStep)) ||
       
   466       (!xFunc && (!xFinal && xStep)) ||
       
   467       (nArg<-1 || nArg>127) ||
       
   468       (255<(nName = strlen(zFunctionName))) ){
       
   469     sqlite3Error(db, SQLITE_ERROR, "bad parameters");
       
   470     return SQLITE_ERROR;
       
   471   }
       
   472   
       
   473 #ifndef SQLITE_OMIT_UTF16
       
   474   /* If SQLITE_UTF16 is specified as the encoding type, transform this
       
   475   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
       
   476   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
       
   477   **
       
   478   ** If SQLITE_ANY is specified, add three versions of the function
       
   479   ** to the hash table.
       
   480   */
       
   481   if( enc==SQLITE_UTF16 ){
       
   482     enc = SQLITE_UTF16NATIVE;
       
   483   }else if( enc==SQLITE_ANY ){
       
   484     int rc;
       
   485     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
       
   486          pUserData, xFunc, xStep, xFinal);
       
   487     if( rc==SQLITE_OK ){
       
   488       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
       
   489           pUserData, xFunc, xStep, xFinal);
       
   490     }
       
   491     if( rc!=SQLITE_OK ){
       
   492       return rc;
       
   493     }
       
   494     enc = SQLITE_UTF16BE;
       
   495   }
       
   496 #else
       
   497   enc = SQLITE_UTF8;
       
   498 #endif
       
   499   
       
   500   /* Check if an existing function is being overridden or deleted. If so,
       
   501   ** and there are active VMs, then return SQLITE_BUSY. If a function
       
   502   ** is being overridden/deleted but there are no active VMs, allow the
       
   503   ** operation to continue but invalidate all precompiled statements.
       
   504   */
       
   505   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 0);
       
   506   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
       
   507     if( db->activeVdbeCnt ){
       
   508       sqlite3Error(db, SQLITE_BUSY, 
       
   509         "Unable to delete/modify user-function due to active statements");
       
   510       assert( !db->mallocFailed );
       
   511       return SQLITE_BUSY;
       
   512     }else{
       
   513       sqlite3ExpirePreparedStatements(db);
       
   514     }
       
   515   }
       
   516 
       
   517   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 1);
       
   518   assert(p || db->mallocFailed);
       
   519   if( !p ){
       
   520     return SQLITE_NOMEM;
       
   521   }
       
   522   p->flags = 0;
       
   523   p->xFunc = xFunc;
       
   524   p->xStep = xStep;
       
   525   p->xFinalize = xFinal;
       
   526   p->pUserData = pUserData;
       
   527   p->nArg = nArg;
       
   528   return SQLITE_OK;
       
   529 }
       
   530 
       
   531 /*
       
   532 ** Create new user functions.
       
   533 */
       
   534 EXPORT_C int sqlite3_create_function(
       
   535   sqlite3 *db,
       
   536   const char *zFunctionName,
       
   537   int nArg,
       
   538   int enc,
       
   539   void *p,
       
   540   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
       
   541   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
       
   542   void (*xFinal)(sqlite3_context*)
       
   543 ){
       
   544   int rc;
       
   545   sqlite3_mutex_enter(db->mutex);
       
   546   assert( !db->mallocFailed );
       
   547   rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
       
   548   rc = sqlite3ApiExit(db, rc);
       
   549   sqlite3_mutex_leave(db->mutex);
       
   550   return rc;
       
   551 }
       
   552 
       
   553 #ifndef SQLITE_OMIT_UTF16
       
   554 EXPORT_C int sqlite3_create_function16(
       
   555   sqlite3 *db,
       
   556   const void *zFunctionName,
       
   557   int nArg,
       
   558   int eTextRep,
       
   559   void *p,
       
   560   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
       
   561   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
       
   562   void (*xFinal)(sqlite3_context*)
       
   563 ){
       
   564   int rc;
       
   565   char *zFunc8;
       
   566   sqlite3_mutex_enter(db->mutex);
       
   567   assert( !db->mallocFailed );
       
   568   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
       
   569   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
       
   570   sqlite3_free(zFunc8);
       
   571   rc = sqlite3ApiExit(db, rc);
       
   572   sqlite3_mutex_leave(db->mutex);
       
   573   return rc;
       
   574 }
       
   575 #endif
       
   576 
       
   577 
       
   578 /*
       
   579 ** Declare that a function has been overloaded by a virtual table.
       
   580 **
       
   581 ** If the function already exists as a regular global function, then
       
   582 ** this routine is a no-op.  If the function does not exist, then create
       
   583 ** a new one that always throws a run-time error.  
       
   584 **
       
   585 ** When virtual tables intend to provide an overloaded function, they
       
   586 ** should call this routine to make sure the global function exists.
       
   587 ** A global function must exist in order for name resolution to work
       
   588 ** properly.
       
   589 */
       
   590 EXPORT_C int sqlite3_overload_function(
       
   591   sqlite3 *db,
       
   592   const char *zName,
       
   593   int nArg
       
   594 ){
       
   595   int nName = strlen(zName);
       
   596   int rc;
       
   597   sqlite3_mutex_enter(db->mutex);
       
   598   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
       
   599     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
       
   600                       0, sqlite3InvalidFunction, 0, 0);
       
   601   }
       
   602   rc = sqlite3ApiExit(db, SQLITE_OK);
       
   603   sqlite3_mutex_leave(db->mutex);
       
   604   return rc;
       
   605 }
       
   606 
       
   607 #ifndef SQLITE_OMIT_TRACE
       
   608 /*
       
   609 ** Register a trace function.  The pArg from the previously registered trace
       
   610 ** is returned.  
       
   611 **
       
   612 ** A NULL trace function means that no tracing is executes.  A non-NULL
       
   613 ** trace is a pointer to a function that is invoked at the start of each
       
   614 ** SQL statement.
       
   615 */
       
   616 EXPORT_C void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
       
   617   void *pOld;
       
   618   sqlite3_mutex_enter(db->mutex);
       
   619   pOld = db->pTraceArg;
       
   620   db->xTrace = xTrace;
       
   621   db->pTraceArg = pArg;
       
   622   sqlite3_mutex_leave(db->mutex);
       
   623   return pOld;
       
   624 }
       
   625 /*
       
   626 ** Register a profile function.  The pArg from the previously registered 
       
   627 ** profile function is returned.  
       
   628 **
       
   629 ** A NULL profile function means that no profiling is executes.  A non-NULL
       
   630 ** profile is a pointer to a function that is invoked at the conclusion of
       
   631 ** each SQL statement that is run.
       
   632 */
       
   633 EXPORT_C void *sqlite3_profile(
       
   634   sqlite3 *db,
       
   635   void (*xProfile)(void*,const char*,sqlite_uint64),
       
   636   void *pArg
       
   637 ){
       
   638   void *pOld;
       
   639   sqlite3_mutex_enter(db->mutex);
       
   640   pOld = db->pProfileArg;
       
   641   db->xProfile = xProfile;
       
   642   db->pProfileArg = pArg;
       
   643   sqlite3_mutex_leave(db->mutex);
       
   644   return pOld;
       
   645 }
       
   646 #endif /* SQLITE_OMIT_TRACE */
       
   647 
       
   648 /*** EXPERIMENTAL ***
       
   649 **
       
   650 ** Register a function to be invoked when a transaction comments.
       
   651 ** If the invoked function returns non-zero, then the commit becomes a
       
   652 ** rollback.
       
   653 */
       
   654 EXPORT_C void *sqlite3_commit_hook(
       
   655   sqlite3 *db,              /* Attach the hook to this database */
       
   656   int (*xCallback)(void*),  /* Function to invoke on each commit */
       
   657   void *pArg                /* Argument to the function */
       
   658 ){
       
   659   void *pOld;
       
   660   sqlite3_mutex_enter(db->mutex);
       
   661   pOld = db->pCommitArg;
       
   662   db->xCommitCallback = xCallback;
       
   663   db->pCommitArg = pArg;
       
   664   sqlite3_mutex_leave(db->mutex);
       
   665   return pOld;
       
   666 }
       
   667 
       
   668 /*
       
   669 ** Register a callback to be invoked each time a row is updated,
       
   670 ** inserted or deleted using this database connection.
       
   671 */
       
   672 EXPORT_C void *sqlite3_update_hook(
       
   673   sqlite3 *db,              /* Attach the hook to this database */
       
   674   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
       
   675   void *pArg                /* Argument to the function */
       
   676 ){
       
   677   void *pRet;
       
   678   sqlite3_mutex_enter(db->mutex);
       
   679   pRet = db->pUpdateArg;
       
   680   db->xUpdateCallback = xCallback;
       
   681   db->pUpdateArg = pArg;
       
   682   sqlite3_mutex_leave(db->mutex);
       
   683   return pRet;
       
   684 }
       
   685 
       
   686 /*
       
   687 ** Register a callback to be invoked each time a transaction is rolled
       
   688 ** back by this database connection.
       
   689 */
       
   690 EXPORT_C void *sqlite3_rollback_hook(
       
   691   sqlite3 *db,              /* Attach the hook to this database */
       
   692   void (*xCallback)(void*), /* Callback function */
       
   693   void *pArg                /* Argument to the function */
       
   694 ){
       
   695   void *pRet;
       
   696   sqlite3_mutex_enter(db->mutex);
       
   697   pRet = db->pRollbackArg;
       
   698   db->xRollbackCallback = xCallback;
       
   699   db->pRollbackArg = pArg;
       
   700   sqlite3_mutex_leave(db->mutex);
       
   701   return pRet;
       
   702 }
       
   703 
       
   704 /*
       
   705 ** This routine is called to create a connection to a database BTree
       
   706 ** driver.  If zFilename is the name of a file, then that file is
       
   707 ** opened and used.  If zFilename is the magic name ":memory:" then
       
   708 ** the database is stored in memory (and is thus forgotten as soon as
       
   709 ** the connection is closed.)  If zFilename is NULL then the database
       
   710 ** is a "virtual" database for transient use only and is deleted as
       
   711 ** soon as the connection is closed.
       
   712 **
       
   713 ** A virtual database can be either a disk file (that is automatically
       
   714 ** deleted when the file is closed) or it an be held entirely in memory,
       
   715 ** depending on the values of the TEMP_STORE compile-time macro and the
       
   716 ** db->temp_store variable, according to the following chart:
       
   717 **
       
   718 **       TEMP_STORE     db->temp_store     Location of temporary database
       
   719 **       ----------     --------------     ------------------------------
       
   720 **           0               any             file
       
   721 **           1                1              file
       
   722 **           1                2              memory
       
   723 **           1                0              file
       
   724 **           2                1              file
       
   725 **           2                2              memory
       
   726 **           2                0              memory
       
   727 **           3               any             memory
       
   728 */
       
   729 int sqlite3BtreeFactory(
       
   730   const sqlite3 *db,        /* Main database when opening aux otherwise 0 */
       
   731   const char *zFilename,    /* Name of the file containing the BTree database */
       
   732   int omitJournal,          /* if TRUE then do not journal this file */
       
   733   int nCache,               /* How many pages in the page cache */
       
   734   int vfsFlags,             /* Flags passed through to vfsOpen */
       
   735   Btree **ppBtree           /* Pointer to new Btree object written here */
       
   736 ){
       
   737   int btFlags = 0;
       
   738   int rc;
       
   739   
       
   740 
       
   741   assert( sqlite3_mutex_held(db->mutex) );
       
   742   assert( ppBtree != 0);
       
   743   
       
   744 
       
   745   if( omitJournal ){
       
   746     btFlags |= BTREE_OMIT_JOURNAL;
       
   747   }
       
   748   if( db->flags & SQLITE_NoReadlock ){
       
   749     btFlags |= BTREE_NO_READLOCK;
       
   750   }
       
   751   if( zFilename==0 ){
       
   752 #if TEMP_STORE==0
       
   753     /* Do nothing */
       
   754 #endif
       
   755 #ifndef SQLITE_OMIT_MEMORYDB
       
   756 #if TEMP_STORE==1
       
   757     if( db->temp_store==2 ) zFilename = ":memory:";
       
   758 #endif
       
   759 #if TEMP_STORE==2
       
   760     if( db->temp_store!=1 ) zFilename = ":memory:";
       
   761 #endif
       
   762 #if TEMP_STORE==3
       
   763     zFilename = ":memory:";
       
   764 #endif
       
   765 #endif /* SQLITE_OMIT_MEMORYDB */
       
   766   }
       
   767 
       
   768   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
       
   769     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
       
   770   }
       
   771   rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
       
   772 
       
   773   if( rc==SQLITE_OK ){
       
   774     sqlite3BtreeSetCacheSize(*ppBtree, nCache);
       
   775   }
       
   776   return rc;
       
   777 }
       
   778 
       
   779 /*
       
   780 ** Return UTF-8 encoded English language explanation of the most recent
       
   781 ** error.
       
   782 */
       
   783 EXPORT_C const char *sqlite3_errmsg(sqlite3 *db){
       
   784   const char *z;
       
   785   if( !db ){
       
   786     return sqlite3ErrStr(SQLITE_NOMEM);
       
   787   }
       
   788   if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
       
   789     return sqlite3ErrStr(SQLITE_MISUSE);
       
   790   }
       
   791   sqlite3_mutex_enter(db->mutex);
       
   792   assert( !db->mallocFailed );
       
   793   z = (char*)sqlite3_value_text(db->pErr);
       
   794   if( z==0 ){
       
   795     z = sqlite3ErrStr(db->errCode);
       
   796   }
       
   797   sqlite3_mutex_leave(db->mutex);
       
   798   return z;
       
   799 }
       
   800 
       
   801 #ifndef SQLITE_OMIT_UTF16
       
   802 /*
       
   803 ** Return UTF-16 encoded English language explanation of the most recent
       
   804 ** error.
       
   805 */
       
   806 EXPORT_C const void *sqlite3_errmsg16(sqlite3 *db){
       
   807   /* Because all the characters in the string are in the unicode
       
   808   ** range 0x00-0xFF, if we pad the big-endian string with a 
       
   809   ** zero byte, we can obtain the little-endian string with
       
   810   ** &big_endian[1].
       
   811   */
       
   812   static const char outOfMemBe[] = {
       
   813     0, 'o', 0, 'u', 0, 't', 0, ' ', 
       
   814     0, 'o', 0, 'f', 0, ' ', 
       
   815     0, 'm', 0, 'e', 0, 'm', 0, 'o', 0, 'r', 0, 'y', 0, 0, 0
       
   816   };
       
   817   static const char misuseBe [] = {
       
   818     0, 'l', 0, 'i', 0, 'b', 0, 'r', 0, 'a', 0, 'r', 0, 'y', 0, ' ', 
       
   819     0, 'r', 0, 'o', 0, 'u', 0, 't', 0, 'i', 0, 'n', 0, 'e', 0, ' ', 
       
   820     0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ', 
       
   821     0, 'o', 0, 'u', 0, 't', 0, ' ', 
       
   822     0, 'o', 0, 'f', 0, ' ', 
       
   823     0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
       
   824   };
       
   825 
       
   826   const void *z;
       
   827   if( !db ){
       
   828     return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
       
   829   }
       
   830   if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
       
   831     return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
       
   832   }
       
   833   sqlite3_mutex_enter(db->mutex);
       
   834   assert( !db->mallocFailed );
       
   835   z = sqlite3_value_text16(db->pErr);
       
   836   if( z==0 ){
       
   837     sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
       
   838          SQLITE_UTF8, SQLITE_STATIC);
       
   839     z = sqlite3_value_text16(db->pErr);
       
   840   }
       
   841   sqlite3ApiExit(0, 0);
       
   842   sqlite3_mutex_leave(db->mutex);
       
   843   return z;
       
   844 }
       
   845 #endif /* SQLITE_OMIT_UTF16 */
       
   846 
       
   847 /*
       
   848 ** Return the most recent error code generated by an SQLite routine. If NULL is
       
   849 ** passed to this function, we assume a malloc() failed during sqlite3_open().
       
   850 */
       
   851 EXPORT_C int sqlite3_errcode(sqlite3 *db){
       
   852   if( !db || db->mallocFailed ){
       
   853     return SQLITE_NOMEM;
       
   854   }
       
   855   if( sqlite3SafetyCheck(db) ){
       
   856     return SQLITE_MISUSE;
       
   857   }
       
   858   return db->errCode & db->errMask;
       
   859 }
       
   860 
       
   861 /*
       
   862 ** Create a new collating function for database "db".  The name is zName
       
   863 ** and the encoding is enc.
       
   864 */
       
   865 static int createCollation(
       
   866   sqlite3* db, 
       
   867   const char *zName, 
       
   868   int enc, 
       
   869   void* pCtx,
       
   870   int(*xCompare)(void*,int,const void*,int,const void*),
       
   871   void(*xDel)(void*)
       
   872 ){
       
   873   CollSeq *pColl;
       
   874   int enc2;
       
   875   
       
   876   if( sqlite3SafetyCheck(db) ){
       
   877     return SQLITE_MISUSE;
       
   878   }
       
   879   assert( sqlite3_mutex_held(db->mutex) );
       
   880 
       
   881   /* If SQLITE_UTF16 is specified as the encoding type, transform this
       
   882   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
       
   883   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
       
   884   */
       
   885   enc2 = enc & ~SQLITE_UTF16_ALIGNED;
       
   886   if( enc2==SQLITE_UTF16 ){
       
   887     enc2 = SQLITE_UTF16NATIVE;
       
   888   }
       
   889 
       
   890   if( (enc2&~3)!=0 ){
       
   891     sqlite3Error(db, SQLITE_ERROR, "unknown encoding");
       
   892     return SQLITE_ERROR;
       
   893   }
       
   894 
       
   895   /* Check if this call is removing or replacing an existing collation 
       
   896   ** sequence. If so, and there are active VMs, return busy. If there
       
   897   ** are no active VMs, invalidate any pre-compiled statements.
       
   898   */
       
   899   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, strlen(zName), 0);
       
   900   if( pColl && pColl->xCmp ){
       
   901     if( db->activeVdbeCnt ){
       
   902       sqlite3Error(db, SQLITE_BUSY, 
       
   903         "Unable to delete/modify collation sequence due to active statements");
       
   904       return SQLITE_BUSY;
       
   905     }
       
   906     sqlite3ExpirePreparedStatements(db);
       
   907 
       
   908     /* If collation sequence pColl was created directly by a call to
       
   909     ** sqlite3_create_collation, and not generated by synthCollSeq(),
       
   910     ** then any copies made by synthCollSeq() need to be invalidated.
       
   911     ** Also, collation destructor - CollSeq.xDel() - function may need
       
   912     ** to be called.
       
   913     */ 
       
   914     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
       
   915       CollSeq *aColl = (CollSeq*)sqlite3HashFind(&db->aCollSeq, zName, strlen(zName));
       
   916       int j;
       
   917       for(j=0; j<3; j++){
       
   918         CollSeq *p = &aColl[j];
       
   919         if( p->enc==pColl->enc ){
       
   920           if( p->xDel ){
       
   921             p->xDel(p->pUser);
       
   922           }
       
   923           p->xCmp = 0;
       
   924         }
       
   925       }
       
   926     }
       
   927   }
       
   928 
       
   929   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, strlen(zName), 1);
       
   930   if( pColl ){
       
   931     pColl->xCmp = xCompare;
       
   932     pColl->pUser = pCtx;
       
   933     pColl->xDel = xDel;
       
   934     pColl->enc = enc2 | (enc & SQLITE_UTF16_ALIGNED);
       
   935   }
       
   936   sqlite3Error(db, SQLITE_OK, 0);
       
   937   return SQLITE_OK;
       
   938 }
       
   939 
       
   940 FILE * fpLogFile = NULL;
       
   941 
       
   942 /*
       
   943 ** This routine does the work of opening a database on behalf of
       
   944 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
       
   945 ** is UTF-8 encoded.
       
   946 */
       
   947 static int openDatabase(
       
   948   const char *zFilename, /* Database filename UTF-8 encoded */
       
   949   sqlite3 **ppDb,        /* OUT: Returned database handle */
       
   950   unsigned flags,        /* Operational flags */
       
   951   const char *zVfs       /* Name of the VFS to use */
       
   952 ){
       
   953   sqlite3 *db;
       
   954   int rc;
       
   955   CollSeq *pColl;
       
   956 
       
   957 
       
   958   /* Allocate the sqlite data structure */
       
   959   db = (sqlite3*)sqlite3MallocZero( sizeof(sqlite3) );
       
   960   if( db==0 ) goto opendb_out;
       
   961   db->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
       
   962   if( db->mutex==0 ){
       
   963     sqlite3_free(db);
       
   964     db = 0;
       
   965     goto opendb_out;
       
   966   }
       
   967   sqlite3_mutex_enter(db->mutex);
       
   968   db->errMask = 0xff;
       
   969   db->priorNewRowid = 0;
       
   970   db->nDb = 2;
       
   971   db->magic = SQLITE_MAGIC_BUSY;
       
   972   db->aDb = db->aDbStatic;
       
   973   db->autoCommit = 1;
       
   974   db->nextAutovac = -1;
       
   975   db->flags |= SQLITE_ShortColNames
       
   976 #if SQLITE_DEFAULT_FILE_FORMAT<4
       
   977                  | SQLITE_LegacyFileFmt
       
   978 #endif
       
   979 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
       
   980                  | SQLITE_LoadExtension
       
   981 #endif
       
   982       ;
       
   983   sqlite3HashInit(&db->aFunc, SQLITE_HASH_STRING, 0);
       
   984   sqlite3HashInit(&db->aCollSeq, SQLITE_HASH_STRING, 0);
       
   985 #ifndef SQLITE_OMIT_VIRTUALTABLE
       
   986   sqlite3HashInit(&db->aModule, SQLITE_HASH_STRING, 0);
       
   987 #endif
       
   988 
       
   989   db->pVfs = sqlite3OsDefaultVfs();//sqlite3_vfs_find(zVfs);
       
   990   if( !db->pVfs ){
       
   991     rc = SQLITE_ERROR;
       
   992     db->magic = SQLITE_MAGIC_CLOSED;
       
   993     sqlite3Error(db, rc, "no such vfs: %s", (zVfs?zVfs:"(null)"));
       
   994     goto opendb_out;
       
   995   }
       
   996 
       
   997   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
       
   998   ** and UTF-16, so add a version for each to avoid any unnecessary
       
   999   ** conversions. The only error that can occur here is a malloc() failure.
       
  1000   */
       
  1001   if( createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0) ||
       
  1002       createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0) ||
       
  1003       createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0) ||
       
  1004       (db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0))==0 
       
  1005   ){
       
  1006     assert( db->mallocFailed );
       
  1007     db->magic = SQLITE_MAGIC_CLOSED;
       
  1008     goto opendb_out;
       
  1009   }
       
  1010 
       
  1011   /* Also add a UTF-8 case-insensitive collation sequence. */
       
  1012   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
       
  1013 
       
  1014   /* Set flags on the built-in collating sequences */
       
  1015   db->pDfltColl->type = SQLITE_COLL_BINARY;
       
  1016   pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "NOCASE", 6, 0);
       
  1017   if( pColl ){
       
  1018     pColl->type = SQLITE_COLL_NOCASE;
       
  1019   }
       
  1020 
       
  1021   /* Open the backend database driver */
       
  1022   db->openFlags = flags;
       
  1023   rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE, 
       
  1024                            flags | SQLITE_OPEN_MAIN_DB,
       
  1025                            &db->aDb[0].pBt);
       
  1026   if( rc!=SQLITE_OK ){
       
  1027     sqlite3Error(db, rc, 0);
       
  1028     db->magic = SQLITE_MAGIC_CLOSED;
       
  1029     goto opendb_out;
       
  1030   }
       
  1031   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
       
  1032   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
       
  1033 
       
  1034 
       
  1035   /* The default safety_level for the main database is 'full'; for the temp
       
  1036   ** database it is 'NONE'. This matches the pager layer defaults.  
       
  1037   */
       
  1038   db->aDb[0].zName = "main";
       
  1039   db->aDb[0].safety_level = 3;
       
  1040 #ifndef SQLITE_OMIT_TEMPDB
       
  1041   db->aDb[1].zName = "temp";
       
  1042   db->aDb[1].safety_level = 1;
       
  1043 #endif
       
  1044 
       
  1045   db->magic = SQLITE_MAGIC_OPEN;
       
  1046   if( db->mallocFailed ){
       
  1047     goto opendb_out;
       
  1048   }
       
  1049 
       
  1050   /* Register all built-in functions, but do not attempt to read the
       
  1051   ** database schema yet. This is delayed until the first time the database
       
  1052   ** is accessed.
       
  1053   */
       
  1054   sqlite3Error(db, SQLITE_OK, 0);
       
  1055   sqlite3RegisterBuiltinFunctions(db);
       
  1056 
       
  1057   /* Load automatic extensions - extensions that have been registered
       
  1058   ** using the sqlite3_automatic_extension() API.
       
  1059   */
       
  1060   (void)sqlite3AutoLoadExtensions(db);
       
  1061   if( sqlite3_errcode(db)!=SQLITE_OK ){
       
  1062     goto opendb_out;
       
  1063   }
       
  1064 
       
  1065 #ifdef SQLITE_ENABLE_FTS1
       
  1066   if( !db->mallocFailed ){
       
  1067     extern int sqlite3Fts1Init(sqlite3*);
       
  1068     rc = sqlite3Fts1Init(db);
       
  1069   }
       
  1070 #endif
       
  1071 
       
  1072 #ifdef SQLITE_ENABLE_FTS2
       
  1073   if( !db->mallocFailed && rc==SQLITE_OK ){
       
  1074     extern int sqlite3Fts2Init(sqlite3*);
       
  1075     rc = sqlite3Fts2Init(db);
       
  1076   }
       
  1077 #endif
       
  1078 
       
  1079 #ifdef SQLITE_ENABLE_FTS3
       
  1080   if( !db->mallocFailed && rc==SQLITE_OK ){
       
  1081     extern int sqlite3Fts3Init(sqlite3*);
       
  1082     rc = sqlite3Fts3Init(db);
       
  1083   }
       
  1084 #endif
       
  1085 
       
  1086 #ifdef SQLITE_ENABLE_ICU
       
  1087   if( !db->mallocFailed && rc==SQLITE_OK ){
       
  1088     extern int sqlite3IcuInit(sqlite3*);
       
  1089     rc = sqlite3IcuInit(db);
       
  1090   }
       
  1091 #endif
       
  1092   sqlite3Error(db, rc, 0);
       
  1093 
       
  1094   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
       
  1095   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
       
  1096   ** mode.  Doing nothing at all also makes NORMAL the default.
       
  1097   */
       
  1098 #ifdef SQLITE_DEFAULT_LOCKING_MODE
       
  1099   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
       
  1100   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
       
  1101                           SQLITE_DEFAULT_LOCKING_MODE);
       
  1102 #endif
       
  1103 
       
  1104 opendb_out:
       
  1105   if( db && db->mutex ){
       
  1106     sqlite3_mutex_leave(db->mutex);
       
  1107   }
       
  1108   if( SQLITE_NOMEM==(rc = sqlite3_errcode(db)) ){
       
  1109     sqlite3_close(db);
       
  1110     db = 0;
       
  1111   }
       
  1112   *ppDb = db;
       
  1113   return sqlite3ApiExit(0, rc);
       
  1114 }
       
  1115 
       
  1116 /*
       
  1117 ** Open a new database handle.
       
  1118 */
       
  1119 EXPORT_C int sqlite3_open(
       
  1120   const char *zFilename, 
       
  1121   sqlite3 **ppDb 
       
  1122 ){
       
  1123   return openDatabase(zFilename, ppDb,
       
  1124                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
       
  1125 }
       
  1126 
       
  1127 EXPORT_C int sqlite3_open_v2(
       
  1128   const char *filename,   /* Database filename (UTF-8) */
       
  1129   sqlite3 **ppDb,         /* OUT: SQLite db handle */
       
  1130   int flags,              /* Flags */
       
  1131   const char *zVfs        /* Name of VFS module to use */
       
  1132 ){
       
  1133 
       
  1134   return openDatabase(filename, ppDb, flags, zVfs);
       
  1135 }
       
  1136 
       
  1137 #ifndef SQLITE_OMIT_UTF16
       
  1138 /*
       
  1139 ** Open a new database handle.
       
  1140 */
       
  1141 EXPORT_C int sqlite3_open16(
       
  1142   const void *zFilename, 
       
  1143   sqlite3 **ppDb
       
  1144 ){
       
  1145   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
       
  1146   sqlite3_value *pVal;
       
  1147   int rc = SQLITE_NOMEM;
       
  1148 
       
  1149   assert( zFilename );
       
  1150   assert( ppDb );
       
  1151   *ppDb = 0;
       
  1152   pVal = sqlite3ValueNew(0);
       
  1153   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
       
  1154   zFilename8 = (const char*)sqlite3ValueText(pVal, SQLITE_UTF8);
       
  1155   if( zFilename8 ){
       
  1156     rc = openDatabase(zFilename8, ppDb,
       
  1157                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
       
  1158     if( rc==SQLITE_OK && *ppDb ){
       
  1159       rc = sqlite3_exec(*ppDb, "PRAGMA encoding = 'UTF-16'", 0, 0, 0);
       
  1160       if( rc!=SQLITE_OK ){
       
  1161         sqlite3_close(*ppDb);
       
  1162         *ppDb = 0;
       
  1163       }
       
  1164     }
       
  1165   }
       
  1166   sqlite3ValueFree(pVal);
       
  1167 
       
  1168   return sqlite3ApiExit(0, rc);
       
  1169 }
       
  1170 #endif /* SQLITE_OMIT_UTF16 */
       
  1171 
       
  1172 /*
       
  1173 ** Register a new collation sequence with the database handle db.
       
  1174 */
       
  1175 EXPORT_C int sqlite3_create_collation(
       
  1176   sqlite3* db, 
       
  1177   const char *zName, 
       
  1178   int enc, 
       
  1179   void* pCtx,
       
  1180   int(*xCompare)(void*,int,const void*,int,const void*)
       
  1181 ){
       
  1182   int rc;
       
  1183   sqlite3_mutex_enter(db->mutex);
       
  1184   assert( !db->mallocFailed );
       
  1185   rc = createCollation(db, zName, enc, pCtx, xCompare, 0);
       
  1186   rc = sqlite3ApiExit(db, rc);
       
  1187   sqlite3_mutex_leave(db->mutex);
       
  1188   return rc;
       
  1189 }
       
  1190 
       
  1191 /*
       
  1192 ** Register a new collation sequence with the database handle db.
       
  1193 */
       
  1194 EXPORT_C int sqlite3_create_collation_v2(
       
  1195   sqlite3* db, 
       
  1196   const char *zName, 
       
  1197   int enc, 
       
  1198   void* pCtx,
       
  1199   int(*xCompare)(void*,int,const void*,int,const void*),
       
  1200   void(*xDel)(void*)
       
  1201 ){
       
  1202   int rc;
       
  1203   sqlite3_mutex_enter(db->mutex);
       
  1204   assert( !db->mallocFailed );
       
  1205   rc = createCollation(db, zName, enc, pCtx, xCompare, xDel);
       
  1206   rc = sqlite3ApiExit(db, rc);
       
  1207   sqlite3_mutex_leave(db->mutex);
       
  1208   return rc;
       
  1209 }
       
  1210 
       
  1211 #ifndef SQLITE_OMIT_UTF16
       
  1212 /*
       
  1213 ** Register a new collation sequence with the database handle db.
       
  1214 */
       
  1215 EXPORT_C int sqlite3_create_collation16(
       
  1216   sqlite3* db, 
       
  1217   const char *zName, 
       
  1218   int enc, 
       
  1219   void* pCtx,
       
  1220   int(*xCompare)(void*,int,const void*,int,const void*)
       
  1221 ){
       
  1222   int rc = SQLITE_OK;
       
  1223   char *zName8; 
       
  1224   sqlite3_mutex_enter(db->mutex);
       
  1225   assert( !db->mallocFailed );
       
  1226   zName8 = sqlite3Utf16to8(db, zName, -1);
       
  1227   if( zName8 ){
       
  1228     rc = createCollation(db, zName8, enc, pCtx, xCompare, 0);
       
  1229     sqlite3_free(zName8);
       
  1230   }
       
  1231   rc = sqlite3ApiExit(db, rc);
       
  1232   sqlite3_mutex_leave(db->mutex);
       
  1233   return rc;
       
  1234 }
       
  1235 #endif /* SQLITE_OMIT_UTF16 */
       
  1236 
       
  1237 /*
       
  1238 ** Register a collation sequence factory callback with the database handle
       
  1239 ** db. Replace any previously installed collation sequence factory.
       
  1240 */
       
  1241 EXPORT_C int sqlite3_collation_needed(
       
  1242   sqlite3 *db, 
       
  1243   void *pCollNeededArg, 
       
  1244   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
       
  1245 ){
       
  1246   if( sqlite3SafetyCheck(db) ){
       
  1247     return SQLITE_MISUSE;
       
  1248   }
       
  1249   sqlite3_mutex_enter(db->mutex);
       
  1250   db->xCollNeeded = xCollNeeded;
       
  1251   db->xCollNeeded16 = 0;
       
  1252   db->pCollNeededArg = pCollNeededArg;
       
  1253   sqlite3_mutex_leave(db->mutex);
       
  1254   return SQLITE_OK;
       
  1255 }
       
  1256 
       
  1257 #ifndef SQLITE_OMIT_UTF16
       
  1258 /*
       
  1259 ** Register a collation sequence factory callback with the database handle
       
  1260 ** db. Replace any previously installed collation sequence factory.
       
  1261 */
       
  1262 EXPORT_C int sqlite3_collation_needed16(
       
  1263   sqlite3 *db, 
       
  1264   void *pCollNeededArg, 
       
  1265   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
       
  1266 ){
       
  1267   if( sqlite3SafetyCheck(db) ){
       
  1268     return SQLITE_MISUSE;
       
  1269   }
       
  1270   sqlite3_mutex_enter(db->mutex);
       
  1271   db->xCollNeeded = 0;
       
  1272   db->xCollNeeded16 = xCollNeeded16;
       
  1273   db->pCollNeededArg = pCollNeededArg;
       
  1274   sqlite3_mutex_leave(db->mutex);
       
  1275   return SQLITE_OK;
       
  1276 }
       
  1277 #endif /* SQLITE_OMIT_UTF16 */
       
  1278 
       
  1279 #ifndef SQLITE_OMIT_GLOBALRECOVER
       
  1280 /*
       
  1281 ** This function is now an anachronism. It used to be used to recover from a
       
  1282 ** malloc() failure, but SQLite now does this automatically.
       
  1283 */
       
  1284 EXPORT_C int sqlite3_global_recover(void){
       
  1285   return SQLITE_OK;
       
  1286 }
       
  1287 #endif
       
  1288 
       
  1289 /*
       
  1290 ** Test to see whether or not the database connection is in autocommit
       
  1291 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
       
  1292 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
       
  1293 ** by the next COMMIT or ROLLBACK.
       
  1294 **
       
  1295 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
       
  1296 */
       
  1297 EXPORT_C int sqlite3_get_autocommit(sqlite3 *db){
       
  1298   return db->autoCommit;
       
  1299 }
       
  1300 
       
  1301 #ifdef SQLITE_DEBUG
       
  1302 /*
       
  1303 ** The following routine is subtituted for constant SQLITE_CORRUPT in
       
  1304 ** debugging builds.  This provides a way to set a breakpoint for when
       
  1305 ** corruption is first detected.
       
  1306 */
       
  1307 int sqlite3Corrupt(void){
       
  1308   return SQLITE_CORRUPT;
       
  1309 }
       
  1310 #endif
       
  1311 
       
  1312 /*
       
  1313 ** This is a convenience routine that makes sure that all thread-specific
       
  1314 ** data for this thread has been deallocated.
       
  1315 **
       
  1316 ** SQLite no longer uses thread-specific data so this routine is now a
       
  1317 ** no-op.  It is retained for historical compatibility.
       
  1318 */
       
  1319 EXPORT_C void sqlite3_thread_cleanup(void){
       
  1320 }
       
  1321 
       
  1322 /*
       
  1323 ** Return meta information about a specific column of a database table.
       
  1324 ** See comment in sqlite3.h (sqlite.h.in) for details.
       
  1325 */
       
  1326 #ifdef SQLITE_ENABLE_COLUMN_METADATA
       
  1327 int sqlite3_table_column_metadata(
       
  1328   sqlite3 *db,                /* Connection handle */
       
  1329   const char *zDbName,        /* Database name or NULL */
       
  1330   const char *zTableName,     /* Table name */
       
  1331   const char *zColumnName,    /* Column name */
       
  1332   char const **pzDataType,    /* OUTPUT: Declared data type */
       
  1333   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
       
  1334   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
       
  1335   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
       
  1336   int *pAutoinc               /* OUTPUT: True if colums is auto-increment */
       
  1337 ){
       
  1338   int rc;
       
  1339   char *zErrMsg = 0;
       
  1340   Table *pTab = 0;
       
  1341   Column *pCol = 0;
       
  1342   int iCol;
       
  1343 
       
  1344   char const *zDataType = 0;
       
  1345   char const *zCollSeq = 0;
       
  1346   int notnull = 0;
       
  1347   int primarykey = 0;
       
  1348   int autoinc = 0;
       
  1349 
       
  1350   /* Ensure the database schema has been loaded */
       
  1351   if( sqlite3SafetyOn(db) ){
       
  1352     return SQLITE_MISUSE;
       
  1353   }
       
  1354   sqlite3_mutex_enter(db->mutex);
       
  1355   rc = sqlite3Init(db, &zErrMsg);
       
  1356   if( SQLITE_OK!=rc ){
       
  1357     goto error_out;
       
  1358   }
       
  1359 
       
  1360   /* Locate the table in question */
       
  1361   pTab = sqlite3FindTable(db, zTableName, zDbName);
       
  1362   if( !pTab || pTab->pSelect ){
       
  1363     pTab = 0;
       
  1364     goto error_out;
       
  1365   }
       
  1366 
       
  1367   /* Find the column for which info is requested */
       
  1368   if( sqlite3IsRowid(zColumnName) ){
       
  1369     iCol = pTab->iPKey;
       
  1370     if( iCol>=0 ){
       
  1371       pCol = &pTab->aCol[iCol];
       
  1372     }
       
  1373   }else{
       
  1374     for(iCol=0; iCol<pTab->nCol; iCol++){
       
  1375       pCol = &pTab->aCol[iCol];
       
  1376       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
       
  1377         break;
       
  1378       }
       
  1379     }
       
  1380     if( iCol==pTab->nCol ){
       
  1381       pTab = 0;
       
  1382       goto error_out;
       
  1383     }
       
  1384   }
       
  1385 
       
  1386   /* The following block stores the meta information that will be returned
       
  1387   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
       
  1388   ** and autoinc. At this point there are two possibilities:
       
  1389   ** 
       
  1390   **     1. The specified column name was rowid", "oid" or "_rowid_" 
       
  1391   **        and there is no explicitly declared IPK column. 
       
  1392   **
       
  1393   **     2. The table is not a view and the column name identified an 
       
  1394   **        explicitly declared column. Copy meta information from *pCol.
       
  1395   */ 
       
  1396   if( pCol ){
       
  1397     zDataType = pCol->zType;
       
  1398     zCollSeq = pCol->zColl;
       
  1399     notnull = (pCol->notNull?1:0);
       
  1400     primarykey  = (pCol->isPrimKey?1:0);
       
  1401     autoinc = ((pTab->iPKey==iCol && pTab->autoInc)?1:0);
       
  1402   }else{
       
  1403     zDataType = "INTEGER";
       
  1404     primarykey = 1;
       
  1405   }
       
  1406   if( !zCollSeq ){
       
  1407     zCollSeq = "BINARY";
       
  1408   }
       
  1409 
       
  1410 error_out:
       
  1411   if( sqlite3SafetyOff(db) ){
       
  1412     rc = SQLITE_MISUSE;
       
  1413   }
       
  1414 
       
  1415   /* Whether the function call succeeded or failed, set the output parameters
       
  1416   ** to whatever their local counterparts contain. If an error did occur,
       
  1417   ** this has the effect of zeroing all output parameters.
       
  1418   */
       
  1419   if( pzDataType ) *pzDataType = zDataType;
       
  1420   if( pzCollSeq ) *pzCollSeq = zCollSeq;
       
  1421   if( pNotNull ) *pNotNull = notnull;
       
  1422   if( pPrimaryKey ) *pPrimaryKey = primarykey;
       
  1423   if( pAutoinc ) *pAutoinc = autoinc;
       
  1424 
       
  1425   if( SQLITE_OK==rc && !pTab ){
       
  1426     sqlite3SetString(&zErrMsg, "no such table column: ", zTableName, ".", 
       
  1427         zColumnName, 0);
       
  1428     rc = SQLITE_ERROR;
       
  1429   }
       
  1430   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
       
  1431   sqlite3_free(zErrMsg);
       
  1432   rc = sqlite3ApiExit(db, rc);
       
  1433   sqlite3_mutex_leave(db->mutex);
       
  1434   return rc;
       
  1435 }
       
  1436 #endif
       
  1437 
       
  1438 /*
       
  1439 ** Sleep for a little while.  Return the amount of time slept.
       
  1440 */
       
  1441 EXPORT_C int sqlite3_sleep(int ms){
       
  1442   sqlite3_vfs *pVfs;
       
  1443   int rc;
       
  1444   pVfs = sqlite3_vfs_find(0);
       
  1445 
       
  1446   /* This function works in milliseconds, but the underlying OsSleep() 
       
  1447   ** API uses microseconds. Hence the 1000's.
       
  1448   */
       
  1449   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
       
  1450   return rc;
       
  1451 }
       
  1452 
       
  1453 /*
       
  1454 ** Enable or disable the extended result codes.
       
  1455 */
       
  1456 EXPORT_C int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
       
  1457   sqlite3_mutex_enter(db->mutex);
       
  1458   db->errMask = onoff ? 0xffffffff : 0xff;
       
  1459   sqlite3_mutex_leave(db->mutex);
       
  1460   return SQLITE_OK;
       
  1461 }
       
  1462 
       
  1463 /*
       
  1464 ** Invoke the xFileControl method on a particular database.
       
  1465 */
       
  1466 EXPORT_C int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
       
  1467   int rc = SQLITE_ERROR;
       
  1468   int iDb;
       
  1469   sqlite3_mutex_enter(db->mutex);
       
  1470   if( zDbName==0 ){
       
  1471     iDb = 0;
       
  1472   }else{
       
  1473     for(iDb=0; iDb<db->nDb; iDb++){
       
  1474       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
       
  1475     }
       
  1476   }
       
  1477   if( iDb<db->nDb ){
       
  1478     Btree *pBtree = db->aDb[iDb].pBt;
       
  1479     if( pBtree ){
       
  1480       Pager *pPager;
       
  1481       sqlite3BtreeEnter(pBtree);
       
  1482       pPager = sqlite3BtreePager(pBtree);
       
  1483       if( pPager ){
       
  1484         sqlite3_file *fd = sqlite3PagerFile(pPager);
       
  1485         if( fd ){
       
  1486           rc = sqlite3OsFileControl(fd, op, pArg);
       
  1487         }
       
  1488       }
       
  1489       sqlite3BtreeLeave(pBtree);
       
  1490     }
       
  1491   }
       
  1492   sqlite3_mutex_leave(db->mutex);
       
  1493   return rc;   
       
  1494 }