xref: /sqlite-3.40.0/src/main.c (revision 48864df9)
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 #ifndef SQLITE_AMALGAMATION
30 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
31 ** contains the text of SQLITE_VERSION macro.
32 */
33 const char sqlite3_version[] = SQLITE_VERSION;
34 #endif
35 
36 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
37 ** a pointer to the to the sqlite3_version[] string constant.
38 */
39 const char *sqlite3_libversion(void){ return sqlite3_version; }
40 
41 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
42 ** pointer to a string constant whose value is the same as the
43 ** SQLITE_SOURCE_ID C preprocessor macro.
44 */
45 const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
46 
47 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
48 ** returns an integer equal to SQLITE_VERSION_NUMBER.
49 */
50 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
51 
52 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
53 ** zero if and only if SQLite was compiled with mutexing code omitted due to
54 ** the SQLITE_THREADSAFE compile-time option being set to 0.
55 */
56 int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
57 
58 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
59 /*
60 ** If the following function pointer is not NULL and if
61 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
62 ** I/O active are written using this function.  These messages
63 ** are intended for debugging activity only.
64 */
65 void (*sqlite3IoTrace)(const char*, ...) = 0;
66 #endif
67 
68 /*
69 ** If the following global variable points to a string which is the
70 ** name of a directory, then that directory will be used to store
71 ** temporary files.
72 **
73 ** See also the "PRAGMA temp_store_directory" SQL command.
74 */
75 char *sqlite3_temp_directory = 0;
76 
77 /*
78 ** If the following global variable points to a string which is the
79 ** name of a directory, then that directory will be used to store
80 ** all database files specified with a relative pathname.
81 **
82 ** See also the "PRAGMA data_store_directory" SQL command.
83 */
84 char *sqlite3_data_directory = 0;
85 
86 /*
87 ** Initialize SQLite.
88 **
89 ** This routine must be called to initialize the memory allocation,
90 ** VFS, and mutex subsystems prior to doing any serious work with
91 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
92 ** this routine will be called automatically by key routines such as
93 ** sqlite3_open().
94 **
95 ** This routine is a no-op except on its very first call for the process,
96 ** or for the first call after a call to sqlite3_shutdown.
97 **
98 ** The first thread to call this routine runs the initialization to
99 ** completion.  If subsequent threads call this routine before the first
100 ** thread has finished the initialization process, then the subsequent
101 ** threads must block until the first thread finishes with the initialization.
102 **
103 ** The first thread might call this routine recursively.  Recursive
104 ** calls to this routine should not block, of course.  Otherwise the
105 ** initialization process would never complete.
106 **
107 ** Let X be the first thread to enter this routine.  Let Y be some other
108 ** thread.  Then while the initial invocation of this routine by X is
109 ** incomplete, it is required that:
110 **
111 **    *  Calls to this routine from Y must block until the outer-most
112 **       call by X completes.
113 **
114 **    *  Recursive calls to this routine from thread X return immediately
115 **       without blocking.
116 */
117 int sqlite3_initialize(void){
118   MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
119   int rc;                                      /* Result code */
120 
121 #ifdef SQLITE_OMIT_WSD
122   rc = sqlite3_wsd_init(4096, 24);
123   if( rc!=SQLITE_OK ){
124     return rc;
125   }
126 #endif
127 
128   /* If SQLite is already completely initialized, then this call
129   ** to sqlite3_initialize() should be a no-op.  But the initialization
130   ** must be complete.  So isInit must not be set until the very end
131   ** of this routine.
132   */
133   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
134 
135 #ifdef SQLITE_ENABLE_SQLLOG
136   {
137     extern void sqlite3_init_sqllog(void);
138     sqlite3_init_sqllog();
139   }
140 #endif
141 
142   /* Make sure the mutex subsystem is initialized.  If unable to
143   ** initialize the mutex subsystem, return early with the error.
144   ** If the system is so sick that we are unable to allocate a mutex,
145   ** there is not much SQLite is going to be able to do.
146   **
147   ** The mutex subsystem must take care of serializing its own
148   ** initialization.
149   */
150   rc = sqlite3MutexInit();
151   if( rc ) return rc;
152 
153   /* Initialize the malloc() system and the recursive pInitMutex mutex.
154   ** This operation is protected by the STATIC_MASTER mutex.  Note that
155   ** MutexAlloc() is called for a static mutex prior to initializing the
156   ** malloc subsystem - this implies that the allocation of a static
157   ** mutex must not require support from the malloc subsystem.
158   */
159   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
160   sqlite3_mutex_enter(pMaster);
161   sqlite3GlobalConfig.isMutexInit = 1;
162   if( !sqlite3GlobalConfig.isMallocInit ){
163     rc = sqlite3MallocInit();
164   }
165   if( rc==SQLITE_OK ){
166     sqlite3GlobalConfig.isMallocInit = 1;
167     if( !sqlite3GlobalConfig.pInitMutex ){
168       sqlite3GlobalConfig.pInitMutex =
169            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
170       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
171         rc = SQLITE_NOMEM;
172       }
173     }
174   }
175   if( rc==SQLITE_OK ){
176     sqlite3GlobalConfig.nRefInitMutex++;
177   }
178   sqlite3_mutex_leave(pMaster);
179 
180   /* If rc is not SQLITE_OK at this point, then either the malloc
181   ** subsystem could not be initialized or the system failed to allocate
182   ** the pInitMutex mutex. Return an error in either case.  */
183   if( rc!=SQLITE_OK ){
184     return rc;
185   }
186 
187   /* Do the rest of the initialization under the recursive mutex so
188   ** that we will be able to handle recursive calls into
189   ** sqlite3_initialize().  The recursive calls normally come through
190   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
191   ** recursive calls might also be possible.
192   **
193   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
194   ** to the xInit method, so the xInit method need not be threadsafe.
195   **
196   ** The following mutex is what serializes access to the appdef pcache xInit
197   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
198   ** call to sqlite3PcacheInitialize().
199   */
200   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
201   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
202     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
203     sqlite3GlobalConfig.inProgress = 1;
204     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
205     sqlite3RegisterGlobalFunctions();
206     if( sqlite3GlobalConfig.isPCacheInit==0 ){
207       rc = sqlite3PcacheInitialize();
208     }
209     if( rc==SQLITE_OK ){
210       sqlite3GlobalConfig.isPCacheInit = 1;
211       rc = sqlite3OsInit();
212     }
213     if( rc==SQLITE_OK ){
214       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
215           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
216       sqlite3GlobalConfig.isInit = 1;
217     }
218     sqlite3GlobalConfig.inProgress = 0;
219   }
220   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
221 
222   /* Go back under the static mutex and clean up the recursive
223   ** mutex to prevent a resource leak.
224   */
225   sqlite3_mutex_enter(pMaster);
226   sqlite3GlobalConfig.nRefInitMutex--;
227   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
228     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
229     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
230     sqlite3GlobalConfig.pInitMutex = 0;
231   }
232   sqlite3_mutex_leave(pMaster);
233 
234   /* The following is just a sanity check to make sure SQLite has
235   ** been compiled correctly.  It is important to run this code, but
236   ** we don't want to run it too often and soak up CPU cycles for no
237   ** reason.  So we run it once during initialization.
238   */
239 #ifndef NDEBUG
240 #ifndef SQLITE_OMIT_FLOATING_POINT
241   /* This section of code's only "output" is via assert() statements. */
242   if ( rc==SQLITE_OK ){
243     u64 x = (((u64)1)<<63)-1;
244     double y;
245     assert(sizeof(x)==8);
246     assert(sizeof(x)==sizeof(y));
247     memcpy(&y, &x, 8);
248     assert( sqlite3IsNaN(y) );
249   }
250 #endif
251 #endif
252 
253   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
254   ** compile-time option.
255   */
256 #ifdef SQLITE_EXTRA_INIT
257   if( rc==SQLITE_OK && sqlite3GlobalConfig.isInit ){
258     int SQLITE_EXTRA_INIT(const char*);
259     rc = SQLITE_EXTRA_INIT(0);
260   }
261 #endif
262 
263   return rc;
264 }
265 
266 /*
267 ** Undo the effects of sqlite3_initialize().  Must not be called while
268 ** there are outstanding database connections or memory allocations or
269 ** while any part of SQLite is otherwise in use in any thread.  This
270 ** routine is not threadsafe.  But it is safe to invoke this routine
271 ** on when SQLite is already shut down.  If SQLite is already shut down
272 ** when this routine is invoked, then this routine is a harmless no-op.
273 */
274 int sqlite3_shutdown(void){
275   if( sqlite3GlobalConfig.isInit ){
276 #ifdef SQLITE_EXTRA_SHUTDOWN
277     void SQLITE_EXTRA_SHUTDOWN(void);
278     SQLITE_EXTRA_SHUTDOWN();
279 #endif
280     sqlite3_os_end();
281     sqlite3_reset_auto_extension();
282     sqlite3GlobalConfig.isInit = 0;
283   }
284   if( sqlite3GlobalConfig.isPCacheInit ){
285     sqlite3PcacheShutdown();
286     sqlite3GlobalConfig.isPCacheInit = 0;
287   }
288   if( sqlite3GlobalConfig.isMallocInit ){
289     sqlite3MallocEnd();
290     sqlite3GlobalConfig.isMallocInit = 0;
291 
292 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
293     /* The heap subsystem has now been shutdown and these values are supposed
294     ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
295     ** which would rely on that heap subsystem; therefore, make sure these
296     ** values cannot refer to heap memory that was just invalidated when the
297     ** heap subsystem was shutdown.  This is only done if the current call to
298     ** this function resulted in the heap subsystem actually being shutdown.
299     */
300     sqlite3_data_directory = 0;
301     sqlite3_temp_directory = 0;
302 #endif
303   }
304   if( sqlite3GlobalConfig.isMutexInit ){
305     sqlite3MutexEnd();
306     sqlite3GlobalConfig.isMutexInit = 0;
307   }
308 
309   return SQLITE_OK;
310 }
311 
312 /*
313 ** This API allows applications to modify the global configuration of
314 ** the SQLite library at run-time.
315 **
316 ** This routine should only be called when there are no outstanding
317 ** database connections or memory allocations.  This routine is not
318 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
319 ** behavior.
320 */
321 int sqlite3_config(int op, ...){
322   va_list ap;
323   int rc = SQLITE_OK;
324 
325   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
326   ** the SQLite library is in use. */
327   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
328 
329   va_start(ap, op);
330   switch( op ){
331 
332     /* Mutex configuration options are only available in a threadsafe
333     ** compile.
334     */
335 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
336     case SQLITE_CONFIG_SINGLETHREAD: {
337       /* Disable all mutexing */
338       sqlite3GlobalConfig.bCoreMutex = 0;
339       sqlite3GlobalConfig.bFullMutex = 0;
340       break;
341     }
342     case SQLITE_CONFIG_MULTITHREAD: {
343       /* Disable mutexing of database connections */
344       /* Enable mutexing of core data structures */
345       sqlite3GlobalConfig.bCoreMutex = 1;
346       sqlite3GlobalConfig.bFullMutex = 0;
347       break;
348     }
349     case SQLITE_CONFIG_SERIALIZED: {
350       /* Enable all mutexing */
351       sqlite3GlobalConfig.bCoreMutex = 1;
352       sqlite3GlobalConfig.bFullMutex = 1;
353       break;
354     }
355     case SQLITE_CONFIG_MUTEX: {
356       /* Specify an alternative mutex implementation */
357       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
358       break;
359     }
360     case SQLITE_CONFIG_GETMUTEX: {
361       /* Retrieve the current mutex implementation */
362       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
363       break;
364     }
365 #endif
366 
367 
368     case SQLITE_CONFIG_MALLOC: {
369       /* Specify an alternative malloc implementation */
370       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
371       break;
372     }
373     case SQLITE_CONFIG_GETMALLOC: {
374       /* Retrieve the current malloc() implementation */
375       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
376       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
377       break;
378     }
379     case SQLITE_CONFIG_MEMSTATUS: {
380       /* Enable or disable the malloc status collection */
381       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
382       break;
383     }
384     case SQLITE_CONFIG_SCRATCH: {
385       /* Designate a buffer for scratch memory space */
386       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
387       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
388       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
389       break;
390     }
391     case SQLITE_CONFIG_PAGECACHE: {
392       /* Designate a buffer for page cache memory space */
393       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
394       sqlite3GlobalConfig.szPage = va_arg(ap, int);
395       sqlite3GlobalConfig.nPage = va_arg(ap, int);
396       break;
397     }
398 
399     case SQLITE_CONFIG_PCACHE: {
400       /* no-op */
401       break;
402     }
403     case SQLITE_CONFIG_GETPCACHE: {
404       /* now an error */
405       rc = SQLITE_ERROR;
406       break;
407     }
408 
409     case SQLITE_CONFIG_PCACHE2: {
410       /* Specify an alternative page cache implementation */
411       sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
412       break;
413     }
414     case SQLITE_CONFIG_GETPCACHE2: {
415       if( sqlite3GlobalConfig.pcache2.xInit==0 ){
416         sqlite3PCacheSetDefault();
417       }
418       *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
419       break;
420     }
421 
422 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
423     case SQLITE_CONFIG_HEAP: {
424       /* Designate a buffer for heap memory space */
425       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
426       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
427       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
428 
429       if( sqlite3GlobalConfig.mnReq<1 ){
430         sqlite3GlobalConfig.mnReq = 1;
431       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
432         /* cap min request size at 2^12 */
433         sqlite3GlobalConfig.mnReq = (1<<12);
434       }
435 
436       if( sqlite3GlobalConfig.pHeap==0 ){
437         /* If the heap pointer is NULL, then restore the malloc implementation
438         ** back to NULL pointers too.  This will cause the malloc to go
439         ** back to its default implementation when sqlite3_initialize() is
440         ** run.
441         */
442         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
443       }else{
444         /* The heap pointer is not NULL, then install one of the
445         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
446         ** ENABLE_MEMSYS5 is defined, return an error.
447         */
448 #ifdef SQLITE_ENABLE_MEMSYS3
449         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
450 #endif
451 #ifdef SQLITE_ENABLE_MEMSYS5
452         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
453 #endif
454       }
455       break;
456     }
457 #endif
458 
459     case SQLITE_CONFIG_LOOKASIDE: {
460       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
461       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
462       break;
463     }
464 
465     /* Record a pointer to the logger funcction and its first argument.
466     ** The default is NULL.  Logging is disabled if the function pointer is
467     ** NULL.
468     */
469     case SQLITE_CONFIG_LOG: {
470       /* MSVC is picky about pulling func ptrs from va lists.
471       ** http://support.microsoft.com/kb/47961
472       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
473       */
474       typedef void(*LOGFUNC_t)(void*,int,const char*);
475       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
476       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
477       break;
478     }
479 
480     case SQLITE_CONFIG_URI: {
481       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
482       break;
483     }
484 
485     case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
486       sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
487       break;
488     }
489 
490 #ifdef SQLITE_ENABLE_SQLLOG
491     case SQLITE_CONFIG_SQLLOG: {
492       typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
493       sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
494       sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
495       break;
496     }
497 #endif
498 
499     default: {
500       rc = SQLITE_ERROR;
501       break;
502     }
503   }
504   va_end(ap);
505   return rc;
506 }
507 
508 /*
509 ** Set up the lookaside buffers for a database connection.
510 ** Return SQLITE_OK on success.
511 ** If lookaside is already active, return SQLITE_BUSY.
512 **
513 ** The sz parameter is the number of bytes in each lookaside slot.
514 ** The cnt parameter is the number of slots.  If pStart is NULL the
515 ** space for the lookaside memory is obtained from sqlite3_malloc().
516 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
517 ** the lookaside memory.
518 */
519 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
520   void *pStart;
521   if( db->lookaside.nOut ){
522     return SQLITE_BUSY;
523   }
524   /* Free any existing lookaside buffer for this handle before
525   ** allocating a new one so we don't have to have space for
526   ** both at the same time.
527   */
528   if( db->lookaside.bMalloced ){
529     sqlite3_free(db->lookaside.pStart);
530   }
531   /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
532   ** than a pointer to be useful.
533   */
534   sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
535   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
536   if( cnt<0 ) cnt = 0;
537   if( sz==0 || cnt==0 ){
538     sz = 0;
539     pStart = 0;
540   }else if( pBuf==0 ){
541     sqlite3BeginBenignMalloc();
542     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
543     sqlite3EndBenignMalloc();
544     if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
545   }else{
546     pStart = pBuf;
547   }
548   db->lookaside.pStart = pStart;
549   db->lookaside.pFree = 0;
550   db->lookaside.sz = (u16)sz;
551   if( pStart ){
552     int i;
553     LookasideSlot *p;
554     assert( sz > (int)sizeof(LookasideSlot*) );
555     p = (LookasideSlot*)pStart;
556     for(i=cnt-1; i>=0; i--){
557       p->pNext = db->lookaside.pFree;
558       db->lookaside.pFree = p;
559       p = (LookasideSlot*)&((u8*)p)[sz];
560     }
561     db->lookaside.pEnd = p;
562     db->lookaside.bEnabled = 1;
563     db->lookaside.bMalloced = pBuf==0 ?1:0;
564   }else{
565     db->lookaside.pEnd = 0;
566     db->lookaside.bEnabled = 0;
567     db->lookaside.bMalloced = 0;
568   }
569   return SQLITE_OK;
570 }
571 
572 /*
573 ** Return the mutex associated with a database connection.
574 */
575 sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
576   return db->mutex;
577 }
578 
579 /*
580 ** Free up as much memory as we can from the given database
581 ** connection.
582 */
583 int sqlite3_db_release_memory(sqlite3 *db){
584   int i;
585   sqlite3_mutex_enter(db->mutex);
586   sqlite3BtreeEnterAll(db);
587   for(i=0; i<db->nDb; i++){
588     Btree *pBt = db->aDb[i].pBt;
589     if( pBt ){
590       Pager *pPager = sqlite3BtreePager(pBt);
591       sqlite3PagerShrink(pPager);
592     }
593   }
594   sqlite3BtreeLeaveAll(db);
595   sqlite3_mutex_leave(db->mutex);
596   return SQLITE_OK;
597 }
598 
599 /*
600 ** Configuration settings for an individual database connection
601 */
602 int sqlite3_db_config(sqlite3 *db, int op, ...){
603   va_list ap;
604   int rc;
605   va_start(ap, op);
606   switch( op ){
607     case SQLITE_DBCONFIG_LOOKASIDE: {
608       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
609       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
610       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
611       rc = setupLookaside(db, pBuf, sz, cnt);
612       break;
613     }
614     default: {
615       static const struct {
616         int op;      /* The opcode */
617         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
618       } aFlagOp[] = {
619         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
620         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
621       };
622       unsigned int i;
623       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
624       for(i=0; i<ArraySize(aFlagOp); i++){
625         if( aFlagOp[i].op==op ){
626           int onoff = va_arg(ap, int);
627           int *pRes = va_arg(ap, int*);
628           int oldFlags = db->flags;
629           if( onoff>0 ){
630             db->flags |= aFlagOp[i].mask;
631           }else if( onoff==0 ){
632             db->flags &= ~aFlagOp[i].mask;
633           }
634           if( oldFlags!=db->flags ){
635             sqlite3ExpirePreparedStatements(db);
636           }
637           if( pRes ){
638             *pRes = (db->flags & aFlagOp[i].mask)!=0;
639           }
640           rc = SQLITE_OK;
641           break;
642         }
643       }
644       break;
645     }
646   }
647   va_end(ap);
648   return rc;
649 }
650 
651 
652 /*
653 ** Return true if the buffer z[0..n-1] contains all spaces.
654 */
655 static int allSpaces(const char *z, int n){
656   while( n>0 && z[n-1]==' ' ){ n--; }
657   return n==0;
658 }
659 
660 /*
661 ** This is the default collating function named "BINARY" which is always
662 ** available.
663 **
664 ** If the padFlag argument is not NULL then space padding at the end
665 ** of strings is ignored.  This implements the RTRIM collation.
666 */
667 static int binCollFunc(
668   void *padFlag,
669   int nKey1, const void *pKey1,
670   int nKey2, const void *pKey2
671 ){
672   int rc, n;
673   n = nKey1<nKey2 ? nKey1 : nKey2;
674   rc = memcmp(pKey1, pKey2, n);
675   if( rc==0 ){
676     if( padFlag
677      && allSpaces(((char*)pKey1)+n, nKey1-n)
678      && allSpaces(((char*)pKey2)+n, nKey2-n)
679     ){
680       /* Leave rc unchanged at 0 */
681     }else{
682       rc = nKey1 - nKey2;
683     }
684   }
685   return rc;
686 }
687 
688 /*
689 ** Another built-in collating sequence: NOCASE.
690 **
691 ** This collating sequence is intended to be used for "case independant
692 ** comparison". SQLite's knowledge of upper and lower case equivalents
693 ** extends only to the 26 characters used in the English language.
694 **
695 ** At the moment there is only a UTF-8 implementation.
696 */
697 static int nocaseCollatingFunc(
698   void *NotUsed,
699   int nKey1, const void *pKey1,
700   int nKey2, const void *pKey2
701 ){
702   int r = sqlite3StrNICmp(
703       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
704   UNUSED_PARAMETER(NotUsed);
705   if( 0==r ){
706     r = nKey1-nKey2;
707   }
708   return r;
709 }
710 
711 /*
712 ** Return the ROWID of the most recent insert
713 */
714 sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
715   return db->lastRowid;
716 }
717 
718 /*
719 ** Return the number of changes in the most recent call to sqlite3_exec().
720 */
721 int sqlite3_changes(sqlite3 *db){
722   return db->nChange;
723 }
724 
725 /*
726 ** Return the number of changes since the database handle was opened.
727 */
728 int sqlite3_total_changes(sqlite3 *db){
729   return db->nTotalChange;
730 }
731 
732 /*
733 ** Close all open savepoints. This function only manipulates fields of the
734 ** database handle object, it does not close any savepoints that may be open
735 ** at the b-tree/pager level.
736 */
737 void sqlite3CloseSavepoints(sqlite3 *db){
738   while( db->pSavepoint ){
739     Savepoint *pTmp = db->pSavepoint;
740     db->pSavepoint = pTmp->pNext;
741     sqlite3DbFree(db, pTmp);
742   }
743   db->nSavepoint = 0;
744   db->nStatement = 0;
745   db->isTransactionSavepoint = 0;
746 }
747 
748 /*
749 ** Invoke the destructor function associated with FuncDef p, if any. Except,
750 ** if this is not the last copy of the function, do not invoke it. Multiple
751 ** copies of a single function are created when create_function() is called
752 ** with SQLITE_ANY as the encoding.
753 */
754 static void functionDestroy(sqlite3 *db, FuncDef *p){
755   FuncDestructor *pDestructor = p->pDestructor;
756   if( pDestructor ){
757     pDestructor->nRef--;
758     if( pDestructor->nRef==0 ){
759       pDestructor->xDestroy(pDestructor->pUserData);
760       sqlite3DbFree(db, pDestructor);
761     }
762   }
763 }
764 
765 /*
766 ** Disconnect all sqlite3_vtab objects that belong to database connection
767 ** db. This is called when db is being closed.
768 */
769 static void disconnectAllVtab(sqlite3 *db){
770 #ifndef SQLITE_OMIT_VIRTUALTABLE
771   int i;
772   sqlite3BtreeEnterAll(db);
773   for(i=0; i<db->nDb; i++){
774     Schema *pSchema = db->aDb[i].pSchema;
775     if( db->aDb[i].pSchema ){
776       HashElem *p;
777       for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
778         Table *pTab = (Table *)sqliteHashData(p);
779         if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
780       }
781     }
782   }
783   sqlite3BtreeLeaveAll(db);
784 #else
785   UNUSED_PARAMETER(db);
786 #endif
787 }
788 
789 /*
790 ** Return TRUE if database connection db has unfinalized prepared
791 ** statements or unfinished sqlite3_backup objects.
792 */
793 static int connectionIsBusy(sqlite3 *db){
794   int j;
795   assert( sqlite3_mutex_held(db->mutex) );
796   if( db->pVdbe ) return 1;
797   for(j=0; j<db->nDb; j++){
798     Btree *pBt = db->aDb[j].pBt;
799     if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
800   }
801   return 0;
802 }
803 
804 /*
805 ** Close an existing SQLite database
806 */
807 static int sqlite3Close(sqlite3 *db, int forceZombie){
808   if( !db ){
809     return SQLITE_OK;
810   }
811   if( !sqlite3SafetyCheckSickOrOk(db) ){
812     return SQLITE_MISUSE_BKPT;
813   }
814   sqlite3_mutex_enter(db->mutex);
815 
816   /* Force xDisconnect calls on all virtual tables */
817   disconnectAllVtab(db);
818 
819   /* If a transaction is open, the disconnectAllVtab() call above
820   ** will not have called the xDisconnect() method on any virtual
821   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
822   ** call will do so. We need to do this before the check for active
823   ** SQL statements below, as the v-table implementation may be storing
824   ** some prepared statements internally.
825   */
826   sqlite3VtabRollback(db);
827 
828   /* Legacy behavior (sqlite3_close() behavior) is to return
829   ** SQLITE_BUSY if the connection can not be closed immediately.
830   */
831   if( !forceZombie && connectionIsBusy(db) ){
832     sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
833        "statements or unfinished backups");
834     sqlite3_mutex_leave(db->mutex);
835     return SQLITE_BUSY;
836   }
837 
838 #ifdef SQLITE_ENABLE_SQLLOG
839   if( sqlite3GlobalConfig.xSqllog ){
840     /* Closing the handle. Fourth parameter is passed the value 2. */
841     sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
842   }
843 #endif
844 
845   /* Convert the connection into a zombie and then close it.
846   */
847   db->magic = SQLITE_MAGIC_ZOMBIE;
848   sqlite3LeaveMutexAndCloseZombie(db);
849   return SQLITE_OK;
850 }
851 
852 /*
853 ** Two variations on the public interface for closing a database
854 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
855 ** leaves the connection option if there are unfinalized prepared
856 ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
857 ** version forces the connection to become a zombie if there are
858 ** unclosed resources, and arranges for deallocation when the last
859 ** prepare statement or sqlite3_backup closes.
860 */
861 int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
862 int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
863 
864 
865 /*
866 ** Close the mutex on database connection db.
867 **
868 ** Furthermore, if database connection db is a zombie (meaning that there
869 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
870 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
871 ** finished, then free all resources.
872 */
873 void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
874   HashElem *i;                    /* Hash table iterator */
875   int j;
876 
877   /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
878   ** or if the connection has not yet been closed by sqlite3_close_v2(),
879   ** then just leave the mutex and return.
880   */
881   if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
882     sqlite3_mutex_leave(db->mutex);
883     return;
884   }
885 
886   /* If we reach this point, it means that the database connection has
887   ** closed all sqlite3_stmt and sqlite3_backup objects and has been
888   ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
889   ** go ahead and free all resources.
890   */
891 
892   /* Free any outstanding Savepoint structures. */
893   sqlite3CloseSavepoints(db);
894 
895   /* Close all database connections */
896   for(j=0; j<db->nDb; j++){
897     struct Db *pDb = &db->aDb[j];
898     if( pDb->pBt ){
899       sqlite3BtreeClose(pDb->pBt);
900       pDb->pBt = 0;
901       if( j!=1 ){
902         pDb->pSchema = 0;
903       }
904     }
905   }
906   /* Clear the TEMP schema separately and last */
907   if( db->aDb[1].pSchema ){
908     sqlite3SchemaClear(db->aDb[1].pSchema);
909   }
910   sqlite3VtabUnlockList(db);
911 
912   /* Free up the array of auxiliary databases */
913   sqlite3CollapseDatabaseArray(db);
914   assert( db->nDb<=2 );
915   assert( db->aDb==db->aDbStatic );
916 
917   /* Tell the code in notify.c that the connection no longer holds any
918   ** locks and does not require any further unlock-notify callbacks.
919   */
920   sqlite3ConnectionClosed(db);
921 
922   for(j=0; j<ArraySize(db->aFunc.a); j++){
923     FuncDef *pNext, *pHash, *p;
924     for(p=db->aFunc.a[j]; p; p=pHash){
925       pHash = p->pHash;
926       while( p ){
927         functionDestroy(db, p);
928         pNext = p->pNext;
929         sqlite3DbFree(db, p);
930         p = pNext;
931       }
932     }
933   }
934   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
935     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
936     /* Invoke any destructors registered for collation sequence user data. */
937     for(j=0; j<3; j++){
938       if( pColl[j].xDel ){
939         pColl[j].xDel(pColl[j].pUser);
940       }
941     }
942     sqlite3DbFree(db, pColl);
943   }
944   sqlite3HashClear(&db->aCollSeq);
945 #ifndef SQLITE_OMIT_VIRTUALTABLE
946   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
947     Module *pMod = (Module *)sqliteHashData(i);
948     if( pMod->xDestroy ){
949       pMod->xDestroy(pMod->pAux);
950     }
951     sqlite3DbFree(db, pMod);
952   }
953   sqlite3HashClear(&db->aModule);
954 #endif
955 
956   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
957   if( db->pErr ){
958     sqlite3ValueFree(db->pErr);
959   }
960   sqlite3CloseExtensions(db);
961 
962   db->magic = SQLITE_MAGIC_ERROR;
963 
964   /* The temp-database schema is allocated differently from the other schema
965   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
966   ** So it needs to be freed here. Todo: Why not roll the temp schema into
967   ** the same sqliteMalloc() as the one that allocates the database
968   ** structure?
969   */
970   sqlite3DbFree(db, db->aDb[1].pSchema);
971   sqlite3_mutex_leave(db->mutex);
972   db->magic = SQLITE_MAGIC_CLOSED;
973   sqlite3_mutex_free(db->mutex);
974   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
975   if( db->lookaside.bMalloced ){
976     sqlite3_free(db->lookaside.pStart);
977   }
978   sqlite3_free(db);
979 }
980 
981 /*
982 ** Rollback all database files.  If tripCode is not SQLITE_OK, then
983 ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
984 ** breaker") and made to return tripCode if there are any further
985 ** attempts to use that cursor.
986 */
987 void sqlite3RollbackAll(sqlite3 *db, int tripCode){
988   int i;
989   int inTrans = 0;
990   assert( sqlite3_mutex_held(db->mutex) );
991   sqlite3BeginBenignMalloc();
992   for(i=0; i<db->nDb; i++){
993     Btree *p = db->aDb[i].pBt;
994     if( p ){
995       if( sqlite3BtreeIsInTrans(p) ){
996         inTrans = 1;
997       }
998       sqlite3BtreeRollback(p, tripCode);
999       db->aDb[i].inTrans = 0;
1000     }
1001   }
1002   sqlite3VtabRollback(db);
1003   sqlite3EndBenignMalloc();
1004 
1005   if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
1006     sqlite3ExpirePreparedStatements(db);
1007     sqlite3ResetAllSchemasOfConnection(db);
1008   }
1009 
1010   /* Any deferred constraint violations have now been resolved. */
1011   db->nDeferredCons = 0;
1012 
1013   /* If one has been configured, invoke the rollback-hook callback */
1014   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
1015     db->xRollbackCallback(db->pRollbackArg);
1016   }
1017 }
1018 
1019 /*
1020 ** Return a static string that describes the kind of error specified in the
1021 ** argument.
1022 */
1023 const char *sqlite3ErrStr(int rc){
1024   static const char* const aMsg[] = {
1025     /* SQLITE_OK          */ "not an error",
1026     /* SQLITE_ERROR       */ "SQL logic error or missing database",
1027     /* SQLITE_INTERNAL    */ 0,
1028     /* SQLITE_PERM        */ "access permission denied",
1029     /* SQLITE_ABORT       */ "callback requested query abort",
1030     /* SQLITE_BUSY        */ "database is locked",
1031     /* SQLITE_LOCKED      */ "database table is locked",
1032     /* SQLITE_NOMEM       */ "out of memory",
1033     /* SQLITE_READONLY    */ "attempt to write a readonly database",
1034     /* SQLITE_INTERRUPT   */ "interrupted",
1035     /* SQLITE_IOERR       */ "disk I/O error",
1036     /* SQLITE_CORRUPT     */ "database disk image is malformed",
1037     /* SQLITE_NOTFOUND    */ "unknown operation",
1038     /* SQLITE_FULL        */ "database or disk is full",
1039     /* SQLITE_CANTOPEN    */ "unable to open database file",
1040     /* SQLITE_PROTOCOL    */ "locking protocol",
1041     /* SQLITE_EMPTY       */ "table contains no data",
1042     /* SQLITE_SCHEMA      */ "database schema has changed",
1043     /* SQLITE_TOOBIG      */ "string or blob too big",
1044     /* SQLITE_CONSTRAINT  */ "constraint failed",
1045     /* SQLITE_MISMATCH    */ "datatype mismatch",
1046     /* SQLITE_MISUSE      */ "library routine called out of sequence",
1047     /* SQLITE_NOLFS       */ "large file support is disabled",
1048     /* SQLITE_AUTH        */ "authorization denied",
1049     /* SQLITE_FORMAT      */ "auxiliary database format error",
1050     /* SQLITE_RANGE       */ "bind or column index out of range",
1051     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
1052   };
1053   const char *zErr = "unknown error";
1054   switch( rc ){
1055     case SQLITE_ABORT_ROLLBACK: {
1056       zErr = "abort due to ROLLBACK";
1057       break;
1058     }
1059     default: {
1060       rc &= 0xff;
1061       if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
1062         zErr = aMsg[rc];
1063       }
1064       break;
1065     }
1066   }
1067   return zErr;
1068 }
1069 
1070 /*
1071 ** This routine implements a busy callback that sleeps and tries
1072 ** again until a timeout value is reached.  The timeout value is
1073 ** an integer number of milliseconds passed in as the first
1074 ** argument.
1075 */
1076 static int sqliteDefaultBusyCallback(
1077  void *ptr,               /* Database connection */
1078  int count                /* Number of times table has been busy */
1079 ){
1080 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
1081   static const u8 delays[] =
1082      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
1083   static const u8 totals[] =
1084      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
1085 # define NDELAY ArraySize(delays)
1086   sqlite3 *db = (sqlite3 *)ptr;
1087   int timeout = db->busyTimeout;
1088   int delay, prior;
1089 
1090   assert( count>=0 );
1091   if( count < NDELAY ){
1092     delay = delays[count];
1093     prior = totals[count];
1094   }else{
1095     delay = delays[NDELAY-1];
1096     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
1097   }
1098   if( prior + delay > timeout ){
1099     delay = timeout - prior;
1100     if( delay<=0 ) return 0;
1101   }
1102   sqlite3OsSleep(db->pVfs, delay*1000);
1103   return 1;
1104 #else
1105   sqlite3 *db = (sqlite3 *)ptr;
1106   int timeout = ((sqlite3 *)ptr)->busyTimeout;
1107   if( (count+1)*1000 > timeout ){
1108     return 0;
1109   }
1110   sqlite3OsSleep(db->pVfs, 1000000);
1111   return 1;
1112 #endif
1113 }
1114 
1115 /*
1116 ** Invoke the given busy handler.
1117 **
1118 ** This routine is called when an operation failed with a lock.
1119 ** If this routine returns non-zero, the lock is retried.  If it
1120 ** returns 0, the operation aborts with an SQLITE_BUSY error.
1121 */
1122 int sqlite3InvokeBusyHandler(BusyHandler *p){
1123   int rc;
1124   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
1125   rc = p->xFunc(p->pArg, p->nBusy);
1126   if( rc==0 ){
1127     p->nBusy = -1;
1128   }else{
1129     p->nBusy++;
1130   }
1131   return rc;
1132 }
1133 
1134 /*
1135 ** This routine sets the busy callback for an Sqlite database to the
1136 ** given callback function with the given argument.
1137 */
1138 int sqlite3_busy_handler(
1139   sqlite3 *db,
1140   int (*xBusy)(void*,int),
1141   void *pArg
1142 ){
1143   sqlite3_mutex_enter(db->mutex);
1144   db->busyHandler.xFunc = xBusy;
1145   db->busyHandler.pArg = pArg;
1146   db->busyHandler.nBusy = 0;
1147   db->busyTimeout = 0;
1148   sqlite3_mutex_leave(db->mutex);
1149   return SQLITE_OK;
1150 }
1151 
1152 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1153 /*
1154 ** This routine sets the progress callback for an Sqlite database to the
1155 ** given callback function with the given argument. The progress callback will
1156 ** be invoked every nOps opcodes.
1157 */
1158 void sqlite3_progress_handler(
1159   sqlite3 *db,
1160   int nOps,
1161   int (*xProgress)(void*),
1162   void *pArg
1163 ){
1164   sqlite3_mutex_enter(db->mutex);
1165   if( nOps>0 ){
1166     db->xProgress = xProgress;
1167     db->nProgressOps = nOps;
1168     db->pProgressArg = pArg;
1169   }else{
1170     db->xProgress = 0;
1171     db->nProgressOps = 0;
1172     db->pProgressArg = 0;
1173   }
1174   sqlite3_mutex_leave(db->mutex);
1175 }
1176 #endif
1177 
1178 
1179 /*
1180 ** This routine installs a default busy handler that waits for the
1181 ** specified number of milliseconds before returning 0.
1182 */
1183 int sqlite3_busy_timeout(sqlite3 *db, int ms){
1184   if( ms>0 ){
1185     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
1186     db->busyTimeout = ms;
1187   }else{
1188     sqlite3_busy_handler(db, 0, 0);
1189   }
1190   return SQLITE_OK;
1191 }
1192 
1193 /*
1194 ** Cause any pending operation to stop at its earliest opportunity.
1195 */
1196 void sqlite3_interrupt(sqlite3 *db){
1197   db->u1.isInterrupted = 1;
1198 }
1199 
1200 
1201 /*
1202 ** This function is exactly the same as sqlite3_create_function(), except
1203 ** that it is designed to be called by internal code. The difference is
1204 ** that if a malloc() fails in sqlite3_create_function(), an error code
1205 ** is returned and the mallocFailed flag cleared.
1206 */
1207 int sqlite3CreateFunc(
1208   sqlite3 *db,
1209   const char *zFunctionName,
1210   int nArg,
1211   int enc,
1212   void *pUserData,
1213   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
1214   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
1215   void (*xFinal)(sqlite3_context*),
1216   FuncDestructor *pDestructor
1217 ){
1218   FuncDef *p;
1219   int nName;
1220 
1221   assert( sqlite3_mutex_held(db->mutex) );
1222   if( zFunctionName==0 ||
1223       (xFunc && (xFinal || xStep)) ||
1224       (!xFunc && (xFinal && !xStep)) ||
1225       (!xFunc && (!xFinal && xStep)) ||
1226       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
1227       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
1228     return SQLITE_MISUSE_BKPT;
1229   }
1230 
1231 #ifndef SQLITE_OMIT_UTF16
1232   /* If SQLITE_UTF16 is specified as the encoding type, transform this
1233   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
1234   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
1235   **
1236   ** If SQLITE_ANY is specified, add three versions of the function
1237   ** to the hash table.
1238   */
1239   if( enc==SQLITE_UTF16 ){
1240     enc = SQLITE_UTF16NATIVE;
1241   }else if( enc==SQLITE_ANY ){
1242     int rc;
1243     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
1244          pUserData, xFunc, xStep, xFinal, pDestructor);
1245     if( rc==SQLITE_OK ){
1246       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
1247           pUserData, xFunc, xStep, xFinal, pDestructor);
1248     }
1249     if( rc!=SQLITE_OK ){
1250       return rc;
1251     }
1252     enc = SQLITE_UTF16BE;
1253   }
1254 #else
1255   enc = SQLITE_UTF8;
1256 #endif
1257 
1258   /* Check if an existing function is being overridden or deleted. If so,
1259   ** and there are active VMs, then return SQLITE_BUSY. If a function
1260   ** is being overridden/deleted but there are no active VMs, allow the
1261   ** operation to continue but invalidate all precompiled statements.
1262   */
1263   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
1264   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
1265     if( db->activeVdbeCnt ){
1266       sqlite3Error(db, SQLITE_BUSY,
1267         "unable to delete/modify user-function due to active statements");
1268       assert( !db->mallocFailed );
1269       return SQLITE_BUSY;
1270     }else{
1271       sqlite3ExpirePreparedStatements(db);
1272     }
1273   }
1274 
1275   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
1276   assert(p || db->mallocFailed);
1277   if( !p ){
1278     return SQLITE_NOMEM;
1279   }
1280 
1281   /* If an older version of the function with a configured destructor is
1282   ** being replaced invoke the destructor function here. */
1283   functionDestroy(db, p);
1284 
1285   if( pDestructor ){
1286     pDestructor->nRef++;
1287   }
1288   p->pDestructor = pDestructor;
1289   p->flags = 0;
1290   p->xFunc = xFunc;
1291   p->xStep = xStep;
1292   p->xFinalize = xFinal;
1293   p->pUserData = pUserData;
1294   p->nArg = (u16)nArg;
1295   return SQLITE_OK;
1296 }
1297 
1298 /*
1299 ** Create new user functions.
1300 */
1301 int sqlite3_create_function(
1302   sqlite3 *db,
1303   const char *zFunc,
1304   int nArg,
1305   int enc,
1306   void *p,
1307   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
1308   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
1309   void (*xFinal)(sqlite3_context*)
1310 ){
1311   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
1312                                     xFinal, 0);
1313 }
1314 
1315 int sqlite3_create_function_v2(
1316   sqlite3 *db,
1317   const char *zFunc,
1318   int nArg,
1319   int enc,
1320   void *p,
1321   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
1322   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
1323   void (*xFinal)(sqlite3_context*),
1324   void (*xDestroy)(void *)
1325 ){
1326   int rc = SQLITE_ERROR;
1327   FuncDestructor *pArg = 0;
1328   sqlite3_mutex_enter(db->mutex);
1329   if( xDestroy ){
1330     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
1331     if( !pArg ){
1332       xDestroy(p);
1333       goto out;
1334     }
1335     pArg->xDestroy = xDestroy;
1336     pArg->pUserData = p;
1337   }
1338   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
1339   if( pArg && pArg->nRef==0 ){
1340     assert( rc!=SQLITE_OK );
1341     xDestroy(p);
1342     sqlite3DbFree(db, pArg);
1343   }
1344 
1345  out:
1346   rc = sqlite3ApiExit(db, rc);
1347   sqlite3_mutex_leave(db->mutex);
1348   return rc;
1349 }
1350 
1351 #ifndef SQLITE_OMIT_UTF16
1352 int sqlite3_create_function16(
1353   sqlite3 *db,
1354   const void *zFunctionName,
1355   int nArg,
1356   int eTextRep,
1357   void *p,
1358   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
1359   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
1360   void (*xFinal)(sqlite3_context*)
1361 ){
1362   int rc;
1363   char *zFunc8;
1364   sqlite3_mutex_enter(db->mutex);
1365   assert( !db->mallocFailed );
1366   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
1367   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
1368   sqlite3DbFree(db, zFunc8);
1369   rc = sqlite3ApiExit(db, rc);
1370   sqlite3_mutex_leave(db->mutex);
1371   return rc;
1372 }
1373 #endif
1374 
1375 
1376 /*
1377 ** Declare that a function has been overloaded by a virtual table.
1378 **
1379 ** If the function already exists as a regular global function, then
1380 ** this routine is a no-op.  If the function does not exist, then create
1381 ** a new one that always throws a run-time error.
1382 **
1383 ** When virtual tables intend to provide an overloaded function, they
1384 ** should call this routine to make sure the global function exists.
1385 ** A global function must exist in order for name resolution to work
1386 ** properly.
1387 */
1388 int sqlite3_overload_function(
1389   sqlite3 *db,
1390   const char *zName,
1391   int nArg
1392 ){
1393   int nName = sqlite3Strlen30(zName);
1394   int rc = SQLITE_OK;
1395   sqlite3_mutex_enter(db->mutex);
1396   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
1397     rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
1398                            0, sqlite3InvalidFunction, 0, 0, 0);
1399   }
1400   rc = sqlite3ApiExit(db, rc);
1401   sqlite3_mutex_leave(db->mutex);
1402   return rc;
1403 }
1404 
1405 #ifndef SQLITE_OMIT_TRACE
1406 /*
1407 ** Register a trace function.  The pArg from the previously registered trace
1408 ** is returned.
1409 **
1410 ** A NULL trace function means that no tracing is executes.  A non-NULL
1411 ** trace is a pointer to a function that is invoked at the start of each
1412 ** SQL statement.
1413 */
1414 void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
1415   void *pOld;
1416   sqlite3_mutex_enter(db->mutex);
1417   pOld = db->pTraceArg;
1418   db->xTrace = xTrace;
1419   db->pTraceArg = pArg;
1420   sqlite3_mutex_leave(db->mutex);
1421   return pOld;
1422 }
1423 /*
1424 ** Register a profile function.  The pArg from the previously registered
1425 ** profile function is returned.
1426 **
1427 ** A NULL profile function means that no profiling is executes.  A non-NULL
1428 ** profile is a pointer to a function that is invoked at the conclusion of
1429 ** each SQL statement that is run.
1430 */
1431 void *sqlite3_profile(
1432   sqlite3 *db,
1433   void (*xProfile)(void*,const char*,sqlite_uint64),
1434   void *pArg
1435 ){
1436   void *pOld;
1437   sqlite3_mutex_enter(db->mutex);
1438   pOld = db->pProfileArg;
1439   db->xProfile = xProfile;
1440   db->pProfileArg = pArg;
1441   sqlite3_mutex_leave(db->mutex);
1442   return pOld;
1443 }
1444 #endif /* SQLITE_OMIT_TRACE */
1445 
1446 /*
1447 ** Register a function to be invoked when a transaction commits.
1448 ** If the invoked function returns non-zero, then the commit becomes a
1449 ** rollback.
1450 */
1451 void *sqlite3_commit_hook(
1452   sqlite3 *db,              /* Attach the hook to this database */
1453   int (*xCallback)(void*),  /* Function to invoke on each commit */
1454   void *pArg                /* Argument to the function */
1455 ){
1456   void *pOld;
1457   sqlite3_mutex_enter(db->mutex);
1458   pOld = db->pCommitArg;
1459   db->xCommitCallback = xCallback;
1460   db->pCommitArg = pArg;
1461   sqlite3_mutex_leave(db->mutex);
1462   return pOld;
1463 }
1464 
1465 /*
1466 ** Register a callback to be invoked each time a row is updated,
1467 ** inserted or deleted using this database connection.
1468 */
1469 void *sqlite3_update_hook(
1470   sqlite3 *db,              /* Attach the hook to this database */
1471   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
1472   void *pArg                /* Argument to the function */
1473 ){
1474   void *pRet;
1475   sqlite3_mutex_enter(db->mutex);
1476   pRet = db->pUpdateArg;
1477   db->xUpdateCallback = xCallback;
1478   db->pUpdateArg = pArg;
1479   sqlite3_mutex_leave(db->mutex);
1480   return pRet;
1481 }
1482 
1483 /*
1484 ** Register a callback to be invoked each time a transaction is rolled
1485 ** back by this database connection.
1486 */
1487 void *sqlite3_rollback_hook(
1488   sqlite3 *db,              /* Attach the hook to this database */
1489   void (*xCallback)(void*), /* Callback function */
1490   void *pArg                /* Argument to the function */
1491 ){
1492   void *pRet;
1493   sqlite3_mutex_enter(db->mutex);
1494   pRet = db->pRollbackArg;
1495   db->xRollbackCallback = xCallback;
1496   db->pRollbackArg = pArg;
1497   sqlite3_mutex_leave(db->mutex);
1498   return pRet;
1499 }
1500 
1501 #ifndef SQLITE_OMIT_WAL
1502 /*
1503 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
1504 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
1505 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
1506 ** wal_autocheckpoint()).
1507 */
1508 int sqlite3WalDefaultHook(
1509   void *pClientData,     /* Argument */
1510   sqlite3 *db,           /* Connection */
1511   const char *zDb,       /* Database */
1512   int nFrame             /* Size of WAL */
1513 ){
1514   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
1515     sqlite3BeginBenignMalloc();
1516     sqlite3_wal_checkpoint(db, zDb);
1517     sqlite3EndBenignMalloc();
1518   }
1519   return SQLITE_OK;
1520 }
1521 #endif /* SQLITE_OMIT_WAL */
1522 
1523 /*
1524 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
1525 ** a database after committing a transaction if there are nFrame or
1526 ** more frames in the log file. Passing zero or a negative value as the
1527 ** nFrame parameter disables automatic checkpoints entirely.
1528 **
1529 ** The callback registered by this function replaces any existing callback
1530 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
1531 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
1532 ** configured by this function.
1533 */
1534 int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
1535 #ifdef SQLITE_OMIT_WAL
1536   UNUSED_PARAMETER(db);
1537   UNUSED_PARAMETER(nFrame);
1538 #else
1539   if( nFrame>0 ){
1540     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
1541   }else{
1542     sqlite3_wal_hook(db, 0, 0);
1543   }
1544 #endif
1545   return SQLITE_OK;
1546 }
1547 
1548 /*
1549 ** Register a callback to be invoked each time a transaction is written
1550 ** into the write-ahead-log by this database connection.
1551 */
1552 void *sqlite3_wal_hook(
1553   sqlite3 *db,                    /* Attach the hook to this db handle */
1554   int(*xCallback)(void *, sqlite3*, const char*, int),
1555   void *pArg                      /* First argument passed to xCallback() */
1556 ){
1557 #ifndef SQLITE_OMIT_WAL
1558   void *pRet;
1559   sqlite3_mutex_enter(db->mutex);
1560   pRet = db->pWalArg;
1561   db->xWalCallback = xCallback;
1562   db->pWalArg = pArg;
1563   sqlite3_mutex_leave(db->mutex);
1564   return pRet;
1565 #else
1566   return 0;
1567 #endif
1568 }
1569 
1570 /*
1571 ** Checkpoint database zDb.
1572 */
1573 int sqlite3_wal_checkpoint_v2(
1574   sqlite3 *db,                    /* Database handle */
1575   const char *zDb,                /* Name of attached database (or NULL) */
1576   int eMode,                      /* SQLITE_CHECKPOINT_* value */
1577   int *pnLog,                     /* OUT: Size of WAL log in frames */
1578   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
1579 ){
1580 #ifdef SQLITE_OMIT_WAL
1581   return SQLITE_OK;
1582 #else
1583   int rc;                         /* Return code */
1584   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
1585 
1586   /* Initialize the output variables to -1 in case an error occurs. */
1587   if( pnLog ) *pnLog = -1;
1588   if( pnCkpt ) *pnCkpt = -1;
1589 
1590   assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
1591   assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
1592   assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
1593   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
1594     return SQLITE_MISUSE;
1595   }
1596 
1597   sqlite3_mutex_enter(db->mutex);
1598   if( zDb && zDb[0] ){
1599     iDb = sqlite3FindDbName(db, zDb);
1600   }
1601   if( iDb<0 ){
1602     rc = SQLITE_ERROR;
1603     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
1604   }else{
1605     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
1606     sqlite3Error(db, rc, 0);
1607   }
1608   rc = sqlite3ApiExit(db, rc);
1609   sqlite3_mutex_leave(db->mutex);
1610   return rc;
1611 #endif
1612 }
1613 
1614 
1615 /*
1616 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
1617 ** to contains a zero-length string, all attached databases are
1618 ** checkpointed.
1619 */
1620 int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
1621   return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
1622 }
1623 
1624 #ifndef SQLITE_OMIT_WAL
1625 /*
1626 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
1627 ** not currently open in WAL mode.
1628 **
1629 ** If a transaction is open on the database being checkpointed, this
1630 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
1631 ** an error occurs while running the checkpoint, an SQLite error code is
1632 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
1633 **
1634 ** The mutex on database handle db should be held by the caller. The mutex
1635 ** associated with the specific b-tree being checkpointed is taken by
1636 ** this function while the checkpoint is running.
1637 **
1638 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
1639 ** checkpointed. If an error is encountered it is returned immediately -
1640 ** no attempt is made to checkpoint any remaining databases.
1641 **
1642 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
1643 */
1644 int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
1645   int rc = SQLITE_OK;             /* Return code */
1646   int i;                          /* Used to iterate through attached dbs */
1647   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
1648 
1649   assert( sqlite3_mutex_held(db->mutex) );
1650   assert( !pnLog || *pnLog==-1 );
1651   assert( !pnCkpt || *pnCkpt==-1 );
1652 
1653   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
1654     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
1655       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
1656       pnLog = 0;
1657       pnCkpt = 0;
1658       if( rc==SQLITE_BUSY ){
1659         bBusy = 1;
1660         rc = SQLITE_OK;
1661       }
1662     }
1663   }
1664 
1665   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
1666 }
1667 #endif /* SQLITE_OMIT_WAL */
1668 
1669 /*
1670 ** This function returns true if main-memory should be used instead of
1671 ** a temporary file for transient pager files and statement journals.
1672 ** The value returned depends on the value of db->temp_store (runtime
1673 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
1674 ** following table describes the relationship between these two values
1675 ** and this functions return value.
1676 **
1677 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
1678 **   -----------------     --------------     ------------------------------
1679 **   0                     any                file      (return 0)
1680 **   1                     1                  file      (return 0)
1681 **   1                     2                  memory    (return 1)
1682 **   1                     0                  file      (return 0)
1683 **   2                     1                  file      (return 0)
1684 **   2                     2                  memory    (return 1)
1685 **   2                     0                  memory    (return 1)
1686 **   3                     any                memory    (return 1)
1687 */
1688 int sqlite3TempInMemory(const sqlite3 *db){
1689 #if SQLITE_TEMP_STORE==1
1690   return ( db->temp_store==2 );
1691 #endif
1692 #if SQLITE_TEMP_STORE==2
1693   return ( db->temp_store!=1 );
1694 #endif
1695 #if SQLITE_TEMP_STORE==3
1696   return 1;
1697 #endif
1698 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
1699   return 0;
1700 #endif
1701 }
1702 
1703 /*
1704 ** Return UTF-8 encoded English language explanation of the most recent
1705 ** error.
1706 */
1707 const char *sqlite3_errmsg(sqlite3 *db){
1708   const char *z;
1709   if( !db ){
1710     return sqlite3ErrStr(SQLITE_NOMEM);
1711   }
1712   if( !sqlite3SafetyCheckSickOrOk(db) ){
1713     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
1714   }
1715   sqlite3_mutex_enter(db->mutex);
1716   if( db->mallocFailed ){
1717     z = sqlite3ErrStr(SQLITE_NOMEM);
1718   }else{
1719     z = (char*)sqlite3_value_text(db->pErr);
1720     assert( !db->mallocFailed );
1721     if( z==0 ){
1722       z = sqlite3ErrStr(db->errCode);
1723     }
1724   }
1725   sqlite3_mutex_leave(db->mutex);
1726   return z;
1727 }
1728 
1729 #ifndef SQLITE_OMIT_UTF16
1730 /*
1731 ** Return UTF-16 encoded English language explanation of the most recent
1732 ** error.
1733 */
1734 const void *sqlite3_errmsg16(sqlite3 *db){
1735   static const u16 outOfMem[] = {
1736     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
1737   };
1738   static const u16 misuse[] = {
1739     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
1740     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
1741     'c', 'a', 'l', 'l', 'e', 'd', ' ',
1742     'o', 'u', 't', ' ',
1743     'o', 'f', ' ',
1744     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
1745   };
1746 
1747   const void *z;
1748   if( !db ){
1749     return (void *)outOfMem;
1750   }
1751   if( !sqlite3SafetyCheckSickOrOk(db) ){
1752     return (void *)misuse;
1753   }
1754   sqlite3_mutex_enter(db->mutex);
1755   if( db->mallocFailed ){
1756     z = (void *)outOfMem;
1757   }else{
1758     z = sqlite3_value_text16(db->pErr);
1759     if( z==0 ){
1760       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
1761            SQLITE_UTF8, SQLITE_STATIC);
1762       z = sqlite3_value_text16(db->pErr);
1763     }
1764     /* A malloc() may have failed within the call to sqlite3_value_text16()
1765     ** above. If this is the case, then the db->mallocFailed flag needs to
1766     ** be cleared before returning. Do this directly, instead of via
1767     ** sqlite3ApiExit(), to avoid setting the database handle error message.
1768     */
1769     db->mallocFailed = 0;
1770   }
1771   sqlite3_mutex_leave(db->mutex);
1772   return z;
1773 }
1774 #endif /* SQLITE_OMIT_UTF16 */
1775 
1776 /*
1777 ** Return the most recent error code generated by an SQLite routine. If NULL is
1778 ** passed to this function, we assume a malloc() failed during sqlite3_open().
1779 */
1780 int sqlite3_errcode(sqlite3 *db){
1781   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
1782     return SQLITE_MISUSE_BKPT;
1783   }
1784   if( !db || db->mallocFailed ){
1785     return SQLITE_NOMEM;
1786   }
1787   return db->errCode & db->errMask;
1788 }
1789 int sqlite3_extended_errcode(sqlite3 *db){
1790   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
1791     return SQLITE_MISUSE_BKPT;
1792   }
1793   if( !db || db->mallocFailed ){
1794     return SQLITE_NOMEM;
1795   }
1796   return db->errCode;
1797 }
1798 
1799 /*
1800 ** Return a string that describes the kind of error specified in the
1801 ** argument.  For now, this simply calls the internal sqlite3ErrStr()
1802 ** function.
1803 */
1804 const char *sqlite3_errstr(int rc){
1805   return sqlite3ErrStr(rc);
1806 }
1807 
1808 /*
1809 ** Create a new collating function for database "db".  The name is zName
1810 ** and the encoding is enc.
1811 */
1812 static int createCollation(
1813   sqlite3* db,
1814   const char *zName,
1815   u8 enc,
1816   void* pCtx,
1817   int(*xCompare)(void*,int,const void*,int,const void*),
1818   void(*xDel)(void*)
1819 ){
1820   CollSeq *pColl;
1821   int enc2;
1822   int nName = sqlite3Strlen30(zName);
1823 
1824   assert( sqlite3_mutex_held(db->mutex) );
1825 
1826   /* If SQLITE_UTF16 is specified as the encoding type, transform this
1827   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
1828   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
1829   */
1830   enc2 = enc;
1831   testcase( enc2==SQLITE_UTF16 );
1832   testcase( enc2==SQLITE_UTF16_ALIGNED );
1833   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
1834     enc2 = SQLITE_UTF16NATIVE;
1835   }
1836   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
1837     return SQLITE_MISUSE_BKPT;
1838   }
1839 
1840   /* Check if this call is removing or replacing an existing collation
1841   ** sequence. If so, and there are active VMs, return busy. If there
1842   ** are no active VMs, invalidate any pre-compiled statements.
1843   */
1844   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
1845   if( pColl && pColl->xCmp ){
1846     if( db->activeVdbeCnt ){
1847       sqlite3Error(db, SQLITE_BUSY,
1848         "unable to delete/modify collation sequence due to active statements");
1849       return SQLITE_BUSY;
1850     }
1851     sqlite3ExpirePreparedStatements(db);
1852 
1853     /* If collation sequence pColl was created directly by a call to
1854     ** sqlite3_create_collation, and not generated by synthCollSeq(),
1855     ** then any copies made by synthCollSeq() need to be invalidated.
1856     ** Also, collation destructor - CollSeq.xDel() - function may need
1857     ** to be called.
1858     */
1859     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
1860       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
1861       int j;
1862       for(j=0; j<3; j++){
1863         CollSeq *p = &aColl[j];
1864         if( p->enc==pColl->enc ){
1865           if( p->xDel ){
1866             p->xDel(p->pUser);
1867           }
1868           p->xCmp = 0;
1869         }
1870       }
1871     }
1872   }
1873 
1874   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
1875   if( pColl==0 ) return SQLITE_NOMEM;
1876   pColl->xCmp = xCompare;
1877   pColl->pUser = pCtx;
1878   pColl->xDel = xDel;
1879   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
1880   sqlite3Error(db, SQLITE_OK, 0);
1881   return SQLITE_OK;
1882 }
1883 
1884 
1885 /*
1886 ** This array defines hard upper bounds on limit values.  The
1887 ** initializer must be kept in sync with the SQLITE_LIMIT_*
1888 ** #defines in sqlite3.h.
1889 */
1890 static const int aHardLimit[] = {
1891   SQLITE_MAX_LENGTH,
1892   SQLITE_MAX_SQL_LENGTH,
1893   SQLITE_MAX_COLUMN,
1894   SQLITE_MAX_EXPR_DEPTH,
1895   SQLITE_MAX_COMPOUND_SELECT,
1896   SQLITE_MAX_VDBE_OP,
1897   SQLITE_MAX_FUNCTION_ARG,
1898   SQLITE_MAX_ATTACHED,
1899   SQLITE_MAX_LIKE_PATTERN_LENGTH,
1900   SQLITE_MAX_VARIABLE_NUMBER,
1901   SQLITE_MAX_TRIGGER_DEPTH,
1902 };
1903 
1904 /*
1905 ** Make sure the hard limits are set to reasonable values
1906 */
1907 #if SQLITE_MAX_LENGTH<100
1908 # error SQLITE_MAX_LENGTH must be at least 100
1909 #endif
1910 #if SQLITE_MAX_SQL_LENGTH<100
1911 # error SQLITE_MAX_SQL_LENGTH must be at least 100
1912 #endif
1913 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
1914 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
1915 #endif
1916 #if SQLITE_MAX_COMPOUND_SELECT<2
1917 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
1918 #endif
1919 #if SQLITE_MAX_VDBE_OP<40
1920 # error SQLITE_MAX_VDBE_OP must be at least 40
1921 #endif
1922 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
1923 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
1924 #endif
1925 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
1926 # error SQLITE_MAX_ATTACHED must be between 0 and 62
1927 #endif
1928 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
1929 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
1930 #endif
1931 #if SQLITE_MAX_COLUMN>32767
1932 # error SQLITE_MAX_COLUMN must not exceed 32767
1933 #endif
1934 #if SQLITE_MAX_TRIGGER_DEPTH<1
1935 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
1936 #endif
1937 
1938 
1939 /*
1940 ** Change the value of a limit.  Report the old value.
1941 ** If an invalid limit index is supplied, report -1.
1942 ** Make no changes but still report the old value if the
1943 ** new limit is negative.
1944 **
1945 ** A new lower limit does not shrink existing constructs.
1946 ** It merely prevents new constructs that exceed the limit
1947 ** from forming.
1948 */
1949 int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
1950   int oldLimit;
1951 
1952 
1953   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
1954   ** there is a hard upper bound set at compile-time by a C preprocessor
1955   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
1956   ** "_MAX_".)
1957   */
1958   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
1959   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
1960   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
1961   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
1962   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
1963   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
1964   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
1965   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
1966   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
1967                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
1968   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
1969   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
1970   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
1971 
1972 
1973   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
1974     return -1;
1975   }
1976   oldLimit = db->aLimit[limitId];
1977   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
1978     if( newLimit>aHardLimit[limitId] ){
1979       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
1980     }
1981     db->aLimit[limitId] = newLimit;
1982   }
1983   return oldLimit;                     /* IMP: R-53341-35419 */
1984 }
1985 
1986 /*
1987 ** This function is used to parse both URIs and non-URI filenames passed by the
1988 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
1989 ** URIs specified as part of ATTACH statements.
1990 **
1991 ** The first argument to this function is the name of the VFS to use (or
1992 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
1993 ** query parameter. The second argument contains the URI (or non-URI filename)
1994 ** itself. When this function is called the *pFlags variable should contain
1995 ** the default flags to open the database handle with. The value stored in
1996 ** *pFlags may be updated before returning if the URI filename contains
1997 ** "cache=xxx" or "mode=xxx" query parameters.
1998 **
1999 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
2000 ** the VFS that should be used to open the database file. *pzFile is set to
2001 ** point to a buffer containing the name of the file to open. It is the
2002 ** responsibility of the caller to eventually call sqlite3_free() to release
2003 ** this buffer.
2004 **
2005 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
2006 ** may be set to point to a buffer containing an English language error
2007 ** message. It is the responsibility of the caller to eventually release
2008 ** this buffer by calling sqlite3_free().
2009 */
2010 int sqlite3ParseUri(
2011   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
2012   const char *zUri,               /* Nul-terminated URI to parse */
2013   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
2014   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
2015   char **pzFile,                  /* OUT: Filename component of URI */
2016   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
2017 ){
2018   int rc = SQLITE_OK;
2019   unsigned int flags = *pFlags;
2020   const char *zVfs = zDefaultVfs;
2021   char *zFile;
2022   char c;
2023   int nUri = sqlite3Strlen30(zUri);
2024 
2025   assert( *pzErrMsg==0 );
2026 
2027   if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
2028    && nUri>=5 && memcmp(zUri, "file:", 5)==0
2029   ){
2030     char *zOpt;
2031     int eState;                   /* Parser state when parsing URI */
2032     int iIn;                      /* Input character index */
2033     int iOut = 0;                 /* Output character index */
2034     int nByte = nUri+2;           /* Bytes of space to allocate */
2035 
2036     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
2037     ** method that there may be extra parameters following the file-name.  */
2038     flags |= SQLITE_OPEN_URI;
2039 
2040     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
2041     zFile = sqlite3_malloc(nByte);
2042     if( !zFile ) return SQLITE_NOMEM;
2043 
2044     /* Discard the scheme and authority segments of the URI. */
2045     if( zUri[5]=='/' && zUri[6]=='/' ){
2046       iIn = 7;
2047       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
2048 
2049       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
2050         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
2051             iIn-7, &zUri[7]);
2052         rc = SQLITE_ERROR;
2053         goto parse_uri_out;
2054       }
2055     }else{
2056       iIn = 5;
2057     }
2058 
2059     /* Copy the filename and any query parameters into the zFile buffer.
2060     ** Decode %HH escape codes along the way.
2061     **
2062     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
2063     ** on the parsing context. As follows:
2064     **
2065     **   0: Parsing file-name.
2066     **   1: Parsing name section of a name=value query parameter.
2067     **   2: Parsing value section of a name=value query parameter.
2068     */
2069     eState = 0;
2070     while( (c = zUri[iIn])!=0 && c!='#' ){
2071       iIn++;
2072       if( c=='%'
2073        && sqlite3Isxdigit(zUri[iIn])
2074        && sqlite3Isxdigit(zUri[iIn+1])
2075       ){
2076         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
2077         octet += sqlite3HexToInt(zUri[iIn++]);
2078 
2079         assert( octet>=0 && octet<256 );
2080         if( octet==0 ){
2081           /* This branch is taken when "%00" appears within the URI. In this
2082           ** case we ignore all text in the remainder of the path, name or
2083           ** value currently being parsed. So ignore the current character
2084           ** and skip to the next "?", "=" or "&", as appropriate. */
2085           while( (c = zUri[iIn])!=0 && c!='#'
2086               && (eState!=0 || c!='?')
2087               && (eState!=1 || (c!='=' && c!='&'))
2088               && (eState!=2 || c!='&')
2089           ){
2090             iIn++;
2091           }
2092           continue;
2093         }
2094         c = octet;
2095       }else if( eState==1 && (c=='&' || c=='=') ){
2096         if( zFile[iOut-1]==0 ){
2097           /* An empty option name. Ignore this option altogether. */
2098           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
2099           continue;
2100         }
2101         if( c=='&' ){
2102           zFile[iOut++] = '\0';
2103         }else{
2104           eState = 2;
2105         }
2106         c = 0;
2107       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
2108         c = 0;
2109         eState = 1;
2110       }
2111       zFile[iOut++] = c;
2112     }
2113     if( eState==1 ) zFile[iOut++] = '\0';
2114     zFile[iOut++] = '\0';
2115     zFile[iOut++] = '\0';
2116 
2117     /* Check if there were any options specified that should be interpreted
2118     ** here. Options that are interpreted here include "vfs" and those that
2119     ** correspond to flags that may be passed to the sqlite3_open_v2()
2120     ** method. */
2121     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
2122     while( zOpt[0] ){
2123       int nOpt = sqlite3Strlen30(zOpt);
2124       char *zVal = &zOpt[nOpt+1];
2125       int nVal = sqlite3Strlen30(zVal);
2126 
2127       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
2128         zVfs = zVal;
2129       }else{
2130         struct OpenMode {
2131           const char *z;
2132           int mode;
2133         } *aMode = 0;
2134         char *zModeType = 0;
2135         int mask = 0;
2136         int limit = 0;
2137 
2138         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
2139           static struct OpenMode aCacheMode[] = {
2140             { "shared",  SQLITE_OPEN_SHAREDCACHE },
2141             { "private", SQLITE_OPEN_PRIVATECACHE },
2142             { 0, 0 }
2143           };
2144 
2145           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
2146           aMode = aCacheMode;
2147           limit = mask;
2148           zModeType = "cache";
2149         }
2150         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
2151           static struct OpenMode aOpenMode[] = {
2152             { "ro",  SQLITE_OPEN_READONLY },
2153             { "rw",  SQLITE_OPEN_READWRITE },
2154             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
2155             { "memory", SQLITE_OPEN_MEMORY },
2156             { 0, 0 }
2157           };
2158 
2159           mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
2160                    | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
2161           aMode = aOpenMode;
2162           limit = mask & flags;
2163           zModeType = "access";
2164         }
2165 
2166         if( aMode ){
2167           int i;
2168           int mode = 0;
2169           for(i=0; aMode[i].z; i++){
2170             const char *z = aMode[i].z;
2171             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
2172               mode = aMode[i].mode;
2173               break;
2174             }
2175           }
2176           if( mode==0 ){
2177             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
2178             rc = SQLITE_ERROR;
2179             goto parse_uri_out;
2180           }
2181           if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
2182             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
2183                                         zModeType, zVal);
2184             rc = SQLITE_PERM;
2185             goto parse_uri_out;
2186           }
2187           flags = (flags & ~mask) | mode;
2188         }
2189       }
2190 
2191       zOpt = &zVal[nVal+1];
2192     }
2193 
2194   }else{
2195     zFile = sqlite3_malloc(nUri+2);
2196     if( !zFile ) return SQLITE_NOMEM;
2197     memcpy(zFile, zUri, nUri);
2198     zFile[nUri] = '\0';
2199     zFile[nUri+1] = '\0';
2200     flags &= ~SQLITE_OPEN_URI;
2201   }
2202 
2203   *ppVfs = sqlite3_vfs_find(zVfs);
2204   if( *ppVfs==0 ){
2205     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
2206     rc = SQLITE_ERROR;
2207   }
2208  parse_uri_out:
2209   if( rc!=SQLITE_OK ){
2210     sqlite3_free(zFile);
2211     zFile = 0;
2212   }
2213   *pFlags = flags;
2214   *pzFile = zFile;
2215   return rc;
2216 }
2217 
2218 
2219 /*
2220 ** This routine does the work of opening a database on behalf of
2221 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
2222 ** is UTF-8 encoded.
2223 */
2224 static int openDatabase(
2225   const char *zFilename, /* Database filename UTF-8 encoded */
2226   sqlite3 **ppDb,        /* OUT: Returned database handle */
2227   unsigned int flags,    /* Operational flags */
2228   const char *zVfs       /* Name of the VFS to use */
2229 ){
2230   sqlite3 *db;                    /* Store allocated handle here */
2231   int rc;                         /* Return code */
2232   int isThreadsafe;               /* True for threadsafe connections */
2233   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
2234   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
2235 
2236   *ppDb = 0;
2237 #ifndef SQLITE_OMIT_AUTOINIT
2238   rc = sqlite3_initialize();
2239   if( rc ) return rc;
2240 #endif
2241 
2242   /* Only allow sensible combinations of bits in the flags argument.
2243   ** Throw an error if any non-sense combination is used.  If we
2244   ** do not block illegal combinations here, it could trigger
2245   ** assert() statements in deeper layers.  Sensible combinations
2246   ** are:
2247   **
2248   **  1:  SQLITE_OPEN_READONLY
2249   **  2:  SQLITE_OPEN_READWRITE
2250   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
2251   */
2252   assert( SQLITE_OPEN_READONLY  == 0x01 );
2253   assert( SQLITE_OPEN_READWRITE == 0x02 );
2254   assert( SQLITE_OPEN_CREATE    == 0x04 );
2255   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
2256   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
2257   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
2258   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
2259 
2260   if( sqlite3GlobalConfig.bCoreMutex==0 ){
2261     isThreadsafe = 0;
2262   }else if( flags & SQLITE_OPEN_NOMUTEX ){
2263     isThreadsafe = 0;
2264   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
2265     isThreadsafe = 1;
2266   }else{
2267     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
2268   }
2269   if( flags & SQLITE_OPEN_PRIVATECACHE ){
2270     flags &= ~SQLITE_OPEN_SHAREDCACHE;
2271   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
2272     flags |= SQLITE_OPEN_SHAREDCACHE;
2273   }
2274 
2275   /* Remove harmful bits from the flags parameter
2276   **
2277   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
2278   ** dealt with in the previous code block.  Besides these, the only
2279   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
2280   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
2281   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
2282   ** off all other flags.
2283   */
2284   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
2285                SQLITE_OPEN_EXCLUSIVE |
2286                SQLITE_OPEN_MAIN_DB |
2287                SQLITE_OPEN_TEMP_DB |
2288                SQLITE_OPEN_TRANSIENT_DB |
2289                SQLITE_OPEN_MAIN_JOURNAL |
2290                SQLITE_OPEN_TEMP_JOURNAL |
2291                SQLITE_OPEN_SUBJOURNAL |
2292                SQLITE_OPEN_MASTER_JOURNAL |
2293                SQLITE_OPEN_NOMUTEX |
2294                SQLITE_OPEN_FULLMUTEX |
2295                SQLITE_OPEN_WAL
2296              );
2297 
2298   /* Allocate the sqlite data structure */
2299   db = sqlite3MallocZero( sizeof(sqlite3) );
2300   if( db==0 ) goto opendb_out;
2301   if( isThreadsafe ){
2302     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
2303     if( db->mutex==0 ){
2304       sqlite3_free(db);
2305       db = 0;
2306       goto opendb_out;
2307     }
2308   }
2309   sqlite3_mutex_enter(db->mutex);
2310   db->errMask = 0xff;
2311   db->nDb = 2;
2312   db->magic = SQLITE_MAGIC_BUSY;
2313   db->aDb = db->aDbStatic;
2314 
2315   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
2316   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
2317   db->autoCommit = 1;
2318   db->nextAutovac = -1;
2319   db->nextPagesize = 0;
2320   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
2321 #if SQLITE_DEFAULT_FILE_FORMAT<4
2322                  | SQLITE_LegacyFileFmt
2323 #endif
2324 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
2325                  | SQLITE_LoadExtension
2326 #endif
2327 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
2328                  | SQLITE_RecTriggers
2329 #endif
2330 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
2331                  | SQLITE_ForeignKeys
2332 #endif
2333       ;
2334   sqlite3HashInit(&db->aCollSeq);
2335 #ifndef SQLITE_OMIT_VIRTUALTABLE
2336   sqlite3HashInit(&db->aModule);
2337 #endif
2338 
2339   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
2340   ** and UTF-16, so add a version for each to avoid any unnecessary
2341   ** conversions. The only error that can occur here is a malloc() failure.
2342   */
2343   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
2344   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
2345   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
2346   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
2347   if( db->mallocFailed ){
2348     goto opendb_out;
2349   }
2350   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
2351   assert( db->pDfltColl!=0 );
2352 
2353   /* Also add a UTF-8 case-insensitive collation sequence. */
2354   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
2355 
2356   /* Parse the filename/URI argument. */
2357   db->openFlags = flags;
2358   rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
2359   if( rc!=SQLITE_OK ){
2360     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
2361     sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
2362     sqlite3_free(zErrMsg);
2363     goto opendb_out;
2364   }
2365 
2366   /* Open the backend database driver */
2367   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
2368                         flags | SQLITE_OPEN_MAIN_DB);
2369   if( rc!=SQLITE_OK ){
2370     if( rc==SQLITE_IOERR_NOMEM ){
2371       rc = SQLITE_NOMEM;
2372     }
2373     sqlite3Error(db, rc, 0);
2374     goto opendb_out;
2375   }
2376   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
2377   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
2378 
2379 
2380   /* The default safety_level for the main database is 'full'; for the temp
2381   ** database it is 'NONE'. This matches the pager layer defaults.
2382   */
2383   db->aDb[0].zName = "main";
2384   db->aDb[0].safety_level = 3;
2385   db->aDb[1].zName = "temp";
2386   db->aDb[1].safety_level = 1;
2387 
2388   db->magic = SQLITE_MAGIC_OPEN;
2389   if( db->mallocFailed ){
2390     goto opendb_out;
2391   }
2392 
2393   /* Register all built-in functions, but do not attempt to read the
2394   ** database schema yet. This is delayed until the first time the database
2395   ** is accessed.
2396   */
2397   sqlite3Error(db, SQLITE_OK, 0);
2398   sqlite3RegisterBuiltinFunctions(db);
2399 
2400   /* Load automatic extensions - extensions that have been registered
2401   ** using the sqlite3_automatic_extension() API.
2402   */
2403   rc = sqlite3_errcode(db);
2404   if( rc==SQLITE_OK ){
2405     sqlite3AutoLoadExtensions(db);
2406     rc = sqlite3_errcode(db);
2407     if( rc!=SQLITE_OK ){
2408       goto opendb_out;
2409     }
2410   }
2411 
2412 #ifdef SQLITE_ENABLE_FTS1
2413   if( !db->mallocFailed ){
2414     extern int sqlite3Fts1Init(sqlite3*);
2415     rc = sqlite3Fts1Init(db);
2416   }
2417 #endif
2418 
2419 #ifdef SQLITE_ENABLE_FTS2
2420   if( !db->mallocFailed && rc==SQLITE_OK ){
2421     extern int sqlite3Fts2Init(sqlite3*);
2422     rc = sqlite3Fts2Init(db);
2423   }
2424 #endif
2425 
2426 #ifdef SQLITE_ENABLE_FTS3
2427   if( !db->mallocFailed && rc==SQLITE_OK ){
2428     rc = sqlite3Fts3Init(db);
2429   }
2430 #endif
2431 
2432 #ifdef SQLITE_ENABLE_ICU
2433   if( !db->mallocFailed && rc==SQLITE_OK ){
2434     rc = sqlite3IcuInit(db);
2435   }
2436 #endif
2437 
2438 #ifdef SQLITE_ENABLE_RTREE
2439   if( !db->mallocFailed && rc==SQLITE_OK){
2440     rc = sqlite3RtreeInit(db);
2441   }
2442 #endif
2443 
2444   sqlite3Error(db, rc, 0);
2445 
2446   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
2447   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
2448   ** mode.  Doing nothing at all also makes NORMAL the default.
2449   */
2450 #ifdef SQLITE_DEFAULT_LOCKING_MODE
2451   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
2452   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
2453                           SQLITE_DEFAULT_LOCKING_MODE);
2454 #endif
2455 
2456   /* Enable the lookaside-malloc subsystem */
2457   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
2458                         sqlite3GlobalConfig.nLookaside);
2459 
2460   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
2461 
2462 opendb_out:
2463   sqlite3_free(zOpen);
2464   if( db ){
2465     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
2466     sqlite3_mutex_leave(db->mutex);
2467   }
2468   rc = sqlite3_errcode(db);
2469   assert( db!=0 || rc==SQLITE_NOMEM );
2470   if( rc==SQLITE_NOMEM ){
2471     sqlite3_close(db);
2472     db = 0;
2473   }else if( rc!=SQLITE_OK ){
2474     db->magic = SQLITE_MAGIC_SICK;
2475   }
2476   *ppDb = db;
2477 #ifdef SQLITE_ENABLE_SQLLOG
2478   if( sqlite3GlobalConfig.xSqllog ){
2479     /* Opening a db handle. Fourth parameter is passed 0. */
2480     void *pArg = sqlite3GlobalConfig.pSqllogArg;
2481     sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
2482   }
2483 #endif
2484   return sqlite3ApiExit(0, rc);
2485 }
2486 
2487 /*
2488 ** Open a new database handle.
2489 */
2490 int sqlite3_open(
2491   const char *zFilename,
2492   sqlite3 **ppDb
2493 ){
2494   return openDatabase(zFilename, ppDb,
2495                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
2496 }
2497 int sqlite3_open_v2(
2498   const char *filename,   /* Database filename (UTF-8) */
2499   sqlite3 **ppDb,         /* OUT: SQLite db handle */
2500   int flags,              /* Flags */
2501   const char *zVfs        /* Name of VFS module to use */
2502 ){
2503   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
2504 }
2505 
2506 #ifndef SQLITE_OMIT_UTF16
2507 /*
2508 ** Open a new database handle.
2509 */
2510 int sqlite3_open16(
2511   const void *zFilename,
2512   sqlite3 **ppDb
2513 ){
2514   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
2515   sqlite3_value *pVal;
2516   int rc;
2517 
2518   assert( zFilename );
2519   assert( ppDb );
2520   *ppDb = 0;
2521 #ifndef SQLITE_OMIT_AUTOINIT
2522   rc = sqlite3_initialize();
2523   if( rc ) return rc;
2524 #endif
2525   pVal = sqlite3ValueNew(0);
2526   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
2527   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
2528   if( zFilename8 ){
2529     rc = openDatabase(zFilename8, ppDb,
2530                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
2531     assert( *ppDb || rc==SQLITE_NOMEM );
2532     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
2533       ENC(*ppDb) = SQLITE_UTF16NATIVE;
2534     }
2535   }else{
2536     rc = SQLITE_NOMEM;
2537   }
2538   sqlite3ValueFree(pVal);
2539 
2540   return sqlite3ApiExit(0, rc);
2541 }
2542 #endif /* SQLITE_OMIT_UTF16 */
2543 
2544 /*
2545 ** Register a new collation sequence with the database handle db.
2546 */
2547 int sqlite3_create_collation(
2548   sqlite3* db,
2549   const char *zName,
2550   int enc,
2551   void* pCtx,
2552   int(*xCompare)(void*,int,const void*,int,const void*)
2553 ){
2554   int rc;
2555   sqlite3_mutex_enter(db->mutex);
2556   assert( !db->mallocFailed );
2557   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
2558   rc = sqlite3ApiExit(db, rc);
2559   sqlite3_mutex_leave(db->mutex);
2560   return rc;
2561 }
2562 
2563 /*
2564 ** Register a new collation sequence with the database handle db.
2565 */
2566 int sqlite3_create_collation_v2(
2567   sqlite3* db,
2568   const char *zName,
2569   int enc,
2570   void* pCtx,
2571   int(*xCompare)(void*,int,const void*,int,const void*),
2572   void(*xDel)(void*)
2573 ){
2574   int rc;
2575   sqlite3_mutex_enter(db->mutex);
2576   assert( !db->mallocFailed );
2577   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
2578   rc = sqlite3ApiExit(db, rc);
2579   sqlite3_mutex_leave(db->mutex);
2580   return rc;
2581 }
2582 
2583 #ifndef SQLITE_OMIT_UTF16
2584 /*
2585 ** Register a new collation sequence with the database handle db.
2586 */
2587 int sqlite3_create_collation16(
2588   sqlite3* db,
2589   const void *zName,
2590   int enc,
2591   void* pCtx,
2592   int(*xCompare)(void*,int,const void*,int,const void*)
2593 ){
2594   int rc = SQLITE_OK;
2595   char *zName8;
2596   sqlite3_mutex_enter(db->mutex);
2597   assert( !db->mallocFailed );
2598   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
2599   if( zName8 ){
2600     rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
2601     sqlite3DbFree(db, zName8);
2602   }
2603   rc = sqlite3ApiExit(db, rc);
2604   sqlite3_mutex_leave(db->mutex);
2605   return rc;
2606 }
2607 #endif /* SQLITE_OMIT_UTF16 */
2608 
2609 /*
2610 ** Register a collation sequence factory callback with the database handle
2611 ** db. Replace any previously installed collation sequence factory.
2612 */
2613 int sqlite3_collation_needed(
2614   sqlite3 *db,
2615   void *pCollNeededArg,
2616   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
2617 ){
2618   sqlite3_mutex_enter(db->mutex);
2619   db->xCollNeeded = xCollNeeded;
2620   db->xCollNeeded16 = 0;
2621   db->pCollNeededArg = pCollNeededArg;
2622   sqlite3_mutex_leave(db->mutex);
2623   return SQLITE_OK;
2624 }
2625 
2626 #ifndef SQLITE_OMIT_UTF16
2627 /*
2628 ** Register a collation sequence factory callback with the database handle
2629 ** db. Replace any previously installed collation sequence factory.
2630 */
2631 int sqlite3_collation_needed16(
2632   sqlite3 *db,
2633   void *pCollNeededArg,
2634   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
2635 ){
2636   sqlite3_mutex_enter(db->mutex);
2637   db->xCollNeeded = 0;
2638   db->xCollNeeded16 = xCollNeeded16;
2639   db->pCollNeededArg = pCollNeededArg;
2640   sqlite3_mutex_leave(db->mutex);
2641   return SQLITE_OK;
2642 }
2643 #endif /* SQLITE_OMIT_UTF16 */
2644 
2645 #ifndef SQLITE_OMIT_DEPRECATED
2646 /*
2647 ** This function is now an anachronism. It used to be used to recover from a
2648 ** malloc() failure, but SQLite now does this automatically.
2649 */
2650 int sqlite3_global_recover(void){
2651   return SQLITE_OK;
2652 }
2653 #endif
2654 
2655 /*
2656 ** Test to see whether or not the database connection is in autocommit
2657 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
2658 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
2659 ** by the next COMMIT or ROLLBACK.
2660 **
2661 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
2662 */
2663 int sqlite3_get_autocommit(sqlite3 *db){
2664   return db->autoCommit;
2665 }
2666 
2667 /*
2668 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
2669 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
2670 ** constants.  They server two purposes:
2671 **
2672 **   1.  Serve as a convenient place to set a breakpoint in a debugger
2673 **       to detect when version error conditions occurs.
2674 **
2675 **   2.  Invoke sqlite3_log() to provide the source code location where
2676 **       a low-level error is first detected.
2677 */
2678 int sqlite3CorruptError(int lineno){
2679   testcase( sqlite3GlobalConfig.xLog!=0 );
2680   sqlite3_log(SQLITE_CORRUPT,
2681               "database corruption at line %d of [%.10s]",
2682               lineno, 20+sqlite3_sourceid());
2683   return SQLITE_CORRUPT;
2684 }
2685 int sqlite3MisuseError(int lineno){
2686   testcase( sqlite3GlobalConfig.xLog!=0 );
2687   sqlite3_log(SQLITE_MISUSE,
2688               "misuse at line %d of [%.10s]",
2689               lineno, 20+sqlite3_sourceid());
2690   return SQLITE_MISUSE;
2691 }
2692 int sqlite3CantopenError(int lineno){
2693   testcase( sqlite3GlobalConfig.xLog!=0 );
2694   sqlite3_log(SQLITE_CANTOPEN,
2695               "cannot open file at line %d of [%.10s]",
2696               lineno, 20+sqlite3_sourceid());
2697   return SQLITE_CANTOPEN;
2698 }
2699 
2700 
2701 #ifndef SQLITE_OMIT_DEPRECATED
2702 /*
2703 ** This is a convenience routine that makes sure that all thread-specific
2704 ** data for this thread has been deallocated.
2705 **
2706 ** SQLite no longer uses thread-specific data so this routine is now a
2707 ** no-op.  It is retained for historical compatibility.
2708 */
2709 void sqlite3_thread_cleanup(void){
2710 }
2711 #endif
2712 
2713 /*
2714 ** Return meta information about a specific column of a database table.
2715 ** See comment in sqlite3.h (sqlite.h.in) for details.
2716 */
2717 #ifdef SQLITE_ENABLE_COLUMN_METADATA
2718 int sqlite3_table_column_metadata(
2719   sqlite3 *db,                /* Connection handle */
2720   const char *zDbName,        /* Database name or NULL */
2721   const char *zTableName,     /* Table name */
2722   const char *zColumnName,    /* Column name */
2723   char const **pzDataType,    /* OUTPUT: Declared data type */
2724   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
2725   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
2726   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
2727   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
2728 ){
2729   int rc;
2730   char *zErrMsg = 0;
2731   Table *pTab = 0;
2732   Column *pCol = 0;
2733   int iCol;
2734 
2735   char const *zDataType = 0;
2736   char const *zCollSeq = 0;
2737   int notnull = 0;
2738   int primarykey = 0;
2739   int autoinc = 0;
2740 
2741   /* Ensure the database schema has been loaded */
2742   sqlite3_mutex_enter(db->mutex);
2743   sqlite3BtreeEnterAll(db);
2744   rc = sqlite3Init(db, &zErrMsg);
2745   if( SQLITE_OK!=rc ){
2746     goto error_out;
2747   }
2748 
2749   /* Locate the table in question */
2750   pTab = sqlite3FindTable(db, zTableName, zDbName);
2751   if( !pTab || pTab->pSelect ){
2752     pTab = 0;
2753     goto error_out;
2754   }
2755 
2756   /* Find the column for which info is requested */
2757   if( sqlite3IsRowid(zColumnName) ){
2758     iCol = pTab->iPKey;
2759     if( iCol>=0 ){
2760       pCol = &pTab->aCol[iCol];
2761     }
2762   }else{
2763     for(iCol=0; iCol<pTab->nCol; iCol++){
2764       pCol = &pTab->aCol[iCol];
2765       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
2766         break;
2767       }
2768     }
2769     if( iCol==pTab->nCol ){
2770       pTab = 0;
2771       goto error_out;
2772     }
2773   }
2774 
2775   /* The following block stores the meta information that will be returned
2776   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
2777   ** and autoinc. At this point there are two possibilities:
2778   **
2779   **     1. The specified column name was rowid", "oid" or "_rowid_"
2780   **        and there is no explicitly declared IPK column.
2781   **
2782   **     2. The table is not a view and the column name identified an
2783   **        explicitly declared column. Copy meta information from *pCol.
2784   */
2785   if( pCol ){
2786     zDataType = pCol->zType;
2787     zCollSeq = pCol->zColl;
2788     notnull = pCol->notNull!=0;
2789     primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
2790     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
2791   }else{
2792     zDataType = "INTEGER";
2793     primarykey = 1;
2794   }
2795   if( !zCollSeq ){
2796     zCollSeq = "BINARY";
2797   }
2798 
2799 error_out:
2800   sqlite3BtreeLeaveAll(db);
2801 
2802   /* Whether the function call succeeded or failed, set the output parameters
2803   ** to whatever their local counterparts contain. If an error did occur,
2804   ** this has the effect of zeroing all output parameters.
2805   */
2806   if( pzDataType ) *pzDataType = zDataType;
2807   if( pzCollSeq ) *pzCollSeq = zCollSeq;
2808   if( pNotNull ) *pNotNull = notnull;
2809   if( pPrimaryKey ) *pPrimaryKey = primarykey;
2810   if( pAutoinc ) *pAutoinc = autoinc;
2811 
2812   if( SQLITE_OK==rc && !pTab ){
2813     sqlite3DbFree(db, zErrMsg);
2814     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
2815         zColumnName);
2816     rc = SQLITE_ERROR;
2817   }
2818   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
2819   sqlite3DbFree(db, zErrMsg);
2820   rc = sqlite3ApiExit(db, rc);
2821   sqlite3_mutex_leave(db->mutex);
2822   return rc;
2823 }
2824 #endif
2825 
2826 /*
2827 ** Sleep for a little while.  Return the amount of time slept.
2828 */
2829 int sqlite3_sleep(int ms){
2830   sqlite3_vfs *pVfs;
2831   int rc;
2832   pVfs = sqlite3_vfs_find(0);
2833   if( pVfs==0 ) return 0;
2834 
2835   /* This function works in milliseconds, but the underlying OsSleep()
2836   ** API uses microseconds. Hence the 1000's.
2837   */
2838   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
2839   return rc;
2840 }
2841 
2842 /*
2843 ** Enable or disable the extended result codes.
2844 */
2845 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
2846   sqlite3_mutex_enter(db->mutex);
2847   db->errMask = onoff ? 0xffffffff : 0xff;
2848   sqlite3_mutex_leave(db->mutex);
2849   return SQLITE_OK;
2850 }
2851 
2852 /*
2853 ** Invoke the xFileControl method on a particular database.
2854 */
2855 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
2856   int rc = SQLITE_ERROR;
2857   Btree *pBtree;
2858 
2859   sqlite3_mutex_enter(db->mutex);
2860   pBtree = sqlite3DbNameToBtree(db, zDbName);
2861   if( pBtree ){
2862     Pager *pPager;
2863     sqlite3_file *fd;
2864     sqlite3BtreeEnter(pBtree);
2865     pPager = sqlite3BtreePager(pBtree);
2866     assert( pPager!=0 );
2867     fd = sqlite3PagerFile(pPager);
2868     assert( fd!=0 );
2869     if( op==SQLITE_FCNTL_FILE_POINTER ){
2870       *(sqlite3_file**)pArg = fd;
2871       rc = SQLITE_OK;
2872     }else if( fd->pMethods ){
2873       rc = sqlite3OsFileControl(fd, op, pArg);
2874     }else{
2875       rc = SQLITE_NOTFOUND;
2876     }
2877     sqlite3BtreeLeave(pBtree);
2878   }
2879   sqlite3_mutex_leave(db->mutex);
2880   return rc;
2881 }
2882 
2883 /*
2884 ** Interface to the testing logic.
2885 */
2886 int sqlite3_test_control(int op, ...){
2887   int rc = 0;
2888 #ifndef SQLITE_OMIT_BUILTIN_TEST
2889   va_list ap;
2890   va_start(ap, op);
2891   switch( op ){
2892 
2893     /*
2894     ** Save the current state of the PRNG.
2895     */
2896     case SQLITE_TESTCTRL_PRNG_SAVE: {
2897       sqlite3PrngSaveState();
2898       break;
2899     }
2900 
2901     /*
2902     ** Restore the state of the PRNG to the last state saved using
2903     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
2904     ** this verb acts like PRNG_RESET.
2905     */
2906     case SQLITE_TESTCTRL_PRNG_RESTORE: {
2907       sqlite3PrngRestoreState();
2908       break;
2909     }
2910 
2911     /*
2912     ** Reset the PRNG back to its uninitialized state.  The next call
2913     ** to sqlite3_randomness() will reseed the PRNG using a single call
2914     ** to the xRandomness method of the default VFS.
2915     */
2916     case SQLITE_TESTCTRL_PRNG_RESET: {
2917       sqlite3PrngResetState();
2918       break;
2919     }
2920 
2921     /*
2922     **  sqlite3_test_control(BITVEC_TEST, size, program)
2923     **
2924     ** Run a test against a Bitvec object of size.  The program argument
2925     ** is an array of integers that defines the test.  Return -1 on a
2926     ** memory allocation error, 0 on success, or non-zero for an error.
2927     ** See the sqlite3BitvecBuiltinTest() for additional information.
2928     */
2929     case SQLITE_TESTCTRL_BITVEC_TEST: {
2930       int sz = va_arg(ap, int);
2931       int *aProg = va_arg(ap, int*);
2932       rc = sqlite3BitvecBuiltinTest(sz, aProg);
2933       break;
2934     }
2935 
2936     /*
2937     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
2938     **
2939     ** Register hooks to call to indicate which malloc() failures
2940     ** are benign.
2941     */
2942     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
2943       typedef void (*void_function)(void);
2944       void_function xBenignBegin;
2945       void_function xBenignEnd;
2946       xBenignBegin = va_arg(ap, void_function);
2947       xBenignEnd = va_arg(ap, void_function);
2948       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
2949       break;
2950     }
2951 
2952     /*
2953     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
2954     **
2955     ** Set the PENDING byte to the value in the argument, if X>0.
2956     ** Make no changes if X==0.  Return the value of the pending byte
2957     ** as it existing before this routine was called.
2958     **
2959     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
2960     ** an incompatible database file format.  Changing the PENDING byte
2961     ** while any database connection is open results in undefined and
2962     ** dileterious behavior.
2963     */
2964     case SQLITE_TESTCTRL_PENDING_BYTE: {
2965       rc = PENDING_BYTE;
2966 #ifndef SQLITE_OMIT_WSD
2967       {
2968         unsigned int newVal = va_arg(ap, unsigned int);
2969         if( newVal ) sqlite3PendingByte = newVal;
2970       }
2971 #endif
2972       break;
2973     }
2974 
2975     /*
2976     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
2977     **
2978     ** This action provides a run-time test to see whether or not
2979     ** assert() was enabled at compile-time.  If X is true and assert()
2980     ** is enabled, then the return value is true.  If X is true and
2981     ** assert() is disabled, then the return value is zero.  If X is
2982     ** false and assert() is enabled, then the assertion fires and the
2983     ** process aborts.  If X is false and assert() is disabled, then the
2984     ** return value is zero.
2985     */
2986     case SQLITE_TESTCTRL_ASSERT: {
2987       volatile int x = 0;
2988       assert( (x = va_arg(ap,int))!=0 );
2989       rc = x;
2990       break;
2991     }
2992 
2993 
2994     /*
2995     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
2996     **
2997     ** This action provides a run-time test to see how the ALWAYS and
2998     ** NEVER macros were defined at compile-time.
2999     **
3000     ** The return value is ALWAYS(X).
3001     **
3002     ** The recommended test is X==2.  If the return value is 2, that means
3003     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
3004     ** default setting.  If the return value is 1, then ALWAYS() is either
3005     ** hard-coded to true or else it asserts if its argument is false.
3006     ** The first behavior (hard-coded to true) is the case if
3007     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
3008     ** behavior (assert if the argument to ALWAYS() is false) is the case if
3009     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
3010     **
3011     ** The run-time test procedure might look something like this:
3012     **
3013     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
3014     **      // ALWAYS() and NEVER() are no-op pass-through macros
3015     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
3016     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
3017     **    }else{
3018     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
3019     **    }
3020     */
3021     case SQLITE_TESTCTRL_ALWAYS: {
3022       int x = va_arg(ap,int);
3023       rc = ALWAYS(x);
3024       break;
3025     }
3026 
3027     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
3028     **
3029     ** Set the nReserve size to N for the main database on the database
3030     ** connection db.
3031     */
3032     case SQLITE_TESTCTRL_RESERVE: {
3033       sqlite3 *db = va_arg(ap, sqlite3*);
3034       int x = va_arg(ap,int);
3035       sqlite3_mutex_enter(db->mutex);
3036       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
3037       sqlite3_mutex_leave(db->mutex);
3038       break;
3039     }
3040 
3041     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
3042     **
3043     ** Enable or disable various optimizations for testing purposes.  The
3044     ** argument N is a bitmask of optimizations to be disabled.  For normal
3045     ** operation N should be 0.  The idea is that a test program (like the
3046     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
3047     ** with various optimizations disabled to verify that the same answer
3048     ** is obtained in every case.
3049     */
3050     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
3051       sqlite3 *db = va_arg(ap, sqlite3*);
3052       db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
3053       break;
3054     }
3055 
3056 #ifdef SQLITE_N_KEYWORD
3057     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
3058     **
3059     ** If zWord is a keyword recognized by the parser, then return the
3060     ** number of keywords.  Or if zWord is not a keyword, return 0.
3061     **
3062     ** This test feature is only available in the amalgamation since
3063     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
3064     ** is built using separate source files.
3065     */
3066     case SQLITE_TESTCTRL_ISKEYWORD: {
3067       const char *zWord = va_arg(ap, const char*);
3068       int n = sqlite3Strlen30(zWord);
3069       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
3070       break;
3071     }
3072 #endif
3073 
3074     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
3075     **
3076     ** Pass pFree into sqlite3ScratchFree().
3077     ** If sz>0 then allocate a scratch buffer into pNew.
3078     */
3079     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
3080       void *pFree, **ppNew;
3081       int sz;
3082       sz = va_arg(ap, int);
3083       ppNew = va_arg(ap, void**);
3084       pFree = va_arg(ap, void*);
3085       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
3086       sqlite3ScratchFree(pFree);
3087       break;
3088     }
3089 
3090     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
3091     **
3092     ** If parameter onoff is non-zero, configure the wrappers so that all
3093     ** subsequent calls to localtime() and variants fail. If onoff is zero,
3094     ** undo this setting.
3095     */
3096     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
3097       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
3098       break;
3099     }
3100 
3101 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
3102     /*   sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
3103     **                        sqlite3_stmt*,const char**);
3104     **
3105     ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
3106     ** a string that describes the optimized parse tree.  This test-control
3107     ** returns a pointer to that string.
3108     */
3109     case SQLITE_TESTCTRL_EXPLAIN_STMT: {
3110       sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
3111       const char **pzRet = va_arg(ap, const char**);
3112       *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
3113       break;
3114     }
3115 #endif
3116 
3117   }
3118   va_end(ap);
3119 #endif /* SQLITE_OMIT_BUILTIN_TEST */
3120   return rc;
3121 }
3122 
3123 /*
3124 ** This is a utility routine, useful to VFS implementations, that checks
3125 ** to see if a database file was a URI that contained a specific query
3126 ** parameter, and if so obtains the value of the query parameter.
3127 **
3128 ** The zFilename argument is the filename pointer passed into the xOpen()
3129 ** method of a VFS implementation.  The zParam argument is the name of the
3130 ** query parameter we seek.  This routine returns the value of the zParam
3131 ** parameter if it exists.  If the parameter does not exist, this routine
3132 ** returns a NULL pointer.
3133 */
3134 const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
3135   if( zFilename==0 ) return 0;
3136   zFilename += sqlite3Strlen30(zFilename) + 1;
3137   while( zFilename[0] ){
3138     int x = strcmp(zFilename, zParam);
3139     zFilename += sqlite3Strlen30(zFilename) + 1;
3140     if( x==0 ) return zFilename;
3141     zFilename += sqlite3Strlen30(zFilename) + 1;
3142   }
3143   return 0;
3144 }
3145 
3146 /*
3147 ** Return a boolean value for a query parameter.
3148 */
3149 int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
3150   const char *z = sqlite3_uri_parameter(zFilename, zParam);
3151   bDflt = bDflt!=0;
3152   return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
3153 }
3154 
3155 /*
3156 ** Return a 64-bit integer value for a query parameter.
3157 */
3158 sqlite3_int64 sqlite3_uri_int64(
3159   const char *zFilename,    /* Filename as passed to xOpen */
3160   const char *zParam,       /* URI parameter sought */
3161   sqlite3_int64 bDflt       /* return if parameter is missing */
3162 ){
3163   const char *z = sqlite3_uri_parameter(zFilename, zParam);
3164   sqlite3_int64 v;
3165   if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
3166     bDflt = v;
3167   }
3168   return bDflt;
3169 }
3170 
3171 /*
3172 ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
3173 */
3174 Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
3175   int i;
3176   for(i=0; i<db->nDb; i++){
3177     if( db->aDb[i].pBt
3178      && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
3179     ){
3180       return db->aDb[i].pBt;
3181     }
3182   }
3183   return 0;
3184 }
3185 
3186 /*
3187 ** Return the filename of the database associated with a database
3188 ** connection.
3189 */
3190 const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
3191   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
3192   return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
3193 }
3194 
3195 /*
3196 ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
3197 ** no such database exists.
3198 */
3199 int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
3200   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
3201   return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
3202 }
3203