xref: /sqlite-3.40.0/src/main.c (revision eb4ac06f)
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.544 2009/04/30 12:25:10 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   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 function returns true if main-memory should be used instead of
1170 ** a temporary file for transient pager files and statement journals.
1171 ** The value returned depends on the value of db->temp_store (runtime
1172 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
1173 ** following table describes the relationship between these two values
1174 ** and this functions return value.
1175 **
1176 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
1177 **   -----------------     --------------     ------------------------------
1178 **   0                     any                file      (return 0)
1179 **   1                     1                  file      (return 0)
1180 **   1                     2                  memory    (return 1)
1181 **   1                     0                  file      (return 0)
1182 **   2                     1                  file      (return 0)
1183 **   2                     2                  memory    (return 1)
1184 **   2                     0                  memory    (return 1)
1185 **   3                     any                memory    (return 1)
1186 */
1187 int sqlite3TempInMemory(const sqlite3 *db){
1188 #if SQLITE_TEMP_STORE==1
1189   return ( db->temp_store==2 );
1190 #endif
1191 #if SQLITE_TEMP_STORE==2
1192   return ( db->temp_store!=1 );
1193 #endif
1194 #if SQLITE_TEMP_STORE==3
1195   return 1;
1196 #endif
1197   return 0;
1198 }
1199 
1200 /*
1201 ** This routine is called to create a connection to a database BTree
1202 ** driver.  If zFilename is the name of a file, then that file is
1203 ** opened and used.  If zFilename is the magic name ":memory:" then
1204 ** the database is stored in memory (and is thus forgotten as soon as
1205 ** the connection is closed.)  If zFilename is NULL then the database
1206 ** is a "virtual" database for transient use only and is deleted as
1207 ** soon as the connection is closed.
1208 **
1209 ** A virtual database can be either a disk file (that is automatically
1210 ** deleted when the file is closed) or it an be held entirely in memory.
1211 ** The sqlite3TempInMemory() function is used to determine which.
1212 */
1213 int sqlite3BtreeFactory(
1214   const sqlite3 *db,        /* Main database when opening aux otherwise 0 */
1215   const char *zFilename,    /* Name of the file containing the BTree database */
1216   int omitJournal,          /* if TRUE then do not journal this file */
1217   int nCache,               /* How many pages in the page cache */
1218   int vfsFlags,             /* Flags passed through to vfsOpen */
1219   Btree **ppBtree           /* Pointer to new Btree object written here */
1220 ){
1221   int btFlags = 0;
1222   int rc;
1223 
1224   assert( sqlite3_mutex_held(db->mutex) );
1225   assert( ppBtree != 0);
1226   if( omitJournal ){
1227     btFlags |= BTREE_OMIT_JOURNAL;
1228   }
1229   if( db->flags & SQLITE_NoReadlock ){
1230     btFlags |= BTREE_NO_READLOCK;
1231   }
1232 #ifndef SQLITE_OMIT_MEMORYDB
1233   if( zFilename==0 && sqlite3TempInMemory(db) ){
1234     zFilename = ":memory:";
1235   }
1236 #endif
1237 
1238   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
1239     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
1240   }
1241   rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
1242 
1243   /* If the B-Tree was successfully opened, set the pager-cache size to the
1244   ** default value. Except, if the call to BtreeOpen() returned a handle
1245   ** open on an existing shared pager-cache, do not change the pager-cache
1246   ** size.
1247   */
1248   if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
1249     sqlite3BtreeSetCacheSize(*ppBtree, nCache);
1250   }
1251   return rc;
1252 }
1253 
1254 /*
1255 ** Return UTF-8 encoded English language explanation of the most recent
1256 ** error.
1257 */
1258 const char *sqlite3_errmsg(sqlite3 *db){
1259   const char *z;
1260   if( !db ){
1261     return sqlite3ErrStr(SQLITE_NOMEM);
1262   }
1263   if( !sqlite3SafetyCheckSickOrOk(db) ){
1264     return sqlite3ErrStr(SQLITE_MISUSE);
1265   }
1266   sqlite3_mutex_enter(db->mutex);
1267   if( db->mallocFailed ){
1268     z = sqlite3ErrStr(SQLITE_NOMEM);
1269   }else{
1270     z = (char*)sqlite3_value_text(db->pErr);
1271     assert( !db->mallocFailed );
1272     if( z==0 ){
1273       z = sqlite3ErrStr(db->errCode);
1274     }
1275   }
1276   sqlite3_mutex_leave(db->mutex);
1277   return z;
1278 }
1279 
1280 #ifndef SQLITE_OMIT_UTF16
1281 /*
1282 ** Return UTF-16 encoded English language explanation of the most recent
1283 ** error.
1284 */
1285 const void *sqlite3_errmsg16(sqlite3 *db){
1286   static const u16 outOfMem[] = {
1287     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
1288   };
1289   static const u16 misuse[] = {
1290     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
1291     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
1292     'c', 'a', 'l', 'l', 'e', 'd', ' ',
1293     'o', 'u', 't', ' ',
1294     'o', 'f', ' ',
1295     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
1296   };
1297 
1298   const void *z;
1299   if( !db ){
1300     return (void *)outOfMem;
1301   }
1302   if( !sqlite3SafetyCheckSickOrOk(db) ){
1303     return (void *)misuse;
1304   }
1305   sqlite3_mutex_enter(db->mutex);
1306   if( db->mallocFailed ){
1307     z = (void *)outOfMem;
1308   }else{
1309     z = sqlite3_value_text16(db->pErr);
1310     if( z==0 ){
1311       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
1312            SQLITE_UTF8, SQLITE_STATIC);
1313       z = sqlite3_value_text16(db->pErr);
1314     }
1315     /* A malloc() may have failed within the call to sqlite3_value_text16()
1316     ** above. If this is the case, then the db->mallocFailed flag needs to
1317     ** be cleared before returning. Do this directly, instead of via
1318     ** sqlite3ApiExit(), to avoid setting the database handle error message.
1319     */
1320     db->mallocFailed = 0;
1321   }
1322   sqlite3_mutex_leave(db->mutex);
1323   return z;
1324 }
1325 #endif /* SQLITE_OMIT_UTF16 */
1326 
1327 /*
1328 ** Return the most recent error code generated by an SQLite routine. If NULL is
1329 ** passed to this function, we assume a malloc() failed during sqlite3_open().
1330 */
1331 int sqlite3_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 & db->errMask;
1339 }
1340 int sqlite3_extended_errcode(sqlite3 *db){
1341   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
1342     return SQLITE_MISUSE;
1343   }
1344   if( !db || db->mallocFailed ){
1345     return SQLITE_NOMEM;
1346   }
1347   return db->errCode;
1348 }
1349 
1350 /*
1351 ** Create a new collating function for database "db".  The name is zName
1352 ** and the encoding is enc.
1353 */
1354 static int createCollation(
1355   sqlite3* db,
1356   const char *zName,
1357   int enc,
1358   void* pCtx,
1359   int(*xCompare)(void*,int,const void*,int,const void*),
1360   void(*xDel)(void*)
1361 ){
1362   CollSeq *pColl;
1363   int enc2;
1364   int nName;
1365 
1366   assert( sqlite3_mutex_held(db->mutex) );
1367 
1368   /* If SQLITE_UTF16 is specified as the encoding type, transform this
1369   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
1370   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
1371   */
1372   enc2 = enc;
1373   testcase( enc2==SQLITE_UTF16 );
1374   testcase( enc2==SQLITE_UTF16_ALIGNED );
1375   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
1376     enc2 = SQLITE_UTF16NATIVE;
1377   }
1378   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
1379     return SQLITE_MISUSE;
1380   }
1381 
1382   /* Check if this call is removing or replacing an existing collation
1383   ** sequence. If so, and there are active VMs, return busy. If there
1384   ** are no active VMs, invalidate any pre-compiled statements.
1385   */
1386   nName = sqlite3Strlen(db, zName);
1387   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 0);
1388   if( pColl && pColl->xCmp ){
1389     if( db->activeVdbeCnt ){
1390       sqlite3Error(db, SQLITE_BUSY,
1391         "unable to delete/modify collation sequence due to active statements");
1392       return SQLITE_BUSY;
1393     }
1394     sqlite3ExpirePreparedStatements(db);
1395 
1396     /* If collation sequence pColl was created directly by a call to
1397     ** sqlite3_create_collation, and not generated by synthCollSeq(),
1398     ** then any copies made by synthCollSeq() need to be invalidated.
1399     ** Also, collation destructor - CollSeq.xDel() - function may need
1400     ** to be called.
1401     */
1402     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
1403       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
1404       int j;
1405       for(j=0; j<3; j++){
1406         CollSeq *p = &aColl[j];
1407         if( p->enc==pColl->enc ){
1408           if( p->xDel ){
1409             p->xDel(p->pUser);
1410           }
1411           p->xCmp = 0;
1412         }
1413       }
1414     }
1415   }
1416 
1417   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 1);
1418   if( pColl ){
1419     pColl->xCmp = xCompare;
1420     pColl->pUser = pCtx;
1421     pColl->xDel = xDel;
1422     pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
1423   }
1424   sqlite3Error(db, SQLITE_OK, 0);
1425   return SQLITE_OK;
1426 }
1427 
1428 
1429 /*
1430 ** This array defines hard upper bounds on limit values.  The
1431 ** initializer must be kept in sync with the SQLITE_LIMIT_*
1432 ** #defines in sqlite3.h.
1433 */
1434 static const int aHardLimit[] = {
1435   SQLITE_MAX_LENGTH,
1436   SQLITE_MAX_SQL_LENGTH,
1437   SQLITE_MAX_COLUMN,
1438   SQLITE_MAX_EXPR_DEPTH,
1439   SQLITE_MAX_COMPOUND_SELECT,
1440   SQLITE_MAX_VDBE_OP,
1441   SQLITE_MAX_FUNCTION_ARG,
1442   SQLITE_MAX_ATTACHED,
1443   SQLITE_MAX_LIKE_PATTERN_LENGTH,
1444   SQLITE_MAX_VARIABLE_NUMBER,
1445 };
1446 
1447 /*
1448 ** Make sure the hard limits are set to reasonable values
1449 */
1450 #if SQLITE_MAX_LENGTH<100
1451 # error SQLITE_MAX_LENGTH must be at least 100
1452 #endif
1453 #if SQLITE_MAX_SQL_LENGTH<100
1454 # error SQLITE_MAX_SQL_LENGTH must be at least 100
1455 #endif
1456 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
1457 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
1458 #endif
1459 #if SQLITE_MAX_COMPOUND_SELECT<2
1460 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
1461 #endif
1462 #if SQLITE_MAX_VDBE_OP<40
1463 # error SQLITE_MAX_VDBE_OP must be at least 40
1464 #endif
1465 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
1466 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
1467 #endif
1468 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
1469 # error SQLITE_MAX_ATTACHED must be between 0 and 30
1470 #endif
1471 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
1472 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
1473 #endif
1474 #if SQLITE_MAX_VARIABLE_NUMBER<1
1475 # error SQLITE_MAX_VARIABLE_NUMBER must be at least 1
1476 #endif
1477 #if SQLITE_MAX_COLUMN>32767
1478 # error SQLITE_MAX_COLUMN must not exceed 32767
1479 #endif
1480 
1481 
1482 /*
1483 ** Change the value of a limit.  Report the old value.
1484 ** If an invalid limit index is supplied, report -1.
1485 ** Make no changes but still report the old value if the
1486 ** new limit is negative.
1487 **
1488 ** A new lower limit does not shrink existing constructs.
1489 ** It merely prevents new constructs that exceed the limit
1490 ** from forming.
1491 */
1492 int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
1493   int oldLimit;
1494   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
1495     return -1;
1496   }
1497   oldLimit = db->aLimit[limitId];
1498   if( newLimit>=0 ){
1499     if( newLimit>aHardLimit[limitId] ){
1500       newLimit = aHardLimit[limitId];
1501     }
1502     db->aLimit[limitId] = newLimit;
1503   }
1504   return oldLimit;
1505 }
1506 
1507 /*
1508 ** This routine does the work of opening a database on behalf of
1509 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
1510 ** is UTF-8 encoded.
1511 */
1512 static int openDatabase(
1513   const char *zFilename, /* Database filename UTF-8 encoded */
1514   sqlite3 **ppDb,        /* OUT: Returned database handle */
1515   unsigned flags,        /* Operational flags */
1516   const char *zVfs       /* Name of the VFS to use */
1517 ){
1518   sqlite3 *db;
1519   int rc;
1520   CollSeq *pColl;
1521   int isThreadsafe;
1522 
1523   *ppDb = 0;
1524 #ifndef SQLITE_OMIT_AUTOINIT
1525   rc = sqlite3_initialize();
1526   if( rc ) return rc;
1527 #endif
1528 
1529   if( sqlite3GlobalConfig.bCoreMutex==0 ){
1530     isThreadsafe = 0;
1531   }else if( flags & SQLITE_OPEN_NOMUTEX ){
1532     isThreadsafe = 0;
1533   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
1534     isThreadsafe = 1;
1535   }else{
1536     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
1537   }
1538 
1539   /* Remove harmful bits from the flags parameter */
1540   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
1541                SQLITE_OPEN_MAIN_DB |
1542                SQLITE_OPEN_TEMP_DB |
1543                SQLITE_OPEN_TRANSIENT_DB |
1544                SQLITE_OPEN_MAIN_JOURNAL |
1545                SQLITE_OPEN_TEMP_JOURNAL |
1546                SQLITE_OPEN_SUBJOURNAL |
1547                SQLITE_OPEN_MASTER_JOURNAL |
1548                SQLITE_OPEN_NOMUTEX |
1549                SQLITE_OPEN_FULLMUTEX
1550              );
1551 
1552   /* Allocate the sqlite data structure */
1553   db = sqlite3MallocZero( sizeof(sqlite3) );
1554   if( db==0 ) goto opendb_out;
1555   if( isThreadsafe ){
1556     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
1557     if( db->mutex==0 ){
1558       sqlite3_free(db);
1559       db = 0;
1560       goto opendb_out;
1561     }
1562   }
1563   sqlite3_mutex_enter(db->mutex);
1564   db->errMask = 0xff;
1565   db->priorNewRowid = 0;
1566   db->nDb = 2;
1567   db->magic = SQLITE_MAGIC_BUSY;
1568   db->aDb = db->aDbStatic;
1569 
1570   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
1571   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
1572   db->autoCommit = 1;
1573   db->nextAutovac = -1;
1574   db->nextPagesize = 0;
1575   db->flags |= SQLITE_ShortColNames
1576 #if SQLITE_DEFAULT_FILE_FORMAT<4
1577                  | SQLITE_LegacyFileFmt
1578 #endif
1579 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
1580                  | SQLITE_LoadExtension
1581 #endif
1582       ;
1583   sqlite3HashInit(&db->aCollSeq, 0);
1584 #ifndef SQLITE_OMIT_VIRTUALTABLE
1585   sqlite3HashInit(&db->aModule, 0);
1586 #endif
1587 
1588   db->pVfs = sqlite3_vfs_find(zVfs);
1589   if( !db->pVfs ){
1590     rc = SQLITE_ERROR;
1591     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
1592     goto opendb_out;
1593   }
1594 
1595   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
1596   ** and UTF-16, so add a version for each to avoid any unnecessary
1597   ** conversions. The only error that can occur here is a malloc() failure.
1598   */
1599   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
1600   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
1601   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
1602   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
1603   if( db->mallocFailed ){
1604     goto opendb_out;
1605   }
1606   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
1607   assert( db->pDfltColl!=0 );
1608 
1609   /* Also add a UTF-8 case-insensitive collation sequence. */
1610   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
1611 
1612   /* Set flags on the built-in collating sequences */
1613   db->pDfltColl->type = SQLITE_COLL_BINARY;
1614   pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "NOCASE", 6, 0);
1615   if( pColl ){
1616     pColl->type = SQLITE_COLL_NOCASE;
1617   }
1618 
1619   /* Open the backend database driver */
1620   db->openFlags = flags;
1621   rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE,
1622                            flags | SQLITE_OPEN_MAIN_DB,
1623                            &db->aDb[0].pBt);
1624   if( rc!=SQLITE_OK ){
1625     if( rc==SQLITE_IOERR_NOMEM ){
1626       rc = SQLITE_NOMEM;
1627     }
1628     sqlite3Error(db, rc, 0);
1629     goto opendb_out;
1630   }
1631   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
1632   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
1633 
1634 
1635   /* The default safety_level for the main database is 'full'; for the temp
1636   ** database it is 'NONE'. This matches the pager layer defaults.
1637   */
1638   db->aDb[0].zName = "main";
1639   db->aDb[0].safety_level = 3;
1640 #ifndef SQLITE_OMIT_TEMPDB
1641   db->aDb[1].zName = "temp";
1642   db->aDb[1].safety_level = 1;
1643 #endif
1644 
1645   db->magic = SQLITE_MAGIC_OPEN;
1646   if( db->mallocFailed ){
1647     goto opendb_out;
1648   }
1649 
1650   /* Register all built-in functions, but do not attempt to read the
1651   ** database schema yet. This is delayed until the first time the database
1652   ** is accessed.
1653   */
1654   sqlite3Error(db, SQLITE_OK, 0);
1655   sqlite3RegisterBuiltinFunctions(db);
1656 
1657   /* Load automatic extensions - extensions that have been registered
1658   ** using the sqlite3_automatic_extension() API.
1659   */
1660   (void)sqlite3AutoLoadExtensions(db);
1661   if( sqlite3_errcode(db)!=SQLITE_OK ){
1662     goto opendb_out;
1663   }
1664 
1665 #ifdef SQLITE_ENABLE_FTS1
1666   if( !db->mallocFailed ){
1667     extern int sqlite3Fts1Init(sqlite3*);
1668     rc = sqlite3Fts1Init(db);
1669   }
1670 #endif
1671 
1672 #ifdef SQLITE_ENABLE_FTS2
1673   if( !db->mallocFailed && rc==SQLITE_OK ){
1674     extern int sqlite3Fts2Init(sqlite3*);
1675     rc = sqlite3Fts2Init(db);
1676   }
1677 #endif
1678 
1679 #ifdef SQLITE_ENABLE_FTS3
1680   if( !db->mallocFailed && rc==SQLITE_OK ){
1681     rc = sqlite3Fts3Init(db);
1682   }
1683 #endif
1684 
1685 #ifdef SQLITE_ENABLE_ICU
1686   if( !db->mallocFailed && rc==SQLITE_OK ){
1687     rc = sqlite3IcuInit(db);
1688   }
1689 #endif
1690 
1691 #ifdef SQLITE_ENABLE_RTREE
1692   if( !db->mallocFailed && rc==SQLITE_OK){
1693     rc = sqlite3RtreeInit(db);
1694   }
1695 #endif
1696 
1697   sqlite3Error(db, rc, 0);
1698 
1699   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
1700   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
1701   ** mode.  Doing nothing at all also makes NORMAL the default.
1702   */
1703 #ifdef SQLITE_DEFAULT_LOCKING_MODE
1704   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
1705   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
1706                           SQLITE_DEFAULT_LOCKING_MODE);
1707 #endif
1708 
1709   /* Enable the lookaside-malloc subsystem */
1710   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
1711                         sqlite3GlobalConfig.nLookaside);
1712 
1713 opendb_out:
1714   if( db ){
1715     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
1716     sqlite3_mutex_leave(db->mutex);
1717   }
1718   rc = sqlite3_errcode(db);
1719   if( rc==SQLITE_NOMEM ){
1720     sqlite3_close(db);
1721     db = 0;
1722   }else if( rc!=SQLITE_OK ){
1723     db->magic = SQLITE_MAGIC_SICK;
1724   }
1725   *ppDb = db;
1726   return sqlite3ApiExit(0, rc);
1727 }
1728 
1729 /*
1730 ** Open a new database handle.
1731 */
1732 int sqlite3_open(
1733   const char *zFilename,
1734   sqlite3 **ppDb
1735 ){
1736   return openDatabase(zFilename, ppDb,
1737                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
1738 }
1739 int sqlite3_open_v2(
1740   const char *filename,   /* Database filename (UTF-8) */
1741   sqlite3 **ppDb,         /* OUT: SQLite db handle */
1742   int flags,              /* Flags */
1743   const char *zVfs        /* Name of VFS module to use */
1744 ){
1745   return openDatabase(filename, ppDb, flags, zVfs);
1746 }
1747 
1748 #ifndef SQLITE_OMIT_UTF16
1749 /*
1750 ** Open a new database handle.
1751 */
1752 int sqlite3_open16(
1753   const void *zFilename,
1754   sqlite3 **ppDb
1755 ){
1756   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
1757   sqlite3_value *pVal;
1758   int rc;
1759 
1760   assert( zFilename );
1761   assert( ppDb );
1762   *ppDb = 0;
1763 #ifndef SQLITE_OMIT_AUTOINIT
1764   rc = sqlite3_initialize();
1765   if( rc ) return rc;
1766 #endif
1767   pVal = sqlite3ValueNew(0);
1768   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
1769   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
1770   if( zFilename8 ){
1771     rc = openDatabase(zFilename8, ppDb,
1772                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
1773     assert( *ppDb || rc==SQLITE_NOMEM );
1774     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
1775       ENC(*ppDb) = SQLITE_UTF16NATIVE;
1776     }
1777   }else{
1778     rc = SQLITE_NOMEM;
1779   }
1780   sqlite3ValueFree(pVal);
1781 
1782   return sqlite3ApiExit(0, rc);
1783 }
1784 #endif /* SQLITE_OMIT_UTF16 */
1785 
1786 /*
1787 ** Register a new collation sequence with the database handle db.
1788 */
1789 int sqlite3_create_collation(
1790   sqlite3* db,
1791   const char *zName,
1792   int enc,
1793   void* pCtx,
1794   int(*xCompare)(void*,int,const void*,int,const void*)
1795 ){
1796   int rc;
1797   sqlite3_mutex_enter(db->mutex);
1798   assert( !db->mallocFailed );
1799   rc = createCollation(db, zName, enc, pCtx, xCompare, 0);
1800   rc = sqlite3ApiExit(db, rc);
1801   sqlite3_mutex_leave(db->mutex);
1802   return rc;
1803 }
1804 
1805 /*
1806 ** Register a new collation sequence with the database handle db.
1807 */
1808 int sqlite3_create_collation_v2(
1809   sqlite3* db,
1810   const char *zName,
1811   int enc,
1812   void* pCtx,
1813   int(*xCompare)(void*,int,const void*,int,const void*),
1814   void(*xDel)(void*)
1815 ){
1816   int rc;
1817   sqlite3_mutex_enter(db->mutex);
1818   assert( !db->mallocFailed );
1819   rc = createCollation(db, zName, enc, pCtx, xCompare, xDel);
1820   rc = sqlite3ApiExit(db, rc);
1821   sqlite3_mutex_leave(db->mutex);
1822   return rc;
1823 }
1824 
1825 #ifndef SQLITE_OMIT_UTF16
1826 /*
1827 ** Register a new collation sequence with the database handle db.
1828 */
1829 int sqlite3_create_collation16(
1830   sqlite3* db,
1831   const void *zName,
1832   int enc,
1833   void* pCtx,
1834   int(*xCompare)(void*,int,const void*,int,const void*)
1835 ){
1836   int rc = SQLITE_OK;
1837   char *zName8;
1838   sqlite3_mutex_enter(db->mutex);
1839   assert( !db->mallocFailed );
1840   zName8 = sqlite3Utf16to8(db, zName, -1);
1841   if( zName8 ){
1842     rc = createCollation(db, zName8, enc, pCtx, xCompare, 0);
1843     sqlite3DbFree(db, zName8);
1844   }
1845   rc = sqlite3ApiExit(db, rc);
1846   sqlite3_mutex_leave(db->mutex);
1847   return rc;
1848 }
1849 #endif /* SQLITE_OMIT_UTF16 */
1850 
1851 /*
1852 ** Register a collation sequence factory callback with the database handle
1853 ** db. Replace any previously installed collation sequence factory.
1854 */
1855 int sqlite3_collation_needed(
1856   sqlite3 *db,
1857   void *pCollNeededArg,
1858   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
1859 ){
1860   sqlite3_mutex_enter(db->mutex);
1861   db->xCollNeeded = xCollNeeded;
1862   db->xCollNeeded16 = 0;
1863   db->pCollNeededArg = pCollNeededArg;
1864   sqlite3_mutex_leave(db->mutex);
1865   return SQLITE_OK;
1866 }
1867 
1868 #ifndef SQLITE_OMIT_UTF16
1869 /*
1870 ** Register a collation sequence factory callback with the database handle
1871 ** db. Replace any previously installed collation sequence factory.
1872 */
1873 int sqlite3_collation_needed16(
1874   sqlite3 *db,
1875   void *pCollNeededArg,
1876   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
1877 ){
1878   sqlite3_mutex_enter(db->mutex);
1879   db->xCollNeeded = 0;
1880   db->xCollNeeded16 = xCollNeeded16;
1881   db->pCollNeededArg = pCollNeededArg;
1882   sqlite3_mutex_leave(db->mutex);
1883   return SQLITE_OK;
1884 }
1885 #endif /* SQLITE_OMIT_UTF16 */
1886 
1887 #ifndef SQLITE_OMIT_GLOBALRECOVER
1888 #ifndef SQLITE_OMIT_DEPRECATED
1889 /*
1890 ** This function is now an anachronism. It used to be used to recover from a
1891 ** malloc() failure, but SQLite now does this automatically.
1892 */
1893 int sqlite3_global_recover(void){
1894   return SQLITE_OK;
1895 }
1896 #endif
1897 #endif
1898 
1899 /*
1900 ** Test to see whether or not the database connection is in autocommit
1901 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
1902 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
1903 ** by the next COMMIT or ROLLBACK.
1904 **
1905 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
1906 */
1907 int sqlite3_get_autocommit(sqlite3 *db){
1908   return db->autoCommit;
1909 }
1910 
1911 #ifdef SQLITE_DEBUG
1912 /*
1913 ** The following routine is subtituted for constant SQLITE_CORRUPT in
1914 ** debugging builds.  This provides a way to set a breakpoint for when
1915 ** corruption is first detected.
1916 */
1917 int sqlite3Corrupt(void){
1918   return SQLITE_CORRUPT;
1919 }
1920 #endif
1921 
1922 #ifndef SQLITE_OMIT_DEPRECATED
1923 /*
1924 ** This is a convenience routine that makes sure that all thread-specific
1925 ** data for this thread has been deallocated.
1926 **
1927 ** SQLite no longer uses thread-specific data so this routine is now a
1928 ** no-op.  It is retained for historical compatibility.
1929 */
1930 void sqlite3_thread_cleanup(void){
1931 }
1932 #endif
1933 
1934 /*
1935 ** Return meta information about a specific column of a database table.
1936 ** See comment in sqlite3.h (sqlite.h.in) for details.
1937 */
1938 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1939 int sqlite3_table_column_metadata(
1940   sqlite3 *db,                /* Connection handle */
1941   const char *zDbName,        /* Database name or NULL */
1942   const char *zTableName,     /* Table name */
1943   const char *zColumnName,    /* Column name */
1944   char const **pzDataType,    /* OUTPUT: Declared data type */
1945   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
1946   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
1947   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
1948   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
1949 ){
1950   int rc;
1951   char *zErrMsg = 0;
1952   Table *pTab = 0;
1953   Column *pCol = 0;
1954   int iCol;
1955 
1956   char const *zDataType = 0;
1957   char const *zCollSeq = 0;
1958   int notnull = 0;
1959   int primarykey = 0;
1960   int autoinc = 0;
1961 
1962   /* Ensure the database schema has been loaded */
1963   sqlite3_mutex_enter(db->mutex);
1964   (void)sqlite3SafetyOn(db);
1965   sqlite3BtreeEnterAll(db);
1966   rc = sqlite3Init(db, &zErrMsg);
1967   if( SQLITE_OK!=rc ){
1968     goto error_out;
1969   }
1970 
1971   /* Locate the table in question */
1972   pTab = sqlite3FindTable(db, zTableName, zDbName);
1973   if( !pTab || pTab->pSelect ){
1974     pTab = 0;
1975     goto error_out;
1976   }
1977 
1978   /* Find the column for which info is requested */
1979   if( sqlite3IsRowid(zColumnName) ){
1980     iCol = pTab->iPKey;
1981     if( iCol>=0 ){
1982       pCol = &pTab->aCol[iCol];
1983     }
1984   }else{
1985     for(iCol=0; iCol<pTab->nCol; iCol++){
1986       pCol = &pTab->aCol[iCol];
1987       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
1988         break;
1989       }
1990     }
1991     if( iCol==pTab->nCol ){
1992       pTab = 0;
1993       goto error_out;
1994     }
1995   }
1996 
1997   /* The following block stores the meta information that will be returned
1998   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
1999   ** and autoinc. At this point there are two possibilities:
2000   **
2001   **     1. The specified column name was rowid", "oid" or "_rowid_"
2002   **        and there is no explicitly declared IPK column.
2003   **
2004   **     2. The table is not a view and the column name identified an
2005   **        explicitly declared column. Copy meta information from *pCol.
2006   */
2007   if( pCol ){
2008     zDataType = pCol->zType;
2009     zCollSeq = pCol->zColl;
2010     notnull = pCol->notNull!=0;
2011     primarykey  = pCol->isPrimKey!=0;
2012     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
2013   }else{
2014     zDataType = "INTEGER";
2015     primarykey = 1;
2016   }
2017   if( !zCollSeq ){
2018     zCollSeq = "BINARY";
2019   }
2020 
2021 error_out:
2022   sqlite3BtreeLeaveAll(db);
2023   (void)sqlite3SafetyOff(db);
2024 
2025   /* Whether the function call succeeded or failed, set the output parameters
2026   ** to whatever their local counterparts contain. If an error did occur,
2027   ** this has the effect of zeroing all output parameters.
2028   */
2029   if( pzDataType ) *pzDataType = zDataType;
2030   if( pzCollSeq ) *pzCollSeq = zCollSeq;
2031   if( pNotNull ) *pNotNull = notnull;
2032   if( pPrimaryKey ) *pPrimaryKey = primarykey;
2033   if( pAutoinc ) *pAutoinc = autoinc;
2034 
2035   if( SQLITE_OK==rc && !pTab ){
2036     sqlite3DbFree(db, zErrMsg);
2037     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
2038         zColumnName);
2039     rc = SQLITE_ERROR;
2040   }
2041   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
2042   sqlite3DbFree(db, zErrMsg);
2043   rc = sqlite3ApiExit(db, rc);
2044   sqlite3_mutex_leave(db->mutex);
2045   return rc;
2046 }
2047 #endif
2048 
2049 /*
2050 ** Sleep for a little while.  Return the amount of time slept.
2051 */
2052 int sqlite3_sleep(int ms){
2053   sqlite3_vfs *pVfs;
2054   int rc;
2055   pVfs = sqlite3_vfs_find(0);
2056   if( pVfs==0 ) return 0;
2057 
2058   /* This function works in milliseconds, but the underlying OsSleep()
2059   ** API uses microseconds. Hence the 1000's.
2060   */
2061   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
2062   return rc;
2063 }
2064 
2065 /*
2066 ** Enable or disable the extended result codes.
2067 */
2068 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
2069   sqlite3_mutex_enter(db->mutex);
2070   db->errMask = onoff ? 0xffffffff : 0xff;
2071   sqlite3_mutex_leave(db->mutex);
2072   return SQLITE_OK;
2073 }
2074 
2075 /*
2076 ** Invoke the xFileControl method on a particular database.
2077 */
2078 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
2079   int rc = SQLITE_ERROR;
2080   int iDb;
2081   sqlite3_mutex_enter(db->mutex);
2082   if( zDbName==0 ){
2083     iDb = 0;
2084   }else{
2085     for(iDb=0; iDb<db->nDb; iDb++){
2086       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
2087     }
2088   }
2089   if( iDb<db->nDb ){
2090     Btree *pBtree = db->aDb[iDb].pBt;
2091     if( pBtree ){
2092       Pager *pPager;
2093       sqlite3_file *fd;
2094       sqlite3BtreeEnter(pBtree);
2095       pPager = sqlite3BtreePager(pBtree);
2096       assert( pPager!=0 );
2097       fd = sqlite3PagerFile(pPager);
2098       assert( fd!=0 );
2099       if( fd->pMethods ){
2100         rc = sqlite3OsFileControl(fd, op, pArg);
2101       }
2102       sqlite3BtreeLeave(pBtree);
2103     }
2104   }
2105   sqlite3_mutex_leave(db->mutex);
2106   return rc;
2107 }
2108 
2109 /*
2110 ** Interface to the testing logic.
2111 */
2112 int sqlite3_test_control(int op, ...){
2113   int rc = 0;
2114 #ifndef SQLITE_OMIT_BUILTIN_TEST
2115   va_list ap;
2116   va_start(ap, op);
2117   switch( op ){
2118 
2119     /*
2120     ** Save the current state of the PRNG.
2121     */
2122     case SQLITE_TESTCTRL_PRNG_SAVE: {
2123       sqlite3PrngSaveState();
2124       break;
2125     }
2126 
2127     /*
2128     ** Restore the state of the PRNG to the last state saved using
2129     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
2130     ** this verb acts like PRNG_RESET.
2131     */
2132     case SQLITE_TESTCTRL_PRNG_RESTORE: {
2133       sqlite3PrngRestoreState();
2134       break;
2135     }
2136 
2137     /*
2138     ** Reset the PRNG back to its uninitialized state.  The next call
2139     ** to sqlite3_randomness() will reseed the PRNG using a single call
2140     ** to the xRandomness method of the default VFS.
2141     */
2142     case SQLITE_TESTCTRL_PRNG_RESET: {
2143       sqlite3PrngResetState();
2144       break;
2145     }
2146 
2147     /*
2148     **  sqlite3_test_control(BITVEC_TEST, size, program)
2149     **
2150     ** Run a test against a Bitvec object of size.  The program argument
2151     ** is an array of integers that defines the test.  Return -1 on a
2152     ** memory allocation error, 0 on success, or non-zero for an error.
2153     ** See the sqlite3BitvecBuiltinTest() for additional information.
2154     */
2155     case SQLITE_TESTCTRL_BITVEC_TEST: {
2156       int sz = va_arg(ap, int);
2157       int *aProg = va_arg(ap, int*);
2158       rc = sqlite3BitvecBuiltinTest(sz, aProg);
2159       break;
2160     }
2161 
2162     /*
2163     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
2164     **
2165     ** Register hooks to call to indicate which malloc() failures
2166     ** are benign.
2167     */
2168     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
2169       typedef void (*void_function)(void);
2170       void_function xBenignBegin;
2171       void_function xBenignEnd;
2172       xBenignBegin = va_arg(ap, void_function);
2173       xBenignEnd = va_arg(ap, void_function);
2174       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
2175       break;
2176     }
2177 
2178     /*
2179     **  sqlite3_test_control(PENDING_BYTE, unsigned int X)
2180     **
2181     ** Set the PENDING byte to the value in the argument, if X>0.
2182     ** Make no changes if X==0.  Return the value of the pending byte
2183     ** as it existing before this routine was called.
2184     **
2185     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
2186     ** an incompatible database file format.  Changing the PENDING byte
2187     ** while any database connection is open results in undefined and
2188     ** dileterious behavior.
2189     */
2190     case SQLITE_TESTCTRL_PENDING_BYTE: {
2191       unsigned int newVal = va_arg(ap, unsigned int);
2192       rc = sqlite3PendingByte;
2193       if( newVal ) sqlite3PendingByte = newVal;
2194       break;
2195     }
2196   }
2197   va_end(ap);
2198 #endif /* SQLITE_OMIT_BUILTIN_TEST */
2199   return rc;
2200 }
2201