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