xref: /sqlite-3.40.0/src/main.c (revision a3f06598)
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.539 2009/04/21 12:02:56 drh 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   const char *z;
742   switch( rc & 0xff ){
743     case SQLITE_ROW:
744     case SQLITE_DONE:
745     case SQLITE_OK:         z = "not an error";                          break;
746     case SQLITE_ERROR:      z = "SQL logic error or missing database";   break;
747     case SQLITE_PERM:       z = "access permission denied";              break;
748     case SQLITE_ABORT:      z = "callback requested query abort";        break;
749     case SQLITE_BUSY:       z = "database is locked";                    break;
750     case SQLITE_LOCKED:     z = "database table is locked";              break;
751     case SQLITE_NOMEM:      z = "out of memory";                         break;
752     case SQLITE_READONLY:   z = "attempt to write a readonly database";  break;
753     case SQLITE_INTERRUPT:  z = "interrupted";                           break;
754     case SQLITE_IOERR:      z = "disk I/O error";                        break;
755     case SQLITE_CORRUPT:    z = "database disk image is malformed";      break;
756     case SQLITE_FULL:       z = "database or disk is full";              break;
757     case SQLITE_CANTOPEN:   z = "unable to open database file";          break;
758     case SQLITE_EMPTY:      z = "table contains no data";                break;
759     case SQLITE_SCHEMA:     z = "database schema has changed";           break;
760     case SQLITE_TOOBIG:     z = "String or BLOB exceeded size limit";    break;
761     case SQLITE_CONSTRAINT: z = "constraint failed";                     break;
762     case SQLITE_MISMATCH:   z = "datatype mismatch";                     break;
763     case SQLITE_MISUSE:     z = "library routine called out of sequence";break;
764     case SQLITE_NOLFS:      z = "large file support is disabled";        break;
765     case SQLITE_AUTH:       z = "authorization denied";                  break;
766     case SQLITE_FORMAT:     z = "auxiliary database format error";       break;
767     case SQLITE_RANGE:      z = "bind or column index out of range";     break;
768     case SQLITE_NOTADB:     z = "file is encrypted or is not a database";break;
769     default:                z = "unknown error";                         break;
770   }
771   return z;
772 }
773 
774 /*
775 ** This routine implements a busy callback that sleeps and tries
776 ** again until a timeout value is reached.  The timeout value is
777 ** an integer number of milliseconds passed in as the first
778 ** argument.
779 */
780 static int sqliteDefaultBusyCallback(
781  void *ptr,               /* Database connection */
782  int count                /* Number of times table has been busy */
783 ){
784 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
785   static const u8 delays[] =
786      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
787   static const u8 totals[] =
788      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
789 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
790   sqlite3 *db = (sqlite3 *)ptr;
791   int timeout = db->busyTimeout;
792   int delay, prior;
793 
794   assert( count>=0 );
795   if( count < NDELAY ){
796     delay = delays[count];
797     prior = totals[count];
798   }else{
799     delay = delays[NDELAY-1];
800     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
801   }
802   if( prior + delay > timeout ){
803     delay = timeout - prior;
804     if( delay<=0 ) return 0;
805   }
806   sqlite3OsSleep(db->pVfs, delay*1000);
807   return 1;
808 #else
809   sqlite3 *db = (sqlite3 *)ptr;
810   int timeout = ((sqlite3 *)ptr)->busyTimeout;
811   if( (count+1)*1000 > timeout ){
812     return 0;
813   }
814   sqlite3OsSleep(db->pVfs, 1000000);
815   return 1;
816 #endif
817 }
818 
819 /*
820 ** Invoke the given busy handler.
821 **
822 ** This routine is called when an operation failed with a lock.
823 ** If this routine returns non-zero, the lock is retried.  If it
824 ** returns 0, the operation aborts with an SQLITE_BUSY error.
825 */
826 int sqlite3InvokeBusyHandler(BusyHandler *p){
827   int rc;
828   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
829   rc = p->xFunc(p->pArg, p->nBusy);
830   if( rc==0 ){
831     p->nBusy = -1;
832   }else{
833     p->nBusy++;
834   }
835   return rc;
836 }
837 
838 /*
839 ** This routine sets the busy callback for an Sqlite database to the
840 ** given callback function with the given argument.
841 */
842 int sqlite3_busy_handler(
843   sqlite3 *db,
844   int (*xBusy)(void*,int),
845   void *pArg
846 ){
847   sqlite3_mutex_enter(db->mutex);
848   db->busyHandler.xFunc = xBusy;
849   db->busyHandler.pArg = pArg;
850   db->busyHandler.nBusy = 0;
851   sqlite3_mutex_leave(db->mutex);
852   return SQLITE_OK;
853 }
854 
855 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
856 /*
857 ** This routine sets the progress callback for an Sqlite database to the
858 ** given callback function with the given argument. The progress callback will
859 ** be invoked every nOps opcodes.
860 */
861 void sqlite3_progress_handler(
862   sqlite3 *db,
863   int nOps,
864   int (*xProgress)(void*),
865   void *pArg
866 ){
867   sqlite3_mutex_enter(db->mutex);
868   if( nOps>0 ){
869     db->xProgress = xProgress;
870     db->nProgressOps = nOps;
871     db->pProgressArg = pArg;
872   }else{
873     db->xProgress = 0;
874     db->nProgressOps = 0;
875     db->pProgressArg = 0;
876   }
877   sqlite3_mutex_leave(db->mutex);
878 }
879 #endif
880 
881 
882 /*
883 ** This routine installs a default busy handler that waits for the
884 ** specified number of milliseconds before returning 0.
885 */
886 int sqlite3_busy_timeout(sqlite3 *db, int ms){
887   if( ms>0 ){
888     db->busyTimeout = ms;
889     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
890   }else{
891     sqlite3_busy_handler(db, 0, 0);
892   }
893   return SQLITE_OK;
894 }
895 
896 /*
897 ** Cause any pending operation to stop at its earliest opportunity.
898 */
899 void sqlite3_interrupt(sqlite3 *db){
900   db->u1.isInterrupted = 1;
901 }
902 
903 
904 /*
905 ** This function is exactly the same as sqlite3_create_function(), except
906 ** that it is designed to be called by internal code. The difference is
907 ** that if a malloc() fails in sqlite3_create_function(), an error code
908 ** is returned and the mallocFailed flag cleared.
909 */
910 int sqlite3CreateFunc(
911   sqlite3 *db,
912   const char *zFunctionName,
913   int nArg,
914   int enc,
915   void *pUserData,
916   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
917   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
918   void (*xFinal)(sqlite3_context*)
919 ){
920   FuncDef *p;
921   int nName;
922 
923   assert( sqlite3_mutex_held(db->mutex) );
924   if( zFunctionName==0 ||
925       (xFunc && (xFinal || xStep)) ||
926       (!xFunc && (xFinal && !xStep)) ||
927       (!xFunc && (!xFinal && xStep)) ||
928       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
929       (255<(nName = sqlite3Strlen(db, zFunctionName))) ){
930     sqlite3Error(db, SQLITE_ERROR, "bad parameters");
931     return SQLITE_ERROR;
932   }
933 
934 #ifndef SQLITE_OMIT_UTF16
935   /* If SQLITE_UTF16 is specified as the encoding type, transform this
936   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
937   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
938   **
939   ** If SQLITE_ANY is specified, add three versions of the function
940   ** to the hash table.
941   */
942   if( enc==SQLITE_UTF16 ){
943     enc = SQLITE_UTF16NATIVE;
944   }else if( enc==SQLITE_ANY ){
945     int rc;
946     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
947          pUserData, xFunc, xStep, xFinal);
948     if( rc==SQLITE_OK ){
949       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
950           pUserData, xFunc, xStep, xFinal);
951     }
952     if( rc!=SQLITE_OK ){
953       return rc;
954     }
955     enc = SQLITE_UTF16BE;
956   }
957 #else
958   enc = SQLITE_UTF8;
959 #endif
960 
961   /* Check if an existing function is being overridden or deleted. If so,
962   ** and there are active VMs, then return SQLITE_BUSY. If a function
963   ** is being overridden/deleted but there are no active VMs, allow the
964   ** operation to continue but invalidate all precompiled statements.
965   */
966   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
967   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
968     if( db->activeVdbeCnt ){
969       sqlite3Error(db, SQLITE_BUSY,
970         "unable to delete/modify user-function due to active statements");
971       assert( !db->mallocFailed );
972       return SQLITE_BUSY;
973     }else{
974       sqlite3ExpirePreparedStatements(db);
975     }
976   }
977 
978   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
979   assert(p || db->mallocFailed);
980   if( !p ){
981     return SQLITE_NOMEM;
982   }
983   p->flags = 0;
984   p->xFunc = xFunc;
985   p->xStep = xStep;
986   p->xFinalize = xFinal;
987   p->pUserData = pUserData;
988   p->nArg = (u16)nArg;
989   return SQLITE_OK;
990 }
991 
992 /*
993 ** Create new user functions.
994 */
995 int sqlite3_create_function(
996   sqlite3 *db,
997   const char *zFunctionName,
998   int nArg,
999   int enc,
1000   void *p,
1001   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
1002   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
1003   void (*xFinal)(sqlite3_context*)
1004 ){
1005   int rc;
1006   sqlite3_mutex_enter(db->mutex);
1007   rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
1008   rc = sqlite3ApiExit(db, rc);
1009   sqlite3_mutex_leave(db->mutex);
1010   return rc;
1011 }
1012 
1013 #ifndef SQLITE_OMIT_UTF16
1014 int sqlite3_create_function16(
1015   sqlite3 *db,
1016   const void *zFunctionName,
1017   int nArg,
1018   int eTextRep,
1019   void *p,
1020   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
1021   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
1022   void (*xFinal)(sqlite3_context*)
1023 ){
1024   int rc;
1025   char *zFunc8;
1026   sqlite3_mutex_enter(db->mutex);
1027   assert( !db->mallocFailed );
1028   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
1029   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
1030   sqlite3DbFree(db, zFunc8);
1031   rc = sqlite3ApiExit(db, rc);
1032   sqlite3_mutex_leave(db->mutex);
1033   return rc;
1034 }
1035 #endif
1036 
1037 
1038 /*
1039 ** Declare that a function has been overloaded by a virtual table.
1040 **
1041 ** If the function already exists as a regular global function, then
1042 ** this routine is a no-op.  If the function does not exist, then create
1043 ** a new one that always throws a run-time error.
1044 **
1045 ** When virtual tables intend to provide an overloaded function, they
1046 ** should call this routine to make sure the global function exists.
1047 ** A global function must exist in order for name resolution to work
1048 ** properly.
1049 */
1050 int sqlite3_overload_function(
1051   sqlite3 *db,
1052   const char *zName,
1053   int nArg
1054 ){
1055   int nName = sqlite3Strlen(db, zName);
1056   int rc;
1057   sqlite3_mutex_enter(db->mutex);
1058   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
1059     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
1060                       0, sqlite3InvalidFunction, 0, 0);
1061   }
1062   rc = sqlite3ApiExit(db, SQLITE_OK);
1063   sqlite3_mutex_leave(db->mutex);
1064   return rc;
1065 }
1066 
1067 #ifndef SQLITE_OMIT_TRACE
1068 /*
1069 ** Register a trace function.  The pArg from the previously registered trace
1070 ** is returned.
1071 **
1072 ** A NULL trace function means that no tracing is executes.  A non-NULL
1073 ** trace is a pointer to a function that is invoked at the start of each
1074 ** SQL statement.
1075 */
1076 void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
1077   void *pOld;
1078   sqlite3_mutex_enter(db->mutex);
1079   pOld = db->pTraceArg;
1080   db->xTrace = xTrace;
1081   db->pTraceArg = pArg;
1082   sqlite3_mutex_leave(db->mutex);
1083   return pOld;
1084 }
1085 /*
1086 ** Register a profile function.  The pArg from the previously registered
1087 ** profile function is returned.
1088 **
1089 ** A NULL profile function means that no profiling is executes.  A non-NULL
1090 ** profile is a pointer to a function that is invoked at the conclusion of
1091 ** each SQL statement that is run.
1092 */
1093 void *sqlite3_profile(
1094   sqlite3 *db,
1095   void (*xProfile)(void*,const char*,sqlite_uint64),
1096   void *pArg
1097 ){
1098   void *pOld;
1099   sqlite3_mutex_enter(db->mutex);
1100   pOld = db->pProfileArg;
1101   db->xProfile = xProfile;
1102   db->pProfileArg = pArg;
1103   sqlite3_mutex_leave(db->mutex);
1104   return pOld;
1105 }
1106 #endif /* SQLITE_OMIT_TRACE */
1107 
1108 /*** EXPERIMENTAL ***
1109 **
1110 ** Register a function to be invoked when a transaction comments.
1111 ** If the invoked function returns non-zero, then the commit becomes a
1112 ** rollback.
1113 */
1114 void *sqlite3_commit_hook(
1115   sqlite3 *db,              /* Attach the hook to this database */
1116   int (*xCallback)(void*),  /* Function to invoke on each commit */
1117   void *pArg                /* Argument to the function */
1118 ){
1119   void *pOld;
1120   sqlite3_mutex_enter(db->mutex);
1121   pOld = db->pCommitArg;
1122   db->xCommitCallback = xCallback;
1123   db->pCommitArg = pArg;
1124   sqlite3_mutex_leave(db->mutex);
1125   return pOld;
1126 }
1127 
1128 /*
1129 ** Register a callback to be invoked each time a row is updated,
1130 ** inserted or deleted using this database connection.
1131 */
1132 void *sqlite3_update_hook(
1133   sqlite3 *db,              /* Attach the hook to this database */
1134   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
1135   void *pArg                /* Argument to the function */
1136 ){
1137   void *pRet;
1138   sqlite3_mutex_enter(db->mutex);
1139   pRet = db->pUpdateArg;
1140   db->xUpdateCallback = xCallback;
1141   db->pUpdateArg = pArg;
1142   sqlite3_mutex_leave(db->mutex);
1143   return pRet;
1144 }
1145 
1146 /*
1147 ** Register a callback to be invoked each time a transaction is rolled
1148 ** back by this database connection.
1149 */
1150 void *sqlite3_rollback_hook(
1151   sqlite3 *db,              /* Attach the hook to this database */
1152   void (*xCallback)(void*), /* Callback function */
1153   void *pArg                /* Argument to the function */
1154 ){
1155   void *pRet;
1156   sqlite3_mutex_enter(db->mutex);
1157   pRet = db->pRollbackArg;
1158   db->xRollbackCallback = xCallback;
1159   db->pRollbackArg = pArg;
1160   sqlite3_mutex_leave(db->mutex);
1161   return pRet;
1162 }
1163 
1164 /*
1165 ** This routine is called to create a connection to a database BTree
1166 ** driver.  If zFilename is the name of a file, then that file is
1167 ** opened and used.  If zFilename is the magic name ":memory:" then
1168 ** the database is stored in memory (and is thus forgotten as soon as
1169 ** the connection is closed.)  If zFilename is NULL then the database
1170 ** is a "virtual" database for transient use only and is deleted as
1171 ** soon as the connection is closed.
1172 **
1173 ** A virtual database can be either a disk file (that is automatically
1174 ** deleted when the file is closed) or it an be held entirely in memory,
1175 ** depending on the values of the SQLITE_TEMP_STORE compile-time macro and the
1176 ** db->temp_store variable, according to the following chart:
1177 **
1178 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
1179 **   -----------------     --------------     ------------------------------
1180 **   0                     any                file
1181 **   1                     1                  file
1182 **   1                     2                  memory
1183 **   1                     0                  file
1184 **   2                     1                  file
1185 **   2                     2                  memory
1186 **   2                     0                  memory
1187 **   3                     any                memory
1188 */
1189 int sqlite3BtreeFactory(
1190   const sqlite3 *db,        /* Main database when opening aux otherwise 0 */
1191   const char *zFilename,    /* Name of the file containing the BTree database */
1192   int omitJournal,          /* if TRUE then do not journal this file */
1193   int nCache,               /* How many pages in the page cache */
1194   int vfsFlags,             /* Flags passed through to vfsOpen */
1195   Btree **ppBtree           /* Pointer to new Btree object written here */
1196 ){
1197   int btFlags = 0;
1198   int rc;
1199 
1200   assert( sqlite3_mutex_held(db->mutex) );
1201   assert( ppBtree != 0);
1202   if( omitJournal ){
1203     btFlags |= BTREE_OMIT_JOURNAL;
1204   }
1205   if( db->flags & SQLITE_NoReadlock ){
1206     btFlags |= BTREE_NO_READLOCK;
1207   }
1208   if( zFilename==0 ){
1209 #if SQLITE_TEMP_STORE==0
1210     /* Do nothing */
1211 #endif
1212 #ifndef SQLITE_OMIT_MEMORYDB
1213 #if SQLITE_TEMP_STORE==1
1214     if( db->temp_store==2 ) zFilename = ":memory:";
1215 #endif
1216 #if SQLITE_TEMP_STORE==2
1217     if( db->temp_store!=1 ) zFilename = ":memory:";
1218 #endif
1219 #if SQLITE_TEMP_STORE==3
1220     zFilename = ":memory:";
1221 #endif
1222 #endif /* SQLITE_OMIT_MEMORYDB */
1223   }
1224 
1225   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
1226     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
1227   }
1228   rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
1229 
1230   /* If the B-Tree was successfully opened, set the pager-cache size to the
1231   ** default value. Except, if the call to BtreeOpen() returned a handle
1232   ** open on an existing shared pager-cache, do not change the pager-cache
1233   ** size.
1234   */
1235   if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
1236     sqlite3BtreeSetCacheSize(*ppBtree, nCache);
1237   }
1238   return rc;
1239 }
1240 
1241 /*
1242 ** Return UTF-8 encoded English language explanation of the most recent
1243 ** error.
1244 */
1245 const char *sqlite3_errmsg(sqlite3 *db){
1246   const char *z;
1247   if( !db ){
1248     return sqlite3ErrStr(SQLITE_NOMEM);
1249   }
1250   if( !sqlite3SafetyCheckSickOrOk(db) ){
1251     return sqlite3ErrStr(SQLITE_MISUSE);
1252   }
1253   sqlite3_mutex_enter(db->mutex);
1254   if( db->mallocFailed ){
1255     z = sqlite3ErrStr(SQLITE_NOMEM);
1256   }else{
1257     z = (char*)sqlite3_value_text(db->pErr);
1258     assert( !db->mallocFailed );
1259     if( z==0 ){
1260       z = sqlite3ErrStr(db->errCode);
1261     }
1262   }
1263   sqlite3_mutex_leave(db->mutex);
1264   return z;
1265 }
1266 
1267 #ifndef SQLITE_OMIT_UTF16
1268 /*
1269 ** Return UTF-16 encoded English language explanation of the most recent
1270 ** error.
1271 */
1272 const void *sqlite3_errmsg16(sqlite3 *db){
1273   static const u16 outOfMem[] = {
1274     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
1275   };
1276   static const u16 misuse[] = {
1277     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
1278     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
1279     'c', 'a', 'l', 'l', 'e', 'd', ' ',
1280     'o', 'u', 't', ' ',
1281     'o', 'f', ' ',
1282     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
1283   };
1284 
1285   const void *z;
1286   if( !db ){
1287     return (void *)outOfMem;
1288   }
1289   if( !sqlite3SafetyCheckSickOrOk(db) ){
1290     return (void *)misuse;
1291   }
1292   sqlite3_mutex_enter(db->mutex);
1293   if( db->mallocFailed ){
1294     z = (void *)outOfMem;
1295   }else{
1296     z = sqlite3_value_text16(db->pErr);
1297     if( z==0 ){
1298       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
1299            SQLITE_UTF8, SQLITE_STATIC);
1300       z = sqlite3_value_text16(db->pErr);
1301     }
1302     /* A malloc() may have failed within the call to sqlite3_value_text16()
1303     ** above. If this is the case, then the db->mallocFailed flag needs to
1304     ** be cleared before returning. Do this directly, instead of via
1305     ** sqlite3ApiExit(), to avoid setting the database handle error message.
1306     */
1307     db->mallocFailed = 0;
1308   }
1309   sqlite3_mutex_leave(db->mutex);
1310   return z;
1311 }
1312 #endif /* SQLITE_OMIT_UTF16 */
1313 
1314 /*
1315 ** Return the most recent error code generated by an SQLite routine. If NULL is
1316 ** passed to this function, we assume a malloc() failed during sqlite3_open().
1317 */
1318 int sqlite3_errcode(sqlite3 *db){
1319   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
1320     return SQLITE_MISUSE;
1321   }
1322   if( !db || db->mallocFailed ){
1323     return SQLITE_NOMEM;
1324   }
1325   return db->errCode & db->errMask;
1326 }
1327 int sqlite3_extended_errcode(sqlite3 *db){
1328   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
1329     return SQLITE_MISUSE;
1330   }
1331   if( !db || db->mallocFailed ){
1332     return SQLITE_NOMEM;
1333   }
1334   return db->errCode;
1335 }
1336 
1337 /*
1338 ** Create a new collating function for database "db".  The name is zName
1339 ** and the encoding is enc.
1340 */
1341 static int createCollation(
1342   sqlite3* db,
1343   const char *zName,
1344   int enc,
1345   void* pCtx,
1346   int(*xCompare)(void*,int,const void*,int,const void*),
1347   void(*xDel)(void*)
1348 ){
1349   CollSeq *pColl;
1350   int enc2;
1351   int nName;
1352 
1353   assert( sqlite3_mutex_held(db->mutex) );
1354 
1355   /* If SQLITE_UTF16 is specified as the encoding type, transform this
1356   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
1357   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
1358   */
1359   enc2 = enc & ~SQLITE_UTF16_ALIGNED;
1360   if( enc2==SQLITE_UTF16 ){
1361     enc2 = SQLITE_UTF16NATIVE;
1362   }
1363   if( (enc2&~3)!=0 ){
1364     return SQLITE_MISUSE;
1365   }
1366 
1367   /* Check if this call is removing or replacing an existing collation
1368   ** sequence. If so, and there are active VMs, return busy. If there
1369   ** are no active VMs, invalidate any pre-compiled statements.
1370   */
1371   nName = sqlite3Strlen(db, zName);
1372   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 0);
1373   if( pColl && pColl->xCmp ){
1374     if( db->activeVdbeCnt ){
1375       sqlite3Error(db, SQLITE_BUSY,
1376         "unable to delete/modify collation sequence due to active statements");
1377       return SQLITE_BUSY;
1378     }
1379     sqlite3ExpirePreparedStatements(db);
1380 
1381     /* If collation sequence pColl was created directly by a call to
1382     ** sqlite3_create_collation, and not generated by synthCollSeq(),
1383     ** then any copies made by synthCollSeq() need to be invalidated.
1384     ** Also, collation destructor - CollSeq.xDel() - function may need
1385     ** to be called.
1386     */
1387     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
1388       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
1389       int j;
1390       for(j=0; j<3; j++){
1391         CollSeq *p = &aColl[j];
1392         if( p->enc==pColl->enc ){
1393           if( p->xDel ){
1394             p->xDel(p->pUser);
1395           }
1396           p->xCmp = 0;
1397         }
1398       }
1399     }
1400   }
1401 
1402   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 1);
1403   if( pColl ){
1404     pColl->xCmp = xCompare;
1405     pColl->pUser = pCtx;
1406     pColl->xDel = xDel;
1407     pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
1408   }
1409   sqlite3Error(db, SQLITE_OK, 0);
1410   return SQLITE_OK;
1411 }
1412 
1413 
1414 /*
1415 ** This array defines hard upper bounds on limit values.  The
1416 ** initializer must be kept in sync with the SQLITE_LIMIT_*
1417 ** #defines in sqlite3.h.
1418 */
1419 static const int aHardLimit[] = {
1420   SQLITE_MAX_LENGTH,
1421   SQLITE_MAX_SQL_LENGTH,
1422   SQLITE_MAX_COLUMN,
1423   SQLITE_MAX_EXPR_DEPTH,
1424   SQLITE_MAX_COMPOUND_SELECT,
1425   SQLITE_MAX_VDBE_OP,
1426   SQLITE_MAX_FUNCTION_ARG,
1427   SQLITE_MAX_ATTACHED,
1428   SQLITE_MAX_LIKE_PATTERN_LENGTH,
1429   SQLITE_MAX_VARIABLE_NUMBER,
1430 };
1431 
1432 /*
1433 ** Make sure the hard limits are set to reasonable values
1434 */
1435 #if SQLITE_MAX_LENGTH<100
1436 # error SQLITE_MAX_LENGTH must be at least 100
1437 #endif
1438 #if SQLITE_MAX_SQL_LENGTH<100
1439 # error SQLITE_MAX_SQL_LENGTH must be at least 100
1440 #endif
1441 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
1442 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
1443 #endif
1444 #if SQLITE_MAX_COMPOUND_SELECT<2
1445 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
1446 #endif
1447 #if SQLITE_MAX_VDBE_OP<40
1448 # error SQLITE_MAX_VDBE_OP must be at least 40
1449 #endif
1450 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
1451 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
1452 #endif
1453 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
1454 # error SQLITE_MAX_ATTACHED must be between 0 and 30
1455 #endif
1456 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
1457 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
1458 #endif
1459 #if SQLITE_MAX_VARIABLE_NUMBER<1
1460 # error SQLITE_MAX_VARIABLE_NUMBER must be at least 1
1461 #endif
1462 #if SQLITE_MAX_COLUMN>32767
1463 # error SQLITE_MAX_COLUMN must not exceed 32767
1464 #endif
1465 
1466 
1467 /*
1468 ** Change the value of a limit.  Report the old value.
1469 ** If an invalid limit index is supplied, report -1.
1470 ** Make no changes but still report the old value if the
1471 ** new limit is negative.
1472 **
1473 ** A new lower limit does not shrink existing constructs.
1474 ** It merely prevents new constructs that exceed the limit
1475 ** from forming.
1476 */
1477 int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
1478   int oldLimit;
1479   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
1480     return -1;
1481   }
1482   oldLimit = db->aLimit[limitId];
1483   if( newLimit>=0 ){
1484     if( newLimit>aHardLimit[limitId] ){
1485       newLimit = aHardLimit[limitId];
1486     }
1487     db->aLimit[limitId] = newLimit;
1488   }
1489   return oldLimit;
1490 }
1491 
1492 /*
1493 ** This routine does the work of opening a database on behalf of
1494 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
1495 ** is UTF-8 encoded.
1496 */
1497 static int openDatabase(
1498   const char *zFilename, /* Database filename UTF-8 encoded */
1499   sqlite3 **ppDb,        /* OUT: Returned database handle */
1500   unsigned flags,        /* Operational flags */
1501   const char *zVfs       /* Name of the VFS to use */
1502 ){
1503   sqlite3 *db;
1504   int rc;
1505   CollSeq *pColl;
1506   int isThreadsafe;
1507 
1508 #ifndef SQLITE_OMIT_AUTOINIT
1509   rc = sqlite3_initialize();
1510   if( rc ) return rc;
1511 #endif
1512 
1513   if( sqlite3GlobalConfig.bCoreMutex==0 ){
1514     isThreadsafe = 0;
1515   }else if( flags & SQLITE_OPEN_NOMUTEX ){
1516     isThreadsafe = 0;
1517   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
1518     isThreadsafe = 1;
1519   }else{
1520     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
1521   }
1522 
1523   /* Remove harmful bits from the flags parameter */
1524   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
1525                SQLITE_OPEN_MAIN_DB |
1526                SQLITE_OPEN_TEMP_DB |
1527                SQLITE_OPEN_TRANSIENT_DB |
1528                SQLITE_OPEN_MAIN_JOURNAL |
1529                SQLITE_OPEN_TEMP_JOURNAL |
1530                SQLITE_OPEN_SUBJOURNAL |
1531                SQLITE_OPEN_MASTER_JOURNAL |
1532                SQLITE_OPEN_NOMUTEX |
1533                SQLITE_OPEN_FULLMUTEX
1534              );
1535 
1536   /* Allocate the sqlite data structure */
1537   db = sqlite3MallocZero( sizeof(sqlite3) );
1538   if( db==0 ) goto opendb_out;
1539   if( isThreadsafe ){
1540     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
1541     if( db->mutex==0 ){
1542       sqlite3_free(db);
1543       db = 0;
1544       goto opendb_out;
1545     }
1546   }
1547   sqlite3_mutex_enter(db->mutex);
1548   db->errMask = 0xff;
1549   db->priorNewRowid = 0;
1550   db->nDb = 2;
1551   db->magic = SQLITE_MAGIC_BUSY;
1552   db->aDb = db->aDbStatic;
1553 
1554   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
1555   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
1556   db->autoCommit = 1;
1557   db->nextAutovac = -1;
1558   db->nextPagesize = 0;
1559   db->flags |= SQLITE_ShortColNames
1560 #if SQLITE_DEFAULT_FILE_FORMAT<4
1561                  | SQLITE_LegacyFileFmt
1562 #endif
1563 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
1564                  | SQLITE_LoadExtension
1565 #endif
1566       ;
1567   sqlite3HashInit(&db->aCollSeq, 0);
1568 #ifndef SQLITE_OMIT_VIRTUALTABLE
1569   sqlite3HashInit(&db->aModule, 0);
1570 #endif
1571 
1572   db->pVfs = sqlite3_vfs_find(zVfs);
1573   if( !db->pVfs ){
1574     rc = SQLITE_ERROR;
1575     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
1576     goto opendb_out;
1577   }
1578 
1579   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
1580   ** and UTF-16, so add a version for each to avoid any unnecessary
1581   ** conversions. The only error that can occur here is a malloc() failure.
1582   */
1583   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
1584   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
1585   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
1586   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
1587   if( db->mallocFailed ){
1588     goto opendb_out;
1589   }
1590   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
1591   assert( db->pDfltColl!=0 );
1592 
1593   /* Also add a UTF-8 case-insensitive collation sequence. */
1594   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
1595 
1596   /* Set flags on the built-in collating sequences */
1597   db->pDfltColl->type = SQLITE_COLL_BINARY;
1598   pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "NOCASE", 6, 0);
1599   if( pColl ){
1600     pColl->type = SQLITE_COLL_NOCASE;
1601   }
1602 
1603   /* Open the backend database driver */
1604   db->openFlags = flags;
1605   rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE,
1606                            flags | SQLITE_OPEN_MAIN_DB,
1607                            &db->aDb[0].pBt);
1608   if( rc!=SQLITE_OK ){
1609     if( rc==SQLITE_IOERR_NOMEM ){
1610       rc = SQLITE_NOMEM;
1611     }
1612     sqlite3Error(db, rc, 0);
1613     goto opendb_out;
1614   }
1615   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
1616   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
1617 
1618 
1619   /* The default safety_level for the main database is 'full'; for the temp
1620   ** database it is 'NONE'. This matches the pager layer defaults.
1621   */
1622   db->aDb[0].zName = "main";
1623   db->aDb[0].safety_level = 3;
1624 #ifndef SQLITE_OMIT_TEMPDB
1625   db->aDb[1].zName = "temp";
1626   db->aDb[1].safety_level = 1;
1627 #endif
1628 
1629   db->magic = SQLITE_MAGIC_OPEN;
1630   if( db->mallocFailed ){
1631     goto opendb_out;
1632   }
1633 
1634   /* Register all built-in functions, but do not attempt to read the
1635   ** database schema yet. This is delayed until the first time the database
1636   ** is accessed.
1637   */
1638   sqlite3Error(db, SQLITE_OK, 0);
1639   sqlite3RegisterBuiltinFunctions(db);
1640 
1641   /* Load automatic extensions - extensions that have been registered
1642   ** using the sqlite3_automatic_extension() API.
1643   */
1644   (void)sqlite3AutoLoadExtensions(db);
1645   if( sqlite3_errcode(db)!=SQLITE_OK ){
1646     goto opendb_out;
1647   }
1648 
1649 #ifdef SQLITE_ENABLE_FTS1
1650   if( !db->mallocFailed ){
1651     extern int sqlite3Fts1Init(sqlite3*);
1652     rc = sqlite3Fts1Init(db);
1653   }
1654 #endif
1655 
1656 #ifdef SQLITE_ENABLE_FTS2
1657   if( !db->mallocFailed && rc==SQLITE_OK ){
1658     extern int sqlite3Fts2Init(sqlite3*);
1659     rc = sqlite3Fts2Init(db);
1660   }
1661 #endif
1662 
1663 #ifdef SQLITE_ENABLE_FTS3
1664   if( !db->mallocFailed && rc==SQLITE_OK ){
1665     rc = sqlite3Fts3Init(db);
1666   }
1667 #endif
1668 
1669 #ifdef SQLITE_ENABLE_ICU
1670   if( !db->mallocFailed && rc==SQLITE_OK ){
1671     rc = sqlite3IcuInit(db);
1672   }
1673 #endif
1674 
1675 #ifdef SQLITE_ENABLE_RTREE
1676   if( !db->mallocFailed && rc==SQLITE_OK){
1677     rc = sqlite3RtreeInit(db);
1678   }
1679 #endif
1680 
1681   sqlite3Error(db, rc, 0);
1682 
1683   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
1684   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
1685   ** mode.  Doing nothing at all also makes NORMAL the default.
1686   */
1687 #ifdef SQLITE_DEFAULT_LOCKING_MODE
1688   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
1689   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
1690                           SQLITE_DEFAULT_LOCKING_MODE);
1691 #endif
1692 
1693   /* Enable the lookaside-malloc subsystem */
1694   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
1695                         sqlite3GlobalConfig.nLookaside);
1696 
1697 opendb_out:
1698   if( db ){
1699     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
1700     sqlite3_mutex_leave(db->mutex);
1701   }
1702   rc = sqlite3_errcode(db);
1703   if( rc==SQLITE_NOMEM ){
1704     sqlite3_close(db);
1705     db = 0;
1706   }else if( rc!=SQLITE_OK ){
1707     db->magic = SQLITE_MAGIC_SICK;
1708   }
1709   *ppDb = db;
1710   return sqlite3ApiExit(0, rc);
1711 }
1712 
1713 /*
1714 ** Open a new database handle.
1715 */
1716 int sqlite3_open(
1717   const char *zFilename,
1718   sqlite3 **ppDb
1719 ){
1720   return openDatabase(zFilename, ppDb,
1721                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
1722 }
1723 int sqlite3_open_v2(
1724   const char *filename,   /* Database filename (UTF-8) */
1725   sqlite3 **ppDb,         /* OUT: SQLite db handle */
1726   int flags,              /* Flags */
1727   const char *zVfs        /* Name of VFS module to use */
1728 ){
1729   return openDatabase(filename, ppDb, flags, zVfs);
1730 }
1731 
1732 #ifndef SQLITE_OMIT_UTF16
1733 /*
1734 ** Open a new database handle.
1735 */
1736 int sqlite3_open16(
1737   const void *zFilename,
1738   sqlite3 **ppDb
1739 ){
1740   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
1741   sqlite3_value *pVal;
1742   int rc;
1743 
1744   assert( zFilename );
1745   assert( ppDb );
1746   *ppDb = 0;
1747 #ifndef SQLITE_OMIT_AUTOINIT
1748   rc = sqlite3_initialize();
1749   if( rc ) return rc;
1750 #endif
1751   pVal = sqlite3ValueNew(0);
1752   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
1753   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
1754   if( zFilename8 ){
1755     rc = openDatabase(zFilename8, ppDb,
1756                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
1757     assert( *ppDb || rc==SQLITE_NOMEM );
1758     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
1759       ENC(*ppDb) = SQLITE_UTF16NATIVE;
1760     }
1761   }else{
1762     rc = SQLITE_NOMEM;
1763   }
1764   sqlite3ValueFree(pVal);
1765 
1766   return sqlite3ApiExit(0, rc);
1767 }
1768 #endif /* SQLITE_OMIT_UTF16 */
1769 
1770 /*
1771 ** Register a new collation sequence with the database handle db.
1772 */
1773 int sqlite3_create_collation(
1774   sqlite3* db,
1775   const char *zName,
1776   int enc,
1777   void* pCtx,
1778   int(*xCompare)(void*,int,const void*,int,const void*)
1779 ){
1780   int rc;
1781   sqlite3_mutex_enter(db->mutex);
1782   assert( !db->mallocFailed );
1783   rc = createCollation(db, zName, enc, pCtx, xCompare, 0);
1784   rc = sqlite3ApiExit(db, rc);
1785   sqlite3_mutex_leave(db->mutex);
1786   return rc;
1787 }
1788 
1789 /*
1790 ** Register a new collation sequence with the database handle db.
1791 */
1792 int sqlite3_create_collation_v2(
1793   sqlite3* db,
1794   const char *zName,
1795   int enc,
1796   void* pCtx,
1797   int(*xCompare)(void*,int,const void*,int,const void*),
1798   void(*xDel)(void*)
1799 ){
1800   int rc;
1801   sqlite3_mutex_enter(db->mutex);
1802   assert( !db->mallocFailed );
1803   rc = createCollation(db, zName, enc, pCtx, xCompare, xDel);
1804   rc = sqlite3ApiExit(db, rc);
1805   sqlite3_mutex_leave(db->mutex);
1806   return rc;
1807 }
1808 
1809 #ifndef SQLITE_OMIT_UTF16
1810 /*
1811 ** Register a new collation sequence with the database handle db.
1812 */
1813 int sqlite3_create_collation16(
1814   sqlite3* db,
1815   const void *zName,
1816   int enc,
1817   void* pCtx,
1818   int(*xCompare)(void*,int,const void*,int,const void*)
1819 ){
1820   int rc = SQLITE_OK;
1821   char *zName8;
1822   sqlite3_mutex_enter(db->mutex);
1823   assert( !db->mallocFailed );
1824   zName8 = sqlite3Utf16to8(db, zName, -1);
1825   if( zName8 ){
1826     rc = createCollation(db, zName8, enc, pCtx, xCompare, 0);
1827     sqlite3DbFree(db, zName8);
1828   }
1829   rc = sqlite3ApiExit(db, rc);
1830   sqlite3_mutex_leave(db->mutex);
1831   return rc;
1832 }
1833 #endif /* SQLITE_OMIT_UTF16 */
1834 
1835 /*
1836 ** Register a collation sequence factory callback with the database handle
1837 ** db. Replace any previously installed collation sequence factory.
1838 */
1839 int sqlite3_collation_needed(
1840   sqlite3 *db,
1841   void *pCollNeededArg,
1842   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
1843 ){
1844   sqlite3_mutex_enter(db->mutex);
1845   db->xCollNeeded = xCollNeeded;
1846   db->xCollNeeded16 = 0;
1847   db->pCollNeededArg = pCollNeededArg;
1848   sqlite3_mutex_leave(db->mutex);
1849   return SQLITE_OK;
1850 }
1851 
1852 #ifndef SQLITE_OMIT_UTF16
1853 /*
1854 ** Register a collation sequence factory callback with the database handle
1855 ** db. Replace any previously installed collation sequence factory.
1856 */
1857 int sqlite3_collation_needed16(
1858   sqlite3 *db,
1859   void *pCollNeededArg,
1860   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
1861 ){
1862   sqlite3_mutex_enter(db->mutex);
1863   db->xCollNeeded = 0;
1864   db->xCollNeeded16 = xCollNeeded16;
1865   db->pCollNeededArg = pCollNeededArg;
1866   sqlite3_mutex_leave(db->mutex);
1867   return SQLITE_OK;
1868 }
1869 #endif /* SQLITE_OMIT_UTF16 */
1870 
1871 #ifndef SQLITE_OMIT_GLOBALRECOVER
1872 #ifndef SQLITE_OMIT_DEPRECATED
1873 /*
1874 ** This function is now an anachronism. It used to be used to recover from a
1875 ** malloc() failure, but SQLite now does this automatically.
1876 */
1877 int sqlite3_global_recover(void){
1878   return SQLITE_OK;
1879 }
1880 #endif
1881 #endif
1882 
1883 /*
1884 ** Test to see whether or not the database connection is in autocommit
1885 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
1886 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
1887 ** by the next COMMIT or ROLLBACK.
1888 **
1889 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
1890 */
1891 int sqlite3_get_autocommit(sqlite3 *db){
1892   return db->autoCommit;
1893 }
1894 
1895 #ifdef SQLITE_DEBUG
1896 /*
1897 ** The following routine is subtituted for constant SQLITE_CORRUPT in
1898 ** debugging builds.  This provides a way to set a breakpoint for when
1899 ** corruption is first detected.
1900 */
1901 int sqlite3Corrupt(void){
1902   return SQLITE_CORRUPT;
1903 }
1904 #endif
1905 
1906 #ifndef SQLITE_OMIT_DEPRECATED
1907 /*
1908 ** This is a convenience routine that makes sure that all thread-specific
1909 ** data for this thread has been deallocated.
1910 **
1911 ** SQLite no longer uses thread-specific data so this routine is now a
1912 ** no-op.  It is retained for historical compatibility.
1913 */
1914 void sqlite3_thread_cleanup(void){
1915 }
1916 #endif
1917 
1918 /*
1919 ** Return meta information about a specific column of a database table.
1920 ** See comment in sqlite3.h (sqlite.h.in) for details.
1921 */
1922 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1923 int sqlite3_table_column_metadata(
1924   sqlite3 *db,                /* Connection handle */
1925   const char *zDbName,        /* Database name or NULL */
1926   const char *zTableName,     /* Table name */
1927   const char *zColumnName,    /* Column name */
1928   char const **pzDataType,    /* OUTPUT: Declared data type */
1929   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
1930   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
1931   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
1932   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
1933 ){
1934   int rc;
1935   char *zErrMsg = 0;
1936   Table *pTab = 0;
1937   Column *pCol = 0;
1938   int iCol;
1939 
1940   char const *zDataType = 0;
1941   char const *zCollSeq = 0;
1942   int notnull = 0;
1943   int primarykey = 0;
1944   int autoinc = 0;
1945 
1946   /* Ensure the database schema has been loaded */
1947   sqlite3_mutex_enter(db->mutex);
1948   (void)sqlite3SafetyOn(db);
1949   sqlite3BtreeEnterAll(db);
1950   rc = sqlite3Init(db, &zErrMsg);
1951   if( SQLITE_OK!=rc ){
1952     goto error_out;
1953   }
1954 
1955   /* Locate the table in question */
1956   pTab = sqlite3FindTable(db, zTableName, zDbName);
1957   if( !pTab || pTab->pSelect ){
1958     pTab = 0;
1959     goto error_out;
1960   }
1961 
1962   /* Find the column for which info is requested */
1963   if( sqlite3IsRowid(zColumnName) ){
1964     iCol = pTab->iPKey;
1965     if( iCol>=0 ){
1966       pCol = &pTab->aCol[iCol];
1967     }
1968   }else{
1969     for(iCol=0; iCol<pTab->nCol; iCol++){
1970       pCol = &pTab->aCol[iCol];
1971       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
1972         break;
1973       }
1974     }
1975     if( iCol==pTab->nCol ){
1976       pTab = 0;
1977       goto error_out;
1978     }
1979   }
1980 
1981   /* The following block stores the meta information that will be returned
1982   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
1983   ** and autoinc. At this point there are two possibilities:
1984   **
1985   **     1. The specified column name was rowid", "oid" or "_rowid_"
1986   **        and there is no explicitly declared IPK column.
1987   **
1988   **     2. The table is not a view and the column name identified an
1989   **        explicitly declared column. Copy meta information from *pCol.
1990   */
1991   if( pCol ){
1992     zDataType = pCol->zType;
1993     zCollSeq = pCol->zColl;
1994     notnull = pCol->notNull!=0;
1995     primarykey  = pCol->isPrimKey!=0;
1996     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
1997   }else{
1998     zDataType = "INTEGER";
1999     primarykey = 1;
2000   }
2001   if( !zCollSeq ){
2002     zCollSeq = "BINARY";
2003   }
2004 
2005 error_out:
2006   sqlite3BtreeLeaveAll(db);
2007   (void)sqlite3SafetyOff(db);
2008 
2009   /* Whether the function call succeeded or failed, set the output parameters
2010   ** to whatever their local counterparts contain. If an error did occur,
2011   ** this has the effect of zeroing all output parameters.
2012   */
2013   if( pzDataType ) *pzDataType = zDataType;
2014   if( pzCollSeq ) *pzCollSeq = zCollSeq;
2015   if( pNotNull ) *pNotNull = notnull;
2016   if( pPrimaryKey ) *pPrimaryKey = primarykey;
2017   if( pAutoinc ) *pAutoinc = autoinc;
2018 
2019   if( SQLITE_OK==rc && !pTab ){
2020     sqlite3DbFree(db, zErrMsg);
2021     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
2022         zColumnName);
2023     rc = SQLITE_ERROR;
2024   }
2025   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
2026   sqlite3DbFree(db, zErrMsg);
2027   rc = sqlite3ApiExit(db, rc);
2028   sqlite3_mutex_leave(db->mutex);
2029   return rc;
2030 }
2031 #endif
2032 
2033 /*
2034 ** Sleep for a little while.  Return the amount of time slept.
2035 */
2036 int sqlite3_sleep(int ms){
2037   sqlite3_vfs *pVfs;
2038   int rc;
2039   pVfs = sqlite3_vfs_find(0);
2040   if( pVfs==0 ) return 0;
2041 
2042   /* This function works in milliseconds, but the underlying OsSleep()
2043   ** API uses microseconds. Hence the 1000's.
2044   */
2045   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
2046   return rc;
2047 }
2048 
2049 /*
2050 ** Enable or disable the extended result codes.
2051 */
2052 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
2053   sqlite3_mutex_enter(db->mutex);
2054   db->errMask = onoff ? 0xffffffff : 0xff;
2055   sqlite3_mutex_leave(db->mutex);
2056   return SQLITE_OK;
2057 }
2058 
2059 /*
2060 ** Invoke the xFileControl method on a particular database.
2061 */
2062 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
2063   int rc = SQLITE_ERROR;
2064   int iDb;
2065   sqlite3_mutex_enter(db->mutex);
2066   if( zDbName==0 ){
2067     iDb = 0;
2068   }else{
2069     for(iDb=0; iDb<db->nDb; iDb++){
2070       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
2071     }
2072   }
2073   if( iDb<db->nDb ){
2074     Btree *pBtree = db->aDb[iDb].pBt;
2075     if( pBtree ){
2076       Pager *pPager;
2077       sqlite3_file *fd;
2078       sqlite3BtreeEnter(pBtree);
2079       pPager = sqlite3BtreePager(pBtree);
2080       assert( pPager!=0 );
2081       fd = sqlite3PagerFile(pPager);
2082       assert( fd!=0 );
2083       if( fd->pMethods ){
2084         rc = sqlite3OsFileControl(fd, op, pArg);
2085       }
2086       sqlite3BtreeLeave(pBtree);
2087     }
2088   }
2089   sqlite3_mutex_leave(db->mutex);
2090   return rc;
2091 }
2092 
2093 /*
2094 ** Interface to the testing logic.
2095 */
2096 int sqlite3_test_control(int op, ...){
2097   int rc = 0;
2098 #ifndef SQLITE_OMIT_BUILTIN_TEST
2099   va_list ap;
2100   va_start(ap, op);
2101   switch( op ){
2102 
2103     /*
2104     ** Save the current state of the PRNG.
2105     */
2106     case SQLITE_TESTCTRL_PRNG_SAVE: {
2107       sqlite3PrngSaveState();
2108       break;
2109     }
2110 
2111     /*
2112     ** Restore the state of the PRNG to the last state saved using
2113     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
2114     ** this verb acts like PRNG_RESET.
2115     */
2116     case SQLITE_TESTCTRL_PRNG_RESTORE: {
2117       sqlite3PrngRestoreState();
2118       break;
2119     }
2120 
2121     /*
2122     ** Reset the PRNG back to its uninitialized state.  The next call
2123     ** to sqlite3_randomness() will reseed the PRNG using a single call
2124     ** to the xRandomness method of the default VFS.
2125     */
2126     case SQLITE_TESTCTRL_PRNG_RESET: {
2127       sqlite3PrngResetState();
2128       break;
2129     }
2130 
2131     /*
2132     **  sqlite3_test_control(BITVEC_TEST, size, program)
2133     **
2134     ** Run a test against a Bitvec object of size.  The program argument
2135     ** is an array of integers that defines the test.  Return -1 on a
2136     ** memory allocation error, 0 on success, or non-zero for an error.
2137     ** See the sqlite3BitvecBuiltinTest() for additional information.
2138     */
2139     case SQLITE_TESTCTRL_BITVEC_TEST: {
2140       int sz = va_arg(ap, int);
2141       int *aProg = va_arg(ap, int*);
2142       rc = sqlite3BitvecBuiltinTest(sz, aProg);
2143       break;
2144     }
2145 
2146     /*
2147     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
2148     **
2149     ** Register hooks to call to indicate which malloc() failures
2150     ** are benign.
2151     */
2152     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
2153       typedef void (*void_function)(void);
2154       void_function xBenignBegin;
2155       void_function xBenignEnd;
2156       xBenignBegin = va_arg(ap, void_function);
2157       xBenignEnd = va_arg(ap, void_function);
2158       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
2159       break;
2160     }
2161 
2162     /*
2163     **  sqlite3_test_control(PENDING_BYTE, unsigned int X)
2164     **
2165     ** Set the PENDING byte to the value in the argument, if X>0.
2166     ** Make no changes if X==0.  Return the value of the pending byte
2167     ** as it existing before this routine was called.
2168     **
2169     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
2170     ** an incompatible database file format.  Changing the PENDING byte
2171     ** while any database connection is open results in undefined and
2172     ** dileterious behavior.
2173     */
2174     case SQLITE_TESTCTRL_PENDING_BYTE: {
2175       unsigned int newVal = va_arg(ap, unsigned int);
2176       rc = sqlite3PendingByte;
2177       if( newVal ) sqlite3PendingByte = newVal;
2178       break;
2179     }
2180   }
2181   va_end(ap);
2182 #endif /* SQLITE_OMIT_BUILTIN_TEST */
2183   return rc;
2184 }
2185