Home | History | Annotate | Download | only in src
      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 #include "sqliteInt.h"
     18 
     19 #ifdef SQLITE_ENABLE_FTS3
     20 # include "fts3.h"
     21 #endif
     22 #ifdef SQLITE_ENABLE_RTREE
     23 # include "rtree.h"
     24 #endif
     25 #ifdef SQLITE_ENABLE_ICU
     26 # include "sqliteicu.h"
     27 #endif
     28 
     29 #ifndef SQLITE_AMALGAMATION
     30 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
     31 ** contains the text of SQLITE_VERSION macro.
     32 */
     33 const char sqlite3_version[] = SQLITE_VERSION;
     34 #endif
     35 
     36 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
     37 ** a pointer to the to the sqlite3_version[] string constant.
     38 */
     39 const char *sqlite3_libversion(void){ return sqlite3_version; }
     40 
     41 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
     42 ** pointer to a string constant whose value is the same as the
     43 ** SQLITE_SOURCE_ID C preprocessor macro.
     44 */
     45 const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
     46 
     47 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
     48 ** returns an integer equal to SQLITE_VERSION_NUMBER.
     49 */
     50 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
     51 
     52 /* IMPLEMENTATION-OF: R-54823-41343 The sqlite3_threadsafe() function returns
     53 ** zero if and only if SQLite was compiled mutexing code omitted due to
     54 ** the SQLITE_THREADSAFE compile-time option being set to 0.
     55 */
     56 int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
     57 
     58 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
     59 /*
     60 ** If the following function pointer is not NULL and if
     61 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
     62 ** I/O active are written using this function.  These messages
     63 ** are intended for debugging activity only.
     64 */
     65 void (*sqlite3IoTrace)(const char*, ...) = 0;
     66 #endif
     67 
     68 /*
     69 ** If the following global variable points to a string which is the
     70 ** name of a directory, then that directory will be used to store
     71 ** temporary files.
     72 **
     73 ** See also the "PRAGMA temp_store_directory" SQL command.
     74 */
     75 char *sqlite3_temp_directory = 0;
     76 
     77 /*
     78 ** Initialize SQLite.
     79 **
     80 ** This routine must be called to initialize the memory allocation,
     81 ** VFS, and mutex subsystems prior to doing any serious work with
     82 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
     83 ** this routine will be called automatically by key routines such as
     84 ** sqlite3_open().
     85 **
     86 ** This routine is a no-op except on its very first call for the process,
     87 ** or for the first call after a call to sqlite3_shutdown.
     88 **
     89 ** The first thread to call this routine runs the initialization to
     90 ** completion.  If subsequent threads call this routine before the first
     91 ** thread has finished the initialization process, then the subsequent
     92 ** threads must block until the first thread finishes with the initialization.
     93 **
     94 ** The first thread might call this routine recursively.  Recursive
     95 ** calls to this routine should not block, of course.  Otherwise the
     96 ** initialization process would never complete.
     97 **
     98 ** Let X be the first thread to enter this routine.  Let Y be some other
     99 ** thread.  Then while the initial invocation of this routine by X is
    100 ** incomplete, it is required that:
    101 **
    102 **    *  Calls to this routine from Y must block until the outer-most
    103 **       call by X completes.
    104 **
    105 **    *  Recursive calls to this routine from thread X return immediately
    106 **       without blocking.
    107 */
    108 int sqlite3_initialize(void){
    109   sqlite3_mutex *pMaster;                      /* The main static mutex */
    110   int rc;                                      /* Result code */
    111 
    112 #ifdef SQLITE_OMIT_WSD
    113   rc = sqlite3_wsd_init(4096, 24);
    114   if( rc!=SQLITE_OK ){
    115     return rc;
    116   }
    117 #endif
    118 
    119   /* If SQLite is already completely initialized, then this call
    120   ** to sqlite3_initialize() should be a no-op.  But the initialization
    121   ** must be complete.  So isInit must not be set until the very end
    122   ** of this routine.
    123   */
    124   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
    125 
    126   /* Make sure the mutex subsystem is initialized.  If unable to
    127   ** initialize the mutex subsystem, return early with the error.
    128   ** If the system is so sick that we are unable to allocate a mutex,
    129   ** there is not much SQLite is going to be able to do.
    130   **
    131   ** The mutex subsystem must take care of serializing its own
    132   ** initialization.
    133   */
    134   rc = sqlite3MutexInit();
    135   if( rc ) return rc;
    136 
    137   /* Initialize the malloc() system and the recursive pInitMutex mutex.
    138   ** This operation is protected by the STATIC_MASTER mutex.  Note that
    139   ** MutexAlloc() is called for a static mutex prior to initializing the
    140   ** malloc subsystem - this implies that the allocation of a static
    141   ** mutex must not require support from the malloc subsystem.
    142   */
    143   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
    144   sqlite3_mutex_enter(pMaster);
    145   sqlite3GlobalConfig.isMutexInit = 1;
    146   if( !sqlite3GlobalConfig.isMallocInit ){
    147     rc = sqlite3MallocInit();
    148   }
    149   if( rc==SQLITE_OK ){
    150     sqlite3GlobalConfig.isMallocInit = 1;
    151     if( !sqlite3GlobalConfig.pInitMutex ){
    152       sqlite3GlobalConfig.pInitMutex =
    153            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
    154       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
    155         rc = SQLITE_NOMEM;
    156       }
    157     }
    158   }
    159   if( rc==SQLITE_OK ){
    160     sqlite3GlobalConfig.nRefInitMutex++;
    161   }
    162   sqlite3_mutex_leave(pMaster);
    163 
    164   /* If rc is not SQLITE_OK at this point, then either the malloc
    165   ** subsystem could not be initialized or the system failed to allocate
    166   ** the pInitMutex mutex. Return an error in either case.  */
    167   if( rc!=SQLITE_OK ){
    168     return rc;
    169   }
    170 
    171   /* Do the rest of the initialization under the recursive mutex so
    172   ** that we will be able to handle recursive calls into
    173   ** sqlite3_initialize().  The recursive calls normally come through
    174   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
    175   ** recursive calls might also be possible.
    176   **
    177   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
    178   ** to the xInit method, so the xInit method need not be threadsafe.
    179   **
    180   ** The following mutex is what serializes access to the appdef pcache xInit
    181   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
    182   ** call to sqlite3PcacheInitialize().
    183   */
    184   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
    185   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
    186     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
    187     sqlite3GlobalConfig.inProgress = 1;
    188     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
    189     sqlite3RegisterGlobalFunctions();
    190     if( sqlite3GlobalConfig.isPCacheInit==0 ){
    191       rc = sqlite3PcacheInitialize();
    192     }
    193     if( rc==SQLITE_OK ){
    194       sqlite3GlobalConfig.isPCacheInit = 1;
    195       rc = sqlite3OsInit();
    196     }
    197     if( rc==SQLITE_OK ){
    198       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
    199           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
    200       sqlite3GlobalConfig.isInit = 1;
    201     }
    202     sqlite3GlobalConfig.inProgress = 0;
    203   }
    204   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
    205 
    206   /* Go back under the static mutex and clean up the recursive
    207   ** mutex to prevent a resource leak.
    208   */
    209   sqlite3_mutex_enter(pMaster);
    210   sqlite3GlobalConfig.nRefInitMutex--;
    211   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
    212     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
    213     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
    214     sqlite3GlobalConfig.pInitMutex = 0;
    215   }
    216   sqlite3_mutex_leave(pMaster);
    217 
    218   /* The following is just a sanity check to make sure SQLite has
    219   ** been compiled correctly.  It is important to run this code, but
    220   ** we don't want to run it too often and soak up CPU cycles for no
    221   ** reason.  So we run it once during initialization.
    222   */
    223 #ifndef NDEBUG
    224 #ifndef SQLITE_OMIT_FLOATING_POINT
    225   /* This section of code's only "output" is via assert() statements. */
    226   if ( rc==SQLITE_OK ){
    227     u64 x = (((u64)1)<<63)-1;
    228     double y;
    229     assert(sizeof(x)==8);
    230     assert(sizeof(x)==sizeof(y));
    231     memcpy(&y, &x, 8);
    232     assert( sqlite3IsNaN(y) );
    233   }
    234 #endif
    235 #endif
    236 
    237   return rc;
    238 }
    239 
    240 /*
    241 ** Undo the effects of sqlite3_initialize().  Must not be called while
    242 ** there are outstanding database connections or memory allocations or
    243 ** while any part of SQLite is otherwise in use in any thread.  This
    244 ** routine is not threadsafe.  But it is safe to invoke this routine
    245 ** on when SQLite is already shut down.  If SQLite is already shut down
    246 ** when this routine is invoked, then this routine is a harmless no-op.
    247 */
    248 int sqlite3_shutdown(void){
    249   if( sqlite3GlobalConfig.isInit ){
    250     sqlite3_os_end();
    251     sqlite3_reset_auto_extension();
    252     sqlite3GlobalConfig.isInit = 0;
    253   }
    254   if( sqlite3GlobalConfig.isPCacheInit ){
    255     sqlite3PcacheShutdown();
    256     sqlite3GlobalConfig.isPCacheInit = 0;
    257   }
    258   if( sqlite3GlobalConfig.isMallocInit ){
    259     sqlite3MallocEnd();
    260     sqlite3GlobalConfig.isMallocInit = 0;
    261   }
    262   if( sqlite3GlobalConfig.isMutexInit ){
    263     sqlite3MutexEnd();
    264     sqlite3GlobalConfig.isMutexInit = 0;
    265   }
    266 
    267   return SQLITE_OK;
    268 }
    269 
    270 /*
    271 ** This API allows applications to modify the global configuration of
    272 ** the SQLite library at run-time.
    273 **
    274 ** This routine should only be called when there are no outstanding
    275 ** database connections or memory allocations.  This routine is not
    276 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
    277 ** behavior.
    278 */
    279 int sqlite3_config(int op, ...){
    280   va_list ap;
    281   int rc = SQLITE_OK;
    282 
    283   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
    284   ** the SQLite library is in use. */
    285   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
    286 
    287   va_start(ap, op);
    288   switch( op ){
    289 
    290     /* Mutex configuration options are only available in a threadsafe
    291     ** compile.
    292     */
    293 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
    294     case SQLITE_CONFIG_SINGLETHREAD: {
    295       /* Disable all mutexing */
    296       sqlite3GlobalConfig.bCoreMutex = 0;
    297       sqlite3GlobalConfig.bFullMutex = 0;
    298       break;
    299     }
    300     case SQLITE_CONFIG_MULTITHREAD: {
    301       /* Disable mutexing of database connections */
    302       /* Enable mutexing of core data structures */
    303       sqlite3GlobalConfig.bCoreMutex = 1;
    304       sqlite3GlobalConfig.bFullMutex = 0;
    305       break;
    306     }
    307     case SQLITE_CONFIG_SERIALIZED: {
    308       /* Enable all mutexing */
    309       sqlite3GlobalConfig.bCoreMutex = 1;
    310       sqlite3GlobalConfig.bFullMutex = 1;
    311       break;
    312     }
    313     case SQLITE_CONFIG_MUTEX: {
    314       /* Specify an alternative mutex implementation */
    315       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
    316       break;
    317     }
    318     case SQLITE_CONFIG_GETMUTEX: {
    319       /* Retrieve the current mutex implementation */
    320       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
    321       break;
    322     }
    323 #endif
    324 
    325 
    326     case SQLITE_CONFIG_MALLOC: {
    327       /* Specify an alternative malloc implementation */
    328       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
    329       break;
    330     }
    331     case SQLITE_CONFIG_GETMALLOC: {
    332       /* Retrieve the current malloc() implementation */
    333       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
    334       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
    335       break;
    336     }
    337     case SQLITE_CONFIG_MEMSTATUS: {
    338       /* Enable or disable the malloc status collection */
    339       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
    340       break;
    341     }
    342     case SQLITE_CONFIG_SCRATCH: {
    343       /* Designate a buffer for scratch memory space */
    344       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
    345       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
    346       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
    347       break;
    348     }
    349     case SQLITE_CONFIG_PAGECACHE: {
    350       /* Designate a buffer for page cache memory space */
    351       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
    352       sqlite3GlobalConfig.szPage = va_arg(ap, int);
    353       sqlite3GlobalConfig.nPage = va_arg(ap, int);
    354       break;
    355     }
    356 
    357     case SQLITE_CONFIG_PCACHE: {
    358       /* Specify an alternative page cache implementation */
    359       sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
    360       break;
    361     }
    362 
    363     case SQLITE_CONFIG_GETPCACHE: {
    364       if( sqlite3GlobalConfig.pcache.xInit==0 ){
    365         sqlite3PCacheSetDefault();
    366       }
    367       *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
    368       break;
    369     }
    370 
    371 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
    372     case SQLITE_CONFIG_HEAP: {
    373       /* Designate a buffer for heap memory space */
    374       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
    375       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
    376       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
    377 
    378       if( sqlite3GlobalConfig.mnReq<1 ){
    379         sqlite3GlobalConfig.mnReq = 1;
    380       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
    381         /* cap min request size at 2^12 */
    382         sqlite3GlobalConfig.mnReq = (1<<12);
    383       }
    384 
    385       if( sqlite3GlobalConfig.pHeap==0 ){
    386         /* If the heap pointer is NULL, then restore the malloc implementation
    387         ** back to NULL pointers too.  This will cause the malloc to go
    388         ** back to its default implementation when sqlite3_initialize() is
    389         ** run.
    390         */
    391         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
    392       }else{
    393         /* The heap pointer is not NULL, then install one of the
    394         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
    395         ** ENABLE_MEMSYS5 is defined, return an error.
    396         */
    397 #ifdef SQLITE_ENABLE_MEMSYS3
    398         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
    399 #endif
    400 #ifdef SQLITE_ENABLE_MEMSYS5
    401         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
    402 #endif
    403       }
    404       break;
    405     }
    406 #endif
    407 
    408     case SQLITE_CONFIG_LOOKASIDE: {
    409       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
    410       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
    411       break;
    412     }
    413 
    414     /* Record a pointer to the logger funcction and its first argument.
    415     ** The default is NULL.  Logging is disabled if the function pointer is
    416     ** NULL.
    417     */
    418     case SQLITE_CONFIG_LOG: {
    419       /* MSVC is picky about pulling func ptrs from va lists.
    420       ** http://support.microsoft.com/kb/47961
    421       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
    422       */
    423       typedef void(*LOGFUNC_t)(void*,int,const char*);
    424       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
    425       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
    426       break;
    427     }
    428 
    429     default: {
    430       rc = SQLITE_ERROR;
    431       break;
    432     }
    433   }
    434   va_end(ap);
    435   return rc;
    436 }
    437 
    438 /*
    439 ** Set up the lookaside buffers for a database connection.
    440 ** Return SQLITE_OK on success.
    441 ** If lookaside is already active, return SQLITE_BUSY.
    442 **
    443 ** The sz parameter is the number of bytes in each lookaside slot.
    444 ** The cnt parameter is the number of slots.  If pStart is NULL the
    445 ** space for the lookaside memory is obtained from sqlite3_malloc().
    446 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
    447 ** the lookaside memory.
    448 */
    449 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
    450   void *pStart;
    451   if( db->lookaside.nOut ){
    452     return SQLITE_BUSY;
    453   }
    454   /* Free any existing lookaside buffer for this handle before
    455   ** allocating a new one so we don't have to have space for
    456   ** both at the same time.
    457   */
    458   if( db->lookaside.bMalloced ){
    459     sqlite3_free(db->lookaside.pStart);
    460   }
    461   /* The size of a lookaside slot needs to be larger than a pointer
    462   ** to be useful.
    463   */
    464   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
    465   if( cnt<0 ) cnt = 0;
    466   if( sz==0 || cnt==0 ){
    467     sz = 0;
    468     pStart = 0;
    469   }else if( pBuf==0 ){
    470     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
    471     sqlite3BeginBenignMalloc();
    472     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
    473     sqlite3EndBenignMalloc();
    474   }else{
    475     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
    476     pStart = pBuf;
    477   }
    478   db->lookaside.pStart = pStart;
    479   db->lookaside.pFree = 0;
    480   db->lookaside.sz = (u16)sz;
    481   if( pStart ){
    482     int i;
    483     LookasideSlot *p;
    484     assert( sz > (int)sizeof(LookasideSlot*) );
    485     p = (LookasideSlot*)pStart;
    486     for(i=cnt-1; i>=0; i--){
    487       p->pNext = db->lookaside.pFree;
    488       db->lookaside.pFree = p;
    489       p = (LookasideSlot*)&((u8*)p)[sz];
    490     }
    491     db->lookaside.pEnd = p;
    492     db->lookaside.bEnabled = 1;
    493     db->lookaside.bMalloced = pBuf==0 ?1:0;
    494   }else{
    495     db->lookaside.pEnd = 0;
    496     db->lookaside.bEnabled = 0;
    497     db->lookaside.bMalloced = 0;
    498   }
    499   return SQLITE_OK;
    500 }
    501 
    502 /*
    503 ** Return the mutex associated with a database connection.
    504 */
    505 sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
    506   return db->mutex;
    507 }
    508 
    509 /*
    510 ** Configuration settings for an individual database connection
    511 */
    512 int sqlite3_db_config(sqlite3 *db, int op, ...){
    513   va_list ap;
    514   int rc;
    515   va_start(ap, op);
    516   switch( op ){
    517     case SQLITE_DBCONFIG_LOOKASIDE: {
    518       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
    519       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
    520       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
    521       rc = setupLookaside(db, pBuf, sz, cnt);
    522       break;
    523     }
    524     default: {
    525       static const struct {
    526         int op;      /* The opcode */
    527         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
    528       } aFlagOp[] = {
    529         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
    530         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
    531       };
    532       unsigned int i;
    533       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
    534       for(i=0; i<ArraySize(aFlagOp); i++){
    535         if( aFlagOp[i].op==op ){
    536           int onoff = va_arg(ap, int);
    537           int *pRes = va_arg(ap, int*);
    538           int oldFlags = db->flags;
    539           if( onoff>0 ){
    540             db->flags |= aFlagOp[i].mask;
    541           }else if( onoff==0 ){
    542             db->flags &= ~aFlagOp[i].mask;
    543           }
    544           if( oldFlags!=db->flags ){
    545             sqlite3ExpirePreparedStatements(db);
    546           }
    547           if( pRes ){
    548             *pRes = (db->flags & aFlagOp[i].mask)!=0;
    549           }
    550           rc = SQLITE_OK;
    551           break;
    552         }
    553       }
    554       break;
    555     }
    556   }
    557   va_end(ap);
    558   return rc;
    559 }
    560 
    561 
    562 /*
    563 ** Return true if the buffer z[0..n-1] contains all spaces.
    564 */
    565 static int allSpaces(const char *z, int n){
    566   while( n>0 && z[n-1]==' ' ){ n--; }
    567   return n==0;
    568 }
    569 
    570 /*
    571 ** This is the default collating function named "BINARY" which is always
    572 ** available.
    573 **
    574 ** If the padFlag argument is not NULL then space padding at the end
    575 ** of strings is ignored.  This implements the RTRIM collation.
    576 */
    577 static int binCollFunc(
    578   void *padFlag,
    579   int nKey1, const void *pKey1,
    580   int nKey2, const void *pKey2
    581 ){
    582   int rc, n;
    583   n = nKey1<nKey2 ? nKey1 : nKey2;
    584   rc = memcmp(pKey1, pKey2, n);
    585   if( rc==0 ){
    586     if( padFlag
    587      && allSpaces(((char*)pKey1)+n, nKey1-n)
    588      && allSpaces(((char*)pKey2)+n, nKey2-n)
    589     ){
    590       /* Leave rc unchanged at 0 */
    591     }else{
    592       rc = nKey1 - nKey2;
    593     }
    594   }
    595   return rc;
    596 }
    597 
    598 /*
    599 ** Another built-in collating sequence: NOCASE.
    600 **
    601 ** This collating sequence is intended to be used for "case independant
    602 ** comparison". SQLite's knowledge of upper and lower case equivalents
    603 ** extends only to the 26 characters used in the English language.
    604 **
    605 ** At the moment there is only a UTF-8 implementation.
    606 */
    607 static int nocaseCollatingFunc(
    608   void *NotUsed,
    609   int nKey1, const void *pKey1,
    610   int nKey2, const void *pKey2
    611 ){
    612   int r = sqlite3StrNICmp(
    613       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
    614   UNUSED_PARAMETER(NotUsed);
    615   if( 0==r ){
    616     r = nKey1-nKey2;
    617   }
    618   return r;
    619 }
    620 
    621 /*
    622 ** Return the ROWID of the most recent insert
    623 */
    624 sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
    625   return db->lastRowid;
    626 }
    627 
    628 /*
    629 ** Return the number of changes in the most recent call to sqlite3_exec().
    630 */
    631 int sqlite3_changes(sqlite3 *db){
    632   return db->nChange;
    633 }
    634 
    635 /*
    636 ** Return the number of changes since the database handle was opened.
    637 */
    638 int sqlite3_total_changes(sqlite3 *db){
    639   return db->nTotalChange;
    640 }
    641 
    642 /*
    643 ** Close all open savepoints. This function only manipulates fields of the
    644 ** database handle object, it does not close any savepoints that may be open
    645 ** at the b-tree/pager level.
    646 */
    647 void sqlite3CloseSavepoints(sqlite3 *db){
    648   while( db->pSavepoint ){
    649     Savepoint *pTmp = db->pSavepoint;
    650     db->pSavepoint = pTmp->pNext;
    651     sqlite3DbFree(db, pTmp);
    652   }
    653   db->nSavepoint = 0;
    654   db->nStatement = 0;
    655   db->isTransactionSavepoint = 0;
    656 }
    657 
    658 /*
    659 ** Invoke the destructor function associated with FuncDef p, if any. Except,
    660 ** if this is not the last copy of the function, do not invoke it. Multiple
    661 ** copies of a single function are created when create_function() is called
    662 ** with SQLITE_ANY as the encoding.
    663 */
    664 static void functionDestroy(sqlite3 *db, FuncDef *p){
    665   FuncDestructor *pDestructor = p->pDestructor;
    666   if( pDestructor ){
    667     pDestructor->nRef--;
    668     if( pDestructor->nRef==0 ){
    669       pDestructor->xDestroy(pDestructor->pUserData);
    670       sqlite3DbFree(db, pDestructor);
    671     }
    672   }
    673 }
    674 
    675 /*
    676 ** Close an existing SQLite database
    677 */
    678 int sqlite3_close(sqlite3 *db){
    679   HashElem *i;                    /* Hash table iterator */
    680   int j;
    681 
    682   if( !db ){
    683     return SQLITE_OK;
    684   }
    685   if( !sqlite3SafetyCheckSickOrOk(db) ){
    686     return SQLITE_MISUSE_BKPT;
    687   }
    688   sqlite3_mutex_enter(db->mutex);
    689 
    690   /* Force xDestroy calls on all virtual tables */
    691   sqlite3ResetInternalSchema(db, -1);
    692 
    693   /* If a transaction is open, the ResetInternalSchema() call above
    694   ** will not have called the xDisconnect() method on any virtual
    695   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
    696   ** call will do so. We need to do this before the check for active
    697   ** SQL statements below, as the v-table implementation may be storing
    698   ** some prepared statements internally.
    699   */
    700   sqlite3VtabRollback(db);
    701 
    702   /* If there are any outstanding VMs, return SQLITE_BUSY. */
    703   if( db->pVdbe ){
    704     sqlite3Error(db, SQLITE_BUSY,
    705         "unable to close due to unfinalised statements");
    706     sqlite3_mutex_leave(db->mutex);
    707     return SQLITE_BUSY;
    708   }
    709   assert( sqlite3SafetyCheckSickOrOk(db) );
    710 
    711   for(j=0; j<db->nDb; j++){
    712     Btree *pBt = db->aDb[j].pBt;
    713     if( pBt && sqlite3BtreeIsInBackup(pBt) ){
    714       sqlite3Error(db, SQLITE_BUSY,
    715           "unable to close due to unfinished backup operation");
    716       sqlite3_mutex_leave(db->mutex);
    717       return SQLITE_BUSY;
    718     }
    719   }
    720 
    721   /* Free any outstanding Savepoint structures. */
    722   sqlite3CloseSavepoints(db);
    723 
    724   for(j=0; j<db->nDb; j++){
    725     struct Db *pDb = &db->aDb[j];
    726     if( pDb->pBt ){
    727       sqlite3BtreeClose(pDb->pBt);
    728       pDb->pBt = 0;
    729       if( j!=1 ){
    730         pDb->pSchema = 0;
    731       }
    732     }
    733   }
    734   sqlite3ResetInternalSchema(db, -1);
    735 
    736   /* Tell the code in notify.c that the connection no longer holds any
    737   ** locks and does not require any further unlock-notify callbacks.
    738   */
    739   sqlite3ConnectionClosed(db);
    740 
    741   assert( db->nDb<=2 );
    742   assert( db->aDb==db->aDbStatic );
    743   for(j=0; j<ArraySize(db->aFunc.a); j++){
    744     FuncDef *pNext, *pHash, *p;
    745     for(p=db->aFunc.a[j]; p; p=pHash){
    746       pHash = p->pHash;
    747       while( p ){
    748         functionDestroy(db, p);
    749         pNext = p->pNext;
    750         sqlite3DbFree(db, p);
    751         p = pNext;
    752       }
    753     }
    754   }
    755   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
    756     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
    757     /* Invoke any destructors registered for collation sequence user data. */
    758     for(j=0; j<3; j++){
    759       if( pColl[j].xDel ){
    760         pColl[j].xDel(pColl[j].pUser);
    761       }
    762     }
    763     sqlite3DbFree(db, pColl);
    764   }
    765   sqlite3HashClear(&db->aCollSeq);
    766 #ifndef SQLITE_OMIT_VIRTUALTABLE
    767   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
    768     Module *pMod = (Module *)sqliteHashData(i);
    769     if( pMod->xDestroy ){
    770       pMod->xDestroy(pMod->pAux);
    771     }
    772     sqlite3DbFree(db, pMod);
    773   }
    774   sqlite3HashClear(&db->aModule);
    775 #endif
    776 
    777   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
    778   if( db->pErr ){
    779     sqlite3ValueFree(db->pErr);
    780   }
    781   sqlite3CloseExtensions(db);
    782 
    783   db->magic = SQLITE_MAGIC_ERROR;
    784 
    785   /* The temp-database schema is allocated differently from the other schema
    786   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
    787   ** So it needs to be freed here. Todo: Why not roll the temp schema into
    788   ** the same sqliteMalloc() as the one that allocates the database
    789   ** structure?
    790   */
    791   sqlite3DbFree(db, db->aDb[1].pSchema);
    792   sqlite3_mutex_leave(db->mutex);
    793   db->magic = SQLITE_MAGIC_CLOSED;
    794   sqlite3_mutex_free(db->mutex);
    795   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
    796   if( db->lookaside.bMalloced ){
    797     sqlite3_free(db->lookaside.pStart);
    798   }
    799   sqlite3_free(db);
    800   return SQLITE_OK;
    801 }
    802 
    803 /*
    804 ** Rollback all database files.
    805 */
    806 void sqlite3RollbackAll(sqlite3 *db){
    807   int i;
    808   int inTrans = 0;
    809   assert( sqlite3_mutex_held(db->mutex) );
    810   sqlite3BeginBenignMalloc();
    811   for(i=0; i<db->nDb; i++){
    812     if( db->aDb[i].pBt ){
    813       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
    814         inTrans = 1;
    815       }
    816       sqlite3BtreeRollback(db->aDb[i].pBt);
    817       db->aDb[i].inTrans = 0;
    818     }
    819   }
    820   sqlite3VtabRollback(db);
    821   sqlite3EndBenignMalloc();
    822 
    823   if( db->flags&SQLITE_InternChanges ){
    824     sqlite3ExpirePreparedStatements(db);
    825     sqlite3ResetInternalSchema(db, -1);
    826   }
    827 
    828   /* Any deferred constraint violations have now been resolved. */
    829   db->nDeferredCons = 0;
    830 
    831   /* If one has been configured, invoke the rollback-hook callback */
    832   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
    833     db->xRollbackCallback(db->pRollbackArg);
    834   }
    835 }
    836 
    837 /*
    838 ** Return a static string that describes the kind of error specified in the
    839 ** argument.
    840 */
    841 const char *sqlite3ErrStr(int rc){
    842   static const char* const aMsg[] = {
    843     /* SQLITE_OK          */ "not an error",
    844     /* SQLITE_ERROR       */ "SQL logic error or missing database",
    845     /* SQLITE_INTERNAL    */ 0,
    846     /* SQLITE_PERM        */ "access permission denied",
    847     /* SQLITE_ABORT       */ "callback requested query abort",
    848     /* SQLITE_BUSY        */ "database is locked",
    849     /* SQLITE_LOCKED      */ "database table is locked",
    850     /* SQLITE_NOMEM       */ "out of memory",
    851     /* SQLITE_READONLY    */ "attempt to write a readonly database",
    852     /* SQLITE_INTERRUPT   */ "interrupted",
    853     /* SQLITE_IOERR       */ "disk I/O error",
    854     /* SQLITE_CORRUPT     */ "database disk image is malformed",
    855     /* SQLITE_NOTFOUND    */ "unknown operation",
    856     /* SQLITE_FULL        */ "database or disk is full",
    857     /* SQLITE_CANTOPEN    */ "unable to open database file",
    858     /* SQLITE_PROTOCOL    */ "locking protocol",
    859     /* SQLITE_EMPTY       */ "table contains no data",
    860     /* SQLITE_SCHEMA      */ "database schema has changed",
    861     /* SQLITE_TOOBIG      */ "string or blob too big",
    862     /* SQLITE_CONSTRAINT  */ "constraint failed",
    863     /* SQLITE_MISMATCH    */ "datatype mismatch",
    864     /* SQLITE_MISUSE      */ "library routine called out of sequence",
    865     /* SQLITE_NOLFS       */ "large file support is disabled",
    866     /* SQLITE_AUTH        */ "authorization denied",
    867     /* SQLITE_FORMAT      */ "auxiliary database format error",
    868     /* SQLITE_RANGE       */ "bind or column index out of range",
    869     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
    870   };
    871   rc &= 0xff;
    872   if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
    873     return aMsg[rc];
    874   }else{
    875     return "unknown error";
    876   }
    877 }
    878 
    879 /*
    880 ** This routine implements a busy callback that sleeps and tries
    881 ** again until a timeout value is reached.  The timeout value is
    882 ** an integer number of milliseconds passed in as the first
    883 ** argument.
    884 */
    885 static int sqliteDefaultBusyCallback(
    886  void *ptr,               /* Database connection */
    887  int count                /* Number of times table has been busy */
    888 ){
    889 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
    890   static const u8 delays[] =
    891      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
    892   static const u8 totals[] =
    893      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
    894 # define NDELAY ArraySize(delays)
    895   sqlite3 *db = (sqlite3 *)ptr;
    896   int timeout = db->busyTimeout;
    897   int delay, prior;
    898 
    899   assert( count>=0 );
    900   if( count < NDELAY ){
    901     delay = delays[count];
    902     prior = totals[count];
    903   }else{
    904     delay = delays[NDELAY-1];
    905     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
    906   }
    907   if( prior + delay > timeout ){
    908     delay = timeout - prior;
    909     if( delay<=0 ) return 0;
    910   }
    911   sqlite3OsSleep(db->pVfs, delay*1000);
    912   return 1;
    913 #else
    914   sqlite3 *db = (sqlite3 *)ptr;
    915   int timeout = ((sqlite3 *)ptr)->busyTimeout;
    916   if( (count+1)*1000 > timeout ){
    917     return 0;
    918   }
    919   sqlite3OsSleep(db->pVfs, 1000000);
    920   return 1;
    921 #endif
    922 }
    923 
    924 /*
    925 ** Invoke the given busy handler.
    926 **
    927 ** This routine is called when an operation failed with a lock.
    928 ** If this routine returns non-zero, the lock is retried.  If it
    929 ** returns 0, the operation aborts with an SQLITE_BUSY error.
    930 */
    931 int sqlite3InvokeBusyHandler(BusyHandler *p){
    932   int rc;
    933   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
    934   rc = p->xFunc(p->pArg, p->nBusy);
    935   if( rc==0 ){
    936     p->nBusy = -1;
    937   }else{
    938     p->nBusy++;
    939   }
    940   return rc;
    941 }
    942 
    943 /*
    944 ** This routine sets the busy callback for an Sqlite database to the
    945 ** given callback function with the given argument.
    946 */
    947 int sqlite3_busy_handler(
    948   sqlite3 *db,
    949   int (*xBusy)(void*,int),
    950   void *pArg
    951 ){
    952   sqlite3_mutex_enter(db->mutex);
    953   db->busyHandler.xFunc = xBusy;
    954   db->busyHandler.pArg = pArg;
    955   db->busyHandler.nBusy = 0;
    956   sqlite3_mutex_leave(db->mutex);
    957   return SQLITE_OK;
    958 }
    959 
    960 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
    961 /*
    962 ** This routine sets the progress callback for an Sqlite database to the
    963 ** given callback function with the given argument. The progress callback will
    964 ** be invoked every nOps opcodes.
    965 */
    966 void sqlite3_progress_handler(
    967   sqlite3 *db,
    968   int nOps,
    969   int (*xProgress)(void*),
    970   void *pArg
    971 ){
    972   sqlite3_mutex_enter(db->mutex);
    973   if( nOps>0 ){
    974     db->xProgress = xProgress;
    975     db->nProgressOps = nOps;
    976     db->pProgressArg = pArg;
    977   }else{
    978     db->xProgress = 0;
    979     db->nProgressOps = 0;
    980     db->pProgressArg = 0;
    981   }
    982   sqlite3_mutex_leave(db->mutex);
    983 }
    984 #endif
    985 
    986 
    987 /*
    988 ** This routine installs a default busy handler that waits for the
    989 ** specified number of milliseconds before returning 0.
    990 */
    991 int sqlite3_busy_timeout(sqlite3 *db, int ms){
    992   if( ms>0 ){
    993     db->busyTimeout = ms;
    994     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
    995   }else{
    996     sqlite3_busy_handler(db, 0, 0);
    997   }
    998   return SQLITE_OK;
    999 }
   1000 
   1001 /*
   1002 ** Cause any pending operation to stop at its earliest opportunity.
   1003 */
   1004 void sqlite3_interrupt(sqlite3 *db){
   1005   db->u1.isInterrupted = 1;
   1006 }
   1007 
   1008 
   1009 /*
   1010 ** This function is exactly the same as sqlite3_create_function(), except
   1011 ** that it is designed to be called by internal code. The difference is
   1012 ** that if a malloc() fails in sqlite3_create_function(), an error code
   1013 ** is returned and the mallocFailed flag cleared.
   1014 */
   1015 int sqlite3CreateFunc(
   1016   sqlite3 *db,
   1017   const char *zFunctionName,
   1018   int nArg,
   1019   int enc,
   1020   void *pUserData,
   1021   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
   1022   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   1023   void (*xFinal)(sqlite3_context*),
   1024   FuncDestructor *pDestructor
   1025 ){
   1026   FuncDef *p;
   1027   int nName;
   1028 
   1029   assert( sqlite3_mutex_held(db->mutex) );
   1030   if( zFunctionName==0 ||
   1031       (xFunc && (xFinal || xStep)) ||
   1032       (!xFunc && (xFinal && !xStep)) ||
   1033       (!xFunc && (!xFinal && xStep)) ||
   1034       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
   1035       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
   1036     return SQLITE_MISUSE_BKPT;
   1037   }
   1038 
   1039 #ifndef SQLITE_OMIT_UTF16
   1040   /* If SQLITE_UTF16 is specified as the encoding type, transform this
   1041   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
   1042   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
   1043   **
   1044   ** If SQLITE_ANY is specified, add three versions of the function
   1045   ** to the hash table.
   1046   */
   1047   if( enc==SQLITE_UTF16 ){
   1048     enc = SQLITE_UTF16NATIVE;
   1049   }else if( enc==SQLITE_ANY ){
   1050     int rc;
   1051     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
   1052          pUserData, xFunc, xStep, xFinal, pDestructor);
   1053     if( rc==SQLITE_OK ){
   1054       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
   1055           pUserData, xFunc, xStep, xFinal, pDestructor);
   1056     }
   1057     if( rc!=SQLITE_OK ){
   1058       return rc;
   1059     }
   1060     enc = SQLITE_UTF16BE;
   1061   }
   1062 #else
   1063   enc = SQLITE_UTF8;
   1064 #endif
   1065 
   1066   /* Check if an existing function is being overridden or deleted. If so,
   1067   ** and there are active VMs, then return SQLITE_BUSY. If a function
   1068   ** is being overridden/deleted but there are no active VMs, allow the
   1069   ** operation to continue but invalidate all precompiled statements.
   1070   */
   1071   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
   1072   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
   1073     if( db->activeVdbeCnt ){
   1074       sqlite3Error(db, SQLITE_BUSY,
   1075         "unable to delete/modify user-function due to active statements");
   1076       assert( !db->mallocFailed );
   1077       return SQLITE_BUSY;
   1078     }else{
   1079       sqlite3ExpirePreparedStatements(db);
   1080     }
   1081   }
   1082 
   1083   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
   1084   assert(p || db->mallocFailed);
   1085   if( !p ){
   1086     return SQLITE_NOMEM;
   1087   }
   1088 
   1089   /* If an older version of the function with a configured destructor is
   1090   ** being replaced invoke the destructor function here. */
   1091   functionDestroy(db, p);
   1092 
   1093   if( pDestructor ){
   1094     pDestructor->nRef++;
   1095   }
   1096   p->pDestructor = pDestructor;
   1097   p->flags = 0;
   1098   p->xFunc = xFunc;
   1099   p->xStep = xStep;
   1100   p->xFinalize = xFinal;
   1101   p->pUserData = pUserData;
   1102   p->nArg = (u16)nArg;
   1103   return SQLITE_OK;
   1104 }
   1105 
   1106 /*
   1107 ** Create new user functions.
   1108 */
   1109 int sqlite3_create_function(
   1110   sqlite3 *db,
   1111   const char *zFunc,
   1112   int nArg,
   1113   int enc,
   1114   void *p,
   1115   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
   1116   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   1117   void (*xFinal)(sqlite3_context*)
   1118 ){
   1119   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
   1120                                     xFinal, 0);
   1121 }
   1122 
   1123 int sqlite3_create_function_v2(
   1124   sqlite3 *db,
   1125   const char *zFunc,
   1126   int nArg,
   1127   int enc,
   1128   void *p,
   1129   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
   1130   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   1131   void (*xFinal)(sqlite3_context*),
   1132   void (*xDestroy)(void *)
   1133 ){
   1134   int rc = SQLITE_ERROR;
   1135   FuncDestructor *pArg = 0;
   1136   sqlite3_mutex_enter(db->mutex);
   1137   if( xDestroy ){
   1138     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
   1139     if( !pArg ){
   1140       xDestroy(p);
   1141       goto out;
   1142     }
   1143     pArg->xDestroy = xDestroy;
   1144     pArg->pUserData = p;
   1145   }
   1146   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
   1147   if( pArg && pArg->nRef==0 ){
   1148     assert( rc!=SQLITE_OK );
   1149     xDestroy(p);
   1150     sqlite3DbFree(db, pArg);
   1151   }
   1152 
   1153  out:
   1154   rc = sqlite3ApiExit(db, rc);
   1155   sqlite3_mutex_leave(db->mutex);
   1156   return rc;
   1157 }
   1158 
   1159 #ifndef SQLITE_OMIT_UTF16
   1160 int sqlite3_create_function16(
   1161   sqlite3 *db,
   1162   const void *zFunctionName,
   1163   int nArg,
   1164   int eTextRep,
   1165   void *p,
   1166   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   1167   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   1168   void (*xFinal)(sqlite3_context*)
   1169 ){
   1170   int rc;
   1171   char *zFunc8;
   1172   sqlite3_mutex_enter(db->mutex);
   1173   assert( !db->mallocFailed );
   1174   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
   1175   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
   1176   sqlite3DbFree(db, zFunc8);
   1177   rc = sqlite3ApiExit(db, rc);
   1178   sqlite3_mutex_leave(db->mutex);
   1179   return rc;
   1180 }
   1181 #endif
   1182 
   1183 
   1184 /*
   1185 ** Declare that a function has been overloaded by a virtual table.
   1186 **
   1187 ** If the function already exists as a regular global function, then
   1188 ** this routine is a no-op.  If the function does not exist, then create
   1189 ** a new one that always throws a run-time error.
   1190 **
   1191 ** When virtual tables intend to provide an overloaded function, they
   1192 ** should call this routine to make sure the global function exists.
   1193 ** A global function must exist in order for name resolution to work
   1194 ** properly.
   1195 */
   1196 int sqlite3_overload_function(
   1197   sqlite3 *db,
   1198   const char *zName,
   1199   int nArg
   1200 ){
   1201   int nName = sqlite3Strlen30(zName);
   1202   int rc;
   1203   sqlite3_mutex_enter(db->mutex);
   1204   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
   1205     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
   1206                       0, sqlite3InvalidFunction, 0, 0, 0);
   1207   }
   1208   rc = sqlite3ApiExit(db, SQLITE_OK);
   1209   sqlite3_mutex_leave(db->mutex);
   1210   return rc;
   1211 }
   1212 
   1213 #ifndef SQLITE_OMIT_TRACE
   1214 /*
   1215 ** Register a trace function.  The pArg from the previously registered trace
   1216 ** is returned.
   1217 **
   1218 ** A NULL trace function means that no tracing is executes.  A non-NULL
   1219 ** trace is a pointer to a function that is invoked at the start of each
   1220 ** SQL statement.
   1221 */
   1222 void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
   1223   void *pOld;
   1224   sqlite3_mutex_enter(db->mutex);
   1225   pOld = db->pTraceArg;
   1226   db->xTrace = xTrace;
   1227   db->pTraceArg = pArg;
   1228   sqlite3_mutex_leave(db->mutex);
   1229   return pOld;
   1230 }
   1231 /*
   1232 ** Register a profile function.  The pArg from the previously registered
   1233 ** profile function is returned.
   1234 **
   1235 ** A NULL profile function means that no profiling is executes.  A non-NULL
   1236 ** profile is a pointer to a function that is invoked at the conclusion of
   1237 ** each SQL statement that is run.
   1238 */
   1239 void *sqlite3_profile(
   1240   sqlite3 *db,
   1241   void (*xProfile)(void*,const char*,sqlite_uint64),
   1242   void *pArg
   1243 ){
   1244   void *pOld;
   1245   sqlite3_mutex_enter(db->mutex);
   1246   pOld = db->pProfileArg;
   1247   db->xProfile = xProfile;
   1248   db->pProfileArg = pArg;
   1249   sqlite3_mutex_leave(db->mutex);
   1250   return pOld;
   1251 }
   1252 #endif /* SQLITE_OMIT_TRACE */
   1253 
   1254 /*** EXPERIMENTAL ***
   1255 **
   1256 ** Register a function to be invoked when a transaction comments.
   1257 ** If the invoked function returns non-zero, then the commit becomes a
   1258 ** rollback.
   1259 */
   1260 void *sqlite3_commit_hook(
   1261   sqlite3 *db,              /* Attach the hook to this database */
   1262   int (*xCallback)(void*),  /* Function to invoke on each commit */
   1263   void *pArg                /* Argument to the function */
   1264 ){
   1265   void *pOld;
   1266   sqlite3_mutex_enter(db->mutex);
   1267   pOld = db->pCommitArg;
   1268   db->xCommitCallback = xCallback;
   1269   db->pCommitArg = pArg;
   1270   sqlite3_mutex_leave(db->mutex);
   1271   return pOld;
   1272 }
   1273 
   1274 /*
   1275 ** Register a callback to be invoked each time a row is updated,
   1276 ** inserted or deleted using this database connection.
   1277 */
   1278 void *sqlite3_update_hook(
   1279   sqlite3 *db,              /* Attach the hook to this database */
   1280   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
   1281   void *pArg                /* Argument to the function */
   1282 ){
   1283   void *pRet;
   1284   sqlite3_mutex_enter(db->mutex);
   1285   pRet = db->pUpdateArg;
   1286   db->xUpdateCallback = xCallback;
   1287   db->pUpdateArg = pArg;
   1288   sqlite3_mutex_leave(db->mutex);
   1289   return pRet;
   1290 }
   1291 
   1292 /*
   1293 ** Register a callback to be invoked each time a transaction is rolled
   1294 ** back by this database connection.
   1295 */
   1296 void *sqlite3_rollback_hook(
   1297   sqlite3 *db,              /* Attach the hook to this database */
   1298   void (*xCallback)(void*), /* Callback function */
   1299   void *pArg                /* Argument to the function */
   1300 ){
   1301   void *pRet;
   1302   sqlite3_mutex_enter(db->mutex);
   1303   pRet = db->pRollbackArg;
   1304   db->xRollbackCallback = xCallback;
   1305   db->pRollbackArg = pArg;
   1306   sqlite3_mutex_leave(db->mutex);
   1307   return pRet;
   1308 }
   1309 
   1310 #ifndef SQLITE_OMIT_WAL
   1311 /*
   1312 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
   1313 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
   1314 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
   1315 ** wal_autocheckpoint()).
   1316 */
   1317 int sqlite3WalDefaultHook(
   1318   void *pClientData,     /* Argument */
   1319   sqlite3 *db,           /* Connection */
   1320   const char *zDb,       /* Database */
   1321   int nFrame             /* Size of WAL */
   1322 ){
   1323   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
   1324     sqlite3BeginBenignMalloc();
   1325     sqlite3_wal_checkpoint(db, zDb);
   1326     sqlite3EndBenignMalloc();
   1327   }
   1328   return SQLITE_OK;
   1329 }
   1330 #endif /* SQLITE_OMIT_WAL */
   1331 
   1332 /*
   1333 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
   1334 ** a database after committing a transaction if there are nFrame or
   1335 ** more frames in the log file. Passing zero or a negative value as the
   1336 ** nFrame parameter disables automatic checkpoints entirely.
   1337 **
   1338 ** The callback registered by this function replaces any existing callback
   1339 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
   1340 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
   1341 ** configured by this function.
   1342 */
   1343 int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
   1344 #ifdef SQLITE_OMIT_WAL
   1345   UNUSED_PARAMETER(db);
   1346   UNUSED_PARAMETER(nFrame);
   1347 #else
   1348   if( nFrame>0 ){
   1349     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
   1350   }else{
   1351     sqlite3_wal_hook(db, 0, 0);
   1352   }
   1353 #endif
   1354   return SQLITE_OK;
   1355 }
   1356 
   1357 /*
   1358 ** Register a callback to be invoked each time a transaction is written
   1359 ** into the write-ahead-log by this database connection.
   1360 */
   1361 void *sqlite3_wal_hook(
   1362   sqlite3 *db,                    /* Attach the hook to this db handle */
   1363   int(*xCallback)(void *, sqlite3*, const char*, int),
   1364   void *pArg                      /* First argument passed to xCallback() */
   1365 ){
   1366 #ifndef SQLITE_OMIT_WAL
   1367   void *pRet;
   1368   sqlite3_mutex_enter(db->mutex);
   1369   pRet = db->pWalArg;
   1370   db->xWalCallback = xCallback;
   1371   db->pWalArg = pArg;
   1372   sqlite3_mutex_leave(db->mutex);
   1373   return pRet;
   1374 #else
   1375   return 0;
   1376 #endif
   1377 }
   1378 
   1379 /*
   1380 ** Checkpoint database zDb.
   1381 */
   1382 int sqlite3_wal_checkpoint_v2(
   1383   sqlite3 *db,                    /* Database handle */
   1384   const char *zDb,                /* Name of attached database (or NULL) */
   1385   int eMode,                      /* SQLITE_CHECKPOINT_* value */
   1386   int *pnLog,                     /* OUT: Size of WAL log in frames */
   1387   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
   1388 ){
   1389 #ifdef SQLITE_OMIT_WAL
   1390   return SQLITE_OK;
   1391 #else
   1392   int rc;                         /* Return code */
   1393   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
   1394 
   1395   /* Initialize the output variables to -1 in case an error occurs. */
   1396   if( pnLog ) *pnLog = -1;
   1397   if( pnCkpt ) *pnCkpt = -1;
   1398 
   1399   assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
   1400   assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
   1401   assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
   1402   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
   1403     return SQLITE_MISUSE;
   1404   }
   1405 
   1406   sqlite3_mutex_enter(db->mutex);
   1407   if( zDb && zDb[0] ){
   1408     iDb = sqlite3FindDbName(db, zDb);
   1409   }
   1410   if( iDb<0 ){
   1411     rc = SQLITE_ERROR;
   1412     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
   1413   }else{
   1414     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
   1415     sqlite3Error(db, rc, 0);
   1416   }
   1417   rc = sqlite3ApiExit(db, rc);
   1418   sqlite3_mutex_leave(db->mutex);
   1419   return rc;
   1420 #endif
   1421 }
   1422 
   1423 
   1424 /*
   1425 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
   1426 ** to contains a zero-length string, all attached databases are
   1427 ** checkpointed.
   1428 */
   1429 int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
   1430   return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
   1431 }
   1432 
   1433 #ifndef SQLITE_OMIT_WAL
   1434 /*
   1435 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
   1436 ** not currently open in WAL mode.
   1437 **
   1438 ** If a transaction is open on the database being checkpointed, this
   1439 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
   1440 ** an error occurs while running the checkpoint, an SQLite error code is
   1441 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
   1442 **
   1443 ** The mutex on database handle db should be held by the caller. The mutex
   1444 ** associated with the specific b-tree being checkpointed is taken by
   1445 ** this function while the checkpoint is running.
   1446 **
   1447 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
   1448 ** checkpointed. If an error is encountered it is returned immediately -
   1449 ** no attempt is made to checkpoint any remaining databases.
   1450 **
   1451 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
   1452 */
   1453 int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
   1454   int rc = SQLITE_OK;             /* Return code */
   1455   int i;                          /* Used to iterate through attached dbs */
   1456   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
   1457 
   1458   assert( sqlite3_mutex_held(db->mutex) );
   1459   assert( !pnLog || *pnLog==-1 );
   1460   assert( !pnCkpt || *pnCkpt==-1 );
   1461 
   1462   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
   1463     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
   1464       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
   1465       pnLog = 0;
   1466       pnCkpt = 0;
   1467       if( rc==SQLITE_BUSY ){
   1468         bBusy = 1;
   1469         rc = SQLITE_OK;
   1470       }
   1471     }
   1472   }
   1473 
   1474   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
   1475 }
   1476 #endif /* SQLITE_OMIT_WAL */
   1477 
   1478 /*
   1479 ** This function returns true if main-memory should be used instead of
   1480 ** a temporary file for transient pager files and statement journals.
   1481 ** The value returned depends on the value of db->temp_store (runtime
   1482 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
   1483 ** following table describes the relationship between these two values
   1484 ** and this functions return value.
   1485 **
   1486 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
   1487 **   -----------------     --------------     ------------------------------
   1488 **   0                     any                file      (return 0)
   1489 **   1                     1                  file      (return 0)
   1490 **   1                     2                  memory    (return 1)
   1491 **   1                     0                  file      (return 0)
   1492 **   2                     1                  file      (return 0)
   1493 **   2                     2                  memory    (return 1)
   1494 **   2                     0                  memory    (return 1)
   1495 **   3                     any                memory    (return 1)
   1496 */
   1497 int sqlite3TempInMemory(const sqlite3 *db){
   1498 #if SQLITE_TEMP_STORE==1
   1499   return ( db->temp_store==2 );
   1500 #endif
   1501 #if SQLITE_TEMP_STORE==2
   1502   return ( db->temp_store!=1 );
   1503 #endif
   1504 #if SQLITE_TEMP_STORE==3
   1505   return 1;
   1506 #endif
   1507 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
   1508   return 0;
   1509 #endif
   1510 }
   1511 
   1512 /*
   1513 ** Return UTF-8 encoded English language explanation of the most recent
   1514 ** error.
   1515 */
   1516 const char *sqlite3_errmsg(sqlite3 *db){
   1517   const char *z;
   1518   if( !db ){
   1519     return sqlite3ErrStr(SQLITE_NOMEM);
   1520   }
   1521   if( !sqlite3SafetyCheckSickOrOk(db) ){
   1522     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
   1523   }
   1524   sqlite3_mutex_enter(db->mutex);
   1525   if( db->mallocFailed ){
   1526     z = sqlite3ErrStr(SQLITE_NOMEM);
   1527   }else{
   1528     z = (char*)sqlite3_value_text(db->pErr);
   1529     assert( !db->mallocFailed );
   1530     if( z==0 ){
   1531       z = sqlite3ErrStr(db->errCode);
   1532     }
   1533   }
   1534   sqlite3_mutex_leave(db->mutex);
   1535   return z;
   1536 }
   1537 
   1538 #ifndef SQLITE_OMIT_UTF16
   1539 /*
   1540 ** Return UTF-16 encoded English language explanation of the most recent
   1541 ** error.
   1542 */
   1543 const void *sqlite3_errmsg16(sqlite3 *db){
   1544   static const u16 outOfMem[] = {
   1545     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
   1546   };
   1547   static const u16 misuse[] = {
   1548     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
   1549     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
   1550     'c', 'a', 'l', 'l', 'e', 'd', ' ',
   1551     'o', 'u', 't', ' ',
   1552     'o', 'f', ' ',
   1553     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
   1554   };
   1555 
   1556   const void *z;
   1557   if( !db ){
   1558     return (void *)outOfMem;
   1559   }
   1560   if( !sqlite3SafetyCheckSickOrOk(db) ){
   1561     return (void *)misuse;
   1562   }
   1563   sqlite3_mutex_enter(db->mutex);
   1564   if( db->mallocFailed ){
   1565     z = (void *)outOfMem;
   1566   }else{
   1567     z = sqlite3_value_text16(db->pErr);
   1568     if( z==0 ){
   1569       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
   1570            SQLITE_UTF8, SQLITE_STATIC);
   1571       z = sqlite3_value_text16(db->pErr);
   1572     }
   1573     /* A malloc() may have failed within the call to sqlite3_value_text16()
   1574     ** above. If this is the case, then the db->mallocFailed flag needs to
   1575     ** be cleared before returning. Do this directly, instead of via
   1576     ** sqlite3ApiExit(), to avoid setting the database handle error message.
   1577     */
   1578     db->mallocFailed = 0;
   1579   }
   1580   sqlite3_mutex_leave(db->mutex);
   1581   return z;
   1582 }
   1583 #endif /* SQLITE_OMIT_UTF16 */
   1584 
   1585 /*
   1586 ** Return the most recent error code generated by an SQLite routine. If NULL is
   1587 ** passed to this function, we assume a malloc() failed during sqlite3_open().
   1588 */
   1589 int sqlite3_errcode(sqlite3 *db){
   1590   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
   1591     return SQLITE_MISUSE_BKPT;
   1592   }
   1593   if( !db || db->mallocFailed ){
   1594     return SQLITE_NOMEM;
   1595   }
   1596   return db->errCode & db->errMask;
   1597 }
   1598 int sqlite3_extended_errcode(sqlite3 *db){
   1599   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
   1600     return SQLITE_MISUSE_BKPT;
   1601   }
   1602   if( !db || db->mallocFailed ){
   1603     return SQLITE_NOMEM;
   1604   }
   1605   return db->errCode;
   1606 }
   1607 
   1608 /*
   1609 ** Create a new collating function for database "db".  The name is zName
   1610 ** and the encoding is enc.
   1611 */
   1612 static int createCollation(
   1613   sqlite3* db,
   1614   const char *zName,
   1615   u8 enc,
   1616   u8 collType,
   1617   void* pCtx,
   1618   int(*xCompare)(void*,int,const void*,int,const void*),
   1619   void(*xDel)(void*)
   1620 ){
   1621   CollSeq *pColl;
   1622   int enc2;
   1623   int nName = sqlite3Strlen30(zName);
   1624 
   1625   assert( sqlite3_mutex_held(db->mutex) );
   1626 
   1627   /* If SQLITE_UTF16 is specified as the encoding type, transform this
   1628   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
   1629   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
   1630   */
   1631   enc2 = enc;
   1632   testcase( enc2==SQLITE_UTF16 );
   1633   testcase( enc2==SQLITE_UTF16_ALIGNED );
   1634   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
   1635     enc2 = SQLITE_UTF16NATIVE;
   1636   }
   1637   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
   1638     return SQLITE_MISUSE_BKPT;
   1639   }
   1640 
   1641   /* Check if this call is removing or replacing an existing collation
   1642   ** sequence. If so, and there are active VMs, return busy. If there
   1643   ** are no active VMs, invalidate any pre-compiled statements.
   1644   */
   1645   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
   1646   if( pColl && pColl->xCmp ){
   1647     if( db->activeVdbeCnt ){
   1648       sqlite3Error(db, SQLITE_BUSY,
   1649         "unable to delete/modify collation sequence due to active statements");
   1650       return SQLITE_BUSY;
   1651     }
   1652     sqlite3ExpirePreparedStatements(db);
   1653 
   1654     /* If collation sequence pColl was created directly by a call to
   1655     ** sqlite3_create_collation, and not generated by synthCollSeq(),
   1656     ** then any copies made by synthCollSeq() need to be invalidated.
   1657     ** Also, collation destructor - CollSeq.xDel() - function may need
   1658     ** to be called.
   1659     */
   1660     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
   1661       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
   1662       int j;
   1663       for(j=0; j<3; j++){
   1664         CollSeq *p = &aColl[j];
   1665         if( p->enc==pColl->enc ){
   1666           if( p->xDel ){
   1667             p->xDel(p->pUser);
   1668           }
   1669           p->xCmp = 0;
   1670         }
   1671       }
   1672     }
   1673   }
   1674 
   1675   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
   1676   if( pColl==0 ) return SQLITE_NOMEM;
   1677   pColl->xCmp = xCompare;
   1678   pColl->pUser = pCtx;
   1679   pColl->xDel = xDel;
   1680   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
   1681   pColl->type = collType;
   1682   sqlite3Error(db, SQLITE_OK, 0);
   1683   return SQLITE_OK;
   1684 }
   1685 
   1686 
   1687 /*
   1688 ** This array defines hard upper bounds on limit values.  The
   1689 ** initializer must be kept in sync with the SQLITE_LIMIT_*
   1690 ** #defines in sqlite3.h.
   1691 */
   1692 static const int aHardLimit[] = {
   1693   SQLITE_MAX_LENGTH,
   1694   SQLITE_MAX_SQL_LENGTH,
   1695   SQLITE_MAX_COLUMN,
   1696   SQLITE_MAX_EXPR_DEPTH,
   1697   SQLITE_MAX_COMPOUND_SELECT,
   1698   SQLITE_MAX_VDBE_OP,
   1699   SQLITE_MAX_FUNCTION_ARG,
   1700   SQLITE_MAX_ATTACHED,
   1701   SQLITE_MAX_LIKE_PATTERN_LENGTH,
   1702   SQLITE_MAX_VARIABLE_NUMBER,
   1703   SQLITE_MAX_TRIGGER_DEPTH,
   1704 };
   1705 
   1706 /*
   1707 ** Make sure the hard limits are set to reasonable values
   1708 */
   1709 #if SQLITE_MAX_LENGTH<100
   1710 # error SQLITE_MAX_LENGTH must be at least 100
   1711 #endif
   1712 #if SQLITE_MAX_SQL_LENGTH<100
   1713 # error SQLITE_MAX_SQL_LENGTH must be at least 100
   1714 #endif
   1715 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
   1716 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
   1717 #endif
   1718 #if SQLITE_MAX_COMPOUND_SELECT<2
   1719 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
   1720 #endif
   1721 #if SQLITE_MAX_VDBE_OP<40
   1722 # error SQLITE_MAX_VDBE_OP must be at least 40
   1723 #endif
   1724 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
   1725 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
   1726 #endif
   1727 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
   1728 # error SQLITE_MAX_ATTACHED must be between 0 and 62
   1729 #endif
   1730 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
   1731 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
   1732 #endif
   1733 #if SQLITE_MAX_COLUMN>32767
   1734 # error SQLITE_MAX_COLUMN must not exceed 32767
   1735 #endif
   1736 #if SQLITE_MAX_TRIGGER_DEPTH<1
   1737 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
   1738 #endif
   1739 
   1740 
   1741 /*
   1742 ** Change the value of a limit.  Report the old value.
   1743 ** If an invalid limit index is supplied, report -1.
   1744 ** Make no changes but still report the old value if the
   1745 ** new limit is negative.
   1746 **
   1747 ** A new lower limit does not shrink existing constructs.
   1748 ** It merely prevents new constructs that exceed the limit
   1749 ** from forming.
   1750 */
   1751 int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
   1752   int oldLimit;
   1753 
   1754 
   1755   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
   1756   ** there is a hard upper bound set at compile-time by a C preprocessor
   1757   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
   1758   ** "_MAX_".)
   1759   */
   1760   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
   1761   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
   1762   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
   1763   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
   1764   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
   1765   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
   1766   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
   1767   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
   1768   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
   1769                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
   1770   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
   1771   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
   1772   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
   1773 
   1774 
   1775   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
   1776     return -1;
   1777   }
   1778   oldLimit = db->aLimit[limitId];
   1779   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
   1780     if( newLimit>aHardLimit[limitId] ){
   1781       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
   1782     }
   1783     db->aLimit[limitId] = newLimit;
   1784   }
   1785   return oldLimit;                     /* IMP: R-53341-35419 */
   1786 }
   1787 
   1788 /*
   1789 ** This routine does the work of opening a database on behalf of
   1790 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
   1791 ** is UTF-8 encoded.
   1792 */
   1793 static int openDatabase(
   1794   const char *zFilename, /* Database filename UTF-8 encoded */
   1795   sqlite3 **ppDb,        /* OUT: Returned database handle */
   1796   unsigned flags,        /* Operational flags */
   1797   const char *zVfs       /* Name of the VFS to use */
   1798 ){
   1799   sqlite3 *db;
   1800   int rc;
   1801   int isThreadsafe;
   1802 
   1803   *ppDb = 0;
   1804 #ifndef SQLITE_OMIT_AUTOINIT
   1805   rc = sqlite3_initialize();
   1806   if( rc ) return rc;
   1807 #endif
   1808 
   1809   /* Only allow sensible combinations of bits in the flags argument.
   1810   ** Throw an error if any non-sense combination is used.  If we
   1811   ** do not block illegal combinations here, it could trigger
   1812   ** assert() statements in deeper layers.  Sensible combinations
   1813   ** are:
   1814   **
   1815   **  1:  SQLITE_OPEN_READONLY
   1816   **  2:  SQLITE_OPEN_READWRITE
   1817   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
   1818   */
   1819   assert( SQLITE_OPEN_READONLY  == 0x01 );
   1820   assert( SQLITE_OPEN_READWRITE == 0x02 );
   1821   assert( SQLITE_OPEN_CREATE    == 0x04 );
   1822   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
   1823   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
   1824   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
   1825   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE;
   1826 
   1827   if( sqlite3GlobalConfig.bCoreMutex==0 ){
   1828     isThreadsafe = 0;
   1829   }else if( flags & SQLITE_OPEN_NOMUTEX ){
   1830     isThreadsafe = 0;
   1831   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
   1832     isThreadsafe = 1;
   1833   }else{
   1834     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
   1835   }
   1836   if( flags & SQLITE_OPEN_PRIVATECACHE ){
   1837     flags &= ~SQLITE_OPEN_SHAREDCACHE;
   1838   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
   1839     flags |= SQLITE_OPEN_SHAREDCACHE;
   1840   }
   1841 
   1842   /* Remove harmful bits from the flags parameter
   1843   **
   1844   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
   1845   ** dealt with in the previous code block.  Besides these, the only
   1846   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
   1847   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
   1848   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
   1849   ** off all other flags.
   1850   */
   1851   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
   1852                SQLITE_OPEN_EXCLUSIVE |
   1853                SQLITE_OPEN_MAIN_DB |
   1854                SQLITE_OPEN_TEMP_DB |
   1855                SQLITE_OPEN_TRANSIENT_DB |
   1856                SQLITE_OPEN_MAIN_JOURNAL |
   1857                SQLITE_OPEN_TEMP_JOURNAL |
   1858                SQLITE_OPEN_SUBJOURNAL |
   1859                SQLITE_OPEN_MASTER_JOURNAL |
   1860                SQLITE_OPEN_NOMUTEX |
   1861                SQLITE_OPEN_FULLMUTEX |
   1862                SQLITE_OPEN_WAL
   1863              );
   1864 
   1865   /* Allocate the sqlite data structure */
   1866   db = sqlite3MallocZero( sizeof(sqlite3) );
   1867   if( db==0 ) goto opendb_out;
   1868   if( isThreadsafe ){
   1869     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
   1870     if( db->mutex==0 ){
   1871       sqlite3_free(db);
   1872       db = 0;
   1873       goto opendb_out;
   1874     }
   1875   }
   1876   sqlite3_mutex_enter(db->mutex);
   1877   db->errMask = 0xff;
   1878   db->nDb = 2;
   1879   db->magic = SQLITE_MAGIC_BUSY;
   1880   db->aDb = db->aDbStatic;
   1881 
   1882   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
   1883   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
   1884   db->autoCommit = 1;
   1885   db->nextAutovac = -1;
   1886   db->nextPagesize = 0;
   1887   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
   1888 #if SQLITE_DEFAULT_FILE_FORMAT<4
   1889                  | SQLITE_LegacyFileFmt
   1890 #endif
   1891 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
   1892                  | SQLITE_LoadExtension
   1893 #endif
   1894 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
   1895                  | SQLITE_RecTriggers
   1896 #endif
   1897 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
   1898                  | SQLITE_ForeignKeys
   1899 #endif
   1900       ;
   1901   sqlite3HashInit(&db->aCollSeq);
   1902 #ifndef SQLITE_OMIT_VIRTUALTABLE
   1903   sqlite3HashInit(&db->aModule);
   1904 #endif
   1905 
   1906   db->pVfs = sqlite3_vfs_find(zVfs);
   1907   if( !db->pVfs ){
   1908     rc = SQLITE_ERROR;
   1909     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
   1910     goto opendb_out;
   1911   }
   1912 
   1913   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
   1914   ** and UTF-16, so add a version for each to avoid any unnecessary
   1915   ** conversions. The only error that can occur here is a malloc() failure.
   1916   */
   1917   createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
   1918                   binCollFunc, 0);
   1919   createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
   1920                   binCollFunc, 0);
   1921   createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
   1922                   binCollFunc, 0);
   1923   createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
   1924                   binCollFunc, 0);
   1925   if( db->mallocFailed ){
   1926     goto opendb_out;
   1927   }
   1928   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
   1929   assert( db->pDfltColl!=0 );
   1930 
   1931   /* Also add a UTF-8 case-insensitive collation sequence. */
   1932   createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
   1933                   nocaseCollatingFunc, 0);
   1934 
   1935   /* Open the backend database driver */
   1936   db->openFlags = flags;
   1937   rc = sqlite3BtreeOpen(zFilename, db, &db->aDb[0].pBt, 0,
   1938                         flags | SQLITE_OPEN_MAIN_DB);
   1939   if( rc!=SQLITE_OK ){
   1940     if( rc==SQLITE_IOERR_NOMEM ){
   1941       rc = SQLITE_NOMEM;
   1942     }
   1943     sqlite3Error(db, rc, 0);
   1944     goto opendb_out;
   1945   }
   1946   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
   1947   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
   1948 
   1949 
   1950   /* The default safety_level for the main database is 'full'; for the temp
   1951   ** database it is 'NONE'. This matches the pager layer defaults.
   1952   */
   1953   db->aDb[0].zName = "main";
   1954   db->aDb[0].safety_level = 3;
   1955   db->aDb[1].zName = "temp";
   1956   db->aDb[1].safety_level = 1;
   1957 
   1958   db->magic = SQLITE_MAGIC_OPEN;
   1959   if( db->mallocFailed ){
   1960     goto opendb_out;
   1961   }
   1962 
   1963   /* Register all built-in functions, but do not attempt to read the
   1964   ** database schema yet. This is delayed until the first time the database
   1965   ** is accessed.
   1966   */
   1967   sqlite3Error(db, SQLITE_OK, 0);
   1968   sqlite3RegisterBuiltinFunctions(db);
   1969 
   1970   /* Load automatic extensions - extensions that have been registered
   1971   ** using the sqlite3_automatic_extension() API.
   1972   */
   1973   sqlite3AutoLoadExtensions(db);
   1974   rc = sqlite3_errcode(db);
   1975   if( rc!=SQLITE_OK ){
   1976     goto opendb_out;
   1977   }
   1978 
   1979 #ifdef SQLITE_ENABLE_FTS1
   1980   if( !db->mallocFailed ){
   1981     extern int sqlite3Fts1Init(sqlite3*);
   1982     rc = sqlite3Fts1Init(db);
   1983   }
   1984 #endif
   1985 
   1986 #ifdef SQLITE_ENABLE_FTS2
   1987   if( !db->mallocFailed && rc==SQLITE_OK ){
   1988     extern int sqlite3Fts2Init(sqlite3*);
   1989     rc = sqlite3Fts2Init(db);
   1990   }
   1991 #endif
   1992 
   1993 #ifdef SQLITE_ENABLE_FTS3
   1994   if( !db->mallocFailed && rc==SQLITE_OK ){
   1995     rc = sqlite3Fts3Init(db);
   1996   }
   1997 #endif
   1998 
   1999 #ifdef SQLITE_ENABLE_ICU
   2000   if( !db->mallocFailed && rc==SQLITE_OK ){
   2001     rc = sqlite3IcuInit(db);
   2002   }
   2003 #endif
   2004 
   2005 #ifdef SQLITE_ENABLE_RTREE
   2006   if( !db->mallocFailed && rc==SQLITE_OK){
   2007     rc = sqlite3RtreeInit(db);
   2008   }
   2009 #endif
   2010 
   2011   sqlite3Error(db, rc, 0);
   2012 
   2013   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
   2014   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
   2015   ** mode.  Doing nothing at all also makes NORMAL the default.
   2016   */
   2017 #ifdef SQLITE_DEFAULT_LOCKING_MODE
   2018   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
   2019   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
   2020                           SQLITE_DEFAULT_LOCKING_MODE);
   2021 #endif
   2022 
   2023   /* Enable the lookaside-malloc subsystem */
   2024   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
   2025                         sqlite3GlobalConfig.nLookaside);
   2026 
   2027   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
   2028 
   2029 opendb_out:
   2030   if( db ){
   2031     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
   2032     sqlite3_mutex_leave(db->mutex);
   2033   }
   2034   rc = sqlite3_errcode(db);
   2035   if( rc==SQLITE_NOMEM ){
   2036     sqlite3_close(db);
   2037     db = 0;
   2038   }else if( rc!=SQLITE_OK ){
   2039     db->magic = SQLITE_MAGIC_SICK;
   2040   }
   2041   *ppDb = db;
   2042   return sqlite3ApiExit(0, rc);
   2043 }
   2044 
   2045 /*
   2046 ** Open a new database handle.
   2047 */
   2048 int sqlite3_open(
   2049   const char *zFilename,
   2050   sqlite3 **ppDb
   2051 ){
   2052   return openDatabase(zFilename, ppDb,
   2053                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
   2054 }
   2055 int sqlite3_open_v2(
   2056   const char *filename,   /* Database filename (UTF-8) */
   2057   sqlite3 **ppDb,         /* OUT: SQLite db handle */
   2058   int flags,              /* Flags */
   2059   const char *zVfs        /* Name of VFS module to use */
   2060 ){
   2061   return openDatabase(filename, ppDb, flags, zVfs);
   2062 }
   2063 
   2064 #ifndef SQLITE_OMIT_UTF16
   2065 /*
   2066 ** Open a new database handle.
   2067 */
   2068 int sqlite3_open16(
   2069   const void *zFilename,
   2070   sqlite3 **ppDb
   2071 ){
   2072   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
   2073   sqlite3_value *pVal;
   2074   int rc;
   2075 
   2076   assert( zFilename );
   2077   assert( ppDb );
   2078   *ppDb = 0;
   2079 #ifndef SQLITE_OMIT_AUTOINIT
   2080   rc = sqlite3_initialize();
   2081   if( rc ) return rc;
   2082 #endif
   2083   pVal = sqlite3ValueNew(0);
   2084   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
   2085   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
   2086   if( zFilename8 ){
   2087     rc = openDatabase(zFilename8, ppDb,
   2088                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
   2089     assert( *ppDb || rc==SQLITE_NOMEM );
   2090     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
   2091       ENC(*ppDb) = SQLITE_UTF16NATIVE;
   2092     }
   2093   }else{
   2094     rc = SQLITE_NOMEM;
   2095   }
   2096   sqlite3ValueFree(pVal);
   2097 
   2098   return sqlite3ApiExit(0, rc);
   2099 }
   2100 #endif /* SQLITE_OMIT_UTF16 */
   2101 
   2102 /*
   2103 ** Register a new collation sequence with the database handle db.
   2104 */
   2105 int sqlite3_create_collation(
   2106   sqlite3* db,
   2107   const char *zName,
   2108   int enc,
   2109   void* pCtx,
   2110   int(*xCompare)(void*,int,const void*,int,const void*)
   2111 ){
   2112   int rc;
   2113   sqlite3_mutex_enter(db->mutex);
   2114   assert( !db->mallocFailed );
   2115   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
   2116   rc = sqlite3ApiExit(db, rc);
   2117   sqlite3_mutex_leave(db->mutex);
   2118   return rc;
   2119 }
   2120 
   2121 /*
   2122 ** Register a new collation sequence with the database handle db.
   2123 */
   2124 int sqlite3_create_collation_v2(
   2125   sqlite3* db,
   2126   const char *zName,
   2127   int enc,
   2128   void* pCtx,
   2129   int(*xCompare)(void*,int,const void*,int,const void*),
   2130   void(*xDel)(void*)
   2131 ){
   2132   int rc;
   2133   sqlite3_mutex_enter(db->mutex);
   2134   assert( !db->mallocFailed );
   2135   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
   2136   rc = sqlite3ApiExit(db, rc);
   2137   sqlite3_mutex_leave(db->mutex);
   2138   return rc;
   2139 }
   2140 
   2141 #ifndef SQLITE_OMIT_UTF16
   2142 /*
   2143 ** Register a new collation sequence with the database handle db.
   2144 */
   2145 int sqlite3_create_collation16(
   2146   sqlite3* db,
   2147   const void *zName,
   2148   int enc,
   2149   void* pCtx,
   2150   int(*xCompare)(void*,int,const void*,int,const void*)
   2151 ){
   2152   int rc = SQLITE_OK;
   2153   char *zName8;
   2154   sqlite3_mutex_enter(db->mutex);
   2155   assert( !db->mallocFailed );
   2156   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
   2157   if( zName8 ){
   2158     rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
   2159     sqlite3DbFree(db, zName8);
   2160   }
   2161   rc = sqlite3ApiExit(db, rc);
   2162   sqlite3_mutex_leave(db->mutex);
   2163   return rc;
   2164 }
   2165 #endif /* SQLITE_OMIT_UTF16 */
   2166 
   2167 /*
   2168 ** Register a collation sequence factory callback with the database handle
   2169 ** db. Replace any previously installed collation sequence factory.
   2170 */
   2171 int sqlite3_collation_needed(
   2172   sqlite3 *db,
   2173   void *pCollNeededArg,
   2174   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
   2175 ){
   2176   sqlite3_mutex_enter(db->mutex);
   2177   db->xCollNeeded = xCollNeeded;
   2178   db->xCollNeeded16 = 0;
   2179   db->pCollNeededArg = pCollNeededArg;
   2180   sqlite3_mutex_leave(db->mutex);
   2181   return SQLITE_OK;
   2182 }
   2183 
   2184 #ifndef SQLITE_OMIT_UTF16
   2185 /*
   2186 ** Register a collation sequence factory callback with the database handle
   2187 ** db. Replace any previously installed collation sequence factory.
   2188 */
   2189 int sqlite3_collation_needed16(
   2190   sqlite3 *db,
   2191   void *pCollNeededArg,
   2192   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
   2193 ){
   2194   sqlite3_mutex_enter(db->mutex);
   2195   db->xCollNeeded = 0;
   2196   db->xCollNeeded16 = xCollNeeded16;
   2197   db->pCollNeededArg = pCollNeededArg;
   2198   sqlite3_mutex_leave(db->mutex);
   2199   return SQLITE_OK;
   2200 }
   2201 #endif /* SQLITE_OMIT_UTF16 */
   2202 
   2203 #ifndef SQLITE_OMIT_DEPRECATED
   2204 /*
   2205 ** This function is now an anachronism. It used to be used to recover from a
   2206 ** malloc() failure, but SQLite now does this automatically.
   2207 */
   2208 int sqlite3_global_recover(void){
   2209   return SQLITE_OK;
   2210 }
   2211 #endif
   2212 
   2213 /*
   2214 ** Test to see whether or not the database connection is in autocommit
   2215 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
   2216 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
   2217 ** by the next COMMIT or ROLLBACK.
   2218 **
   2219 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
   2220 */
   2221 int sqlite3_get_autocommit(sqlite3 *db){
   2222   return db->autoCommit;
   2223 }
   2224 
   2225 /*
   2226 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
   2227 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
   2228 ** constants.  They server two purposes:
   2229 **
   2230 **   1.  Serve as a convenient place to set a breakpoint in a debugger
   2231 **       to detect when version error conditions occurs.
   2232 **
   2233 **   2.  Invoke sqlite3_log() to provide the source code location where
   2234 **       a low-level error is first detected.
   2235 */
   2236 int sqlite3CorruptError(int lineno){
   2237   testcase( sqlite3GlobalConfig.xLog!=0 );
   2238   sqlite3_log(SQLITE_CORRUPT,
   2239               "database corruption at line %d of [%.10s]",
   2240               lineno, 20+sqlite3_sourceid());
   2241   return SQLITE_CORRUPT;
   2242 }
   2243 int sqlite3MisuseError(int lineno){
   2244   testcase( sqlite3GlobalConfig.xLog!=0 );
   2245   sqlite3_log(SQLITE_MISUSE,
   2246               "misuse at line %d of [%.10s]",
   2247               lineno, 20+sqlite3_sourceid());
   2248   return SQLITE_MISUSE;
   2249 }
   2250 int sqlite3CantopenError(int lineno){
   2251   testcase( sqlite3GlobalConfig.xLog!=0 );
   2252   sqlite3_log(SQLITE_CANTOPEN,
   2253               "cannot open file at line %d of [%.10s]",
   2254               lineno, 20+sqlite3_sourceid());
   2255   return SQLITE_CANTOPEN;
   2256 }
   2257 
   2258 
   2259 #ifndef SQLITE_OMIT_DEPRECATED
   2260 /*
   2261 ** This is a convenience routine that makes sure that all thread-specific
   2262 ** data for this thread has been deallocated.
   2263 **
   2264 ** SQLite no longer uses thread-specific data so this routine is now a
   2265 ** no-op.  It is retained for historical compatibility.
   2266 */
   2267 void sqlite3_thread_cleanup(void){
   2268 }
   2269 #endif
   2270 
   2271 /*
   2272 ** Return meta information about a specific column of a database table.
   2273 ** See comment in sqlite3.h (sqlite.h.in) for details.
   2274 */
   2275 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   2276 int sqlite3_table_column_metadata(
   2277   sqlite3 *db,                /* Connection handle */
   2278   const char *zDbName,        /* Database name or NULL */
   2279   const char *zTableName,     /* Table name */
   2280   const char *zColumnName,    /* Column name */
   2281   char const **pzDataType,    /* OUTPUT: Declared data type */
   2282   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
   2283   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
   2284   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
   2285   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
   2286 ){
   2287   int rc;
   2288   char *zErrMsg = 0;
   2289   Table *pTab = 0;
   2290   Column *pCol = 0;
   2291   int iCol;
   2292 
   2293   char const *zDataType = 0;
   2294   char const *zCollSeq = 0;
   2295   int notnull = 0;
   2296   int primarykey = 0;
   2297   int autoinc = 0;
   2298 
   2299   /* Ensure the database schema has been loaded */
   2300   sqlite3_mutex_enter(db->mutex);
   2301   sqlite3BtreeEnterAll(db);
   2302   rc = sqlite3Init(db, &zErrMsg);
   2303   if( SQLITE_OK!=rc ){
   2304     goto error_out;
   2305   }
   2306 
   2307   /* Locate the table in question */
   2308   pTab = sqlite3FindTable(db, zTableName, zDbName);
   2309   if( !pTab || pTab->pSelect ){
   2310     pTab = 0;
   2311     goto error_out;
   2312   }
   2313 
   2314   /* Find the column for which info is requested */
   2315   if( sqlite3IsRowid(zColumnName) ){
   2316     iCol = pTab->iPKey;
   2317     if( iCol>=0 ){
   2318       pCol = &pTab->aCol[iCol];
   2319     }
   2320   }else{
   2321     for(iCol=0; iCol<pTab->nCol; iCol++){
   2322       pCol = &pTab->aCol[iCol];
   2323       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
   2324         break;
   2325       }
   2326     }
   2327     if( iCol==pTab->nCol ){
   2328       pTab = 0;
   2329       goto error_out;
   2330     }
   2331   }
   2332 
   2333   /* The following block stores the meta information that will be returned
   2334   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
   2335   ** and autoinc. At this point there are two possibilities:
   2336   **
   2337   **     1. The specified column name was rowid", "oid" or "_rowid_"
   2338   **        and there is no explicitly declared IPK column.
   2339   **
   2340   **     2. The table is not a view and the column name identified an
   2341   **        explicitly declared column. Copy meta information from *pCol.
   2342   */
   2343   if( pCol ){
   2344     zDataType = pCol->zType;
   2345     zCollSeq = pCol->zColl;
   2346     notnull = pCol->notNull!=0;
   2347     primarykey  = pCol->isPrimKey!=0;
   2348     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
   2349   }else{
   2350     zDataType = "INTEGER";
   2351     primarykey = 1;
   2352   }
   2353   if( !zCollSeq ){
   2354     zCollSeq = "BINARY";
   2355   }
   2356 
   2357 error_out:
   2358   sqlite3BtreeLeaveAll(db);
   2359 
   2360   /* Whether the function call succeeded or failed, set the output parameters
   2361   ** to whatever their local counterparts contain. If an error did occur,
   2362   ** this has the effect of zeroing all output parameters.
   2363   */
   2364   if( pzDataType ) *pzDataType = zDataType;
   2365   if( pzCollSeq ) *pzCollSeq = zCollSeq;
   2366   if( pNotNull ) *pNotNull = notnull;
   2367   if( pPrimaryKey ) *pPrimaryKey = primarykey;
   2368   if( pAutoinc ) *pAutoinc = autoinc;
   2369 
   2370   if( SQLITE_OK==rc && !pTab ){
   2371     sqlite3DbFree(db, zErrMsg);
   2372     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
   2373         zColumnName);
   2374     rc = SQLITE_ERROR;
   2375   }
   2376   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
   2377   sqlite3DbFree(db, zErrMsg);
   2378   rc = sqlite3ApiExit(db, rc);
   2379   sqlite3_mutex_leave(db->mutex);
   2380   return rc;
   2381 }
   2382 #endif
   2383 
   2384 /*
   2385 ** Sleep for a little while.  Return the amount of time slept.
   2386 */
   2387 int sqlite3_sleep(int ms){
   2388   sqlite3_vfs *pVfs;
   2389   int rc;
   2390   pVfs = sqlite3_vfs_find(0);
   2391   if( pVfs==0 ) return 0;
   2392 
   2393   /* This function works in milliseconds, but the underlying OsSleep()
   2394   ** API uses microseconds. Hence the 1000's.
   2395   */
   2396   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
   2397   return rc;
   2398 }
   2399 
   2400 /*
   2401 ** Enable or disable the extended result codes.
   2402 */
   2403 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
   2404   sqlite3_mutex_enter(db->mutex);
   2405   db->errMask = onoff ? 0xffffffff : 0xff;
   2406   sqlite3_mutex_leave(db->mutex);
   2407   return SQLITE_OK;
   2408 }
   2409 
   2410 /*
   2411 ** Invoke the xFileControl method on a particular database.
   2412 */
   2413 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
   2414   int rc = SQLITE_ERROR;
   2415   int iDb;
   2416   sqlite3_mutex_enter(db->mutex);
   2417   if( zDbName==0 ){
   2418     iDb = 0;
   2419   }else{
   2420     for(iDb=0; iDb<db->nDb; iDb++){
   2421       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
   2422     }
   2423   }
   2424   if( iDb<db->nDb ){
   2425     Btree *pBtree = db->aDb[iDb].pBt;
   2426     if( pBtree ){
   2427       Pager *pPager;
   2428       sqlite3_file *fd;
   2429       sqlite3BtreeEnter(pBtree);
   2430       pPager = sqlite3BtreePager(pBtree);
   2431       assert( pPager!=0 );
   2432       fd = sqlite3PagerFile(pPager);
   2433       assert( fd!=0 );
   2434       if( op==SQLITE_FCNTL_FILE_POINTER ){
   2435         *(sqlite3_file**)pArg = fd;
   2436         rc = SQLITE_OK;
   2437       }else if( fd->pMethods ){
   2438         rc = sqlite3OsFileControl(fd, op, pArg);
   2439       }else{
   2440         rc = SQLITE_NOTFOUND;
   2441       }
   2442       sqlite3BtreeLeave(pBtree);
   2443     }
   2444   }
   2445   sqlite3_mutex_leave(db->mutex);
   2446   return rc;
   2447 }
   2448 
   2449 /*
   2450 ** Interface to the testing logic.
   2451 */
   2452 int sqlite3_test_control(int op, ...){
   2453   int rc = 0;
   2454 #ifndef SQLITE_OMIT_BUILTIN_TEST
   2455   va_list ap;
   2456   va_start(ap, op);
   2457   switch( op ){
   2458 
   2459     /*
   2460     ** Save the current state of the PRNG.
   2461     */
   2462     case SQLITE_TESTCTRL_PRNG_SAVE: {
   2463       sqlite3PrngSaveState();
   2464       break;
   2465     }
   2466 
   2467     /*
   2468     ** Restore the state of the PRNG to the last state saved using
   2469     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
   2470     ** this verb acts like PRNG_RESET.
   2471     */
   2472     case SQLITE_TESTCTRL_PRNG_RESTORE: {
   2473       sqlite3PrngRestoreState();
   2474       break;
   2475     }
   2476 
   2477     /*
   2478     ** Reset the PRNG back to its uninitialized state.  The next call
   2479     ** to sqlite3_randomness() will reseed the PRNG using a single call
   2480     ** to the xRandomness method of the default VFS.
   2481     */
   2482     case SQLITE_TESTCTRL_PRNG_RESET: {
   2483       sqlite3PrngResetState();
   2484       break;
   2485     }
   2486 
   2487     /*
   2488     **  sqlite3_test_control(BITVEC_TEST, size, program)
   2489     **
   2490     ** Run a test against a Bitvec object of size.  The program argument
   2491     ** is an array of integers that defines the test.  Return -1 on a
   2492     ** memory allocation error, 0 on success, or non-zero for an error.
   2493     ** See the sqlite3BitvecBuiltinTest() for additional information.
   2494     */
   2495     case SQLITE_TESTCTRL_BITVEC_TEST: {
   2496       int sz = va_arg(ap, int);
   2497       int *aProg = va_arg(ap, int*);
   2498       rc = sqlite3BitvecBuiltinTest(sz, aProg);
   2499       break;
   2500     }
   2501 
   2502     /*
   2503     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
   2504     **
   2505     ** Register hooks to call to indicate which malloc() failures
   2506     ** are benign.
   2507     */
   2508     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
   2509       typedef void (*void_function)(void);
   2510       void_function xBenignBegin;
   2511       void_function xBenignEnd;
   2512       xBenignBegin = va_arg(ap, void_function);
   2513       xBenignEnd = va_arg(ap, void_function);
   2514       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
   2515       break;
   2516     }
   2517 
   2518     /*
   2519     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
   2520     **
   2521     ** Set the PENDING byte to the value in the argument, if X>0.
   2522     ** Make no changes if X==0.  Return the value of the pending byte
   2523     ** as it existing before this routine was called.
   2524     **
   2525     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
   2526     ** an incompatible database file format.  Changing the PENDING byte
   2527     ** while any database connection is open results in undefined and
   2528     ** dileterious behavior.
   2529     */
   2530     case SQLITE_TESTCTRL_PENDING_BYTE: {
   2531       rc = PENDING_BYTE;
   2532 #ifndef SQLITE_OMIT_WSD
   2533       {
   2534         unsigned int newVal = va_arg(ap, unsigned int);
   2535         if( newVal ) sqlite3PendingByte = newVal;
   2536       }
   2537 #endif
   2538       break;
   2539     }
   2540 
   2541     /*
   2542     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
   2543     **
   2544     ** This action provides a run-time test to see whether or not
   2545     ** assert() was enabled at compile-time.  If X is true and assert()
   2546     ** is enabled, then the return value is true.  If X is true and
   2547     ** assert() is disabled, then the return value is zero.  If X is
   2548     ** false and assert() is enabled, then the assertion fires and the
   2549     ** process aborts.  If X is false and assert() is disabled, then the
   2550     ** return value is zero.
   2551     */
   2552     case SQLITE_TESTCTRL_ASSERT: {
   2553       volatile int x = 0;
   2554       assert( (x = va_arg(ap,int))!=0 );
   2555       rc = x;
   2556       break;
   2557     }
   2558 
   2559 
   2560     /*
   2561     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
   2562     **
   2563     ** This action provides a run-time test to see how the ALWAYS and
   2564     ** NEVER macros were defined at compile-time.
   2565     **
   2566     ** The return value is ALWAYS(X).
   2567     **
   2568     ** The recommended test is X==2.  If the return value is 2, that means
   2569     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
   2570     ** default setting.  If the return value is 1, then ALWAYS() is either
   2571     ** hard-coded to true or else it asserts if its argument is false.
   2572     ** The first behavior (hard-coded to true) is the case if
   2573     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
   2574     ** behavior (assert if the argument to ALWAYS() is false) is the case if
   2575     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
   2576     **
   2577     ** The run-time test procedure might look something like this:
   2578     **
   2579     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
   2580     **      // ALWAYS() and NEVER() are no-op pass-through macros
   2581     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
   2582     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
   2583     **    }else{
   2584     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
   2585     **    }
   2586     */
   2587     case SQLITE_TESTCTRL_ALWAYS: {
   2588       int x = va_arg(ap,int);
   2589       rc = ALWAYS(x);
   2590       break;
   2591     }
   2592 
   2593     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
   2594     **
   2595     ** Set the nReserve size to N for the main database on the database
   2596     ** connection db.
   2597     */
   2598     case SQLITE_TESTCTRL_RESERVE: {
   2599       sqlite3 *db = va_arg(ap, sqlite3*);
   2600       int x = va_arg(ap,int);
   2601       sqlite3_mutex_enter(db->mutex);
   2602       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
   2603       sqlite3_mutex_leave(db->mutex);
   2604       break;
   2605     }
   2606 
   2607     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
   2608     **
   2609     ** Enable or disable various optimizations for testing purposes.  The
   2610     ** argument N is a bitmask of optimizations to be disabled.  For normal
   2611     ** operation N should be 0.  The idea is that a test program (like the
   2612     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
   2613     ** with various optimizations disabled to verify that the same answer
   2614     ** is obtained in every case.
   2615     */
   2616     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
   2617       sqlite3 *db = va_arg(ap, sqlite3*);
   2618       int x = va_arg(ap,int);
   2619       db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
   2620       break;
   2621     }
   2622 
   2623 #ifdef SQLITE_N_KEYWORD
   2624     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
   2625     **
   2626     ** If zWord is a keyword recognized by the parser, then return the
   2627     ** number of keywords.  Or if zWord is not a keyword, return 0.
   2628     **
   2629     ** This test feature is only available in the amalgamation since
   2630     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
   2631     ** is built using separate source files.
   2632     */
   2633     case SQLITE_TESTCTRL_ISKEYWORD: {
   2634       const char *zWord = va_arg(ap, const char*);
   2635       int n = sqlite3Strlen30(zWord);
   2636       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
   2637       break;
   2638     }
   2639 #endif
   2640 
   2641     /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ)
   2642     **
   2643     ** Return the size of a pcache header in bytes.
   2644     */
   2645     case SQLITE_TESTCTRL_PGHDRSZ: {
   2646       rc = sizeof(PgHdr);
   2647       break;
   2648     }
   2649 
   2650     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
   2651     **
   2652     ** Pass pFree into sqlite3ScratchFree().
   2653     ** If sz>0 then allocate a scratch buffer into pNew.
   2654     */
   2655     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
   2656       void *pFree, **ppNew;
   2657       int sz;
   2658       sz = va_arg(ap, int);
   2659       ppNew = va_arg(ap, void**);
   2660       pFree = va_arg(ap, void*);
   2661       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
   2662       sqlite3ScratchFree(pFree);
   2663       break;
   2664     }
   2665 
   2666   }
   2667   va_end(ap);
   2668 #endif /* SQLITE_OMIT_BUILTIN_TEST */
   2669   return rc;
   2670 }
   2671