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