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