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