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