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