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