xref: /sqlite-3.40.0/src/main.c (revision a3628d14)
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** Main file for the SQLite library.  The routines in this file
13 ** implement the programmer interface to the library.  Routines in
14 ** other files are for internal use by SQLite and should not be
15 ** accessed by users of the library.
16 **
17 ** $Id: main.c,v 1.542 2009/04/28 15:35:39 danielk1977 Exp $
18 */
19 #include "sqliteInt.h"
20 
21 #ifdef SQLITE_ENABLE_FTS3
22 # include "fts3.h"
23 #endif
24 #ifdef SQLITE_ENABLE_RTREE
25 # include "rtree.h"
26 #endif
27 #ifdef SQLITE_ENABLE_ICU
28 # include "sqliteicu.h"
29 #endif
30 
31 /*
32 ** The version of the library
33 */
34 #ifndef SQLITE_AMALGAMATION
35 const char sqlite3_version[] = SQLITE_VERSION;
36 #endif
37 const char *sqlite3_libversion(void){ return sqlite3_version; }
38 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
39 int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
40 
41 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
42 /*
43 ** If the following function pointer is not NULL and if
44 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
45 ** I/O active are written using this function.  These messages
46 ** are intended for debugging activity only.
47 */
48 void (*sqlite3IoTrace)(const char*, ...) = 0;
49 #endif
50 
51 /*
52 ** If the following global variable points to a string which is the
53 ** name of a directory, then that directory will be used to store
54 ** temporary files.
55 **
56 ** See also the "PRAGMA temp_store_directory" SQL command.
57 */
58 char *sqlite3_temp_directory = 0;
59 
60 /*
61 ** Initialize SQLite.
62 **
63 ** This routine must be called to initialize the memory allocation,
64 ** VFS, and mutex subsystems prior to doing any serious work with
65 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
66 ** this routine will be called automatically by key routines such as
67 ** sqlite3_open().
68 **
69 ** This routine is a no-op except on its very first call for the process,
70 ** or for the first call after a call to sqlite3_shutdown.
71 **
72 ** The first thread to call this routine runs the initialization to
73 ** completion.  If subsequent threads call this routine before the first
74 ** thread has finished the initialization process, then the subsequent
75 ** threads must block until the first thread finishes with the initialization.
76 **
77 ** The first thread might call this routine recursively.  Recursive
78 ** calls to this routine should not block, of course.  Otherwise the
79 ** initialization process would never complete.
80 **
81 ** Let X be the first thread to enter this routine.  Let Y be some other
82 ** thread.  Then while the initial invocation of this routine by X is
83 ** incomplete, it is required that:
84 **
85 **    *  Calls to this routine from Y must block until the outer-most
86 **       call by X completes.
87 **
88 **    *  Recursive calls to this routine from thread X return immediately
89 **       without blocking.
90 */
91 int sqlite3_initialize(void){
92   sqlite3_mutex *pMaster;                      /* The main static mutex */
93   int rc;                                      /* Result code */
94 
95 #ifdef SQLITE_OMIT_WSD
96   rc = sqlite3_wsd_init(4096, 24);
97   if( rc!=SQLITE_OK ){
98     return rc;
99   }
100 #endif
101 
102   /* If SQLite is already completely initialized, then this call
103   ** to sqlite3_initialize() should be a no-op.  But the initialization
104   ** must be complete.  So isInit must not be set until the very end
105   ** of this routine.
106   */
107   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
108 
109   /* Make sure the mutex subsystem is initialized.  If unable to
110   ** initialize the mutex subsystem, return early with the error.
111   ** If the system is so sick that we are unable to allocate a mutex,
112   ** there is not much SQLite is going to be able to do.
113   **
114   ** The mutex subsystem must take care of serializing its own
115   ** initialization.
116   */
117   rc = sqlite3MutexInit();
118   if( rc ) return rc;
119 
120   /* Initialize the malloc() system and the recursive pInitMutex mutex.
121   ** This operation is protected by the STATIC_MASTER mutex.  Note that
122   ** MutexAlloc() is called for a static mutex prior to initializing the
123   ** malloc subsystem - this implies that the allocation of a static
124   ** mutex must not require support from the malloc subsystem.
125   */
126   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
127   sqlite3_mutex_enter(pMaster);
128   if( !sqlite3GlobalConfig.isMallocInit ){
129     rc = sqlite3MallocInit();
130   }
131   if( rc==SQLITE_OK ){
132     sqlite3GlobalConfig.isMallocInit = 1;
133     if( !sqlite3GlobalConfig.pInitMutex ){
134       sqlite3GlobalConfig.pInitMutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
135       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
136         rc = SQLITE_NOMEM;
137       }
138     }
139   }
140   if( rc==SQLITE_OK ){
141     sqlite3GlobalConfig.nRefInitMutex++;
142   }
143   sqlite3_mutex_leave(pMaster);
144 
145   /* If unable to initialize the malloc subsystem, then return early.
146   ** There is little hope of getting SQLite to run if the malloc
147   ** subsystem cannot be initialized.
148   */
149   if( rc!=SQLITE_OK ){
150     return rc;
151   }
152 
153   /* Do the rest of the initialization under the recursive mutex so
154   ** that we will be able to handle recursive calls into
155   ** sqlite3_initialize().  The recursive calls normally come through
156   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
157   ** recursive calls might also be possible.
158   */
159   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
160   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
161     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
162     sqlite3GlobalConfig.inProgress = 1;
163     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
164     sqlite3RegisterGlobalFunctions();
165     rc = sqlite3PcacheInitialize();
166     if( rc==SQLITE_OK ){
167       rc = sqlite3_os_init();
168     }
169     if( rc==SQLITE_OK ){
170       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
171           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
172       sqlite3GlobalConfig.isInit = 1;
173     }
174     sqlite3GlobalConfig.inProgress = 0;
175   }
176   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
177 
178   /* Go back under the static mutex and clean up the recursive
179   ** mutex to prevent a resource leak.
180   */
181   sqlite3_mutex_enter(pMaster);
182   sqlite3GlobalConfig.nRefInitMutex--;
183   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
184     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
185     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
186     sqlite3GlobalConfig.pInitMutex = 0;
187   }
188   sqlite3_mutex_leave(pMaster);
189 
190   /* The following is just a sanity check to make sure SQLite has
191   ** been compiled correctly.  It is important to run this code, but
192   ** we don't want to run it too often and soak up CPU cycles for no
193   ** reason.  So we run it once during initialization.
194   */
195 #ifndef NDEBUG
196 #ifndef SQLITE_OMIT_FLOATING_POINT
197   /* This section of code's only "output" is via assert() statements. */
198   if ( rc==SQLITE_OK ){
199     u64 x = (((u64)1)<<63)-1;
200     double y;
201     assert(sizeof(x)==8);
202     assert(sizeof(x)==sizeof(y));
203     memcpy(&y, &x, 8);
204     assert( sqlite3IsNaN(y) );
205   }
206 #endif
207 #endif
208 
209   return rc;
210 }
211 
212 /*
213 ** Undo the effects of sqlite3_initialize().  Must not be called while
214 ** there are outstanding database connections or memory allocations or
215 ** while any part of SQLite is otherwise in use in any thread.  This
216 ** routine is not threadsafe.  But it is safe to invoke this routine
217 ** on when SQLite is already shut down.  If SQLite is already shut down
218 ** when this routine is invoked, then this routine is a harmless no-op.
219 */
220 int sqlite3_shutdown(void){
221   if( sqlite3GlobalConfig.isInit ){
222     sqlite3GlobalConfig.isMallocInit = 0;
223     sqlite3PcacheShutdown();
224     sqlite3_os_end();
225     sqlite3_reset_auto_extension();
226     sqlite3MallocEnd();
227     sqlite3MutexEnd();
228     sqlite3GlobalConfig.isInit = 0;
229   }
230   return SQLITE_OK;
231 }
232 
233 /*
234 ** This API allows applications to modify the global configuration of
235 ** the SQLite library at run-time.
236 **
237 ** This routine should only be called when there are no outstanding
238 ** database connections or memory allocations.  This routine is not
239 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
240 ** behavior.
241 */
242 int sqlite3_config(int op, ...){
243   va_list ap;
244   int rc = SQLITE_OK;
245 
246   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
247   ** the SQLite library is in use. */
248   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE;
249 
250   va_start(ap, op);
251   switch( op ){
252 
253     /* Mutex configuration options are only available in a threadsafe
254     ** compile.
255     */
256 #if SQLITE_THREADSAFE
257     case SQLITE_CONFIG_SINGLETHREAD: {
258       /* Disable all mutexing */
259       sqlite3GlobalConfig.bCoreMutex = 0;
260       sqlite3GlobalConfig.bFullMutex = 0;
261       break;
262     }
263     case SQLITE_CONFIG_MULTITHREAD: {
264       /* Disable mutexing of database connections */
265       /* Enable mutexing of core data structures */
266       sqlite3GlobalConfig.bCoreMutex = 1;
267       sqlite3GlobalConfig.bFullMutex = 0;
268       break;
269     }
270     case SQLITE_CONFIG_SERIALIZED: {
271       /* Enable all mutexing */
272       sqlite3GlobalConfig.bCoreMutex = 1;
273       sqlite3GlobalConfig.bFullMutex = 1;
274       break;
275     }
276     case SQLITE_CONFIG_MUTEX: {
277       /* Specify an alternative mutex implementation */
278       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
279       break;
280     }
281     case SQLITE_CONFIG_GETMUTEX: {
282       /* Retrieve the current mutex implementation */
283       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
284       break;
285     }
286 #endif
287 
288 
289     case SQLITE_CONFIG_MALLOC: {
290       /* Specify an alternative malloc implementation */
291       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
292       break;
293     }
294     case SQLITE_CONFIG_GETMALLOC: {
295       /* Retrieve the current malloc() implementation */
296       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
297       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
298       break;
299     }
300     case SQLITE_CONFIG_MEMSTATUS: {
301       /* Enable or disable the malloc status collection */
302       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
303       break;
304     }
305     case SQLITE_CONFIG_SCRATCH: {
306       /* Designate a buffer for scratch memory space */
307       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
308       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
309       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
310       break;
311     }
312     case SQLITE_CONFIG_PAGECACHE: {
313       /* Designate a buffer for scratch memory space */
314       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
315       sqlite3GlobalConfig.szPage = va_arg(ap, int);
316       sqlite3GlobalConfig.nPage = va_arg(ap, int);
317       break;
318     }
319 
320     case SQLITE_CONFIG_PCACHE: {
321       /* Specify an alternative malloc implementation */
322       sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
323       break;
324     }
325 
326     case SQLITE_CONFIG_GETPCACHE: {
327       if( sqlite3GlobalConfig.pcache.xInit==0 ){
328         sqlite3PCacheSetDefault();
329       }
330       *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
331       break;
332     }
333 
334 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
335     case SQLITE_CONFIG_HEAP: {
336       /* Designate a buffer for heap memory space */
337       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
338       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
339       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
340 
341       if( sqlite3GlobalConfig.pHeap==0 ){
342         /* If the heap pointer is NULL, then restore the malloc implementation
343         ** back to NULL pointers too.  This will cause the malloc to go
344         ** back to its default implementation when sqlite3_initialize() is
345         ** run.
346         */
347         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
348       }else{
349         /* The heap pointer is not NULL, then install one of the
350         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
351         ** ENABLE_MEMSYS5 is defined, return an error.
352         ** the default case and return an error.
353         */
354 #ifdef SQLITE_ENABLE_MEMSYS3
355         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
356 #endif
357 #ifdef SQLITE_ENABLE_MEMSYS5
358         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
359 #endif
360       }
361       break;
362     }
363 #endif
364 
365     case SQLITE_CONFIG_LOOKASIDE: {
366       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
367       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
368       break;
369     }
370 
371     default: {
372       rc = SQLITE_ERROR;
373       break;
374     }
375   }
376   va_end(ap);
377   return rc;
378 }
379 
380 /*
381 ** Set up the lookaside buffers for a database connection.
382 ** Return SQLITE_OK on success.
383 ** If lookaside is already active, return SQLITE_BUSY.
384 **
385 ** The sz parameter is the number of bytes in each lookaside slot.
386 ** The cnt parameter is the number of slots.  If pStart is NULL the
387 ** space for the lookaside memory is obtained from sqlite3_malloc().
388 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
389 ** the lookaside memory.
390 */
391 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
392   void *pStart;
393   if( db->lookaside.nOut ){
394     return SQLITE_BUSY;
395   }
396   /* Free any existing lookaside buffer for this handle before
397   ** allocating a new one so we don't have to have space for
398   ** both at the same time.
399   */
400   if( db->lookaside.bMalloced ){
401     sqlite3_free(db->lookaside.pStart);
402   }
403   /* The size of a lookaside slot needs to be larger than a pointer
404   ** to be useful.
405   */
406   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
407   if( cnt<0 ) cnt = 0;
408   if( sz==0 || cnt==0 ){
409     sz = 0;
410     pStart = 0;
411   }else if( pBuf==0 ){
412     sz = ROUND8(sz);
413     sqlite3BeginBenignMalloc();
414     pStart = sqlite3Malloc( sz*cnt );
415     sqlite3EndBenignMalloc();
416   }else{
417     sz = ROUNDDOWN8(sz);
418     pStart = pBuf;
419   }
420   db->lookaside.pStart = pStart;
421   db->lookaside.pFree = 0;
422   db->lookaside.sz = (u16)sz;
423   if( pStart ){
424     int i;
425     LookasideSlot *p;
426     assert( sz > (int)sizeof(LookasideSlot*) );
427     p = (LookasideSlot*)pStart;
428     for(i=cnt-1; i>=0; i--){
429       p->pNext = db->lookaside.pFree;
430       db->lookaside.pFree = p;
431       p = (LookasideSlot*)&((u8*)p)[sz];
432     }
433     db->lookaside.pEnd = p;
434     db->lookaside.bEnabled = 1;
435     db->lookaside.bMalloced = pBuf==0 ?1:0;
436   }else{
437     db->lookaside.pEnd = 0;
438     db->lookaside.bEnabled = 0;
439     db->lookaside.bMalloced = 0;
440   }
441   return SQLITE_OK;
442 }
443 
444 /*
445 ** Return the mutex associated with a database connection.
446 */
447 sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
448   return db->mutex;
449 }
450 
451 /*
452 ** Configuration settings for an individual database connection
453 */
454 int sqlite3_db_config(sqlite3 *db, int op, ...){
455   va_list ap;
456   int rc;
457   va_start(ap, op);
458   switch( op ){
459     case SQLITE_DBCONFIG_LOOKASIDE: {
460       void *pBuf = va_arg(ap, void*);
461       int sz = va_arg(ap, int);
462       int cnt = va_arg(ap, int);
463       rc = setupLookaside(db, pBuf, sz, cnt);
464       break;
465     }
466     default: {
467       rc = SQLITE_ERROR;
468       break;
469     }
470   }
471   va_end(ap);
472   return rc;
473 }
474 
475 
476 /*
477 ** Return true if the buffer z[0..n-1] contains all spaces.
478 */
479 static int allSpaces(const char *z, int n){
480   while( n>0 && z[n-1]==' ' ){ n--; }
481   return n==0;
482 }
483 
484 /*
485 ** This is the default collating function named "BINARY" which is always
486 ** available.
487 **
488 ** If the padFlag argument is not NULL then space padding at the end
489 ** of strings is ignored.  This implements the RTRIM collation.
490 */
491 static int binCollFunc(
492   void *padFlag,
493   int nKey1, const void *pKey1,
494   int nKey2, const void *pKey2
495 ){
496   int rc, n;
497   n = nKey1<nKey2 ? nKey1 : nKey2;
498   rc = memcmp(pKey1, pKey2, n);
499   if( rc==0 ){
500     if( padFlag
501      && allSpaces(((char*)pKey1)+n, nKey1-n)
502      && allSpaces(((char*)pKey2)+n, nKey2-n)
503     ){
504       /* Leave rc unchanged at 0 */
505     }else{
506       rc = nKey1 - nKey2;
507     }
508   }
509   return rc;
510 }
511 
512 /*
513 ** Another built-in collating sequence: NOCASE.
514 **
515 ** This collating sequence is intended to be used for "case independant
516 ** comparison". SQLite's knowledge of upper and lower case equivalents
517 ** extends only to the 26 characters used in the English language.
518 **
519 ** At the moment there is only a UTF-8 implementation.
520 */
521 static int nocaseCollatingFunc(
522   void *NotUsed,
523   int nKey1, const void *pKey1,
524   int nKey2, const void *pKey2
525 ){
526   int r = sqlite3StrNICmp(
527       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
528   UNUSED_PARAMETER(NotUsed);
529   if( 0==r ){
530     r = nKey1-nKey2;
531   }
532   return r;
533 }
534 
535 /*
536 ** Return the ROWID of the most recent insert
537 */
538 sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
539   return db->lastRowid;
540 }
541 
542 /*
543 ** Return the number of changes in the most recent call to sqlite3_exec().
544 */
545 int sqlite3_changes(sqlite3 *db){
546   return db->nChange;
547 }
548 
549 /*
550 ** Return the number of changes since the database handle was opened.
551 */
552 int sqlite3_total_changes(sqlite3 *db){
553   return db->nTotalChange;
554 }
555 
556 /*
557 ** Close all open savepoints. This function only manipulates fields of the
558 ** database handle object, it does not close any savepoints that may be open
559 ** at the b-tree/pager level.
560 */
561 void sqlite3CloseSavepoints(sqlite3 *db){
562   while( db->pSavepoint ){
563     Savepoint *pTmp = db->pSavepoint;
564     db->pSavepoint = pTmp->pNext;
565     sqlite3DbFree(db, pTmp);
566   }
567   db->nSavepoint = 0;
568   db->nStatement = 0;
569   db->isTransactionSavepoint = 0;
570 }
571 
572 /*
573 ** Close an existing SQLite database
574 */
575 int sqlite3_close(sqlite3 *db){
576   HashElem *i;
577   int j;
578 
579   if( !db ){
580     return SQLITE_OK;
581   }
582   if( !sqlite3SafetyCheckSickOrOk(db) ){
583     return SQLITE_MISUSE;
584   }
585   sqlite3_mutex_enter(db->mutex);
586 
587 #ifdef SQLITE_SSE
588   {
589     extern void sqlite3SseCleanup(sqlite3*);
590     sqlite3SseCleanup(db);
591   }
592 #endif
593 
594   sqlite3ResetInternalSchema(db, 0);
595 
596   /* If a transaction is open, the ResetInternalSchema() call above
597   ** will not have called the xDisconnect() method on any virtual
598   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
599   ** call will do so. We need to do this before the check for active
600   ** SQL statements below, as the v-table implementation may be storing
601   ** some prepared statements internally.
602   */
603   sqlite3VtabRollback(db);
604 
605   /* If there are any outstanding VMs, return SQLITE_BUSY. */
606   if( db->pVdbe ){
607     sqlite3Error(db, SQLITE_BUSY,
608         "unable to close due to unfinalised statements");
609     sqlite3_mutex_leave(db->mutex);
610     return SQLITE_BUSY;
611   }
612   assert( sqlite3SafetyCheckSickOrOk(db) );
613 
614   for(j=0; j<db->nDb; j++){
615     Btree *pBt = db->aDb[j].pBt;
616     if( pBt && sqlite3BtreeIsInBackup(pBt) ){
617       sqlite3Error(db, SQLITE_BUSY,
618           "unable to close due to unfinished backup operation");
619       sqlite3_mutex_leave(db->mutex);
620       return SQLITE_BUSY;
621     }
622   }
623 
624   /* Free any outstanding Savepoint structures. */
625   sqlite3CloseSavepoints(db);
626 
627   for(j=0; j<db->nDb; j++){
628     struct Db *pDb = &db->aDb[j];
629     if( pDb->pBt ){
630       sqlite3BtreeClose(pDb->pBt);
631       pDb->pBt = 0;
632       if( j!=1 ){
633         pDb->pSchema = 0;
634       }
635     }
636   }
637   sqlite3ResetInternalSchema(db, 0);
638 
639   /* Tell the code in notify.c that the connection no longer holds any
640   ** locks and does not require any further unlock-notify callbacks.
641   */
642   sqlite3ConnectionClosed(db);
643 
644   assert( db->nDb<=2 );
645   assert( db->aDb==db->aDbStatic );
646   for(j=0; j<ArraySize(db->aFunc.a); j++){
647     FuncDef *pNext, *pHash, *p;
648     for(p=db->aFunc.a[j]; p; p=pHash){
649       pHash = p->pHash;
650       while( p ){
651         pNext = p->pNext;
652         sqlite3DbFree(db, p);
653         p = pNext;
654       }
655     }
656   }
657   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
658     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
659     /* Invoke any destructors registered for collation sequence user data. */
660     for(j=0; j<3; j++){
661       if( pColl[j].xDel ){
662         pColl[j].xDel(pColl[j].pUser);
663       }
664     }
665     sqlite3DbFree(db, pColl);
666   }
667   sqlite3HashClear(&db->aCollSeq);
668 #ifndef SQLITE_OMIT_VIRTUALTABLE
669   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
670     Module *pMod = (Module *)sqliteHashData(i);
671     if( pMod->xDestroy ){
672       pMod->xDestroy(pMod->pAux);
673     }
674     sqlite3DbFree(db, pMod);
675   }
676   sqlite3HashClear(&db->aModule);
677 #endif
678 
679   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
680   if( db->pErr ){
681     sqlite3ValueFree(db->pErr);
682   }
683   sqlite3CloseExtensions(db);
684 
685   db->magic = SQLITE_MAGIC_ERROR;
686 
687   /* The temp-database schema is allocated differently from the other schema
688   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
689   ** So it needs to be freed here. Todo: Why not roll the temp schema into
690   ** the same sqliteMalloc() as the one that allocates the database
691   ** structure?
692   */
693   sqlite3DbFree(db, db->aDb[1].pSchema);
694   sqlite3_mutex_leave(db->mutex);
695   db->magic = SQLITE_MAGIC_CLOSED;
696   sqlite3_mutex_free(db->mutex);
697   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
698   if( db->lookaside.bMalloced ){
699     sqlite3_free(db->lookaside.pStart);
700   }
701   sqlite3_free(db);
702   return SQLITE_OK;
703 }
704 
705 /*
706 ** Rollback all database files.
707 */
708 void sqlite3RollbackAll(sqlite3 *db){
709   int i;
710   int inTrans = 0;
711   assert( sqlite3_mutex_held(db->mutex) );
712   sqlite3BeginBenignMalloc();
713   for(i=0; i<db->nDb; i++){
714     if( db->aDb[i].pBt ){
715       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
716         inTrans = 1;
717       }
718       sqlite3BtreeRollback(db->aDb[i].pBt);
719       db->aDb[i].inTrans = 0;
720     }
721   }
722   sqlite3VtabRollback(db);
723   sqlite3EndBenignMalloc();
724 
725   if( db->flags&SQLITE_InternChanges ){
726     sqlite3ExpirePreparedStatements(db);
727     sqlite3ResetInternalSchema(db, 0);
728   }
729 
730   /* If one has been configured, invoke the rollback-hook callback */
731   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
732     db->xRollbackCallback(db->pRollbackArg);
733   }
734 }
735 
736 /*
737 ** Return a static string that describes the kind of error specified in the
738 ** argument.
739 */
740 const char *sqlite3ErrStr(int rc){
741   static const char* const aMsg[] = {
742     /* SQLITE_OK          */ "not an error",
743     /* SQLITE_ERROR       */ "SQL logic error or missing database",
744     /* SQLITE_INTERNAL    */ 0,
745     /* SQLITE_PERM        */ "access permission denied",
746     /* SQLITE_ABORT       */ "callback requested query abort",
747     /* SQLITE_BUSY        */ "database is locked",
748     /* SQLITE_LOCKED      */ "database table is locked",
749     /* SQLITE_NOMEM       */ "out of memory",
750     /* SQLITE_READONLY    */ "attempt to write a readonly database",
751     /* SQLITE_INTERRUPT   */ "interrupted",
752     /* SQLITE_IOERR       */ "disk I/O error",
753     /* SQLITE_CORRUPT     */ "database disk image is malformed",
754     /* SQLITE_NOTFOUND    */ 0,
755     /* SQLITE_FULL        */ "database or disk is full",
756     /* SQLITE_CANTOPEN    */ "unable to open database file",
757     /* SQLITE_PROTOCOL    */ 0,
758     /* SQLITE_EMPTY       */ "table contains no data",
759     /* SQLITE_SCHEMA      */ "database schema has changed",
760     /* SQLITE_TOOBIG      */ "String or BLOB exceeded size limit",
761     /* SQLITE_CONSTRAINT  */ "constraint failed",
762     /* SQLITE_MISMATCH    */ "datatype mismatch",
763     /* SQLITE_MISUSE      */ "library routine called out of sequence",
764     /* SQLITE_NOLFS       */ "large file support is disabled",
765     /* SQLITE_AUTH        */ "authorization denied",
766     /* SQLITE_FORMAT      */ "auxiliary database format error",
767     /* SQLITE_RANGE       */ "bind or column index out of range",
768     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
769   };
770   rc &= 0xff;
771   if( ALWAYS(rc>=0) && rc<sizeof(aMsg)/sizeof(aMsg[0]) && aMsg[rc]!=0 ){
772     return aMsg[rc];
773   }else{
774     return "unknown error";
775   }
776 }
777 
778 /*
779 ** This routine implements a busy callback that sleeps and tries
780 ** again until a timeout value is reached.  The timeout value is
781 ** an integer number of milliseconds passed in as the first
782 ** argument.
783 */
784 static int sqliteDefaultBusyCallback(
785  void *ptr,               /* Database connection */
786  int count                /* Number of times table has been busy */
787 ){
788 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
789   static const u8 delays[] =
790      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
791   static const u8 totals[] =
792      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
793 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
794   sqlite3 *db = (sqlite3 *)ptr;
795   int timeout = db->busyTimeout;
796   int delay, prior;
797 
798   assert( count>=0 );
799   if( count < NDELAY ){
800     delay = delays[count];
801     prior = totals[count];
802   }else{
803     delay = delays[NDELAY-1];
804     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
805   }
806   if( prior + delay > timeout ){
807     delay = timeout - prior;
808     if( delay<=0 ) return 0;
809   }
810   sqlite3OsSleep(db->pVfs, delay*1000);
811   return 1;
812 #else
813   sqlite3 *db = (sqlite3 *)ptr;
814   int timeout = ((sqlite3 *)ptr)->busyTimeout;
815   if( (count+1)*1000 > timeout ){
816     return 0;
817   }
818   sqlite3OsSleep(db->pVfs, 1000000);
819   return 1;
820 #endif
821 }
822 
823 /*
824 ** Invoke the given busy handler.
825 **
826 ** This routine is called when an operation failed with a lock.
827 ** If this routine returns non-zero, the lock is retried.  If it
828 ** returns 0, the operation aborts with an SQLITE_BUSY error.
829 */
830 int sqlite3InvokeBusyHandler(BusyHandler *p){
831   int rc;
832   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
833   rc = p->xFunc(p->pArg, p->nBusy);
834   if( rc==0 ){
835     p->nBusy = -1;
836   }else{
837     p->nBusy++;
838   }
839   return rc;
840 }
841 
842 /*
843 ** This routine sets the busy callback for an Sqlite database to the
844 ** given callback function with the given argument.
845 */
846 int sqlite3_busy_handler(
847   sqlite3 *db,
848   int (*xBusy)(void*,int),
849   void *pArg
850 ){
851   sqlite3_mutex_enter(db->mutex);
852   db->busyHandler.xFunc = xBusy;
853   db->busyHandler.pArg = pArg;
854   db->busyHandler.nBusy = 0;
855   sqlite3_mutex_leave(db->mutex);
856   return SQLITE_OK;
857 }
858 
859 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
860 /*
861 ** This routine sets the progress callback for an Sqlite database to the
862 ** given callback function with the given argument. The progress callback will
863 ** be invoked every nOps opcodes.
864 */
865 void sqlite3_progress_handler(
866   sqlite3 *db,
867   int nOps,
868   int (*xProgress)(void*),
869   void *pArg
870 ){
871   sqlite3_mutex_enter(db->mutex);
872   if( nOps>0 ){
873     db->xProgress = xProgress;
874     db->nProgressOps = nOps;
875     db->pProgressArg = pArg;
876   }else{
877     db->xProgress = 0;
878     db->nProgressOps = 0;
879     db->pProgressArg = 0;
880   }
881   sqlite3_mutex_leave(db->mutex);
882 }
883 #endif
884 
885 
886 /*
887 ** This routine installs a default busy handler that waits for the
888 ** specified number of milliseconds before returning 0.
889 */
890 int sqlite3_busy_timeout(sqlite3 *db, int ms){
891   if( ms>0 ){
892     db->busyTimeout = ms;
893     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
894   }else{
895     sqlite3_busy_handler(db, 0, 0);
896   }
897   return SQLITE_OK;
898 }
899 
900 /*
901 ** Cause any pending operation to stop at its earliest opportunity.
902 */
903 void sqlite3_interrupt(sqlite3 *db){
904   db->u1.isInterrupted = 1;
905 }
906 
907 
908 /*
909 ** This function is exactly the same as sqlite3_create_function(), except
910 ** that it is designed to be called by internal code. The difference is
911 ** that if a malloc() fails in sqlite3_create_function(), an error code
912 ** is returned and the mallocFailed flag cleared.
913 */
914 int sqlite3CreateFunc(
915   sqlite3 *db,
916   const char *zFunctionName,
917   int nArg,
918   int enc,
919   void *pUserData,
920   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
921   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
922   void (*xFinal)(sqlite3_context*)
923 ){
924   FuncDef *p;
925   int nName;
926 
927   assert( sqlite3_mutex_held(db->mutex) );
928   if( zFunctionName==0 ||
929       (xFunc && (xFinal || xStep)) ||
930       (!xFunc && (xFinal && !xStep)) ||
931       (!xFunc && (!xFinal && xStep)) ||
932       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
933       (255<(nName = sqlite3Strlen(db, zFunctionName))) ){
934     sqlite3Error(db, SQLITE_ERROR, "bad parameters");
935     return SQLITE_ERROR;
936   }
937 
938 #ifndef SQLITE_OMIT_UTF16
939   /* If SQLITE_UTF16 is specified as the encoding type, transform this
940   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
941   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
942   **
943   ** If SQLITE_ANY is specified, add three versions of the function
944   ** to the hash table.
945   */
946   if( enc==SQLITE_UTF16 ){
947     enc = SQLITE_UTF16NATIVE;
948   }else if( enc==SQLITE_ANY ){
949     int rc;
950     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
951          pUserData, xFunc, xStep, xFinal);
952     if( rc==SQLITE_OK ){
953       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
954           pUserData, xFunc, xStep, xFinal);
955     }
956     if( rc!=SQLITE_OK ){
957       return rc;
958     }
959     enc = SQLITE_UTF16BE;
960   }
961 #else
962   enc = SQLITE_UTF8;
963 #endif
964 
965   /* Check if an existing function is being overridden or deleted. If so,
966   ** and there are active VMs, then return SQLITE_BUSY. If a function
967   ** is being overridden/deleted but there are no active VMs, allow the
968   ** operation to continue but invalidate all precompiled statements.
969   */
970   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
971   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
972     if( db->activeVdbeCnt ){
973       sqlite3Error(db, SQLITE_BUSY,
974         "unable to delete/modify user-function due to active statements");
975       assert( !db->mallocFailed );
976       return SQLITE_BUSY;
977     }else{
978       sqlite3ExpirePreparedStatements(db);
979     }
980   }
981 
982   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
983   assert(p || db->mallocFailed);
984   if( !p ){
985     return SQLITE_NOMEM;
986   }
987   p->flags = 0;
988   p->xFunc = xFunc;
989   p->xStep = xStep;
990   p->xFinalize = xFinal;
991   p->pUserData = pUserData;
992   p->nArg = (u16)nArg;
993   return SQLITE_OK;
994 }
995 
996 /*
997 ** Create new user functions.
998 */
999 int sqlite3_create_function(
1000   sqlite3 *db,
1001   const char *zFunctionName,
1002   int nArg,
1003   int enc,
1004   void *p,
1005   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
1006   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
1007   void (*xFinal)(sqlite3_context*)
1008 ){
1009   int rc;
1010   sqlite3_mutex_enter(db->mutex);
1011   rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
1012   rc = sqlite3ApiExit(db, rc);
1013   sqlite3_mutex_leave(db->mutex);
1014   return rc;
1015 }
1016 
1017 #ifndef SQLITE_OMIT_UTF16
1018 int sqlite3_create_function16(
1019   sqlite3 *db,
1020   const void *zFunctionName,
1021   int nArg,
1022   int eTextRep,
1023   void *p,
1024   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
1025   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
1026   void (*xFinal)(sqlite3_context*)
1027 ){
1028   int rc;
1029   char *zFunc8;
1030   sqlite3_mutex_enter(db->mutex);
1031   assert( !db->mallocFailed );
1032   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
1033   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
1034   sqlite3DbFree(db, zFunc8);
1035   rc = sqlite3ApiExit(db, rc);
1036   sqlite3_mutex_leave(db->mutex);
1037   return rc;
1038 }
1039 #endif
1040 
1041 
1042 /*
1043 ** Declare that a function has been overloaded by a virtual table.
1044 **
1045 ** If the function already exists as a regular global function, then
1046 ** this routine is a no-op.  If the function does not exist, then create
1047 ** a new one that always throws a run-time error.
1048 **
1049 ** When virtual tables intend to provide an overloaded function, they
1050 ** should call this routine to make sure the global function exists.
1051 ** A global function must exist in order for name resolution to work
1052 ** properly.
1053 */
1054 int sqlite3_overload_function(
1055   sqlite3 *db,
1056   const char *zName,
1057   int nArg
1058 ){
1059   int nName = sqlite3Strlen(db, zName);
1060   int rc;
1061   sqlite3_mutex_enter(db->mutex);
1062   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
1063     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
1064                       0, sqlite3InvalidFunction, 0, 0);
1065   }
1066   rc = sqlite3ApiExit(db, SQLITE_OK);
1067   sqlite3_mutex_leave(db->mutex);
1068   return rc;
1069 }
1070 
1071 #ifndef SQLITE_OMIT_TRACE
1072 /*
1073 ** Register a trace function.  The pArg from the previously registered trace
1074 ** is returned.
1075 **
1076 ** A NULL trace function means that no tracing is executes.  A non-NULL
1077 ** trace is a pointer to a function that is invoked at the start of each
1078 ** SQL statement.
1079 */
1080 void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
1081   void *pOld;
1082   sqlite3_mutex_enter(db->mutex);
1083   pOld = db->pTraceArg;
1084   db->xTrace = xTrace;
1085   db->pTraceArg = pArg;
1086   sqlite3_mutex_leave(db->mutex);
1087   return pOld;
1088 }
1089 /*
1090 ** Register a profile function.  The pArg from the previously registered
1091 ** profile function is returned.
1092 **
1093 ** A NULL profile function means that no profiling is executes.  A non-NULL
1094 ** profile is a pointer to a function that is invoked at the conclusion of
1095 ** each SQL statement that is run.
1096 */
1097 void *sqlite3_profile(
1098   sqlite3 *db,
1099   void (*xProfile)(void*,const char*,sqlite_uint64),
1100   void *pArg
1101 ){
1102   void *pOld;
1103   sqlite3_mutex_enter(db->mutex);
1104   pOld = db->pProfileArg;
1105   db->xProfile = xProfile;
1106   db->pProfileArg = pArg;
1107   sqlite3_mutex_leave(db->mutex);
1108   return pOld;
1109 }
1110 #endif /* SQLITE_OMIT_TRACE */
1111 
1112 /*** EXPERIMENTAL ***
1113 **
1114 ** Register a function to be invoked when a transaction comments.
1115 ** If the invoked function returns non-zero, then the commit becomes a
1116 ** rollback.
1117 */
1118 void *sqlite3_commit_hook(
1119   sqlite3 *db,              /* Attach the hook to this database */
1120   int (*xCallback)(void*),  /* Function to invoke on each commit */
1121   void *pArg                /* Argument to the function */
1122 ){
1123   void *pOld;
1124   sqlite3_mutex_enter(db->mutex);
1125   pOld = db->pCommitArg;
1126   db->xCommitCallback = xCallback;
1127   db->pCommitArg = pArg;
1128   sqlite3_mutex_leave(db->mutex);
1129   return pOld;
1130 }
1131 
1132 /*
1133 ** Register a callback to be invoked each time a row is updated,
1134 ** inserted or deleted using this database connection.
1135 */
1136 void *sqlite3_update_hook(
1137   sqlite3 *db,              /* Attach the hook to this database */
1138   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
1139   void *pArg                /* Argument to the function */
1140 ){
1141   void *pRet;
1142   sqlite3_mutex_enter(db->mutex);
1143   pRet = db->pUpdateArg;
1144   db->xUpdateCallback = xCallback;
1145   db->pUpdateArg = pArg;
1146   sqlite3_mutex_leave(db->mutex);
1147   return pRet;
1148 }
1149 
1150 /*
1151 ** Register a callback to be invoked each time a transaction is rolled
1152 ** back by this database connection.
1153 */
1154 void *sqlite3_rollback_hook(
1155   sqlite3 *db,              /* Attach the hook to this database */
1156   void (*xCallback)(void*), /* Callback function */
1157   void *pArg                /* Argument to the function */
1158 ){
1159   void *pRet;
1160   sqlite3_mutex_enter(db->mutex);
1161   pRet = db->pRollbackArg;
1162   db->xRollbackCallback = xCallback;
1163   db->pRollbackArg = pArg;
1164   sqlite3_mutex_leave(db->mutex);
1165   return pRet;
1166 }
1167 
1168 /*
1169 ** This routine is called to create a connection to a database BTree
1170 ** driver.  If zFilename is the name of a file, then that file is
1171 ** opened and used.  If zFilename is the magic name ":memory:" then
1172 ** the database is stored in memory (and is thus forgotten as soon as
1173 ** the connection is closed.)  If zFilename is NULL then the database
1174 ** is a "virtual" database for transient use only and is deleted as
1175 ** soon as the connection is closed.
1176 **
1177 ** A virtual database can be either a disk file (that is automatically
1178 ** deleted when the file is closed) or it an be held entirely in memory,
1179 ** depending on the values of the SQLITE_TEMP_STORE compile-time macro and the
1180 ** db->temp_store variable, according to the following chart:
1181 **
1182 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
1183 **   -----------------     --------------     ------------------------------
1184 **   0                     any                file
1185 **   1                     1                  file
1186 **   1                     2                  memory
1187 **   1                     0                  file
1188 **   2                     1                  file
1189 **   2                     2                  memory
1190 **   2                     0                  memory
1191 **   3                     any                memory
1192 */
1193 int sqlite3BtreeFactory(
1194   const sqlite3 *db,        /* Main database when opening aux otherwise 0 */
1195   const char *zFilename,    /* Name of the file containing the BTree database */
1196   int omitJournal,          /* if TRUE then do not journal this file */
1197   int nCache,               /* How many pages in the page cache */
1198   int vfsFlags,             /* Flags passed through to vfsOpen */
1199   Btree **ppBtree           /* Pointer to new Btree object written here */
1200 ){
1201   int btFlags = 0;
1202   int rc;
1203 
1204   assert( sqlite3_mutex_held(db->mutex) );
1205   assert( ppBtree != 0);
1206   if( omitJournal ){
1207     btFlags |= BTREE_OMIT_JOURNAL;
1208   }
1209   if( db->flags & SQLITE_NoReadlock ){
1210     btFlags |= BTREE_NO_READLOCK;
1211   }
1212   if( zFilename==0 ){
1213 #if SQLITE_TEMP_STORE==0
1214     /* Do nothing */
1215 #endif
1216 #ifndef SQLITE_OMIT_MEMORYDB
1217 #if SQLITE_TEMP_STORE==1
1218     if( db->temp_store==2 ) zFilename = ":memory:";
1219 #endif
1220 #if SQLITE_TEMP_STORE==2
1221     if( db->temp_store!=1 ) zFilename = ":memory:";
1222 #endif
1223 #if SQLITE_TEMP_STORE==3
1224     zFilename = ":memory:";
1225 #endif
1226 #endif /* SQLITE_OMIT_MEMORYDB */
1227   }
1228 
1229   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
1230     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
1231   }
1232   rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
1233 
1234   /* If the B-Tree was successfully opened, set the pager-cache size to the
1235   ** default value. Except, if the call to BtreeOpen() returned a handle
1236   ** open on an existing shared pager-cache, do not change the pager-cache
1237   ** size.
1238   */
1239   if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
1240     sqlite3BtreeSetCacheSize(*ppBtree, nCache);
1241   }
1242   return rc;
1243 }
1244 
1245 /*
1246 ** Return UTF-8 encoded English language explanation of the most recent
1247 ** error.
1248 */
1249 const char *sqlite3_errmsg(sqlite3 *db){
1250   const char *z;
1251   if( !db ){
1252     return sqlite3ErrStr(SQLITE_NOMEM);
1253   }
1254   if( !sqlite3SafetyCheckSickOrOk(db) ){
1255     return sqlite3ErrStr(SQLITE_MISUSE);
1256   }
1257   sqlite3_mutex_enter(db->mutex);
1258   if( db->mallocFailed ){
1259     z = sqlite3ErrStr(SQLITE_NOMEM);
1260   }else{
1261     z = (char*)sqlite3_value_text(db->pErr);
1262     assert( !db->mallocFailed );
1263     if( z==0 ){
1264       z = sqlite3ErrStr(db->errCode);
1265     }
1266   }
1267   sqlite3_mutex_leave(db->mutex);
1268   return z;
1269 }
1270 
1271 #ifndef SQLITE_OMIT_UTF16
1272 /*
1273 ** Return UTF-16 encoded English language explanation of the most recent
1274 ** error.
1275 */
1276 const void *sqlite3_errmsg16(sqlite3 *db){
1277   static const u16 outOfMem[] = {
1278     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
1279   };
1280   static const u16 misuse[] = {
1281     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
1282     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
1283     'c', 'a', 'l', 'l', 'e', 'd', ' ',
1284     'o', 'u', 't', ' ',
1285     'o', 'f', ' ',
1286     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
1287   };
1288 
1289   const void *z;
1290   if( !db ){
1291     return (void *)outOfMem;
1292   }
1293   if( !sqlite3SafetyCheckSickOrOk(db) ){
1294     return (void *)misuse;
1295   }
1296   sqlite3_mutex_enter(db->mutex);
1297   if( db->mallocFailed ){
1298     z = (void *)outOfMem;
1299   }else{
1300     z = sqlite3_value_text16(db->pErr);
1301     if( z==0 ){
1302       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
1303            SQLITE_UTF8, SQLITE_STATIC);
1304       z = sqlite3_value_text16(db->pErr);
1305     }
1306     /* A malloc() may have failed within the call to sqlite3_value_text16()
1307     ** above. If this is the case, then the db->mallocFailed flag needs to
1308     ** be cleared before returning. Do this directly, instead of via
1309     ** sqlite3ApiExit(), to avoid setting the database handle error message.
1310     */
1311     db->mallocFailed = 0;
1312   }
1313   sqlite3_mutex_leave(db->mutex);
1314   return z;
1315 }
1316 #endif /* SQLITE_OMIT_UTF16 */
1317 
1318 /*
1319 ** Return the most recent error code generated by an SQLite routine. If NULL is
1320 ** passed to this function, we assume a malloc() failed during sqlite3_open().
1321 */
1322 int sqlite3_errcode(sqlite3 *db){
1323   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
1324     return SQLITE_MISUSE;
1325   }
1326   if( !db || db->mallocFailed ){
1327     return SQLITE_NOMEM;
1328   }
1329   return db->errCode & db->errMask;
1330 }
1331 int sqlite3_extended_errcode(sqlite3 *db){
1332   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
1333     return SQLITE_MISUSE;
1334   }
1335   if( !db || db->mallocFailed ){
1336     return SQLITE_NOMEM;
1337   }
1338   return db->errCode;
1339 }
1340 
1341 /*
1342 ** Create a new collating function for database "db".  The name is zName
1343 ** and the encoding is enc.
1344 */
1345 static int createCollation(
1346   sqlite3* db,
1347   const char *zName,
1348   int enc,
1349   void* pCtx,
1350   int(*xCompare)(void*,int,const void*,int,const void*),
1351   void(*xDel)(void*)
1352 ){
1353   CollSeq *pColl;
1354   int enc2;
1355   int nName;
1356 
1357   assert( sqlite3_mutex_held(db->mutex) );
1358 
1359   /* If SQLITE_UTF16 is specified as the encoding type, transform this
1360   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
1361   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
1362   */
1363   enc2 = enc;
1364   testcase( enc2==SQLITE_UTF16 );
1365   testcase( enc2==SQLITE_UTF16_ALIGNED );
1366   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
1367     enc2 = SQLITE_UTF16NATIVE;
1368   }
1369   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
1370     return SQLITE_MISUSE;
1371   }
1372 
1373   /* Check if this call is removing or replacing an existing collation
1374   ** sequence. If so, and there are active VMs, return busy. If there
1375   ** are no active VMs, invalidate any pre-compiled statements.
1376   */
1377   nName = sqlite3Strlen(db, zName);
1378   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 0);
1379   if( pColl && pColl->xCmp ){
1380     if( db->activeVdbeCnt ){
1381       sqlite3Error(db, SQLITE_BUSY,
1382         "unable to delete/modify collation sequence due to active statements");
1383       return SQLITE_BUSY;
1384     }
1385     sqlite3ExpirePreparedStatements(db);
1386 
1387     /* If collation sequence pColl was created directly by a call to
1388     ** sqlite3_create_collation, and not generated by synthCollSeq(),
1389     ** then any copies made by synthCollSeq() need to be invalidated.
1390     ** Also, collation destructor - CollSeq.xDel() - function may need
1391     ** to be called.
1392     */
1393     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
1394       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
1395       int j;
1396       for(j=0; j<3; j++){
1397         CollSeq *p = &aColl[j];
1398         if( p->enc==pColl->enc ){
1399           if( p->xDel ){
1400             p->xDel(p->pUser);
1401           }
1402           p->xCmp = 0;
1403         }
1404       }
1405     }
1406   }
1407 
1408   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 1);
1409   if( pColl ){
1410     pColl->xCmp = xCompare;
1411     pColl->pUser = pCtx;
1412     pColl->xDel = xDel;
1413     pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
1414   }
1415   sqlite3Error(db, SQLITE_OK, 0);
1416   return SQLITE_OK;
1417 }
1418 
1419 
1420 /*
1421 ** This array defines hard upper bounds on limit values.  The
1422 ** initializer must be kept in sync with the SQLITE_LIMIT_*
1423 ** #defines in sqlite3.h.
1424 */
1425 static const int aHardLimit[] = {
1426   SQLITE_MAX_LENGTH,
1427   SQLITE_MAX_SQL_LENGTH,
1428   SQLITE_MAX_COLUMN,
1429   SQLITE_MAX_EXPR_DEPTH,
1430   SQLITE_MAX_COMPOUND_SELECT,
1431   SQLITE_MAX_VDBE_OP,
1432   SQLITE_MAX_FUNCTION_ARG,
1433   SQLITE_MAX_ATTACHED,
1434   SQLITE_MAX_LIKE_PATTERN_LENGTH,
1435   SQLITE_MAX_VARIABLE_NUMBER,
1436 };
1437 
1438 /*
1439 ** Make sure the hard limits are set to reasonable values
1440 */
1441 #if SQLITE_MAX_LENGTH<100
1442 # error SQLITE_MAX_LENGTH must be at least 100
1443 #endif
1444 #if SQLITE_MAX_SQL_LENGTH<100
1445 # error SQLITE_MAX_SQL_LENGTH must be at least 100
1446 #endif
1447 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
1448 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
1449 #endif
1450 #if SQLITE_MAX_COMPOUND_SELECT<2
1451 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
1452 #endif
1453 #if SQLITE_MAX_VDBE_OP<40
1454 # error SQLITE_MAX_VDBE_OP must be at least 40
1455 #endif
1456 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
1457 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
1458 #endif
1459 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
1460 # error SQLITE_MAX_ATTACHED must be between 0 and 30
1461 #endif
1462 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
1463 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
1464 #endif
1465 #if SQLITE_MAX_VARIABLE_NUMBER<1
1466 # error SQLITE_MAX_VARIABLE_NUMBER must be at least 1
1467 #endif
1468 #if SQLITE_MAX_COLUMN>32767
1469 # error SQLITE_MAX_COLUMN must not exceed 32767
1470 #endif
1471 
1472 
1473 /*
1474 ** Change the value of a limit.  Report the old value.
1475 ** If an invalid limit index is supplied, report -1.
1476 ** Make no changes but still report the old value if the
1477 ** new limit is negative.
1478 **
1479 ** A new lower limit does not shrink existing constructs.
1480 ** It merely prevents new constructs that exceed the limit
1481 ** from forming.
1482 */
1483 int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
1484   int oldLimit;
1485   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
1486     return -1;
1487   }
1488   oldLimit = db->aLimit[limitId];
1489   if( newLimit>=0 ){
1490     if( newLimit>aHardLimit[limitId] ){
1491       newLimit = aHardLimit[limitId];
1492     }
1493     db->aLimit[limitId] = newLimit;
1494   }
1495   return oldLimit;
1496 }
1497 
1498 /*
1499 ** This routine does the work of opening a database on behalf of
1500 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
1501 ** is UTF-8 encoded.
1502 */
1503 static int openDatabase(
1504   const char *zFilename, /* Database filename UTF-8 encoded */
1505   sqlite3 **ppDb,        /* OUT: Returned database handle */
1506   unsigned flags,        /* Operational flags */
1507   const char *zVfs       /* Name of the VFS to use */
1508 ){
1509   sqlite3 *db;
1510   int rc;
1511   CollSeq *pColl;
1512   int isThreadsafe;
1513 
1514   *ppDb = 0;
1515 #ifndef SQLITE_OMIT_AUTOINIT
1516   rc = sqlite3_initialize();
1517   if( rc ) return rc;
1518 #endif
1519 
1520   if( sqlite3GlobalConfig.bCoreMutex==0 ){
1521     isThreadsafe = 0;
1522   }else if( flags & SQLITE_OPEN_NOMUTEX ){
1523     isThreadsafe = 0;
1524   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
1525     isThreadsafe = 1;
1526   }else{
1527     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
1528   }
1529 
1530   /* Remove harmful bits from the flags parameter */
1531   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
1532                SQLITE_OPEN_MAIN_DB |
1533                SQLITE_OPEN_TEMP_DB |
1534                SQLITE_OPEN_TRANSIENT_DB |
1535                SQLITE_OPEN_MAIN_JOURNAL |
1536                SQLITE_OPEN_TEMP_JOURNAL |
1537                SQLITE_OPEN_SUBJOURNAL |
1538                SQLITE_OPEN_MASTER_JOURNAL |
1539                SQLITE_OPEN_NOMUTEX |
1540                SQLITE_OPEN_FULLMUTEX
1541              );
1542 
1543   /* Allocate the sqlite data structure */
1544   db = sqlite3MallocZero( sizeof(sqlite3) );
1545   if( db==0 ) goto opendb_out;
1546   if( isThreadsafe ){
1547     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
1548     if( db->mutex==0 ){
1549       sqlite3_free(db);
1550       db = 0;
1551       goto opendb_out;
1552     }
1553   }
1554   sqlite3_mutex_enter(db->mutex);
1555   db->errMask = 0xff;
1556   db->priorNewRowid = 0;
1557   db->nDb = 2;
1558   db->magic = SQLITE_MAGIC_BUSY;
1559   db->aDb = db->aDbStatic;
1560 
1561   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
1562   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
1563   db->autoCommit = 1;
1564   db->nextAutovac = -1;
1565   db->nextPagesize = 0;
1566   db->flags |= SQLITE_ShortColNames
1567 #if SQLITE_DEFAULT_FILE_FORMAT<4
1568                  | SQLITE_LegacyFileFmt
1569 #endif
1570 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
1571                  | SQLITE_LoadExtension
1572 #endif
1573       ;
1574   sqlite3HashInit(&db->aCollSeq, 0);
1575 #ifndef SQLITE_OMIT_VIRTUALTABLE
1576   sqlite3HashInit(&db->aModule, 0);
1577 #endif
1578 
1579   db->pVfs = sqlite3_vfs_find(zVfs);
1580   if( !db->pVfs ){
1581     rc = SQLITE_ERROR;
1582     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
1583     goto opendb_out;
1584   }
1585 
1586   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
1587   ** and UTF-16, so add a version for each to avoid any unnecessary
1588   ** conversions. The only error that can occur here is a malloc() failure.
1589   */
1590   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
1591   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
1592   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
1593   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
1594   if( db->mallocFailed ){
1595     goto opendb_out;
1596   }
1597   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
1598   assert( db->pDfltColl!=0 );
1599 
1600   /* Also add a UTF-8 case-insensitive collation sequence. */
1601   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
1602 
1603   /* Set flags on the built-in collating sequences */
1604   db->pDfltColl->type = SQLITE_COLL_BINARY;
1605   pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "NOCASE", 6, 0);
1606   if( pColl ){
1607     pColl->type = SQLITE_COLL_NOCASE;
1608   }
1609 
1610   /* Open the backend database driver */
1611   db->openFlags = flags;
1612   rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE,
1613                            flags | SQLITE_OPEN_MAIN_DB,
1614                            &db->aDb[0].pBt);
1615   if( rc!=SQLITE_OK ){
1616     if( rc==SQLITE_IOERR_NOMEM ){
1617       rc = SQLITE_NOMEM;
1618     }
1619     sqlite3Error(db, rc, 0);
1620     goto opendb_out;
1621   }
1622   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
1623   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
1624 
1625 
1626   /* The default safety_level for the main database is 'full'; for the temp
1627   ** database it is 'NONE'. This matches the pager layer defaults.
1628   */
1629   db->aDb[0].zName = "main";
1630   db->aDb[0].safety_level = 3;
1631 #ifndef SQLITE_OMIT_TEMPDB
1632   db->aDb[1].zName = "temp";
1633   db->aDb[1].safety_level = 1;
1634 #endif
1635 
1636   db->magic = SQLITE_MAGIC_OPEN;
1637   if( db->mallocFailed ){
1638     goto opendb_out;
1639   }
1640 
1641   /* Register all built-in functions, but do not attempt to read the
1642   ** database schema yet. This is delayed until the first time the database
1643   ** is accessed.
1644   */
1645   sqlite3Error(db, SQLITE_OK, 0);
1646   sqlite3RegisterBuiltinFunctions(db);
1647 
1648   /* Load automatic extensions - extensions that have been registered
1649   ** using the sqlite3_automatic_extension() API.
1650   */
1651   (void)sqlite3AutoLoadExtensions(db);
1652   if( sqlite3_errcode(db)!=SQLITE_OK ){
1653     goto opendb_out;
1654   }
1655 
1656 #ifdef SQLITE_ENABLE_FTS1
1657   if( !db->mallocFailed ){
1658     extern int sqlite3Fts1Init(sqlite3*);
1659     rc = sqlite3Fts1Init(db);
1660   }
1661 #endif
1662 
1663 #ifdef SQLITE_ENABLE_FTS2
1664   if( !db->mallocFailed && rc==SQLITE_OK ){
1665     extern int sqlite3Fts2Init(sqlite3*);
1666     rc = sqlite3Fts2Init(db);
1667   }
1668 #endif
1669 
1670 #ifdef SQLITE_ENABLE_FTS3
1671   if( !db->mallocFailed && rc==SQLITE_OK ){
1672     rc = sqlite3Fts3Init(db);
1673   }
1674 #endif
1675 
1676 #ifdef SQLITE_ENABLE_ICU
1677   if( !db->mallocFailed && rc==SQLITE_OK ){
1678     rc = sqlite3IcuInit(db);
1679   }
1680 #endif
1681 
1682 #ifdef SQLITE_ENABLE_RTREE
1683   if( !db->mallocFailed && rc==SQLITE_OK){
1684     rc = sqlite3RtreeInit(db);
1685   }
1686 #endif
1687 
1688   sqlite3Error(db, rc, 0);
1689 
1690   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
1691   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
1692   ** mode.  Doing nothing at all also makes NORMAL the default.
1693   */
1694 #ifdef SQLITE_DEFAULT_LOCKING_MODE
1695   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
1696   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
1697                           SQLITE_DEFAULT_LOCKING_MODE);
1698 #endif
1699 
1700   /* Enable the lookaside-malloc subsystem */
1701   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
1702                         sqlite3GlobalConfig.nLookaside);
1703 
1704 opendb_out:
1705   if( db ){
1706     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
1707     sqlite3_mutex_leave(db->mutex);
1708   }
1709   rc = sqlite3_errcode(db);
1710   if( rc==SQLITE_NOMEM ){
1711     sqlite3_close(db);
1712     db = 0;
1713   }else if( rc!=SQLITE_OK ){
1714     db->magic = SQLITE_MAGIC_SICK;
1715   }
1716   *ppDb = db;
1717   return sqlite3ApiExit(0, rc);
1718 }
1719 
1720 /*
1721 ** Open a new database handle.
1722 */
1723 int sqlite3_open(
1724   const char *zFilename,
1725   sqlite3 **ppDb
1726 ){
1727   return openDatabase(zFilename, ppDb,
1728                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
1729 }
1730 int sqlite3_open_v2(
1731   const char *filename,   /* Database filename (UTF-8) */
1732   sqlite3 **ppDb,         /* OUT: SQLite db handle */
1733   int flags,              /* Flags */
1734   const char *zVfs        /* Name of VFS module to use */
1735 ){
1736   return openDatabase(filename, ppDb, flags, zVfs);
1737 }
1738 
1739 #ifndef SQLITE_OMIT_UTF16
1740 /*
1741 ** Open a new database handle.
1742 */
1743 int sqlite3_open16(
1744   const void *zFilename,
1745   sqlite3 **ppDb
1746 ){
1747   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
1748   sqlite3_value *pVal;
1749   int rc;
1750 
1751   assert( zFilename );
1752   assert( ppDb );
1753   *ppDb = 0;
1754 #ifndef SQLITE_OMIT_AUTOINIT
1755   rc = sqlite3_initialize();
1756   if( rc ) return rc;
1757 #endif
1758   pVal = sqlite3ValueNew(0);
1759   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
1760   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
1761   if( zFilename8 ){
1762     rc = openDatabase(zFilename8, ppDb,
1763                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
1764     assert( *ppDb || rc==SQLITE_NOMEM );
1765     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
1766       ENC(*ppDb) = SQLITE_UTF16NATIVE;
1767     }
1768   }else{
1769     rc = SQLITE_NOMEM;
1770   }
1771   sqlite3ValueFree(pVal);
1772 
1773   return sqlite3ApiExit(0, rc);
1774 }
1775 #endif /* SQLITE_OMIT_UTF16 */
1776 
1777 /*
1778 ** Register a new collation sequence with the database handle db.
1779 */
1780 int sqlite3_create_collation(
1781   sqlite3* db,
1782   const char *zName,
1783   int enc,
1784   void* pCtx,
1785   int(*xCompare)(void*,int,const void*,int,const void*)
1786 ){
1787   int rc;
1788   sqlite3_mutex_enter(db->mutex);
1789   assert( !db->mallocFailed );
1790   rc = createCollation(db, zName, enc, pCtx, xCompare, 0);
1791   rc = sqlite3ApiExit(db, rc);
1792   sqlite3_mutex_leave(db->mutex);
1793   return rc;
1794 }
1795 
1796 /*
1797 ** Register a new collation sequence with the database handle db.
1798 */
1799 int sqlite3_create_collation_v2(
1800   sqlite3* db,
1801   const char *zName,
1802   int enc,
1803   void* pCtx,
1804   int(*xCompare)(void*,int,const void*,int,const void*),
1805   void(*xDel)(void*)
1806 ){
1807   int rc;
1808   sqlite3_mutex_enter(db->mutex);
1809   assert( !db->mallocFailed );
1810   rc = createCollation(db, zName, enc, pCtx, xCompare, xDel);
1811   rc = sqlite3ApiExit(db, rc);
1812   sqlite3_mutex_leave(db->mutex);
1813   return rc;
1814 }
1815 
1816 #ifndef SQLITE_OMIT_UTF16
1817 /*
1818 ** Register a new collation sequence with the database handle db.
1819 */
1820 int sqlite3_create_collation16(
1821   sqlite3* db,
1822   const void *zName,
1823   int enc,
1824   void* pCtx,
1825   int(*xCompare)(void*,int,const void*,int,const void*)
1826 ){
1827   int rc = SQLITE_OK;
1828   char *zName8;
1829   sqlite3_mutex_enter(db->mutex);
1830   assert( !db->mallocFailed );
1831   zName8 = sqlite3Utf16to8(db, zName, -1);
1832   if( zName8 ){
1833     rc = createCollation(db, zName8, enc, pCtx, xCompare, 0);
1834     sqlite3DbFree(db, zName8);
1835   }
1836   rc = sqlite3ApiExit(db, rc);
1837   sqlite3_mutex_leave(db->mutex);
1838   return rc;
1839 }
1840 #endif /* SQLITE_OMIT_UTF16 */
1841 
1842 /*
1843 ** Register a collation sequence factory callback with the database handle
1844 ** db. Replace any previously installed collation sequence factory.
1845 */
1846 int sqlite3_collation_needed(
1847   sqlite3 *db,
1848   void *pCollNeededArg,
1849   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
1850 ){
1851   sqlite3_mutex_enter(db->mutex);
1852   db->xCollNeeded = xCollNeeded;
1853   db->xCollNeeded16 = 0;
1854   db->pCollNeededArg = pCollNeededArg;
1855   sqlite3_mutex_leave(db->mutex);
1856   return SQLITE_OK;
1857 }
1858 
1859 #ifndef SQLITE_OMIT_UTF16
1860 /*
1861 ** Register a collation sequence factory callback with the database handle
1862 ** db. Replace any previously installed collation sequence factory.
1863 */
1864 int sqlite3_collation_needed16(
1865   sqlite3 *db,
1866   void *pCollNeededArg,
1867   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
1868 ){
1869   sqlite3_mutex_enter(db->mutex);
1870   db->xCollNeeded = 0;
1871   db->xCollNeeded16 = xCollNeeded16;
1872   db->pCollNeededArg = pCollNeededArg;
1873   sqlite3_mutex_leave(db->mutex);
1874   return SQLITE_OK;
1875 }
1876 #endif /* SQLITE_OMIT_UTF16 */
1877 
1878 #ifndef SQLITE_OMIT_GLOBALRECOVER
1879 #ifndef SQLITE_OMIT_DEPRECATED
1880 /*
1881 ** This function is now an anachronism. It used to be used to recover from a
1882 ** malloc() failure, but SQLite now does this automatically.
1883 */
1884 int sqlite3_global_recover(void){
1885   return SQLITE_OK;
1886 }
1887 #endif
1888 #endif
1889 
1890 /*
1891 ** Test to see whether or not the database connection is in autocommit
1892 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
1893 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
1894 ** by the next COMMIT or ROLLBACK.
1895 **
1896 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
1897 */
1898 int sqlite3_get_autocommit(sqlite3 *db){
1899   return db->autoCommit;
1900 }
1901 
1902 #ifdef SQLITE_DEBUG
1903 /*
1904 ** The following routine is subtituted for constant SQLITE_CORRUPT in
1905 ** debugging builds.  This provides a way to set a breakpoint for when
1906 ** corruption is first detected.
1907 */
1908 int sqlite3Corrupt(void){
1909   return SQLITE_CORRUPT;
1910 }
1911 #endif
1912 
1913 #ifndef SQLITE_OMIT_DEPRECATED
1914 /*
1915 ** This is a convenience routine that makes sure that all thread-specific
1916 ** data for this thread has been deallocated.
1917 **
1918 ** SQLite no longer uses thread-specific data so this routine is now a
1919 ** no-op.  It is retained for historical compatibility.
1920 */
1921 void sqlite3_thread_cleanup(void){
1922 }
1923 #endif
1924 
1925 /*
1926 ** Return meta information about a specific column of a database table.
1927 ** See comment in sqlite3.h (sqlite.h.in) for details.
1928 */
1929 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1930 int sqlite3_table_column_metadata(
1931   sqlite3 *db,                /* Connection handle */
1932   const char *zDbName,        /* Database name or NULL */
1933   const char *zTableName,     /* Table name */
1934   const char *zColumnName,    /* Column name */
1935   char const **pzDataType,    /* OUTPUT: Declared data type */
1936   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
1937   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
1938   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
1939   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
1940 ){
1941   int rc;
1942   char *zErrMsg = 0;
1943   Table *pTab = 0;
1944   Column *pCol = 0;
1945   int iCol;
1946 
1947   char const *zDataType = 0;
1948   char const *zCollSeq = 0;
1949   int notnull = 0;
1950   int primarykey = 0;
1951   int autoinc = 0;
1952 
1953   /* Ensure the database schema has been loaded */
1954   sqlite3_mutex_enter(db->mutex);
1955   (void)sqlite3SafetyOn(db);
1956   sqlite3BtreeEnterAll(db);
1957   rc = sqlite3Init(db, &zErrMsg);
1958   if( SQLITE_OK!=rc ){
1959     goto error_out;
1960   }
1961 
1962   /* Locate the table in question */
1963   pTab = sqlite3FindTable(db, zTableName, zDbName);
1964   if( !pTab || pTab->pSelect ){
1965     pTab = 0;
1966     goto error_out;
1967   }
1968 
1969   /* Find the column for which info is requested */
1970   if( sqlite3IsRowid(zColumnName) ){
1971     iCol = pTab->iPKey;
1972     if( iCol>=0 ){
1973       pCol = &pTab->aCol[iCol];
1974     }
1975   }else{
1976     for(iCol=0; iCol<pTab->nCol; iCol++){
1977       pCol = &pTab->aCol[iCol];
1978       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
1979         break;
1980       }
1981     }
1982     if( iCol==pTab->nCol ){
1983       pTab = 0;
1984       goto error_out;
1985     }
1986   }
1987 
1988   /* The following block stores the meta information that will be returned
1989   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
1990   ** and autoinc. At this point there are two possibilities:
1991   **
1992   **     1. The specified column name was rowid", "oid" or "_rowid_"
1993   **        and there is no explicitly declared IPK column.
1994   **
1995   **     2. The table is not a view and the column name identified an
1996   **        explicitly declared column. Copy meta information from *pCol.
1997   */
1998   if( pCol ){
1999     zDataType = pCol->zType;
2000     zCollSeq = pCol->zColl;
2001     notnull = pCol->notNull!=0;
2002     primarykey  = pCol->isPrimKey!=0;
2003     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
2004   }else{
2005     zDataType = "INTEGER";
2006     primarykey = 1;
2007   }
2008   if( !zCollSeq ){
2009     zCollSeq = "BINARY";
2010   }
2011 
2012 error_out:
2013   sqlite3BtreeLeaveAll(db);
2014   (void)sqlite3SafetyOff(db);
2015 
2016   /* Whether the function call succeeded or failed, set the output parameters
2017   ** to whatever their local counterparts contain. If an error did occur,
2018   ** this has the effect of zeroing all output parameters.
2019   */
2020   if( pzDataType ) *pzDataType = zDataType;
2021   if( pzCollSeq ) *pzCollSeq = zCollSeq;
2022   if( pNotNull ) *pNotNull = notnull;
2023   if( pPrimaryKey ) *pPrimaryKey = primarykey;
2024   if( pAutoinc ) *pAutoinc = autoinc;
2025 
2026   if( SQLITE_OK==rc && !pTab ){
2027     sqlite3DbFree(db, zErrMsg);
2028     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
2029         zColumnName);
2030     rc = SQLITE_ERROR;
2031   }
2032   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
2033   sqlite3DbFree(db, zErrMsg);
2034   rc = sqlite3ApiExit(db, rc);
2035   sqlite3_mutex_leave(db->mutex);
2036   return rc;
2037 }
2038 #endif
2039 
2040 /*
2041 ** Sleep for a little while.  Return the amount of time slept.
2042 */
2043 int sqlite3_sleep(int ms){
2044   sqlite3_vfs *pVfs;
2045   int rc;
2046   pVfs = sqlite3_vfs_find(0);
2047   if( pVfs==0 ) return 0;
2048 
2049   /* This function works in milliseconds, but the underlying OsSleep()
2050   ** API uses microseconds. Hence the 1000's.
2051   */
2052   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
2053   return rc;
2054 }
2055 
2056 /*
2057 ** Enable or disable the extended result codes.
2058 */
2059 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
2060   sqlite3_mutex_enter(db->mutex);
2061   db->errMask = onoff ? 0xffffffff : 0xff;
2062   sqlite3_mutex_leave(db->mutex);
2063   return SQLITE_OK;
2064 }
2065 
2066 /*
2067 ** Invoke the xFileControl method on a particular database.
2068 */
2069 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
2070   int rc = SQLITE_ERROR;
2071   int iDb;
2072   sqlite3_mutex_enter(db->mutex);
2073   if( zDbName==0 ){
2074     iDb = 0;
2075   }else{
2076     for(iDb=0; iDb<db->nDb; iDb++){
2077       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
2078     }
2079   }
2080   if( iDb<db->nDb ){
2081     Btree *pBtree = db->aDb[iDb].pBt;
2082     if( pBtree ){
2083       Pager *pPager;
2084       sqlite3_file *fd;
2085       sqlite3BtreeEnter(pBtree);
2086       pPager = sqlite3BtreePager(pBtree);
2087       assert( pPager!=0 );
2088       fd = sqlite3PagerFile(pPager);
2089       assert( fd!=0 );
2090       if( fd->pMethods ){
2091         rc = sqlite3OsFileControl(fd, op, pArg);
2092       }
2093       sqlite3BtreeLeave(pBtree);
2094     }
2095   }
2096   sqlite3_mutex_leave(db->mutex);
2097   return rc;
2098 }
2099 
2100 /*
2101 ** Interface to the testing logic.
2102 */
2103 int sqlite3_test_control(int op, ...){
2104   int rc = 0;
2105 #ifndef SQLITE_OMIT_BUILTIN_TEST
2106   va_list ap;
2107   va_start(ap, op);
2108   switch( op ){
2109 
2110     /*
2111     ** Save the current state of the PRNG.
2112     */
2113     case SQLITE_TESTCTRL_PRNG_SAVE: {
2114       sqlite3PrngSaveState();
2115       break;
2116     }
2117 
2118     /*
2119     ** Restore the state of the PRNG to the last state saved using
2120     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
2121     ** this verb acts like PRNG_RESET.
2122     */
2123     case SQLITE_TESTCTRL_PRNG_RESTORE: {
2124       sqlite3PrngRestoreState();
2125       break;
2126     }
2127 
2128     /*
2129     ** Reset the PRNG back to its uninitialized state.  The next call
2130     ** to sqlite3_randomness() will reseed the PRNG using a single call
2131     ** to the xRandomness method of the default VFS.
2132     */
2133     case SQLITE_TESTCTRL_PRNG_RESET: {
2134       sqlite3PrngResetState();
2135       break;
2136     }
2137 
2138     /*
2139     **  sqlite3_test_control(BITVEC_TEST, size, program)
2140     **
2141     ** Run a test against a Bitvec object of size.  The program argument
2142     ** is an array of integers that defines the test.  Return -1 on a
2143     ** memory allocation error, 0 on success, or non-zero for an error.
2144     ** See the sqlite3BitvecBuiltinTest() for additional information.
2145     */
2146     case SQLITE_TESTCTRL_BITVEC_TEST: {
2147       int sz = va_arg(ap, int);
2148       int *aProg = va_arg(ap, int*);
2149       rc = sqlite3BitvecBuiltinTest(sz, aProg);
2150       break;
2151     }
2152 
2153     /*
2154     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
2155     **
2156     ** Register hooks to call to indicate which malloc() failures
2157     ** are benign.
2158     */
2159     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
2160       typedef void (*void_function)(void);
2161       void_function xBenignBegin;
2162       void_function xBenignEnd;
2163       xBenignBegin = va_arg(ap, void_function);
2164       xBenignEnd = va_arg(ap, void_function);
2165       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
2166       break;
2167     }
2168 
2169     /*
2170     **  sqlite3_test_control(PENDING_BYTE, unsigned int X)
2171     **
2172     ** Set the PENDING byte to the value in the argument, if X>0.
2173     ** Make no changes if X==0.  Return the value of the pending byte
2174     ** as it existing before this routine was called.
2175     **
2176     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
2177     ** an incompatible database file format.  Changing the PENDING byte
2178     ** while any database connection is open results in undefined and
2179     ** dileterious behavior.
2180     */
2181     case SQLITE_TESTCTRL_PENDING_BYTE: {
2182       unsigned int newVal = va_arg(ap, unsigned int);
2183       rc = sqlite3PendingByte;
2184       if( newVal ) sqlite3PendingByte = newVal;
2185       break;
2186     }
2187   }
2188   va_end(ap);
2189 #endif /* SQLITE_OMIT_BUILTIN_TEST */
2190   return rc;
2191 }
2192