xref: /sqlite-3.40.0/src/main.c (revision c8e9f681)
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 #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
26 # include "sqliteicu.h"
27 #endif
28 
29 /*
30 ** This is an extension initializer that is a no-op and always
31 ** succeeds, except that it fails if the fault-simulation is set
32 ** to 500.
33 */
34 static int sqlite3TestExtInit(sqlite3 *db){
35   (void)db;
36   return sqlite3FaultSim(500);
37 }
38 
39 
40 /*
41 ** Forward declarations of external module initializer functions
42 ** for modules that need them.
43 */
44 #ifdef SQLITE_ENABLE_FTS1
45 int sqlite3Fts1Init(sqlite3*);
46 #endif
47 #ifdef SQLITE_ENABLE_FTS2
48 int sqlite3Fts2Init(sqlite3*);
49 #endif
50 #ifdef SQLITE_ENABLE_FTS5
51 int sqlite3Fts5Init(sqlite3*);
52 #endif
53 #ifdef SQLITE_ENABLE_STMTVTAB
54 int sqlite3StmtVtabInit(sqlite3*);
55 #endif
56 
57 /*
58 ** An array of pointers to extension initializer functions for
59 ** built-in extensions.
60 */
61 static int (*const sqlite3BuiltinExtensions[])(sqlite3*) = {
62 #ifdef SQLITE_ENABLE_FTS1
63   sqlite3Fts1Init,
64 #endif
65 #ifdef SQLITE_ENABLE_FTS2
66   sqlite3Fts2Init,
67 #endif
68 #ifdef SQLITE_ENABLE_FTS3
69   sqlite3Fts3Init,
70 #endif
71 #ifdef SQLITE_ENABLE_FTS5
72   sqlite3Fts5Init,
73 #endif
74 #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
75   sqlite3IcuInit,
76 #endif
77 #ifdef SQLITE_ENABLE_RTREE
78   sqlite3RtreeInit,
79 #endif
80 #ifdef SQLITE_ENABLE_DBPAGE_VTAB
81   sqlite3DbpageRegister,
82 #endif
83 #ifdef SQLITE_ENABLE_DBSTAT_VTAB
84   sqlite3DbstatRegister,
85 #endif
86   sqlite3TestExtInit,
87 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
88   sqlite3JsonTableFunctions,
89 #endif
90 #ifdef SQLITE_ENABLE_STMTVTAB
91   sqlite3StmtVtabInit,
92 #endif
93 #ifdef SQLITE_ENABLE_BYTECODE_VTAB
94   sqlite3VdbeBytecodeVtabInit,
95 #endif
96 };
97 
98 #ifndef SQLITE_AMALGAMATION
99 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
100 ** contains the text of SQLITE_VERSION macro.
101 */
102 const char sqlite3_version[] = SQLITE_VERSION;
103 #endif
104 
105 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
106 ** a pointer to the to the sqlite3_version[] string constant.
107 */
108 const char *sqlite3_libversion(void){ return sqlite3_version; }
109 
110 /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
111 ** pointer to a string constant whose value is the same as the
112 ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
113 ** an edited copy of the amalgamation, then the last four characters of
114 ** the hash might be different from SQLITE_SOURCE_ID.
115 */
116 const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
117 
118 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
119 ** returns an integer equal to SQLITE_VERSION_NUMBER.
120 */
121 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
122 
123 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
124 ** zero if and only if SQLite was compiled with mutexing code omitted due to
125 ** the SQLITE_THREADSAFE compile-time option being set to 0.
126 */
127 int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
128 
129 /*
130 ** When compiling the test fixture or with debugging enabled (on Win32),
131 ** this variable being set to non-zero will cause OSTRACE macros to emit
132 ** extra diagnostic information.
133 */
134 #ifdef SQLITE_HAVE_OS_TRACE
135 # ifndef SQLITE_DEBUG_OS_TRACE
136 #   define SQLITE_DEBUG_OS_TRACE 0
137 # endif
138   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
139 #endif
140 
141 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
142 /*
143 ** If the following function pointer is not NULL and if
144 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
145 ** I/O active are written using this function.  These messages
146 ** are intended for debugging activity only.
147 */
148 SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
149 #endif
150 
151 /*
152 ** If the following global variable points to a string which is the
153 ** name of a directory, then that directory will be used to store
154 ** temporary files.
155 **
156 ** See also the "PRAGMA temp_store_directory" SQL command.
157 */
158 char *sqlite3_temp_directory = 0;
159 
160 /*
161 ** If the following global variable points to a string which is the
162 ** name of a directory, then that directory will be used to store
163 ** all database files specified with a relative pathname.
164 **
165 ** See also the "PRAGMA data_store_directory" SQL command.
166 */
167 char *sqlite3_data_directory = 0;
168 
169 /*
170 ** Initialize SQLite.
171 **
172 ** This routine must be called to initialize the memory allocation,
173 ** VFS, and mutex subsystems prior to doing any serious work with
174 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
175 ** this routine will be called automatically by key routines such as
176 ** sqlite3_open().
177 **
178 ** This routine is a no-op except on its very first call for the process,
179 ** or for the first call after a call to sqlite3_shutdown.
180 **
181 ** The first thread to call this routine runs the initialization to
182 ** completion.  If subsequent threads call this routine before the first
183 ** thread has finished the initialization process, then the subsequent
184 ** threads must block until the first thread finishes with the initialization.
185 **
186 ** The first thread might call this routine recursively.  Recursive
187 ** calls to this routine should not block, of course.  Otherwise the
188 ** initialization process would never complete.
189 **
190 ** Let X be the first thread to enter this routine.  Let Y be some other
191 ** thread.  Then while the initial invocation of this routine by X is
192 ** incomplete, it is required that:
193 **
194 **    *  Calls to this routine from Y must block until the outer-most
195 **       call by X completes.
196 **
197 **    *  Recursive calls to this routine from thread X return immediately
198 **       without blocking.
199 */
200 int sqlite3_initialize(void){
201   MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )      /* The main static mutex */
202   int rc;                                      /* Result code */
203 #ifdef SQLITE_EXTRA_INIT
204   int bRunExtraInit = 0;                       /* Extra initialization needed */
205 #endif
206 
207 #ifdef SQLITE_OMIT_WSD
208   rc = sqlite3_wsd_init(4096, 24);
209   if( rc!=SQLITE_OK ){
210     return rc;
211   }
212 #endif
213 
214   /* If the following assert() fails on some obscure processor/compiler
215   ** combination, the work-around is to set the correct pointer
216   ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
217   assert( SQLITE_PTRSIZE==sizeof(char*) );
218 
219   /* If SQLite is already completely initialized, then this call
220   ** to sqlite3_initialize() should be a no-op.  But the initialization
221   ** must be complete.  So isInit must not be set until the very end
222   ** of this routine.
223   */
224   if( sqlite3GlobalConfig.isInit ){
225     sqlite3MemoryBarrier();
226     return SQLITE_OK;
227   }
228 
229   /* Make sure the mutex subsystem is initialized.  If unable to
230   ** initialize the mutex subsystem, return early with the error.
231   ** If the system is so sick that we are unable to allocate a mutex,
232   ** there is not much SQLite is going to be able to do.
233   **
234   ** The mutex subsystem must take care of serializing its own
235   ** initialization.
236   */
237   rc = sqlite3MutexInit();
238   if( rc ) return rc;
239 
240   /* Initialize the malloc() system and the recursive pInitMutex mutex.
241   ** This operation is protected by the STATIC_MAIN mutex.  Note that
242   ** MutexAlloc() is called for a static mutex prior to initializing the
243   ** malloc subsystem - this implies that the allocation of a static
244   ** mutex must not require support from the malloc subsystem.
245   */
246   MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
247   sqlite3_mutex_enter(pMainMtx);
248   sqlite3GlobalConfig.isMutexInit = 1;
249   if( !sqlite3GlobalConfig.isMallocInit ){
250     rc = sqlite3MallocInit();
251   }
252   if( rc==SQLITE_OK ){
253     sqlite3GlobalConfig.isMallocInit = 1;
254     if( !sqlite3GlobalConfig.pInitMutex ){
255       sqlite3GlobalConfig.pInitMutex =
256            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
257       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
258         rc = SQLITE_NOMEM_BKPT;
259       }
260     }
261   }
262   if( rc==SQLITE_OK ){
263     sqlite3GlobalConfig.nRefInitMutex++;
264   }
265   sqlite3_mutex_leave(pMainMtx);
266 
267   /* If rc is not SQLITE_OK at this point, then either the malloc
268   ** subsystem could not be initialized or the system failed to allocate
269   ** the pInitMutex mutex. Return an error in either case.  */
270   if( rc!=SQLITE_OK ){
271     return rc;
272   }
273 
274   /* Do the rest of the initialization under the recursive mutex so
275   ** that we will be able to handle recursive calls into
276   ** sqlite3_initialize().  The recursive calls normally come through
277   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
278   ** recursive calls might also be possible.
279   **
280   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
281   ** to the xInit method, so the xInit method need not be threadsafe.
282   **
283   ** The following mutex is what serializes access to the appdef pcache xInit
284   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
285   ** call to sqlite3PcacheInitialize().
286   */
287   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
288   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
289     sqlite3GlobalConfig.inProgress = 1;
290 #ifdef SQLITE_ENABLE_SQLLOG
291     {
292       extern void sqlite3_init_sqllog(void);
293       sqlite3_init_sqllog();
294     }
295 #endif
296     memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
297     sqlite3RegisterBuiltinFunctions();
298     if( sqlite3GlobalConfig.isPCacheInit==0 ){
299       rc = sqlite3PcacheInitialize();
300     }
301     if( rc==SQLITE_OK ){
302       sqlite3GlobalConfig.isPCacheInit = 1;
303       rc = sqlite3OsInit();
304     }
305 #ifndef SQLITE_OMIT_DESERIALIZE
306     if( rc==SQLITE_OK ){
307       rc = sqlite3MemdbInit();
308     }
309 #endif
310     if( rc==SQLITE_OK ){
311       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
312           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
313       sqlite3MemoryBarrier();
314       sqlite3GlobalConfig.isInit = 1;
315 #ifdef SQLITE_EXTRA_INIT
316       bRunExtraInit = 1;
317 #endif
318     }
319     sqlite3GlobalConfig.inProgress = 0;
320   }
321   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
322 
323   /* Go back under the static mutex and clean up the recursive
324   ** mutex to prevent a resource leak.
325   */
326   sqlite3_mutex_enter(pMainMtx);
327   sqlite3GlobalConfig.nRefInitMutex--;
328   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
329     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
330     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
331     sqlite3GlobalConfig.pInitMutex = 0;
332   }
333   sqlite3_mutex_leave(pMainMtx);
334 
335   /* The following is just a sanity check to make sure SQLite has
336   ** been compiled correctly.  It is important to run this code, but
337   ** we don't want to run it too often and soak up CPU cycles for no
338   ** reason.  So we run it once during initialization.
339   */
340 #ifndef NDEBUG
341 #ifndef SQLITE_OMIT_FLOATING_POINT
342   /* This section of code's only "output" is via assert() statements. */
343   if( rc==SQLITE_OK ){
344     u64 x = (((u64)1)<<63)-1;
345     double y;
346     assert(sizeof(x)==8);
347     assert(sizeof(x)==sizeof(y));
348     memcpy(&y, &x, 8);
349     assert( sqlite3IsNaN(y) );
350   }
351 #endif
352 #endif
353 
354   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
355   ** compile-time option.
356   */
357 #ifdef SQLITE_EXTRA_INIT
358   if( bRunExtraInit ){
359     int SQLITE_EXTRA_INIT(const char*);
360     rc = SQLITE_EXTRA_INIT(0);
361   }
362 #endif
363 
364   return rc;
365 }
366 
367 /*
368 ** Undo the effects of sqlite3_initialize().  Must not be called while
369 ** there are outstanding database connections or memory allocations or
370 ** while any part of SQLite is otherwise in use in any thread.  This
371 ** routine is not threadsafe.  But it is safe to invoke this routine
372 ** on when SQLite is already shut down.  If SQLite is already shut down
373 ** when this routine is invoked, then this routine is a harmless no-op.
374 */
375 int sqlite3_shutdown(void){
376 #ifdef SQLITE_OMIT_WSD
377   int rc = sqlite3_wsd_init(4096, 24);
378   if( rc!=SQLITE_OK ){
379     return rc;
380   }
381 #endif
382 
383   if( sqlite3GlobalConfig.isInit ){
384 #ifdef SQLITE_EXTRA_SHUTDOWN
385     void SQLITE_EXTRA_SHUTDOWN(void);
386     SQLITE_EXTRA_SHUTDOWN();
387 #endif
388     sqlite3_os_end();
389     sqlite3_reset_auto_extension();
390     sqlite3GlobalConfig.isInit = 0;
391   }
392   if( sqlite3GlobalConfig.isPCacheInit ){
393     sqlite3PcacheShutdown();
394     sqlite3GlobalConfig.isPCacheInit = 0;
395   }
396   if( sqlite3GlobalConfig.isMallocInit ){
397     sqlite3MallocEnd();
398     sqlite3GlobalConfig.isMallocInit = 0;
399 
400 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
401     /* The heap subsystem has now been shutdown and these values are supposed
402     ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
403     ** which would rely on that heap subsystem; therefore, make sure these
404     ** values cannot refer to heap memory that was just invalidated when the
405     ** heap subsystem was shutdown.  This is only done if the current call to
406     ** this function resulted in the heap subsystem actually being shutdown.
407     */
408     sqlite3_data_directory = 0;
409     sqlite3_temp_directory = 0;
410 #endif
411   }
412   if( sqlite3GlobalConfig.isMutexInit ){
413     sqlite3MutexEnd();
414     sqlite3GlobalConfig.isMutexInit = 0;
415   }
416 
417   return SQLITE_OK;
418 }
419 
420 /*
421 ** This API allows applications to modify the global configuration of
422 ** the SQLite library at run-time.
423 **
424 ** This routine should only be called when there are no outstanding
425 ** database connections or memory allocations.  This routine is not
426 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
427 ** behavior.
428 */
429 int sqlite3_config(int op, ...){
430   va_list ap;
431   int rc = SQLITE_OK;
432 
433   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
434   ** the SQLite library is in use. */
435   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
436 
437   va_start(ap, op);
438   switch( op ){
439 
440     /* Mutex configuration options are only available in a threadsafe
441     ** compile.
442     */
443 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0  /* IMP: R-54466-46756 */
444     case SQLITE_CONFIG_SINGLETHREAD: {
445       /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
446       ** Single-thread. */
447       sqlite3GlobalConfig.bCoreMutex = 0;  /* Disable mutex on core */
448       sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
449       break;
450     }
451 #endif
452 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
453     case SQLITE_CONFIG_MULTITHREAD: {
454       /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
455       ** Multi-thread. */
456       sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
457       sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
458       break;
459     }
460 #endif
461 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
462     case SQLITE_CONFIG_SERIALIZED: {
463       /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
464       ** Serialized. */
465       sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
466       sqlite3GlobalConfig.bFullMutex = 1;  /* Enable mutex on connections */
467       break;
468     }
469 #endif
470 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
471     case SQLITE_CONFIG_MUTEX: {
472       /* Specify an alternative mutex implementation */
473       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
474       break;
475     }
476 #endif
477 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
478     case SQLITE_CONFIG_GETMUTEX: {
479       /* Retrieve the current mutex implementation */
480       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
481       break;
482     }
483 #endif
484 
485     case SQLITE_CONFIG_MALLOC: {
486       /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
487       ** single argument which is a pointer to an instance of the
488       ** sqlite3_mem_methods structure. The argument specifies alternative
489       ** low-level memory allocation routines to be used in place of the memory
490       ** allocation routines built into SQLite. */
491       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
492       break;
493     }
494     case SQLITE_CONFIG_GETMALLOC: {
495       /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
496       ** single argument which is a pointer to an instance of the
497       ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
498       ** filled with the currently defined memory allocation routines. */
499       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
500       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
501       break;
502     }
503     case SQLITE_CONFIG_MEMSTATUS: {
504       /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
505       ** single argument of type int, interpreted as a boolean, which enables
506       ** or disables the collection of memory allocation statistics. */
507       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
508       break;
509     }
510     case SQLITE_CONFIG_SMALL_MALLOC: {
511       sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
512       break;
513     }
514     case SQLITE_CONFIG_PAGECACHE: {
515       /* EVIDENCE-OF: R-18761-36601 There are three arguments to
516       ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
517       ** the size of each page cache line (sz), and the number of cache lines
518       ** (N). */
519       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
520       sqlite3GlobalConfig.szPage = va_arg(ap, int);
521       sqlite3GlobalConfig.nPage = va_arg(ap, int);
522       break;
523     }
524     case SQLITE_CONFIG_PCACHE_HDRSZ: {
525       /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
526       ** a single parameter which is a pointer to an integer and writes into
527       ** that integer the number of extra bytes per page required for each page
528       ** in SQLITE_CONFIG_PAGECACHE. */
529       *va_arg(ap, int*) =
530           sqlite3HeaderSizeBtree() +
531           sqlite3HeaderSizePcache() +
532           sqlite3HeaderSizePcache1();
533       break;
534     }
535 
536     case SQLITE_CONFIG_PCACHE: {
537       /* no-op */
538       break;
539     }
540     case SQLITE_CONFIG_GETPCACHE: {
541       /* now an error */
542       rc = SQLITE_ERROR;
543       break;
544     }
545 
546     case SQLITE_CONFIG_PCACHE2: {
547       /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
548       ** single argument which is a pointer to an sqlite3_pcache_methods2
549       ** object. This object specifies the interface to a custom page cache
550       ** implementation. */
551       sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
552       break;
553     }
554     case SQLITE_CONFIG_GETPCACHE2: {
555       /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
556       ** single argument which is a pointer to an sqlite3_pcache_methods2
557       ** object. SQLite copies of the current page cache implementation into
558       ** that object. */
559       if( sqlite3GlobalConfig.pcache2.xInit==0 ){
560         sqlite3PCacheSetDefault();
561       }
562       *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
563       break;
564     }
565 
566 /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
567 ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
568 ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
569 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
570     case SQLITE_CONFIG_HEAP: {
571       /* EVIDENCE-OF: R-19854-42126 There are three arguments to
572       ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
573       ** number of bytes in the memory buffer, and the minimum allocation size.
574       */
575       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
576       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
577       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
578 
579       if( sqlite3GlobalConfig.mnReq<1 ){
580         sqlite3GlobalConfig.mnReq = 1;
581       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
582         /* cap min request size at 2^12 */
583         sqlite3GlobalConfig.mnReq = (1<<12);
584       }
585 
586       if( sqlite3GlobalConfig.pHeap==0 ){
587         /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
588         ** is NULL, then SQLite reverts to using its default memory allocator
589         ** (the system malloc() implementation), undoing any prior invocation of
590         ** SQLITE_CONFIG_MALLOC.
591         **
592         ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
593         ** revert to its default implementation when sqlite3_initialize() is run
594         */
595         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
596       }else{
597         /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
598         ** alternative memory allocator is engaged to handle all of SQLites
599         ** memory allocation needs. */
600 #ifdef SQLITE_ENABLE_MEMSYS3
601         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
602 #endif
603 #ifdef SQLITE_ENABLE_MEMSYS5
604         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
605 #endif
606       }
607       break;
608     }
609 #endif
610 
611     case SQLITE_CONFIG_LOOKASIDE: {
612       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
613       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
614       break;
615     }
616 
617     /* Record a pointer to the logger function and its first argument.
618     ** The default is NULL.  Logging is disabled if the function pointer is
619     ** NULL.
620     */
621     case SQLITE_CONFIG_LOG: {
622       /* MSVC is picky about pulling func ptrs from va lists.
623       ** http://support.microsoft.com/kb/47961
624       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
625       */
626       typedef void(*LOGFUNC_t)(void*,int,const char*);
627       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
628       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
629       break;
630     }
631 
632     /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
633     ** can be changed at start-time using the
634     ** sqlite3_config(SQLITE_CONFIG_URI,1) or
635     ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
636     */
637     case SQLITE_CONFIG_URI: {
638       /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
639       ** argument of type int. If non-zero, then URI handling is globally
640       ** enabled. If the parameter is zero, then URI handling is globally
641       ** disabled. */
642       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
643       break;
644     }
645 
646     case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
647       /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
648       ** option takes a single integer argument which is interpreted as a
649       ** boolean in order to enable or disable the use of covering indices for
650       ** full table scans in the query optimizer. */
651       sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
652       break;
653     }
654 
655 #ifdef SQLITE_ENABLE_SQLLOG
656     case SQLITE_CONFIG_SQLLOG: {
657       typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
658       sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
659       sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
660       break;
661     }
662 #endif
663 
664     case SQLITE_CONFIG_MMAP_SIZE: {
665       /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
666       ** integer (sqlite3_int64) values that are the default mmap size limit
667       ** (the default setting for PRAGMA mmap_size) and the maximum allowed
668       ** mmap size limit. */
669       sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
670       sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
671       /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
672       ** negative, then that argument is changed to its compile-time default.
673       **
674       ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
675       ** silently truncated if necessary so that it does not exceed the
676       ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
677       ** compile-time option.
678       */
679       if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
680         mxMmap = SQLITE_MAX_MMAP_SIZE;
681       }
682       if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
683       if( szMmap>mxMmap) szMmap = mxMmap;
684       sqlite3GlobalConfig.mxMmap = mxMmap;
685       sqlite3GlobalConfig.szMmap = szMmap;
686       break;
687     }
688 
689 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
690     case SQLITE_CONFIG_WIN32_HEAPSIZE: {
691       /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
692       ** unsigned integer value that specifies the maximum size of the created
693       ** heap. */
694       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
695       break;
696     }
697 #endif
698 
699     case SQLITE_CONFIG_PMASZ: {
700       sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
701       break;
702     }
703 
704     case SQLITE_CONFIG_STMTJRNL_SPILL: {
705       sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
706       break;
707     }
708 
709 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
710     case SQLITE_CONFIG_SORTERREF_SIZE: {
711       int iVal = va_arg(ap, int);
712       if( iVal<0 ){
713         iVal = SQLITE_DEFAULT_SORTERREF_SIZE;
714       }
715       sqlite3GlobalConfig.szSorterRef = (u32)iVal;
716       break;
717     }
718 #endif /* SQLITE_ENABLE_SORTER_REFERENCES */
719 
720 #ifndef SQLITE_OMIT_DESERIALIZE
721     case SQLITE_CONFIG_MEMDB_MAXSIZE: {
722       sqlite3GlobalConfig.mxMemdbSize = va_arg(ap, sqlite3_int64);
723       break;
724     }
725 #endif /* SQLITE_OMIT_DESERIALIZE */
726 
727     default: {
728       rc = SQLITE_ERROR;
729       break;
730     }
731   }
732   va_end(ap);
733   return rc;
734 }
735 
736 /*
737 ** Set up the lookaside buffers for a database connection.
738 ** Return SQLITE_OK on success.
739 ** If lookaside is already active, return SQLITE_BUSY.
740 **
741 ** The sz parameter is the number of bytes in each lookaside slot.
742 ** The cnt parameter is the number of slots.  If pStart is NULL the
743 ** space for the lookaside memory is obtained from sqlite3_malloc().
744 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
745 ** the lookaside memory.
746 */
747 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
748 #ifndef SQLITE_OMIT_LOOKASIDE
749   void *pStart;
750   sqlite3_int64 szAlloc = sz*(sqlite3_int64)cnt;
751   int nBig;   /* Number of full-size slots */
752   int nSm;    /* Number smaller LOOKASIDE_SMALL-byte slots */
753 
754   if( sqlite3LookasideUsed(db,0)>0 ){
755     return SQLITE_BUSY;
756   }
757   /* Free any existing lookaside buffer for this handle before
758   ** allocating a new one so we don't have to have space for
759   ** both at the same time.
760   */
761   if( db->lookaside.bMalloced ){
762     sqlite3_free(db->lookaside.pStart);
763   }
764   /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
765   ** than a pointer to be useful.
766   */
767   sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
768   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
769   if( cnt<0 ) cnt = 0;
770   if( sz==0 || cnt==0 ){
771     sz = 0;
772     pStart = 0;
773   }else if( pBuf==0 ){
774     sqlite3BeginBenignMalloc();
775     pStart = sqlite3Malloc( szAlloc );  /* IMP: R-61949-35727 */
776     sqlite3EndBenignMalloc();
777     if( pStart ) szAlloc = sqlite3MallocSize(pStart);
778   }else{
779     pStart = pBuf;
780   }
781 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
782   if( sz>=LOOKASIDE_SMALL*3 ){
783     nBig = szAlloc/(3*LOOKASIDE_SMALL+sz);
784     nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
785   }else if( sz>=LOOKASIDE_SMALL*2 ){
786     nBig = szAlloc/(LOOKASIDE_SMALL+sz);
787     nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
788   }else
789 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
790   if( sz>0 ){
791     nBig = szAlloc/sz;
792     nSm = 0;
793   }else{
794     nBig = nSm = 0;
795   }
796   db->lookaside.pStart = pStart;
797   db->lookaside.pInit = 0;
798   db->lookaside.pFree = 0;
799   db->lookaside.sz = (u16)sz;
800   db->lookaside.szTrue = (u16)sz;
801   if( pStart ){
802     int i;
803     LookasideSlot *p;
804     assert( sz > (int)sizeof(LookasideSlot*) );
805     p = (LookasideSlot*)pStart;
806     for(i=0; i<nBig; i++){
807       p->pNext = db->lookaside.pInit;
808       db->lookaside.pInit = p;
809       p = (LookasideSlot*)&((u8*)p)[sz];
810     }
811 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
812     db->lookaside.pSmallInit = 0;
813     db->lookaside.pSmallFree = 0;
814     db->lookaside.pMiddle = p;
815     for(i=0; i<nSm; i++){
816       p->pNext = db->lookaside.pSmallInit;
817       db->lookaside.pSmallInit = p;
818       p = (LookasideSlot*)&((u8*)p)[LOOKASIDE_SMALL];
819     }
820 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
821     assert( ((uptr)p)<=szAlloc + (uptr)pStart );
822     db->lookaside.pEnd = p;
823     db->lookaside.bDisable = 0;
824     db->lookaside.bMalloced = pBuf==0 ?1:0;
825     db->lookaside.nSlot = nBig+nSm;
826   }else{
827     db->lookaside.pStart = db;
828 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
829     db->lookaside.pSmallInit = 0;
830     db->lookaside.pSmallFree = 0;
831     db->lookaside.pMiddle = db;
832 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
833     db->lookaside.pEnd = db;
834     db->lookaside.bDisable = 1;
835     db->lookaside.sz = 0;
836     db->lookaside.bMalloced = 0;
837     db->lookaside.nSlot = 0;
838   }
839   assert( sqlite3LookasideUsed(db,0)==0 );
840 #endif /* SQLITE_OMIT_LOOKASIDE */
841   return SQLITE_OK;
842 }
843 
844 /*
845 ** Return the mutex associated with a database connection.
846 */
847 sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
848 #ifdef SQLITE_ENABLE_API_ARMOR
849   if( !sqlite3SafetyCheckOk(db) ){
850     (void)SQLITE_MISUSE_BKPT;
851     return 0;
852   }
853 #endif
854   return db->mutex;
855 }
856 
857 /*
858 ** Free up as much memory as we can from the given database
859 ** connection.
860 */
861 int sqlite3_db_release_memory(sqlite3 *db){
862   int i;
863 
864 #ifdef SQLITE_ENABLE_API_ARMOR
865   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
866 #endif
867   sqlite3_mutex_enter(db->mutex);
868   sqlite3BtreeEnterAll(db);
869   for(i=0; i<db->nDb; i++){
870     Btree *pBt = db->aDb[i].pBt;
871     if( pBt ){
872       Pager *pPager = sqlite3BtreePager(pBt);
873       sqlite3PagerShrink(pPager);
874     }
875   }
876   sqlite3BtreeLeaveAll(db);
877   sqlite3_mutex_leave(db->mutex);
878   return SQLITE_OK;
879 }
880 
881 /*
882 ** Flush any dirty pages in the pager-cache for any attached database
883 ** to disk.
884 */
885 int sqlite3_db_cacheflush(sqlite3 *db){
886   int i;
887   int rc = SQLITE_OK;
888   int bSeenBusy = 0;
889 
890 #ifdef SQLITE_ENABLE_API_ARMOR
891   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
892 #endif
893   sqlite3_mutex_enter(db->mutex);
894   sqlite3BtreeEnterAll(db);
895   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
896     Btree *pBt = db->aDb[i].pBt;
897     if( pBt && sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
898       Pager *pPager = sqlite3BtreePager(pBt);
899       rc = sqlite3PagerFlush(pPager);
900       if( rc==SQLITE_BUSY ){
901         bSeenBusy = 1;
902         rc = SQLITE_OK;
903       }
904     }
905   }
906   sqlite3BtreeLeaveAll(db);
907   sqlite3_mutex_leave(db->mutex);
908   return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
909 }
910 
911 /*
912 ** Configuration settings for an individual database connection
913 */
914 int sqlite3_db_config(sqlite3 *db, int op, ...){
915   va_list ap;
916   int rc;
917   va_start(ap, op);
918   switch( op ){
919     case SQLITE_DBCONFIG_MAINDBNAME: {
920       /* IMP: R-06824-28531 */
921       /* IMP: R-36257-52125 */
922       db->aDb[0].zDbSName = va_arg(ap,char*);
923       rc = SQLITE_OK;
924       break;
925     }
926     case SQLITE_DBCONFIG_LOOKASIDE: {
927       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
928       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
929       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
930       rc = setupLookaside(db, pBuf, sz, cnt);
931       break;
932     }
933     default: {
934       static const struct {
935         int op;      /* The opcode */
936         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
937       } aFlagOp[] = {
938         { SQLITE_DBCONFIG_ENABLE_FKEY,           SQLITE_ForeignKeys    },
939         { SQLITE_DBCONFIG_ENABLE_TRIGGER,        SQLITE_EnableTrigger  },
940         { SQLITE_DBCONFIG_ENABLE_VIEW,           SQLITE_EnableView     },
941         { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer  },
942         { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension  },
943         { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE,      SQLITE_NoCkptOnClose  },
944         { SQLITE_DBCONFIG_ENABLE_QPSG,           SQLITE_EnableQPSG     },
945         { SQLITE_DBCONFIG_TRIGGER_EQP,           SQLITE_TriggerEQP     },
946         { SQLITE_DBCONFIG_RESET_DATABASE,        SQLITE_ResetDatabase  },
947         { SQLITE_DBCONFIG_DEFENSIVE,             SQLITE_Defensive      },
948         { SQLITE_DBCONFIG_WRITABLE_SCHEMA,       SQLITE_WriteSchema|
949                                                  SQLITE_NoSchemaError  },
950         { SQLITE_DBCONFIG_LEGACY_ALTER_TABLE,    SQLITE_LegacyAlter    },
951         { SQLITE_DBCONFIG_DQS_DDL,               SQLITE_DqsDDL         },
952         { SQLITE_DBCONFIG_DQS_DML,               SQLITE_DqsDML         },
953         { SQLITE_DBCONFIG_LEGACY_FILE_FORMAT,    SQLITE_LegacyFileFmt  },
954         { SQLITE_DBCONFIG_TRUSTED_SCHEMA,        SQLITE_TrustedSchema  },
955       };
956       unsigned int i;
957       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
958       for(i=0; i<ArraySize(aFlagOp); i++){
959         if( aFlagOp[i].op==op ){
960           int onoff = va_arg(ap, int);
961           int *pRes = va_arg(ap, int*);
962           u64 oldFlags = db->flags;
963           if( onoff>0 ){
964             db->flags |= aFlagOp[i].mask;
965           }else if( onoff==0 ){
966             db->flags &= ~(u64)aFlagOp[i].mask;
967           }
968           if( oldFlags!=db->flags ){
969             sqlite3ExpirePreparedStatements(db, 0);
970           }
971           if( pRes ){
972             *pRes = (db->flags & aFlagOp[i].mask)!=0;
973           }
974           rc = SQLITE_OK;
975           break;
976         }
977       }
978       break;
979     }
980   }
981   va_end(ap);
982   return rc;
983 }
984 
985 /*
986 ** This is the default collating function named "BINARY" which is always
987 ** available.
988 */
989 static int binCollFunc(
990   void *NotUsed,
991   int nKey1, const void *pKey1,
992   int nKey2, const void *pKey2
993 ){
994   int rc, n;
995   UNUSED_PARAMETER(NotUsed);
996   n = nKey1<nKey2 ? nKey1 : nKey2;
997   /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
998   ** strings byte by byte using the memcmp() function from the standard C
999   ** library. */
1000   assert( pKey1 && pKey2 );
1001   rc = memcmp(pKey1, pKey2, n);
1002   if( rc==0 ){
1003     rc = nKey1 - nKey2;
1004   }
1005   return rc;
1006 }
1007 
1008 /*
1009 ** This is the collating function named "RTRIM" which is always
1010 ** available.  Ignore trailing spaces.
1011 */
1012 static int rtrimCollFunc(
1013   void *pUser,
1014   int nKey1, const void *pKey1,
1015   int nKey2, const void *pKey2
1016 ){
1017   const u8 *pK1 = (const u8*)pKey1;
1018   const u8 *pK2 = (const u8*)pKey2;
1019   while( nKey1 && pK1[nKey1-1]==' ' ) nKey1--;
1020   while( nKey2 && pK2[nKey2-1]==' ' ) nKey2--;
1021   return binCollFunc(pUser, nKey1, pKey1, nKey2, pKey2);
1022 }
1023 
1024 /*
1025 ** Return true if CollSeq is the default built-in BINARY.
1026 */
1027 int sqlite3IsBinary(const CollSeq *p){
1028   assert( p==0 || p->xCmp!=binCollFunc || strcmp(p->zName,"BINARY")==0 );
1029   return p==0 || p->xCmp==binCollFunc;
1030 }
1031 
1032 /*
1033 ** Another built-in collating sequence: NOCASE.
1034 **
1035 ** This collating sequence is intended to be used for "case independent
1036 ** comparison". SQLite's knowledge of upper and lower case equivalents
1037 ** extends only to the 26 characters used in the English language.
1038 **
1039 ** At the moment there is only a UTF-8 implementation.
1040 */
1041 static int nocaseCollatingFunc(
1042   void *NotUsed,
1043   int nKey1, const void *pKey1,
1044   int nKey2, const void *pKey2
1045 ){
1046   int r = sqlite3StrNICmp(
1047       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
1048   UNUSED_PARAMETER(NotUsed);
1049   if( 0==r ){
1050     r = nKey1-nKey2;
1051   }
1052   return r;
1053 }
1054 
1055 /*
1056 ** Return the ROWID of the most recent insert
1057 */
1058 sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
1059 #ifdef SQLITE_ENABLE_API_ARMOR
1060   if( !sqlite3SafetyCheckOk(db) ){
1061     (void)SQLITE_MISUSE_BKPT;
1062     return 0;
1063   }
1064 #endif
1065   return db->lastRowid;
1066 }
1067 
1068 /*
1069 ** Set the value returned by the sqlite3_last_insert_rowid() API function.
1070 */
1071 void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
1072 #ifdef SQLITE_ENABLE_API_ARMOR
1073   if( !sqlite3SafetyCheckOk(db) ){
1074     (void)SQLITE_MISUSE_BKPT;
1075     return;
1076   }
1077 #endif
1078   sqlite3_mutex_enter(db->mutex);
1079   db->lastRowid = iRowid;
1080   sqlite3_mutex_leave(db->mutex);
1081 }
1082 
1083 /*
1084 ** Return the number of changes in the most recent call to sqlite3_exec().
1085 */
1086 sqlite3_int64 sqlite3_changes64(sqlite3 *db){
1087 #ifdef SQLITE_ENABLE_API_ARMOR
1088   if( !sqlite3SafetyCheckOk(db) ){
1089     (void)SQLITE_MISUSE_BKPT;
1090     return 0;
1091   }
1092 #endif
1093   return db->nChange;
1094 }
1095 int sqlite3_changes(sqlite3 *db){
1096   return (int)sqlite3_changes64(db);
1097 }
1098 
1099 /*
1100 ** Return the number of changes since the database handle was opened.
1101 */
1102 sqlite3_int64 sqlite3_total_changes64(sqlite3 *db){
1103 #ifdef SQLITE_ENABLE_API_ARMOR
1104   if( !sqlite3SafetyCheckOk(db) ){
1105     (void)SQLITE_MISUSE_BKPT;
1106     return 0;
1107   }
1108 #endif
1109   return db->nTotalChange;
1110 }
1111 int sqlite3_total_changes(sqlite3 *db){
1112   return (int)sqlite3_total_changes64(db);
1113 }
1114 
1115 /*
1116 ** Close all open savepoints. This function only manipulates fields of the
1117 ** database handle object, it does not close any savepoints that may be open
1118 ** at the b-tree/pager level.
1119 */
1120 void sqlite3CloseSavepoints(sqlite3 *db){
1121   while( db->pSavepoint ){
1122     Savepoint *pTmp = db->pSavepoint;
1123     db->pSavepoint = pTmp->pNext;
1124     sqlite3DbFree(db, pTmp);
1125   }
1126   db->nSavepoint = 0;
1127   db->nStatement = 0;
1128   db->isTransactionSavepoint = 0;
1129 }
1130 
1131 /*
1132 ** Invoke the destructor function associated with FuncDef p, if any. Except,
1133 ** if this is not the last copy of the function, do not invoke it. Multiple
1134 ** copies of a single function are created when create_function() is called
1135 ** with SQLITE_ANY as the encoding.
1136 */
1137 static void functionDestroy(sqlite3 *db, FuncDef *p){
1138   FuncDestructor *pDestructor;
1139   assert( (p->funcFlags & SQLITE_FUNC_BUILTIN)==0 );
1140   pDestructor = p->u.pDestructor;
1141   if( pDestructor ){
1142     pDestructor->nRef--;
1143     if( pDestructor->nRef==0 ){
1144       pDestructor->xDestroy(pDestructor->pUserData);
1145       sqlite3DbFree(db, pDestructor);
1146     }
1147   }
1148 }
1149 
1150 /*
1151 ** Disconnect all sqlite3_vtab objects that belong to database connection
1152 ** db. This is called when db is being closed.
1153 */
1154 static void disconnectAllVtab(sqlite3 *db){
1155 #ifndef SQLITE_OMIT_VIRTUALTABLE
1156   int i;
1157   HashElem *p;
1158   sqlite3BtreeEnterAll(db);
1159   for(i=0; i<db->nDb; i++){
1160     Schema *pSchema = db->aDb[i].pSchema;
1161     if( pSchema ){
1162       for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
1163         Table *pTab = (Table *)sqliteHashData(p);
1164         if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
1165       }
1166     }
1167   }
1168   for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
1169     Module *pMod = (Module *)sqliteHashData(p);
1170     if( pMod->pEpoTab ){
1171       sqlite3VtabDisconnect(db, pMod->pEpoTab);
1172     }
1173   }
1174   sqlite3VtabUnlockList(db);
1175   sqlite3BtreeLeaveAll(db);
1176 #else
1177   UNUSED_PARAMETER(db);
1178 #endif
1179 }
1180 
1181 /*
1182 ** Return TRUE if database connection db has unfinalized prepared
1183 ** statements or unfinished sqlite3_backup objects.
1184 */
1185 static int connectionIsBusy(sqlite3 *db){
1186   int j;
1187   assert( sqlite3_mutex_held(db->mutex) );
1188   if( db->pVdbe ) return 1;
1189   for(j=0; j<db->nDb; j++){
1190     Btree *pBt = db->aDb[j].pBt;
1191     if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
1192   }
1193   return 0;
1194 }
1195 
1196 /*
1197 ** Close an existing SQLite database
1198 */
1199 static int sqlite3Close(sqlite3 *db, int forceZombie){
1200   if( !db ){
1201     /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
1202     ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
1203     return SQLITE_OK;
1204   }
1205   if( !sqlite3SafetyCheckSickOrOk(db) ){
1206     return SQLITE_MISUSE_BKPT;
1207   }
1208   sqlite3_mutex_enter(db->mutex);
1209   if( db->mTrace & SQLITE_TRACE_CLOSE ){
1210     db->trace.xV2(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
1211   }
1212 
1213   /* Force xDisconnect calls on all virtual tables */
1214   disconnectAllVtab(db);
1215 
1216   /* If a transaction is open, the disconnectAllVtab() call above
1217   ** will not have called the xDisconnect() method on any virtual
1218   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
1219   ** call will do so. We need to do this before the check for active
1220   ** SQL statements below, as the v-table implementation may be storing
1221   ** some prepared statements internally.
1222   */
1223   sqlite3VtabRollback(db);
1224 
1225   /* Legacy behavior (sqlite3_close() behavior) is to return
1226   ** SQLITE_BUSY if the connection can not be closed immediately.
1227   */
1228   if( !forceZombie && connectionIsBusy(db) ){
1229     sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
1230        "statements or unfinished backups");
1231     sqlite3_mutex_leave(db->mutex);
1232     return SQLITE_BUSY;
1233   }
1234 
1235 #ifdef SQLITE_ENABLE_SQLLOG
1236   if( sqlite3GlobalConfig.xSqllog ){
1237     /* Closing the handle. Fourth parameter is passed the value 2. */
1238     sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
1239   }
1240 #endif
1241 
1242   /* Convert the connection into a zombie and then close it.
1243   */
1244   db->eOpenState = SQLITE_STATE_ZOMBIE;
1245   sqlite3LeaveMutexAndCloseZombie(db);
1246   return SQLITE_OK;
1247 }
1248 
1249 /*
1250 ** Return the transaction state for a single databse, or the maximum
1251 ** transaction state over all attached databases if zSchema is null.
1252 */
1253 int sqlite3_txn_state(sqlite3 *db, const char *zSchema){
1254   int iDb, nDb;
1255   int iTxn = -1;
1256 #ifdef SQLITE_ENABLE_API_ARMOR
1257   if( !sqlite3SafetyCheckOk(db) ){
1258     (void)SQLITE_MISUSE_BKPT;
1259     return -1;
1260   }
1261 #endif
1262   sqlite3_mutex_enter(db->mutex);
1263   if( zSchema ){
1264     nDb = iDb = sqlite3FindDbName(db, zSchema);
1265     if( iDb<0 ) nDb--;
1266   }else{
1267     iDb = 0;
1268     nDb = db->nDb-1;
1269   }
1270   for(; iDb<=nDb; iDb++){
1271     Btree *pBt = db->aDb[iDb].pBt;
1272     int x = pBt!=0 ? sqlite3BtreeTxnState(pBt) : SQLITE_TXN_NONE;
1273     if( x>iTxn ) iTxn = x;
1274   }
1275   sqlite3_mutex_leave(db->mutex);
1276   return iTxn;
1277 }
1278 
1279 /*
1280 ** Two variations on the public interface for closing a database
1281 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
1282 ** leaves the connection open if there are unfinalized prepared
1283 ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
1284 ** version forces the connection to become a zombie if there are
1285 ** unclosed resources, and arranges for deallocation when the last
1286 ** prepare statement or sqlite3_backup closes.
1287 */
1288 int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
1289 int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
1290 
1291 
1292 /*
1293 ** Close the mutex on database connection db.
1294 **
1295 ** Furthermore, if database connection db is a zombie (meaning that there
1296 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
1297 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
1298 ** finished, then free all resources.
1299 */
1300 void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
1301   HashElem *i;                    /* Hash table iterator */
1302   int j;
1303 
1304   /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
1305   ** or if the connection has not yet been closed by sqlite3_close_v2(),
1306   ** then just leave the mutex and return.
1307   */
1308   if( db->eOpenState!=SQLITE_STATE_ZOMBIE || connectionIsBusy(db) ){
1309     sqlite3_mutex_leave(db->mutex);
1310     return;
1311   }
1312 
1313   /* If we reach this point, it means that the database connection has
1314   ** closed all sqlite3_stmt and sqlite3_backup objects and has been
1315   ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
1316   ** go ahead and free all resources.
1317   */
1318 
1319   /* If a transaction is open, roll it back. This also ensures that if
1320   ** any database schemas have been modified by an uncommitted transaction
1321   ** they are reset. And that the required b-tree mutex is held to make
1322   ** the pager rollback and schema reset an atomic operation. */
1323   sqlite3RollbackAll(db, SQLITE_OK);
1324 
1325   /* Free any outstanding Savepoint structures. */
1326   sqlite3CloseSavepoints(db);
1327 
1328   /* Close all database connections */
1329   for(j=0; j<db->nDb; j++){
1330     struct Db *pDb = &db->aDb[j];
1331     if( pDb->pBt ){
1332       sqlite3BtreeClose(pDb->pBt);
1333       pDb->pBt = 0;
1334       if( j!=1 ){
1335         pDb->pSchema = 0;
1336       }
1337     }
1338   }
1339   /* Clear the TEMP schema separately and last */
1340   if( db->aDb[1].pSchema ){
1341     sqlite3SchemaClear(db->aDb[1].pSchema);
1342   }
1343   sqlite3VtabUnlockList(db);
1344 
1345   /* Free up the array of auxiliary databases */
1346   sqlite3CollapseDatabaseArray(db);
1347   assert( db->nDb<=2 );
1348   assert( db->aDb==db->aDbStatic );
1349 
1350   /* Tell the code in notify.c that the connection no longer holds any
1351   ** locks and does not require any further unlock-notify callbacks.
1352   */
1353   sqlite3ConnectionClosed(db);
1354 
1355   for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
1356     FuncDef *pNext, *p;
1357     p = sqliteHashData(i);
1358     do{
1359       functionDestroy(db, p);
1360       pNext = p->pNext;
1361       sqlite3DbFree(db, p);
1362       p = pNext;
1363     }while( p );
1364   }
1365   sqlite3HashClear(&db->aFunc);
1366   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
1367     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
1368     /* Invoke any destructors registered for collation sequence user data. */
1369     for(j=0; j<3; j++){
1370       if( pColl[j].xDel ){
1371         pColl[j].xDel(pColl[j].pUser);
1372       }
1373     }
1374     sqlite3DbFree(db, pColl);
1375   }
1376   sqlite3HashClear(&db->aCollSeq);
1377 #ifndef SQLITE_OMIT_VIRTUALTABLE
1378   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
1379     Module *pMod = (Module *)sqliteHashData(i);
1380     sqlite3VtabEponymousTableClear(db, pMod);
1381     sqlite3VtabModuleUnref(db, pMod);
1382   }
1383   sqlite3HashClear(&db->aModule);
1384 #endif
1385 
1386   sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
1387   sqlite3ValueFree(db->pErr);
1388   sqlite3CloseExtensions(db);
1389 #if SQLITE_USER_AUTHENTICATION
1390   sqlite3_free(db->auth.zAuthUser);
1391   sqlite3_free(db->auth.zAuthPW);
1392 #endif
1393 
1394   db->eOpenState = SQLITE_STATE_ERROR;
1395 
1396   /* The temp-database schema is allocated differently from the other schema
1397   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
1398   ** So it needs to be freed here. Todo: Why not roll the temp schema into
1399   ** the same sqliteMalloc() as the one that allocates the database
1400   ** structure?
1401   */
1402   sqlite3DbFree(db, db->aDb[1].pSchema);
1403   if( db->xAutovacDestr ){
1404     db->xAutovacDestr(db->pAutovacPagesArg);
1405   }
1406   sqlite3_mutex_leave(db->mutex);
1407   db->eOpenState = SQLITE_STATE_CLOSED;
1408   sqlite3_mutex_free(db->mutex);
1409   assert( sqlite3LookasideUsed(db,0)==0 );
1410   if( db->lookaside.bMalloced ){
1411     sqlite3_free(db->lookaside.pStart);
1412   }
1413   sqlite3_free(db);
1414 }
1415 
1416 /*
1417 ** Rollback all database files.  If tripCode is not SQLITE_OK, then
1418 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
1419 ** breaker") and made to return tripCode if there are any further
1420 ** attempts to use that cursor.  Read cursors remain open and valid
1421 ** but are "saved" in case the table pages are moved around.
1422 */
1423 void sqlite3RollbackAll(sqlite3 *db, int tripCode){
1424   int i;
1425   int inTrans = 0;
1426   int schemaChange;
1427   assert( sqlite3_mutex_held(db->mutex) );
1428   sqlite3BeginBenignMalloc();
1429 
1430   /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
1431   ** This is important in case the transaction being rolled back has
1432   ** modified the database schema. If the b-tree mutexes are not taken
1433   ** here, then another shared-cache connection might sneak in between
1434   ** the database rollback and schema reset, which can cause false
1435   ** corruption reports in some cases.  */
1436   sqlite3BtreeEnterAll(db);
1437   schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
1438 
1439   for(i=0; i<db->nDb; i++){
1440     Btree *p = db->aDb[i].pBt;
1441     if( p ){
1442       if( sqlite3BtreeTxnState(p)==SQLITE_TXN_WRITE ){
1443         inTrans = 1;
1444       }
1445       sqlite3BtreeRollback(p, tripCode, !schemaChange);
1446     }
1447   }
1448   sqlite3VtabRollback(db);
1449   sqlite3EndBenignMalloc();
1450 
1451   if( schemaChange ){
1452     sqlite3ExpirePreparedStatements(db, 0);
1453     sqlite3ResetAllSchemasOfConnection(db);
1454   }
1455   sqlite3BtreeLeaveAll(db);
1456 
1457   /* Any deferred constraint violations have now been resolved. */
1458   db->nDeferredCons = 0;
1459   db->nDeferredImmCons = 0;
1460   db->flags &= ~(u64)(SQLITE_DeferFKs|SQLITE_CorruptRdOnly);
1461 
1462   /* If one has been configured, invoke the rollback-hook callback */
1463   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
1464     db->xRollbackCallback(db->pRollbackArg);
1465   }
1466 }
1467 
1468 /*
1469 ** Return a static string containing the name corresponding to the error code
1470 ** specified in the argument.
1471 */
1472 #if defined(SQLITE_NEED_ERR_NAME)
1473 const char *sqlite3ErrName(int rc){
1474   const char *zName = 0;
1475   int i, origRc = rc;
1476   for(i=0; i<2 && zName==0; i++, rc &= 0xff){
1477     switch( rc ){
1478       case SQLITE_OK:                 zName = "SQLITE_OK";                break;
1479       case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
1480       case SQLITE_ERROR_SNAPSHOT:     zName = "SQLITE_ERROR_SNAPSHOT";    break;
1481       case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
1482       case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
1483       case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
1484       case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
1485       case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
1486       case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
1487       case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
1488       case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
1489       case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
1490       case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
1491       case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
1492       case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
1493       case SQLITE_READONLY_CANTINIT:  zName = "SQLITE_READONLY_CANTINIT"; break;
1494       case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
1495       case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
1496       case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break;
1497       case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
1498       case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
1499       case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
1500       case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
1501       case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
1502       case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
1503       case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
1504       case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
1505       case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
1506       case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
1507       case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
1508       case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
1509       case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
1510       case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
1511       case SQLITE_IOERR_CHECKRESERVEDLOCK:
1512                                 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
1513       case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
1514       case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
1515       case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
1516       case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
1517       case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
1518       case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
1519       case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
1520       case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
1521       case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
1522       case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
1523       case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
1524       case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
1525       case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
1526       case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
1527       case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
1528       case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
1529       case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
1530       case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
1531       case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
1532       case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
1533       case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
1534       case SQLITE_CANTOPEN_SYMLINK:   zName = "SQLITE_CANTOPEN_SYMLINK";  break;
1535       case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
1536       case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
1537       case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
1538       case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
1539       case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
1540       case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
1541       case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
1542       case SQLITE_CONSTRAINT_FOREIGNKEY:
1543                                 zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
1544       case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
1545       case SQLITE_CONSTRAINT_PRIMARYKEY:
1546                                 zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
1547       case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
1548       case SQLITE_CONSTRAINT_COMMITHOOK:
1549                                 zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
1550       case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
1551       case SQLITE_CONSTRAINT_FUNCTION:
1552                                 zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
1553       case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
1554       case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
1555       case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
1556       case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
1557       case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
1558       case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
1559       case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
1560       case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
1561       case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
1562       case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
1563       case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
1564       case SQLITE_NOTICE_RECOVER_ROLLBACK:
1565                                 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
1566       case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
1567       case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
1568       case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
1569     }
1570   }
1571   if( zName==0 ){
1572     static char zBuf[50];
1573     sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
1574     zName = zBuf;
1575   }
1576   return zName;
1577 }
1578 #endif
1579 
1580 /*
1581 ** Return a static string that describes the kind of error specified in the
1582 ** argument.
1583 */
1584 const char *sqlite3ErrStr(int rc){
1585   static const char* const aMsg[] = {
1586     /* SQLITE_OK          */ "not an error",
1587     /* SQLITE_ERROR       */ "SQL logic error",
1588     /* SQLITE_INTERNAL    */ 0,
1589     /* SQLITE_PERM        */ "access permission denied",
1590     /* SQLITE_ABORT       */ "query aborted",
1591     /* SQLITE_BUSY        */ "database is locked",
1592     /* SQLITE_LOCKED      */ "database table is locked",
1593     /* SQLITE_NOMEM       */ "out of memory",
1594     /* SQLITE_READONLY    */ "attempt to write a readonly database",
1595     /* SQLITE_INTERRUPT   */ "interrupted",
1596     /* SQLITE_IOERR       */ "disk I/O error",
1597     /* SQLITE_CORRUPT     */ "database disk image is malformed",
1598     /* SQLITE_NOTFOUND    */ "unknown operation",
1599     /* SQLITE_FULL        */ "database or disk is full",
1600     /* SQLITE_CANTOPEN    */ "unable to open database file",
1601     /* SQLITE_PROTOCOL    */ "locking protocol",
1602     /* SQLITE_EMPTY       */ 0,
1603     /* SQLITE_SCHEMA      */ "database schema has changed",
1604     /* SQLITE_TOOBIG      */ "string or blob too big",
1605     /* SQLITE_CONSTRAINT  */ "constraint failed",
1606     /* SQLITE_MISMATCH    */ "datatype mismatch",
1607     /* SQLITE_MISUSE      */ "bad parameter or other API misuse",
1608 #ifdef SQLITE_DISABLE_LFS
1609     /* SQLITE_NOLFS       */ "large file support is disabled",
1610 #else
1611     /* SQLITE_NOLFS       */ 0,
1612 #endif
1613     /* SQLITE_AUTH        */ "authorization denied",
1614     /* SQLITE_FORMAT      */ 0,
1615     /* SQLITE_RANGE       */ "column index out of range",
1616     /* SQLITE_NOTADB      */ "file is not a database",
1617     /* SQLITE_NOTICE      */ "notification message",
1618     /* SQLITE_WARNING     */ "warning message",
1619   };
1620   const char *zErr = "unknown error";
1621   switch( rc ){
1622     case SQLITE_ABORT_ROLLBACK: {
1623       zErr = "abort due to ROLLBACK";
1624       break;
1625     }
1626     case SQLITE_ROW: {
1627       zErr = "another row available";
1628       break;
1629     }
1630     case SQLITE_DONE: {
1631       zErr = "no more rows available";
1632       break;
1633     }
1634     default: {
1635       rc &= 0xff;
1636       if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
1637         zErr = aMsg[rc];
1638       }
1639       break;
1640     }
1641   }
1642   return zErr;
1643 }
1644 
1645 /*
1646 ** This routine implements a busy callback that sleeps and tries
1647 ** again until a timeout value is reached.  The timeout value is
1648 ** an integer number of milliseconds passed in as the first
1649 ** argument.
1650 **
1651 ** Return non-zero to retry the lock.  Return zero to stop trying
1652 ** and cause SQLite to return SQLITE_BUSY.
1653 */
1654 static int sqliteDefaultBusyCallback(
1655   void *ptr,               /* Database connection */
1656   int count                /* Number of times table has been busy */
1657 ){
1658 #if SQLITE_OS_WIN || HAVE_USLEEP
1659   /* This case is for systems that have support for sleeping for fractions of
1660   ** a second.  Examples:  All windows systems, unix systems with usleep() */
1661   static const u8 delays[] =
1662      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
1663   static const u8 totals[] =
1664      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
1665 # define NDELAY ArraySize(delays)
1666   sqlite3 *db = (sqlite3 *)ptr;
1667   int tmout = db->busyTimeout;
1668   int delay, prior;
1669 
1670   assert( count>=0 );
1671   if( count < NDELAY ){
1672     delay = delays[count];
1673     prior = totals[count];
1674   }else{
1675     delay = delays[NDELAY-1];
1676     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
1677   }
1678   if( prior + delay > tmout ){
1679     delay = tmout - prior;
1680     if( delay<=0 ) return 0;
1681   }
1682   sqlite3OsSleep(db->pVfs, delay*1000);
1683   return 1;
1684 #else
1685   /* This case for unix systems that lack usleep() support.  Sleeping
1686   ** must be done in increments of whole seconds */
1687   sqlite3 *db = (sqlite3 *)ptr;
1688   int tmout = ((sqlite3 *)ptr)->busyTimeout;
1689   if( (count+1)*1000 > tmout ){
1690     return 0;
1691   }
1692   sqlite3OsSleep(db->pVfs, 1000000);
1693   return 1;
1694 #endif
1695 }
1696 
1697 /*
1698 ** Invoke the given busy handler.
1699 **
1700 ** This routine is called when an operation failed to acquire a
1701 ** lock on VFS file pFile.
1702 **
1703 ** If this routine returns non-zero, the lock is retried.  If it
1704 ** returns 0, the operation aborts with an SQLITE_BUSY error.
1705 */
1706 int sqlite3InvokeBusyHandler(BusyHandler *p){
1707   int rc;
1708   if( p->xBusyHandler==0 || p->nBusy<0 ) return 0;
1709   rc = p->xBusyHandler(p->pBusyArg, p->nBusy);
1710   if( rc==0 ){
1711     p->nBusy = -1;
1712   }else{
1713     p->nBusy++;
1714   }
1715   return rc;
1716 }
1717 
1718 /*
1719 ** This routine sets the busy callback for an Sqlite database to the
1720 ** given callback function with the given argument.
1721 */
1722 int sqlite3_busy_handler(
1723   sqlite3 *db,
1724   int (*xBusy)(void*,int),
1725   void *pArg
1726 ){
1727 #ifdef SQLITE_ENABLE_API_ARMOR
1728   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
1729 #endif
1730   sqlite3_mutex_enter(db->mutex);
1731   db->busyHandler.xBusyHandler = xBusy;
1732   db->busyHandler.pBusyArg = pArg;
1733   db->busyHandler.nBusy = 0;
1734   db->busyTimeout = 0;
1735   sqlite3_mutex_leave(db->mutex);
1736   return SQLITE_OK;
1737 }
1738 
1739 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1740 /*
1741 ** This routine sets the progress callback for an Sqlite database to the
1742 ** given callback function with the given argument. The progress callback will
1743 ** be invoked every nOps opcodes.
1744 */
1745 void sqlite3_progress_handler(
1746   sqlite3 *db,
1747   int nOps,
1748   int (*xProgress)(void*),
1749   void *pArg
1750 ){
1751 #ifdef SQLITE_ENABLE_API_ARMOR
1752   if( !sqlite3SafetyCheckOk(db) ){
1753     (void)SQLITE_MISUSE_BKPT;
1754     return;
1755   }
1756 #endif
1757   sqlite3_mutex_enter(db->mutex);
1758   if( nOps>0 ){
1759     db->xProgress = xProgress;
1760     db->nProgressOps = (unsigned)nOps;
1761     db->pProgressArg = pArg;
1762   }else{
1763     db->xProgress = 0;
1764     db->nProgressOps = 0;
1765     db->pProgressArg = 0;
1766   }
1767   sqlite3_mutex_leave(db->mutex);
1768 }
1769 #endif
1770 
1771 
1772 /*
1773 ** This routine installs a default busy handler that waits for the
1774 ** specified number of milliseconds before returning 0.
1775 */
1776 int sqlite3_busy_timeout(sqlite3 *db, int ms){
1777 #ifdef SQLITE_ENABLE_API_ARMOR
1778   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
1779 #endif
1780   if( ms>0 ){
1781     sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
1782                              (void*)db);
1783     db->busyTimeout = ms;
1784   }else{
1785     sqlite3_busy_handler(db, 0, 0);
1786   }
1787   return SQLITE_OK;
1788 }
1789 
1790 /*
1791 ** Cause any pending operation to stop at its earliest opportunity.
1792 */
1793 void sqlite3_interrupt(sqlite3 *db){
1794 #ifdef SQLITE_ENABLE_API_ARMOR
1795   if( !sqlite3SafetyCheckOk(db) && (db==0 || db->eOpenState!=SQLITE_STATE_ZOMBIE) ){
1796     (void)SQLITE_MISUSE_BKPT;
1797     return;
1798   }
1799 #endif
1800   AtomicStore(&db->u1.isInterrupted, 1);
1801 }
1802 
1803 
1804 /*
1805 ** This function is exactly the same as sqlite3_create_function(), except
1806 ** that it is designed to be called by internal code. The difference is
1807 ** that if a malloc() fails in sqlite3_create_function(), an error code
1808 ** is returned and the mallocFailed flag cleared.
1809 */
1810 int sqlite3CreateFunc(
1811   sqlite3 *db,
1812   const char *zFunctionName,
1813   int nArg,
1814   int enc,
1815   void *pUserData,
1816   void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
1817   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
1818   void (*xFinal)(sqlite3_context*),
1819   void (*xValue)(sqlite3_context*),
1820   void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
1821   FuncDestructor *pDestructor
1822 ){
1823   FuncDef *p;
1824   int extraFlags;
1825 
1826   assert( sqlite3_mutex_held(db->mutex) );
1827   assert( xValue==0 || xSFunc==0 );
1828   if( zFunctionName==0                /* Must have a valid name */
1829    || (xSFunc!=0 && xFinal!=0)        /* Not both xSFunc and xFinal */
1830    || ((xFinal==0)!=(xStep==0))       /* Both or neither of xFinal and xStep */
1831    || ((xValue==0)!=(xInverse==0))    /* Both or neither of xValue, xInverse */
1832    || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG)
1833    || (255<sqlite3Strlen30(zFunctionName))
1834   ){
1835     return SQLITE_MISUSE_BKPT;
1836   }
1837 
1838   assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
1839   assert( SQLITE_FUNC_DIRECT==SQLITE_DIRECTONLY );
1840   extraFlags = enc &  (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY|
1841                        SQLITE_SUBTYPE|SQLITE_INNOCUOUS);
1842   enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
1843 
1844   /* The SQLITE_INNOCUOUS flag is the same bit as SQLITE_FUNC_UNSAFE.  But
1845   ** the meaning is inverted.  So flip the bit. */
1846   assert( SQLITE_FUNC_UNSAFE==SQLITE_INNOCUOUS );
1847   extraFlags ^= SQLITE_FUNC_UNSAFE;
1848 
1849 
1850 #ifndef SQLITE_OMIT_UTF16
1851   /* If SQLITE_UTF16 is specified as the encoding type, transform this
1852   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
1853   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
1854   **
1855   ** If SQLITE_ANY is specified, add three versions of the function
1856   ** to the hash table.
1857   */
1858   switch( enc ){
1859     case SQLITE_UTF16:
1860       enc = SQLITE_UTF16NATIVE;
1861       break;
1862     case SQLITE_ANY: {
1863       int rc;
1864       rc = sqlite3CreateFunc(db, zFunctionName, nArg,
1865            (SQLITE_UTF8|extraFlags)^SQLITE_FUNC_UNSAFE,
1866            pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
1867       if( rc==SQLITE_OK ){
1868         rc = sqlite3CreateFunc(db, zFunctionName, nArg,
1869              (SQLITE_UTF16LE|extraFlags)^SQLITE_FUNC_UNSAFE,
1870              pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
1871       }
1872       if( rc!=SQLITE_OK ){
1873         return rc;
1874       }
1875       enc = SQLITE_UTF16BE;
1876       break;
1877     }
1878     case SQLITE_UTF8:
1879     case SQLITE_UTF16LE:
1880     case SQLITE_UTF16BE:
1881       break;
1882     default:
1883       enc = SQLITE_UTF8;
1884       break;
1885   }
1886 #else
1887   enc = SQLITE_UTF8;
1888 #endif
1889 
1890   /* Check if an existing function is being overridden or deleted. If so,
1891   ** and there are active VMs, then return SQLITE_BUSY. If a function
1892   ** is being overridden/deleted but there are no active VMs, allow the
1893   ** operation to continue but invalidate all precompiled statements.
1894   */
1895   p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
1896   if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){
1897     if( db->nVdbeActive ){
1898       sqlite3ErrorWithMsg(db, SQLITE_BUSY,
1899         "unable to delete/modify user-function due to active statements");
1900       assert( !db->mallocFailed );
1901       return SQLITE_BUSY;
1902     }else{
1903       sqlite3ExpirePreparedStatements(db, 0);
1904     }
1905   }else if( xSFunc==0 && xFinal==0 ){
1906     /* Trying to delete a function that does not exist.  This is a no-op.
1907     ** https://sqlite.org/forum/forumpost/726219164b */
1908     return SQLITE_OK;
1909   }
1910 
1911   p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
1912   assert(p || db->mallocFailed);
1913   if( !p ){
1914     return SQLITE_NOMEM_BKPT;
1915   }
1916 
1917   /* If an older version of the function with a configured destructor is
1918   ** being replaced invoke the destructor function here. */
1919   functionDestroy(db, p);
1920 
1921   if( pDestructor ){
1922     pDestructor->nRef++;
1923   }
1924   p->u.pDestructor = pDestructor;
1925   p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
1926   testcase( p->funcFlags & SQLITE_DETERMINISTIC );
1927   testcase( p->funcFlags & SQLITE_DIRECTONLY );
1928   p->xSFunc = xSFunc ? xSFunc : xStep;
1929   p->xFinalize = xFinal;
1930   p->xValue = xValue;
1931   p->xInverse = xInverse;
1932   p->pUserData = pUserData;
1933   p->nArg = (u16)nArg;
1934   return SQLITE_OK;
1935 }
1936 
1937 /*
1938 ** Worker function used by utf-8 APIs that create new functions:
1939 **
1940 **    sqlite3_create_function()
1941 **    sqlite3_create_function_v2()
1942 **    sqlite3_create_window_function()
1943 */
1944 static int createFunctionApi(
1945   sqlite3 *db,
1946   const char *zFunc,
1947   int nArg,
1948   int enc,
1949   void *p,
1950   void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
1951   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
1952   void (*xFinal)(sqlite3_context*),
1953   void (*xValue)(sqlite3_context*),
1954   void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
1955   void(*xDestroy)(void*)
1956 ){
1957   int rc = SQLITE_ERROR;
1958   FuncDestructor *pArg = 0;
1959 
1960 #ifdef SQLITE_ENABLE_API_ARMOR
1961   if( !sqlite3SafetyCheckOk(db) ){
1962     return SQLITE_MISUSE_BKPT;
1963   }
1964 #endif
1965   sqlite3_mutex_enter(db->mutex);
1966   if( xDestroy ){
1967     pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor));
1968     if( !pArg ){
1969       sqlite3OomFault(db);
1970       xDestroy(p);
1971       goto out;
1972     }
1973     pArg->nRef = 0;
1974     pArg->xDestroy = xDestroy;
1975     pArg->pUserData = p;
1976   }
1977   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p,
1978       xSFunc, xStep, xFinal, xValue, xInverse, pArg
1979   );
1980   if( pArg && pArg->nRef==0 ){
1981     assert( rc!=SQLITE_OK || (xStep==0 && xFinal==0) );
1982     xDestroy(p);
1983     sqlite3_free(pArg);
1984   }
1985 
1986  out:
1987   rc = sqlite3ApiExit(db, rc);
1988   sqlite3_mutex_leave(db->mutex);
1989   return rc;
1990 }
1991 
1992 /*
1993 ** Create new user functions.
1994 */
1995 int sqlite3_create_function(
1996   sqlite3 *db,
1997   const char *zFunc,
1998   int nArg,
1999   int enc,
2000   void *p,
2001   void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
2002   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
2003   void (*xFinal)(sqlite3_context*)
2004 ){
2005   return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
2006                                     xFinal, 0, 0, 0);
2007 }
2008 int sqlite3_create_function_v2(
2009   sqlite3 *db,
2010   const char *zFunc,
2011   int nArg,
2012   int enc,
2013   void *p,
2014   void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
2015   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
2016   void (*xFinal)(sqlite3_context*),
2017   void (*xDestroy)(void *)
2018 ){
2019   return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
2020                                     xFinal, 0, 0, xDestroy);
2021 }
2022 int sqlite3_create_window_function(
2023   sqlite3 *db,
2024   const char *zFunc,
2025   int nArg,
2026   int enc,
2027   void *p,
2028   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
2029   void (*xFinal)(sqlite3_context*),
2030   void (*xValue)(sqlite3_context*),
2031   void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
2032   void (*xDestroy)(void *)
2033 ){
2034   return createFunctionApi(db, zFunc, nArg, enc, p, 0, xStep,
2035                                     xFinal, xValue, xInverse, xDestroy);
2036 }
2037 
2038 #ifndef SQLITE_OMIT_UTF16
2039 int sqlite3_create_function16(
2040   sqlite3 *db,
2041   const void *zFunctionName,
2042   int nArg,
2043   int eTextRep,
2044   void *p,
2045   void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
2046   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
2047   void (*xFinal)(sqlite3_context*)
2048 ){
2049   int rc;
2050   char *zFunc8;
2051 
2052 #ifdef SQLITE_ENABLE_API_ARMOR
2053   if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
2054 #endif
2055   sqlite3_mutex_enter(db->mutex);
2056   assert( !db->mallocFailed );
2057   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
2058   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0,0,0);
2059   sqlite3DbFree(db, zFunc8);
2060   rc = sqlite3ApiExit(db, rc);
2061   sqlite3_mutex_leave(db->mutex);
2062   return rc;
2063 }
2064 #endif
2065 
2066 
2067 /*
2068 ** The following is the implementation of an SQL function that always
2069 ** fails with an error message stating that the function is used in the
2070 ** wrong context.  The sqlite3_overload_function() API might construct
2071 ** SQL function that use this routine so that the functions will exist
2072 ** for name resolution but are actually overloaded by the xFindFunction
2073 ** method of virtual tables.
2074 */
2075 static void sqlite3InvalidFunction(
2076   sqlite3_context *context,  /* The function calling context */
2077   int NotUsed,               /* Number of arguments to the function */
2078   sqlite3_value **NotUsed2   /* Value of each argument */
2079 ){
2080   const char *zName = (const char*)sqlite3_user_data(context);
2081   char *zErr;
2082   UNUSED_PARAMETER2(NotUsed, NotUsed2);
2083   zErr = sqlite3_mprintf(
2084       "unable to use function %s in the requested context", zName);
2085   sqlite3_result_error(context, zErr, -1);
2086   sqlite3_free(zErr);
2087 }
2088 
2089 /*
2090 ** Declare that a function has been overloaded by a virtual table.
2091 **
2092 ** If the function already exists as a regular global function, then
2093 ** this routine is a no-op.  If the function does not exist, then create
2094 ** a new one that always throws a run-time error.
2095 **
2096 ** When virtual tables intend to provide an overloaded function, they
2097 ** should call this routine to make sure the global function exists.
2098 ** A global function must exist in order for name resolution to work
2099 ** properly.
2100 */
2101 int sqlite3_overload_function(
2102   sqlite3 *db,
2103   const char *zName,
2104   int nArg
2105 ){
2106   int rc;
2107   char *zCopy;
2108 
2109 #ifdef SQLITE_ENABLE_API_ARMOR
2110   if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
2111     return SQLITE_MISUSE_BKPT;
2112   }
2113 #endif
2114   sqlite3_mutex_enter(db->mutex);
2115   rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0;
2116   sqlite3_mutex_leave(db->mutex);
2117   if( rc ) return SQLITE_OK;
2118   zCopy = sqlite3_mprintf(zName);
2119   if( zCopy==0 ) return SQLITE_NOMEM;
2120   return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8,
2121                            zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free);
2122 }
2123 
2124 #ifndef SQLITE_OMIT_TRACE
2125 /*
2126 ** Register a trace function.  The pArg from the previously registered trace
2127 ** is returned.
2128 **
2129 ** A NULL trace function means that no tracing is executes.  A non-NULL
2130 ** trace is a pointer to a function that is invoked at the start of each
2131 ** SQL statement.
2132 */
2133 #ifndef SQLITE_OMIT_DEPRECATED
2134 void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
2135   void *pOld;
2136 
2137 #ifdef SQLITE_ENABLE_API_ARMOR
2138   if( !sqlite3SafetyCheckOk(db) ){
2139     (void)SQLITE_MISUSE_BKPT;
2140     return 0;
2141   }
2142 #endif
2143   sqlite3_mutex_enter(db->mutex);
2144   pOld = db->pTraceArg;
2145   db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
2146   db->trace.xLegacy = xTrace;
2147   db->pTraceArg = pArg;
2148   sqlite3_mutex_leave(db->mutex);
2149   return pOld;
2150 }
2151 #endif /* SQLITE_OMIT_DEPRECATED */
2152 
2153 /* Register a trace callback using the version-2 interface.
2154 */
2155 int sqlite3_trace_v2(
2156   sqlite3 *db,                               /* Trace this connection */
2157   unsigned mTrace,                           /* Mask of events to be traced */
2158   int(*xTrace)(unsigned,void*,void*,void*),  /* Callback to invoke */
2159   void *pArg                                 /* Context */
2160 ){
2161 #ifdef SQLITE_ENABLE_API_ARMOR
2162   if( !sqlite3SafetyCheckOk(db) ){
2163     return SQLITE_MISUSE_BKPT;
2164   }
2165 #endif
2166   sqlite3_mutex_enter(db->mutex);
2167   if( mTrace==0 ) xTrace = 0;
2168   if( xTrace==0 ) mTrace = 0;
2169   db->mTrace = mTrace;
2170   db->trace.xV2 = xTrace;
2171   db->pTraceArg = pArg;
2172   sqlite3_mutex_leave(db->mutex);
2173   return SQLITE_OK;
2174 }
2175 
2176 #ifndef SQLITE_OMIT_DEPRECATED
2177 /*
2178 ** Register a profile function.  The pArg from the previously registered
2179 ** profile function is returned.
2180 **
2181 ** A NULL profile function means that no profiling is executes.  A non-NULL
2182 ** profile is a pointer to a function that is invoked at the conclusion of
2183 ** each SQL statement that is run.
2184 */
2185 void *sqlite3_profile(
2186   sqlite3 *db,
2187   void (*xProfile)(void*,const char*,sqlite_uint64),
2188   void *pArg
2189 ){
2190   void *pOld;
2191 
2192 #ifdef SQLITE_ENABLE_API_ARMOR
2193   if( !sqlite3SafetyCheckOk(db) ){
2194     (void)SQLITE_MISUSE_BKPT;
2195     return 0;
2196   }
2197 #endif
2198   sqlite3_mutex_enter(db->mutex);
2199   pOld = db->pProfileArg;
2200   db->xProfile = xProfile;
2201   db->pProfileArg = pArg;
2202   db->mTrace &= SQLITE_TRACE_NONLEGACY_MASK;
2203   if( db->xProfile ) db->mTrace |= SQLITE_TRACE_XPROFILE;
2204   sqlite3_mutex_leave(db->mutex);
2205   return pOld;
2206 }
2207 #endif /* SQLITE_OMIT_DEPRECATED */
2208 #endif /* SQLITE_OMIT_TRACE */
2209 
2210 /*
2211 ** Register a function to be invoked when a transaction commits.
2212 ** If the invoked function returns non-zero, then the commit becomes a
2213 ** rollback.
2214 */
2215 void *sqlite3_commit_hook(
2216   sqlite3 *db,              /* Attach the hook to this database */
2217   int (*xCallback)(void*),  /* Function to invoke on each commit */
2218   void *pArg                /* Argument to the function */
2219 ){
2220   void *pOld;
2221 
2222 #ifdef SQLITE_ENABLE_API_ARMOR
2223   if( !sqlite3SafetyCheckOk(db) ){
2224     (void)SQLITE_MISUSE_BKPT;
2225     return 0;
2226   }
2227 #endif
2228   sqlite3_mutex_enter(db->mutex);
2229   pOld = db->pCommitArg;
2230   db->xCommitCallback = xCallback;
2231   db->pCommitArg = pArg;
2232   sqlite3_mutex_leave(db->mutex);
2233   return pOld;
2234 }
2235 
2236 /*
2237 ** Register a callback to be invoked each time a row is updated,
2238 ** inserted or deleted using this database connection.
2239 */
2240 void *sqlite3_update_hook(
2241   sqlite3 *db,              /* Attach the hook to this database */
2242   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
2243   void *pArg                /* Argument to the function */
2244 ){
2245   void *pRet;
2246 
2247 #ifdef SQLITE_ENABLE_API_ARMOR
2248   if( !sqlite3SafetyCheckOk(db) ){
2249     (void)SQLITE_MISUSE_BKPT;
2250     return 0;
2251   }
2252 #endif
2253   sqlite3_mutex_enter(db->mutex);
2254   pRet = db->pUpdateArg;
2255   db->xUpdateCallback = xCallback;
2256   db->pUpdateArg = pArg;
2257   sqlite3_mutex_leave(db->mutex);
2258   return pRet;
2259 }
2260 
2261 /*
2262 ** Register a callback to be invoked each time a transaction is rolled
2263 ** back by this database connection.
2264 */
2265 void *sqlite3_rollback_hook(
2266   sqlite3 *db,              /* Attach the hook to this database */
2267   void (*xCallback)(void*), /* Callback function */
2268   void *pArg                /* Argument to the function */
2269 ){
2270   void *pRet;
2271 
2272 #ifdef SQLITE_ENABLE_API_ARMOR
2273   if( !sqlite3SafetyCheckOk(db) ){
2274     (void)SQLITE_MISUSE_BKPT;
2275     return 0;
2276   }
2277 #endif
2278   sqlite3_mutex_enter(db->mutex);
2279   pRet = db->pRollbackArg;
2280   db->xRollbackCallback = xCallback;
2281   db->pRollbackArg = pArg;
2282   sqlite3_mutex_leave(db->mutex);
2283   return pRet;
2284 }
2285 
2286 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2287 /*
2288 ** Register a callback to be invoked each time a row is updated,
2289 ** inserted or deleted using this database connection.
2290 */
2291 void *sqlite3_preupdate_hook(
2292   sqlite3 *db,              /* Attach the hook to this database */
2293   void(*xCallback)(         /* Callback function */
2294     void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
2295   void *pArg                /* First callback argument */
2296 ){
2297   void *pRet;
2298   sqlite3_mutex_enter(db->mutex);
2299   pRet = db->pPreUpdateArg;
2300   db->xPreUpdateCallback = xCallback;
2301   db->pPreUpdateArg = pArg;
2302   sqlite3_mutex_leave(db->mutex);
2303   return pRet;
2304 }
2305 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2306 
2307 /*
2308 ** Register a function to be invoked prior to each autovacuum that
2309 ** determines the number of pages to vacuum.
2310 */
2311 int sqlite3_autovacuum_pages(
2312   sqlite3 *db,                 /* Attach the hook to this database */
2313   unsigned int (*xCallback)(void*,const char*,u32,u32,u32),
2314   void *pArg,                  /* Argument to the function */
2315   void (*xDestructor)(void*)   /* Destructor for pArg */
2316 ){
2317 #ifdef SQLITE_ENABLE_API_ARMOR
2318   if( !sqlite3SafetyCheckOk(db) ){
2319     if( xDestructor ) xDestructor(pArg);
2320     return SQLITE_MISUSE_BKPT;
2321   }
2322 #endif
2323   sqlite3_mutex_enter(db->mutex);
2324   if( db->xAutovacDestr ){
2325     db->xAutovacDestr(db->pAutovacPagesArg);
2326   }
2327   db->xAutovacPages = xCallback;
2328   db->pAutovacPagesArg = pArg;
2329   db->xAutovacDestr = xDestructor;
2330   sqlite3_mutex_leave(db->mutex);
2331   return SQLITE_OK;
2332 }
2333 
2334 
2335 #ifndef SQLITE_OMIT_WAL
2336 /*
2337 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
2338 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
2339 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
2340 ** wal_autocheckpoint()).
2341 */
2342 int sqlite3WalDefaultHook(
2343   void *pClientData,     /* Argument */
2344   sqlite3 *db,           /* Connection */
2345   const char *zDb,       /* Database */
2346   int nFrame             /* Size of WAL */
2347 ){
2348   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
2349     sqlite3BeginBenignMalloc();
2350     sqlite3_wal_checkpoint(db, zDb);
2351     sqlite3EndBenignMalloc();
2352   }
2353   return SQLITE_OK;
2354 }
2355 #endif /* SQLITE_OMIT_WAL */
2356 
2357 /*
2358 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
2359 ** a database after committing a transaction if there are nFrame or
2360 ** more frames in the log file. Passing zero or a negative value as the
2361 ** nFrame parameter disables automatic checkpoints entirely.
2362 **
2363 ** The callback registered by this function replaces any existing callback
2364 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
2365 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
2366 ** configured by this function.
2367 */
2368 int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
2369 #ifdef SQLITE_OMIT_WAL
2370   UNUSED_PARAMETER(db);
2371   UNUSED_PARAMETER(nFrame);
2372 #else
2373 #ifdef SQLITE_ENABLE_API_ARMOR
2374   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
2375 #endif
2376   if( nFrame>0 ){
2377     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
2378   }else{
2379     sqlite3_wal_hook(db, 0, 0);
2380   }
2381 #endif
2382   return SQLITE_OK;
2383 }
2384 
2385 /*
2386 ** Register a callback to be invoked each time a transaction is written
2387 ** into the write-ahead-log by this database connection.
2388 */
2389 void *sqlite3_wal_hook(
2390   sqlite3 *db,                    /* Attach the hook to this db handle */
2391   int(*xCallback)(void *, sqlite3*, const char*, int),
2392   void *pArg                      /* First argument passed to xCallback() */
2393 ){
2394 #ifndef SQLITE_OMIT_WAL
2395   void *pRet;
2396 #ifdef SQLITE_ENABLE_API_ARMOR
2397   if( !sqlite3SafetyCheckOk(db) ){
2398     (void)SQLITE_MISUSE_BKPT;
2399     return 0;
2400   }
2401 #endif
2402   sqlite3_mutex_enter(db->mutex);
2403   pRet = db->pWalArg;
2404   db->xWalCallback = xCallback;
2405   db->pWalArg = pArg;
2406   sqlite3_mutex_leave(db->mutex);
2407   return pRet;
2408 #else
2409   return 0;
2410 #endif
2411 }
2412 
2413 /*
2414 ** Checkpoint database zDb.
2415 */
2416 int sqlite3_wal_checkpoint_v2(
2417   sqlite3 *db,                    /* Database handle */
2418   const char *zDb,                /* Name of attached database (or NULL) */
2419   int eMode,                      /* SQLITE_CHECKPOINT_* value */
2420   int *pnLog,                     /* OUT: Size of WAL log in frames */
2421   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
2422 ){
2423 #ifdef SQLITE_OMIT_WAL
2424   return SQLITE_OK;
2425 #else
2426   int rc;                         /* Return code */
2427   int iDb;                        /* Schema to checkpoint */
2428 
2429 #ifdef SQLITE_ENABLE_API_ARMOR
2430   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
2431 #endif
2432 
2433   /* Initialize the output variables to -1 in case an error occurs. */
2434   if( pnLog ) *pnLog = -1;
2435   if( pnCkpt ) *pnCkpt = -1;
2436 
2437   assert( SQLITE_CHECKPOINT_PASSIVE==0 );
2438   assert( SQLITE_CHECKPOINT_FULL==1 );
2439   assert( SQLITE_CHECKPOINT_RESTART==2 );
2440   assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
2441   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
2442     /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
2443     ** mode: */
2444     return SQLITE_MISUSE;
2445   }
2446 
2447   sqlite3_mutex_enter(db->mutex);
2448   if( zDb && zDb[0] ){
2449     iDb = sqlite3FindDbName(db, zDb);
2450   }else{
2451     iDb = SQLITE_MAX_DB;   /* This means process all schemas */
2452   }
2453   if( iDb<0 ){
2454     rc = SQLITE_ERROR;
2455     sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
2456   }else{
2457     db->busyHandler.nBusy = 0;
2458     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
2459     sqlite3Error(db, rc);
2460   }
2461   rc = sqlite3ApiExit(db, rc);
2462 
2463   /* If there are no active statements, clear the interrupt flag at this
2464   ** point.  */
2465   if( db->nVdbeActive==0 ){
2466     AtomicStore(&db->u1.isInterrupted, 0);
2467   }
2468 
2469   sqlite3_mutex_leave(db->mutex);
2470   return rc;
2471 #endif
2472 }
2473 
2474 
2475 /*
2476 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
2477 ** to contains a zero-length string, all attached databases are
2478 ** checkpointed.
2479 */
2480 int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
2481   /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
2482   ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
2483   return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
2484 }
2485 
2486 #ifndef SQLITE_OMIT_WAL
2487 /*
2488 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
2489 ** not currently open in WAL mode.
2490 **
2491 ** If a transaction is open on the database being checkpointed, this
2492 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
2493 ** an error occurs while running the checkpoint, an SQLite error code is
2494 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
2495 **
2496 ** The mutex on database handle db should be held by the caller. The mutex
2497 ** associated with the specific b-tree being checkpointed is taken by
2498 ** this function while the checkpoint is running.
2499 **
2500 ** If iDb is passed SQLITE_MAX_DB then all attached databases are
2501 ** checkpointed. If an error is encountered it is returned immediately -
2502 ** no attempt is made to checkpoint any remaining databases.
2503 **
2504 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
2505 ** or TRUNCATE.
2506 */
2507 int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
2508   int rc = SQLITE_OK;             /* Return code */
2509   int i;                          /* Used to iterate through attached dbs */
2510   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
2511 
2512   assert( sqlite3_mutex_held(db->mutex) );
2513   assert( !pnLog || *pnLog==-1 );
2514   assert( !pnCkpt || *pnCkpt==-1 );
2515   testcase( iDb==SQLITE_MAX_ATTACHED ); /* See forum post a006d86f72 */
2516   testcase( iDb==SQLITE_MAX_DB );
2517 
2518   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
2519     if( i==iDb || iDb==SQLITE_MAX_DB ){
2520       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
2521       pnLog = 0;
2522       pnCkpt = 0;
2523       if( rc==SQLITE_BUSY ){
2524         bBusy = 1;
2525         rc = SQLITE_OK;
2526       }
2527     }
2528   }
2529 
2530   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
2531 }
2532 #endif /* SQLITE_OMIT_WAL */
2533 
2534 /*
2535 ** This function returns true if main-memory should be used instead of
2536 ** a temporary file for transient pager files and statement journals.
2537 ** The value returned depends on the value of db->temp_store (runtime
2538 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
2539 ** following table describes the relationship between these two values
2540 ** and this functions return value.
2541 **
2542 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
2543 **   -----------------     --------------     ------------------------------
2544 **   0                     any                file      (return 0)
2545 **   1                     1                  file      (return 0)
2546 **   1                     2                  memory    (return 1)
2547 **   1                     0                  file      (return 0)
2548 **   2                     1                  file      (return 0)
2549 **   2                     2                  memory    (return 1)
2550 **   2                     0                  memory    (return 1)
2551 **   3                     any                memory    (return 1)
2552 */
2553 int sqlite3TempInMemory(const sqlite3 *db){
2554 #if SQLITE_TEMP_STORE==1
2555   return ( db->temp_store==2 );
2556 #endif
2557 #if SQLITE_TEMP_STORE==2
2558   return ( db->temp_store!=1 );
2559 #endif
2560 #if SQLITE_TEMP_STORE==3
2561   UNUSED_PARAMETER(db);
2562   return 1;
2563 #endif
2564 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
2565   UNUSED_PARAMETER(db);
2566   return 0;
2567 #endif
2568 }
2569 
2570 /*
2571 ** Return UTF-8 encoded English language explanation of the most recent
2572 ** error.
2573 */
2574 const char *sqlite3_errmsg(sqlite3 *db){
2575   const char *z;
2576   if( !db ){
2577     return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
2578   }
2579   if( !sqlite3SafetyCheckSickOrOk(db) ){
2580     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
2581   }
2582   sqlite3_mutex_enter(db->mutex);
2583   if( db->mallocFailed ){
2584     z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
2585   }else{
2586     testcase( db->pErr==0 );
2587     z = db->errCode ? (char*)sqlite3_value_text(db->pErr) : 0;
2588     assert( !db->mallocFailed );
2589     if( z==0 ){
2590       z = sqlite3ErrStr(db->errCode);
2591     }
2592   }
2593   sqlite3_mutex_leave(db->mutex);
2594   return z;
2595 }
2596 
2597 /*
2598 ** Return the byte offset of the most recent error
2599 */
2600 int sqlite3_error_offset(sqlite3 *db){
2601   int iOffset = -1;
2602   if( db && sqlite3SafetyCheckSickOrOk(db) && db->errCode ){
2603     sqlite3_mutex_enter(db->mutex);
2604     iOffset = db->errByteOffset;
2605     sqlite3_mutex_leave(db->mutex);
2606   }
2607   return iOffset;
2608 }
2609 
2610 #ifndef SQLITE_OMIT_UTF16
2611 /*
2612 ** Return UTF-16 encoded English language explanation of the most recent
2613 ** error.
2614 */
2615 const void *sqlite3_errmsg16(sqlite3 *db){
2616   static const u16 outOfMem[] = {
2617     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
2618   };
2619   static const u16 misuse[] = {
2620     'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
2621     'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
2622     'm', 'i', 's', 'u', 's', 'e', 0
2623   };
2624 
2625   const void *z;
2626   if( !db ){
2627     return (void *)outOfMem;
2628   }
2629   if( !sqlite3SafetyCheckSickOrOk(db) ){
2630     return (void *)misuse;
2631   }
2632   sqlite3_mutex_enter(db->mutex);
2633   if( db->mallocFailed ){
2634     z = (void *)outOfMem;
2635   }else{
2636     z = sqlite3_value_text16(db->pErr);
2637     if( z==0 ){
2638       sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
2639       z = sqlite3_value_text16(db->pErr);
2640     }
2641     /* A malloc() may have failed within the call to sqlite3_value_text16()
2642     ** above. If this is the case, then the db->mallocFailed flag needs to
2643     ** be cleared before returning. Do this directly, instead of via
2644     ** sqlite3ApiExit(), to avoid setting the database handle error message.
2645     */
2646     sqlite3OomClear(db);
2647   }
2648   sqlite3_mutex_leave(db->mutex);
2649   return z;
2650 }
2651 #endif /* SQLITE_OMIT_UTF16 */
2652 
2653 /*
2654 ** Return the most recent error code generated by an SQLite routine. If NULL is
2655 ** passed to this function, we assume a malloc() failed during sqlite3_open().
2656 */
2657 int sqlite3_errcode(sqlite3 *db){
2658   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
2659     return SQLITE_MISUSE_BKPT;
2660   }
2661   if( !db || db->mallocFailed ){
2662     return SQLITE_NOMEM_BKPT;
2663   }
2664   return db->errCode & db->errMask;
2665 }
2666 int sqlite3_extended_errcode(sqlite3 *db){
2667   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
2668     return SQLITE_MISUSE_BKPT;
2669   }
2670   if( !db || db->mallocFailed ){
2671     return SQLITE_NOMEM_BKPT;
2672   }
2673   return db->errCode;
2674 }
2675 int sqlite3_system_errno(sqlite3 *db){
2676   return db ? db->iSysErrno : 0;
2677 }
2678 
2679 /*
2680 ** Return a string that describes the kind of error specified in the
2681 ** argument.  For now, this simply calls the internal sqlite3ErrStr()
2682 ** function.
2683 */
2684 const char *sqlite3_errstr(int rc){
2685   return sqlite3ErrStr(rc);
2686 }
2687 
2688 /*
2689 ** Create a new collating function for database "db".  The name is zName
2690 ** and the encoding is enc.
2691 */
2692 static int createCollation(
2693   sqlite3* db,
2694   const char *zName,
2695   u8 enc,
2696   void* pCtx,
2697   int(*xCompare)(void*,int,const void*,int,const void*),
2698   void(*xDel)(void*)
2699 ){
2700   CollSeq *pColl;
2701   int enc2;
2702 
2703   assert( sqlite3_mutex_held(db->mutex) );
2704 
2705   /* If SQLITE_UTF16 is specified as the encoding type, transform this
2706   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
2707   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
2708   */
2709   enc2 = enc;
2710   testcase( enc2==SQLITE_UTF16 );
2711   testcase( enc2==SQLITE_UTF16_ALIGNED );
2712   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
2713     enc2 = SQLITE_UTF16NATIVE;
2714   }
2715   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
2716     return SQLITE_MISUSE_BKPT;
2717   }
2718 
2719   /* Check if this call is removing or replacing an existing collation
2720   ** sequence. If so, and there are active VMs, return busy. If there
2721   ** are no active VMs, invalidate any pre-compiled statements.
2722   */
2723   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
2724   if( pColl && pColl->xCmp ){
2725     if( db->nVdbeActive ){
2726       sqlite3ErrorWithMsg(db, SQLITE_BUSY,
2727         "unable to delete/modify collation sequence due to active statements");
2728       return SQLITE_BUSY;
2729     }
2730     sqlite3ExpirePreparedStatements(db, 0);
2731 
2732     /* If collation sequence pColl was created directly by a call to
2733     ** sqlite3_create_collation, and not generated by synthCollSeq(),
2734     ** then any copies made by synthCollSeq() need to be invalidated.
2735     ** Also, collation destructor - CollSeq.xDel() - function may need
2736     ** to be called.
2737     */
2738     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
2739       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
2740       int j;
2741       for(j=0; j<3; j++){
2742         CollSeq *p = &aColl[j];
2743         if( p->enc==pColl->enc ){
2744           if( p->xDel ){
2745             p->xDel(p->pUser);
2746           }
2747           p->xCmp = 0;
2748         }
2749       }
2750     }
2751   }
2752 
2753   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
2754   if( pColl==0 ) return SQLITE_NOMEM_BKPT;
2755   pColl->xCmp = xCompare;
2756   pColl->pUser = pCtx;
2757   pColl->xDel = xDel;
2758   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
2759   sqlite3Error(db, SQLITE_OK);
2760   return SQLITE_OK;
2761 }
2762 
2763 
2764 /*
2765 ** This array defines hard upper bounds on limit values.  The
2766 ** initializer must be kept in sync with the SQLITE_LIMIT_*
2767 ** #defines in sqlite3.h.
2768 */
2769 static const int aHardLimit[] = {
2770   SQLITE_MAX_LENGTH,
2771   SQLITE_MAX_SQL_LENGTH,
2772   SQLITE_MAX_COLUMN,
2773   SQLITE_MAX_EXPR_DEPTH,
2774   SQLITE_MAX_COMPOUND_SELECT,
2775   SQLITE_MAX_VDBE_OP,
2776   SQLITE_MAX_FUNCTION_ARG,
2777   SQLITE_MAX_ATTACHED,
2778   SQLITE_MAX_LIKE_PATTERN_LENGTH,
2779   SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
2780   SQLITE_MAX_TRIGGER_DEPTH,
2781   SQLITE_MAX_WORKER_THREADS,
2782 };
2783 
2784 /*
2785 ** Make sure the hard limits are set to reasonable values
2786 */
2787 #if SQLITE_MAX_LENGTH<100
2788 # error SQLITE_MAX_LENGTH must be at least 100
2789 #endif
2790 #if SQLITE_MAX_SQL_LENGTH<100
2791 # error SQLITE_MAX_SQL_LENGTH must be at least 100
2792 #endif
2793 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
2794 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
2795 #endif
2796 #if SQLITE_MAX_COMPOUND_SELECT<2
2797 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
2798 #endif
2799 #if SQLITE_MAX_VDBE_OP<40
2800 # error SQLITE_MAX_VDBE_OP must be at least 40
2801 #endif
2802 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
2803 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
2804 #endif
2805 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
2806 # error SQLITE_MAX_ATTACHED must be between 0 and 125
2807 #endif
2808 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
2809 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
2810 #endif
2811 #if SQLITE_MAX_COLUMN>32767
2812 # error SQLITE_MAX_COLUMN must not exceed 32767
2813 #endif
2814 #if SQLITE_MAX_TRIGGER_DEPTH<1
2815 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
2816 #endif
2817 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
2818 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
2819 #endif
2820 
2821 
2822 /*
2823 ** Change the value of a limit.  Report the old value.
2824 ** If an invalid limit index is supplied, report -1.
2825 ** Make no changes but still report the old value if the
2826 ** new limit is negative.
2827 **
2828 ** A new lower limit does not shrink existing constructs.
2829 ** It merely prevents new constructs that exceed the limit
2830 ** from forming.
2831 */
2832 int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
2833   int oldLimit;
2834 
2835 #ifdef SQLITE_ENABLE_API_ARMOR
2836   if( !sqlite3SafetyCheckOk(db) ){
2837     (void)SQLITE_MISUSE_BKPT;
2838     return -1;
2839   }
2840 #endif
2841 
2842   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
2843   ** there is a hard upper bound set at compile-time by a C preprocessor
2844   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
2845   ** "_MAX_".)
2846   */
2847   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
2848   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
2849   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
2850   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
2851   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
2852   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
2853   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
2854   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
2855   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
2856                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
2857   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
2858   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
2859   assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
2860   assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
2861 
2862 
2863   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
2864     return -1;
2865   }
2866   oldLimit = db->aLimit[limitId];
2867   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
2868     if( newLimit>aHardLimit[limitId] ){
2869       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
2870     }else if( newLimit<1 && limitId==SQLITE_LIMIT_LENGTH ){
2871       newLimit = 1;
2872     }
2873     db->aLimit[limitId] = newLimit;
2874   }
2875   return oldLimit;                     /* IMP: R-53341-35419 */
2876 }
2877 
2878 /*
2879 ** This function is used to parse both URIs and non-URI filenames passed by the
2880 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
2881 ** URIs specified as part of ATTACH statements.
2882 **
2883 ** The first argument to this function is the name of the VFS to use (or
2884 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
2885 ** query parameter. The second argument contains the URI (or non-URI filename)
2886 ** itself. When this function is called the *pFlags variable should contain
2887 ** the default flags to open the database handle with. The value stored in
2888 ** *pFlags may be updated before returning if the URI filename contains
2889 ** "cache=xxx" or "mode=xxx" query parameters.
2890 **
2891 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
2892 ** the VFS that should be used to open the database file. *pzFile is set to
2893 ** point to a buffer containing the name of the file to open.  The value
2894 ** stored in *pzFile is a database name acceptable to sqlite3_uri_parameter()
2895 ** and is in the same format as names created using sqlite3_create_filename().
2896 ** The caller must invoke sqlite3_free_filename() (not sqlite3_free()!) on
2897 ** the value returned in *pzFile to avoid a memory leak.
2898 **
2899 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
2900 ** may be set to point to a buffer containing an English language error
2901 ** message. It is the responsibility of the caller to eventually release
2902 ** this buffer by calling sqlite3_free().
2903 */
2904 int sqlite3ParseUri(
2905   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
2906   const char *zUri,               /* Nul-terminated URI to parse */
2907   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
2908   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
2909   char **pzFile,                  /* OUT: Filename component of URI */
2910   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
2911 ){
2912   int rc = SQLITE_OK;
2913   unsigned int flags = *pFlags;
2914   const char *zVfs = zDefaultVfs;
2915   char *zFile;
2916   char c;
2917   int nUri = sqlite3Strlen30(zUri);
2918 
2919   assert( *pzErrMsg==0 );
2920 
2921   if( ((flags & SQLITE_OPEN_URI)             /* IMP: R-48725-32206 */
2922             || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
2923    && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
2924   ){
2925     char *zOpt;
2926     int eState;                   /* Parser state when parsing URI */
2927     int iIn;                      /* Input character index */
2928     int iOut = 0;                 /* Output character index */
2929     u64 nByte = nUri+8;           /* Bytes of space to allocate */
2930 
2931     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
2932     ** method that there may be extra parameters following the file-name.  */
2933     flags |= SQLITE_OPEN_URI;
2934 
2935     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
2936     zFile = sqlite3_malloc64(nByte);
2937     if( !zFile ) return SQLITE_NOMEM_BKPT;
2938 
2939     memset(zFile, 0, 4);  /* 4-byte of 0x00 is the start of DB name marker */
2940     zFile += 4;
2941 
2942     iIn = 5;
2943 #ifdef SQLITE_ALLOW_URI_AUTHORITY
2944     if( strncmp(zUri+5, "///", 3)==0 ){
2945       iIn = 7;
2946       /* The following condition causes URIs with five leading / characters
2947       ** like file://///host/path to be converted into UNCs like //host/path.
2948       ** The correct URI for that UNC has only two or four leading / characters
2949       ** file://host/path or file:////host/path.  But 5 leading slashes is a
2950       ** common error, we are told, so we handle it as a special case. */
2951       if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
2952     }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
2953       iIn = 16;
2954     }
2955 #else
2956     /* Discard the scheme and authority segments of the URI. */
2957     if( zUri[5]=='/' && zUri[6]=='/' ){
2958       iIn = 7;
2959       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
2960       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
2961         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
2962             iIn-7, &zUri[7]);
2963         rc = SQLITE_ERROR;
2964         goto parse_uri_out;
2965       }
2966     }
2967 #endif
2968 
2969     /* Copy the filename and any query parameters into the zFile buffer.
2970     ** Decode %HH escape codes along the way.
2971     **
2972     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
2973     ** on the parsing context. As follows:
2974     **
2975     **   0: Parsing file-name.
2976     **   1: Parsing name section of a name=value query parameter.
2977     **   2: Parsing value section of a name=value query parameter.
2978     */
2979     eState = 0;
2980     while( (c = zUri[iIn])!=0 && c!='#' ){
2981       iIn++;
2982       if( c=='%'
2983        && sqlite3Isxdigit(zUri[iIn])
2984        && sqlite3Isxdigit(zUri[iIn+1])
2985       ){
2986         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
2987         octet += sqlite3HexToInt(zUri[iIn++]);
2988 
2989         assert( octet>=0 && octet<256 );
2990         if( octet==0 ){
2991 #ifndef SQLITE_ENABLE_URI_00_ERROR
2992           /* This branch is taken when "%00" appears within the URI. In this
2993           ** case we ignore all text in the remainder of the path, name or
2994           ** value currently being parsed. So ignore the current character
2995           ** and skip to the next "?", "=" or "&", as appropriate. */
2996           while( (c = zUri[iIn])!=0 && c!='#'
2997               && (eState!=0 || c!='?')
2998               && (eState!=1 || (c!='=' && c!='&'))
2999               && (eState!=2 || c!='&')
3000           ){
3001             iIn++;
3002           }
3003           continue;
3004 #else
3005           /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
3006           *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
3007           rc = SQLITE_ERROR;
3008           goto parse_uri_out;
3009 #endif
3010         }
3011         c = octet;
3012       }else if( eState==1 && (c=='&' || c=='=') ){
3013         if( zFile[iOut-1]==0 ){
3014           /* An empty option name. Ignore this option altogether. */
3015           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
3016           continue;
3017         }
3018         if( c=='&' ){
3019           zFile[iOut++] = '\0';
3020         }else{
3021           eState = 2;
3022         }
3023         c = 0;
3024       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
3025         c = 0;
3026         eState = 1;
3027       }
3028       zFile[iOut++] = c;
3029     }
3030     if( eState==1 ) zFile[iOut++] = '\0';
3031     memset(zFile+iOut, 0, 4); /* end-of-options + empty journal filenames */
3032 
3033     /* Check if there were any options specified that should be interpreted
3034     ** here. Options that are interpreted here include "vfs" and those that
3035     ** correspond to flags that may be passed to the sqlite3_open_v2()
3036     ** method. */
3037     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
3038     while( zOpt[0] ){
3039       int nOpt = sqlite3Strlen30(zOpt);
3040       char *zVal = &zOpt[nOpt+1];
3041       int nVal = sqlite3Strlen30(zVal);
3042 
3043       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
3044         zVfs = zVal;
3045       }else{
3046         struct OpenMode {
3047           const char *z;
3048           int mode;
3049         } *aMode = 0;
3050         char *zModeType = 0;
3051         int mask = 0;
3052         int limit = 0;
3053 
3054         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
3055           static struct OpenMode aCacheMode[] = {
3056             { "shared",  SQLITE_OPEN_SHAREDCACHE },
3057             { "private", SQLITE_OPEN_PRIVATECACHE },
3058             { 0, 0 }
3059           };
3060 
3061           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
3062           aMode = aCacheMode;
3063           limit = mask;
3064           zModeType = "cache";
3065         }
3066         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
3067           static struct OpenMode aOpenMode[] = {
3068             { "ro",  SQLITE_OPEN_READONLY },
3069             { "rw",  SQLITE_OPEN_READWRITE },
3070             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
3071             { "memory", SQLITE_OPEN_MEMORY },
3072             { 0, 0 }
3073           };
3074 
3075           mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
3076                    | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
3077           aMode = aOpenMode;
3078           limit = mask & flags;
3079           zModeType = "access";
3080         }
3081 
3082         if( aMode ){
3083           int i;
3084           int mode = 0;
3085           for(i=0; aMode[i].z; i++){
3086             const char *z = aMode[i].z;
3087             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
3088               mode = aMode[i].mode;
3089               break;
3090             }
3091           }
3092           if( mode==0 ){
3093             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
3094             rc = SQLITE_ERROR;
3095             goto parse_uri_out;
3096           }
3097           if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
3098             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
3099                                         zModeType, zVal);
3100             rc = SQLITE_PERM;
3101             goto parse_uri_out;
3102           }
3103           flags = (flags & ~mask) | mode;
3104         }
3105       }
3106 
3107       zOpt = &zVal[nVal+1];
3108     }
3109 
3110   }else{
3111     zFile = sqlite3_malloc64(nUri+8);
3112     if( !zFile ) return SQLITE_NOMEM_BKPT;
3113     memset(zFile, 0, 4);
3114     zFile += 4;
3115     if( nUri ){
3116       memcpy(zFile, zUri, nUri);
3117     }
3118     memset(zFile+nUri, 0, 4);
3119     flags &= ~SQLITE_OPEN_URI;
3120   }
3121 
3122   *ppVfs = sqlite3_vfs_find(zVfs);
3123   if( *ppVfs==0 ){
3124     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
3125     rc = SQLITE_ERROR;
3126   }
3127  parse_uri_out:
3128   if( rc!=SQLITE_OK ){
3129     sqlite3_free_filename(zFile);
3130     zFile = 0;
3131   }
3132   *pFlags = flags;
3133   *pzFile = zFile;
3134   return rc;
3135 }
3136 
3137 /*
3138 ** This routine does the core work of extracting URI parameters from a
3139 ** database filename for the sqlite3_uri_parameter() interface.
3140 */
3141 static const char *uriParameter(const char *zFilename, const char *zParam){
3142   zFilename += sqlite3Strlen30(zFilename) + 1;
3143   while( ALWAYS(zFilename!=0) && zFilename[0] ){
3144     int x = strcmp(zFilename, zParam);
3145     zFilename += sqlite3Strlen30(zFilename) + 1;
3146     if( x==0 ) return zFilename;
3147     zFilename += sqlite3Strlen30(zFilename) + 1;
3148   }
3149   return 0;
3150 }
3151 
3152 
3153 
3154 /*
3155 ** This routine does the work of opening a database on behalf of
3156 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
3157 ** is UTF-8 encoded.
3158 */
3159 static int openDatabase(
3160   const char *zFilename, /* Database filename UTF-8 encoded */
3161   sqlite3 **ppDb,        /* OUT: Returned database handle */
3162   unsigned int flags,    /* Operational flags */
3163   const char *zVfs       /* Name of the VFS to use */
3164 ){
3165   sqlite3 *db;                    /* Store allocated handle here */
3166   int rc;                         /* Return code */
3167   int isThreadsafe;               /* True for threadsafe connections */
3168   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
3169   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
3170   int i;                          /* Loop counter */
3171 
3172 #ifdef SQLITE_ENABLE_API_ARMOR
3173   if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
3174 #endif
3175   *ppDb = 0;
3176 #ifndef SQLITE_OMIT_AUTOINIT
3177   rc = sqlite3_initialize();
3178   if( rc ) return rc;
3179 #endif
3180 
3181   if( sqlite3GlobalConfig.bCoreMutex==0 ){
3182     isThreadsafe = 0;
3183   }else if( flags & SQLITE_OPEN_NOMUTEX ){
3184     isThreadsafe = 0;
3185   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
3186     isThreadsafe = 1;
3187   }else{
3188     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
3189   }
3190 
3191   if( flags & SQLITE_OPEN_PRIVATECACHE ){
3192     flags &= ~SQLITE_OPEN_SHAREDCACHE;
3193   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
3194     flags |= SQLITE_OPEN_SHAREDCACHE;
3195   }
3196 
3197   /* Remove harmful bits from the flags parameter
3198   **
3199   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
3200   ** dealt with in the previous code block.  Besides these, the only
3201   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
3202   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
3203   ** SQLITE_OPEN_PRIVATECACHE, SQLITE_OPEN_EXRESCODE, and some reserved
3204   ** bits.  Silently mask off all other flags.
3205   */
3206   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
3207                SQLITE_OPEN_EXCLUSIVE |
3208                SQLITE_OPEN_MAIN_DB |
3209                SQLITE_OPEN_TEMP_DB |
3210                SQLITE_OPEN_TRANSIENT_DB |
3211                SQLITE_OPEN_MAIN_JOURNAL |
3212                SQLITE_OPEN_TEMP_JOURNAL |
3213                SQLITE_OPEN_SUBJOURNAL |
3214                SQLITE_OPEN_SUPER_JOURNAL |
3215                SQLITE_OPEN_NOMUTEX |
3216                SQLITE_OPEN_FULLMUTEX |
3217                SQLITE_OPEN_WAL
3218              );
3219 
3220   /* Allocate the sqlite data structure */
3221   db = sqlite3MallocZero( sizeof(sqlite3) );
3222   if( db==0 ) goto opendb_out;
3223   if( isThreadsafe
3224 #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
3225    || sqlite3GlobalConfig.bCoreMutex
3226 #endif
3227   ){
3228     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
3229     if( db->mutex==0 ){
3230       sqlite3_free(db);
3231       db = 0;
3232       goto opendb_out;
3233     }
3234     if( isThreadsafe==0 ){
3235       sqlite3MutexWarnOnContention(db->mutex);
3236     }
3237   }
3238   sqlite3_mutex_enter(db->mutex);
3239   db->errMask = (flags & SQLITE_OPEN_EXRESCODE)!=0 ? 0xffffffff : 0xff;
3240   db->nDb = 2;
3241   db->eOpenState = SQLITE_STATE_BUSY;
3242   db->aDb = db->aDbStatic;
3243   db->lookaside.bDisable = 1;
3244   db->lookaside.sz = 0;
3245 
3246   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
3247   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
3248   db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
3249   db->autoCommit = 1;
3250   db->nextAutovac = -1;
3251   db->szMmap = sqlite3GlobalConfig.szMmap;
3252   db->nextPagesize = 0;
3253   db->init.azInit = sqlite3StdType; /* Any array of string ptrs will do */
3254 #ifdef SQLITE_ENABLE_SORTER_MMAP
3255   /* Beginning with version 3.37.0, using the VFS xFetch() API to memory-map
3256   ** the temporary files used to do external sorts (see code in vdbesort.c)
3257   ** is disabled. It can still be used either by defining
3258   ** SQLITE_ENABLE_SORTER_MMAP at compile time or by using the
3259   ** SQLITE_TESTCTRL_SORTER_MMAP test-control at runtime. */
3260   db->nMaxSorterMmap = 0x7FFFFFFF;
3261 #endif
3262   db->flags |= SQLITE_ShortColNames
3263                  | SQLITE_EnableTrigger
3264                  | SQLITE_EnableView
3265                  | SQLITE_CacheSpill
3266 #if !defined(SQLITE_TRUSTED_SCHEMA) || SQLITE_TRUSTED_SCHEMA+0!=0
3267                  | SQLITE_TrustedSchema
3268 #endif
3269 /* The SQLITE_DQS compile-time option determines the default settings
3270 ** for SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML.
3271 **
3272 **    SQLITE_DQS     SQLITE_DBCONFIG_DQS_DDL    SQLITE_DBCONFIG_DQS_DML
3273 **    ----------     -----------------------    -----------------------
3274 **     undefined               on                          on
3275 **         3                   on                          on
3276 **         2                   on                         off
3277 **         1                  off                          on
3278 **         0                  off                         off
3279 **
3280 ** Legacy behavior is 3 (double-quoted string literals are allowed anywhere)
3281 ** and so that is the default.  But developers are encouranged to use
3282 ** -DSQLITE_DQS=0 (best) or -DSQLITE_DQS=1 (second choice) if possible.
3283 */
3284 #if !defined(SQLITE_DQS)
3285 # define SQLITE_DQS 3
3286 #endif
3287 #if (SQLITE_DQS&1)==1
3288                  | SQLITE_DqsDML
3289 #endif
3290 #if (SQLITE_DQS&2)==2
3291                  | SQLITE_DqsDDL
3292 #endif
3293 
3294 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
3295                  | SQLITE_AutoIndex
3296 #endif
3297 #if SQLITE_DEFAULT_CKPTFULLFSYNC
3298                  | SQLITE_CkptFullFSync
3299 #endif
3300 #if SQLITE_DEFAULT_FILE_FORMAT<4
3301                  | SQLITE_LegacyFileFmt
3302 #endif
3303 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
3304                  | SQLITE_LoadExtension
3305 #endif
3306 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
3307                  | SQLITE_RecTriggers
3308 #endif
3309 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
3310                  | SQLITE_ForeignKeys
3311 #endif
3312 #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
3313                  | SQLITE_ReverseOrder
3314 #endif
3315 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
3316                  | SQLITE_CellSizeCk
3317 #endif
3318 #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
3319                  | SQLITE_Fts3Tokenizer
3320 #endif
3321 #if defined(SQLITE_ENABLE_QPSG)
3322                  | SQLITE_EnableQPSG
3323 #endif
3324 #if defined(SQLITE_DEFAULT_DEFENSIVE)
3325                  | SQLITE_Defensive
3326 #endif
3327 #if defined(SQLITE_DEFAULT_LEGACY_ALTER_TABLE)
3328                  | SQLITE_LegacyAlter
3329 #endif
3330       ;
3331   sqlite3HashInit(&db->aCollSeq);
3332 #ifndef SQLITE_OMIT_VIRTUALTABLE
3333   sqlite3HashInit(&db->aModule);
3334 #endif
3335 
3336   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
3337   ** and UTF-16, so add a version for each to avoid any unnecessary
3338   ** conversions. The only error that can occur here is a malloc() failure.
3339   **
3340   ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
3341   ** functions:
3342   */
3343   createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
3344   createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
3345   createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
3346   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
3347   createCollation(db, "RTRIM", SQLITE_UTF8, 0, rtrimCollFunc, 0);
3348   if( db->mallocFailed ){
3349     goto opendb_out;
3350   }
3351 
3352   /* Parse the filename/URI argument
3353   **
3354   ** Only allow sensible combinations of bits in the flags argument.
3355   ** Throw an error if any non-sense combination is used.  If we
3356   ** do not block illegal combinations here, it could trigger
3357   ** assert() statements in deeper layers.  Sensible combinations
3358   ** are:
3359   **
3360   **  1:  SQLITE_OPEN_READONLY
3361   **  2:  SQLITE_OPEN_READWRITE
3362   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
3363   */
3364   db->openFlags = flags;
3365   assert( SQLITE_OPEN_READONLY  == 0x01 );
3366   assert( SQLITE_OPEN_READWRITE == 0x02 );
3367   assert( SQLITE_OPEN_CREATE    == 0x04 );
3368   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
3369   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
3370   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
3371   if( ((1<<(flags&7)) & 0x46)==0 ){
3372     rc = SQLITE_MISUSE_BKPT;  /* IMP: R-18321-05872 */
3373   }else{
3374     rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
3375   }
3376   if( rc!=SQLITE_OK ){
3377     if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
3378     sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
3379     sqlite3_free(zErrMsg);
3380     goto opendb_out;
3381   }
3382 
3383   /* Open the backend database driver */
3384   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
3385                         flags | SQLITE_OPEN_MAIN_DB);
3386   if( rc!=SQLITE_OK ){
3387     if( rc==SQLITE_IOERR_NOMEM ){
3388       rc = SQLITE_NOMEM_BKPT;
3389     }
3390     sqlite3Error(db, rc);
3391     goto opendb_out;
3392   }
3393   sqlite3BtreeEnter(db->aDb[0].pBt);
3394   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
3395   if( !db->mallocFailed ){
3396     sqlite3SetTextEncoding(db, SCHEMA_ENC(db));
3397   }
3398   sqlite3BtreeLeave(db->aDb[0].pBt);
3399   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
3400 
3401   /* The default safety_level for the main database is FULL; for the temp
3402   ** database it is OFF. This matches the pager layer defaults.
3403   */
3404   db->aDb[0].zDbSName = "main";
3405   db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
3406   db->aDb[1].zDbSName = "temp";
3407   db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
3408 
3409   db->eOpenState = SQLITE_STATE_OPEN;
3410   if( db->mallocFailed ){
3411     goto opendb_out;
3412   }
3413 
3414   /* Register all built-in functions, but do not attempt to read the
3415   ** database schema yet. This is delayed until the first time the database
3416   ** is accessed.
3417   */
3418   sqlite3Error(db, SQLITE_OK);
3419   sqlite3RegisterPerConnectionBuiltinFunctions(db);
3420   rc = sqlite3_errcode(db);
3421 
3422 
3423   /* Load compiled-in extensions */
3424   for(i=0; rc==SQLITE_OK && i<ArraySize(sqlite3BuiltinExtensions); i++){
3425     rc = sqlite3BuiltinExtensions[i](db);
3426   }
3427 
3428   /* Load automatic extensions - extensions that have been registered
3429   ** using the sqlite3_automatic_extension() API.
3430   */
3431   if( rc==SQLITE_OK ){
3432     sqlite3AutoLoadExtensions(db);
3433     rc = sqlite3_errcode(db);
3434     if( rc!=SQLITE_OK ){
3435       goto opendb_out;
3436     }
3437   }
3438 
3439 #ifdef SQLITE_ENABLE_INTERNAL_FUNCTIONS
3440   /* Testing use only!!! The -DSQLITE_ENABLE_INTERNAL_FUNCTIONS=1 compile-time
3441   ** option gives access to internal functions by default.
3442   ** Testing use only!!! */
3443   db->mDbFlags |= DBFLAG_InternalFunc;
3444 #endif
3445 
3446   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
3447   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
3448   ** mode.  Doing nothing at all also makes NORMAL the default.
3449   */
3450 #ifdef SQLITE_DEFAULT_LOCKING_MODE
3451   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
3452   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
3453                           SQLITE_DEFAULT_LOCKING_MODE);
3454 #endif
3455 
3456   if( rc ) sqlite3Error(db, rc);
3457 
3458   /* Enable the lookaside-malloc subsystem */
3459   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
3460                         sqlite3GlobalConfig.nLookaside);
3461 
3462   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
3463 
3464 opendb_out:
3465   if( db ){
3466     assert( db->mutex!=0 || isThreadsafe==0
3467            || sqlite3GlobalConfig.bFullMutex==0 );
3468     sqlite3_mutex_leave(db->mutex);
3469   }
3470   rc = sqlite3_errcode(db);
3471   assert( db!=0 || (rc&0xff)==SQLITE_NOMEM );
3472   if( (rc&0xff)==SQLITE_NOMEM ){
3473     sqlite3_close(db);
3474     db = 0;
3475   }else if( rc!=SQLITE_OK ){
3476     db->eOpenState = SQLITE_STATE_SICK;
3477   }
3478   *ppDb = db;
3479 #ifdef SQLITE_ENABLE_SQLLOG
3480   if( sqlite3GlobalConfig.xSqllog ){
3481     /* Opening a db handle. Fourth parameter is passed 0. */
3482     void *pArg = sqlite3GlobalConfig.pSqllogArg;
3483     sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
3484   }
3485 #endif
3486   sqlite3_free_filename(zOpen);
3487   return rc;
3488 }
3489 
3490 
3491 /*
3492 ** Open a new database handle.
3493 */
3494 int sqlite3_open(
3495   const char *zFilename,
3496   sqlite3 **ppDb
3497 ){
3498   return openDatabase(zFilename, ppDb,
3499                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
3500 }
3501 int sqlite3_open_v2(
3502   const char *filename,   /* Database filename (UTF-8) */
3503   sqlite3 **ppDb,         /* OUT: SQLite db handle */
3504   int flags,              /* Flags */
3505   const char *zVfs        /* Name of VFS module to use */
3506 ){
3507   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
3508 }
3509 
3510 #ifndef SQLITE_OMIT_UTF16
3511 /*
3512 ** Open a new database handle.
3513 */
3514 int sqlite3_open16(
3515   const void *zFilename,
3516   sqlite3 **ppDb
3517 ){
3518   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
3519   sqlite3_value *pVal;
3520   int rc;
3521 
3522 #ifdef SQLITE_ENABLE_API_ARMOR
3523   if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
3524 #endif
3525   *ppDb = 0;
3526 #ifndef SQLITE_OMIT_AUTOINIT
3527   rc = sqlite3_initialize();
3528   if( rc ) return rc;
3529 #endif
3530   if( zFilename==0 ) zFilename = "\000\000";
3531   pVal = sqlite3ValueNew(0);
3532   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
3533   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
3534   if( zFilename8 ){
3535     rc = openDatabase(zFilename8, ppDb,
3536                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
3537     assert( *ppDb || rc==SQLITE_NOMEM );
3538     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
3539       SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
3540     }
3541   }else{
3542     rc = SQLITE_NOMEM_BKPT;
3543   }
3544   sqlite3ValueFree(pVal);
3545 
3546   return rc & 0xff;
3547 }
3548 #endif /* SQLITE_OMIT_UTF16 */
3549 
3550 /*
3551 ** Register a new collation sequence with the database handle db.
3552 */
3553 int sqlite3_create_collation(
3554   sqlite3* db,
3555   const char *zName,
3556   int enc,
3557   void* pCtx,
3558   int(*xCompare)(void*,int,const void*,int,const void*)
3559 ){
3560   return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
3561 }
3562 
3563 /*
3564 ** Register a new collation sequence with the database handle db.
3565 */
3566 int sqlite3_create_collation_v2(
3567   sqlite3* db,
3568   const char *zName,
3569   int enc,
3570   void* pCtx,
3571   int(*xCompare)(void*,int,const void*,int,const void*),
3572   void(*xDel)(void*)
3573 ){
3574   int rc;
3575 
3576 #ifdef SQLITE_ENABLE_API_ARMOR
3577   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
3578 #endif
3579   sqlite3_mutex_enter(db->mutex);
3580   assert( !db->mallocFailed );
3581   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
3582   rc = sqlite3ApiExit(db, rc);
3583   sqlite3_mutex_leave(db->mutex);
3584   return rc;
3585 }
3586 
3587 #ifndef SQLITE_OMIT_UTF16
3588 /*
3589 ** Register a new collation sequence with the database handle db.
3590 */
3591 int sqlite3_create_collation16(
3592   sqlite3* db,
3593   const void *zName,
3594   int enc,
3595   void* pCtx,
3596   int(*xCompare)(void*,int,const void*,int,const void*)
3597 ){
3598   int rc = SQLITE_OK;
3599   char *zName8;
3600 
3601 #ifdef SQLITE_ENABLE_API_ARMOR
3602   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
3603 #endif
3604   sqlite3_mutex_enter(db->mutex);
3605   assert( !db->mallocFailed );
3606   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
3607   if( zName8 ){
3608     rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
3609     sqlite3DbFree(db, zName8);
3610   }
3611   rc = sqlite3ApiExit(db, rc);
3612   sqlite3_mutex_leave(db->mutex);
3613   return rc;
3614 }
3615 #endif /* SQLITE_OMIT_UTF16 */
3616 
3617 /*
3618 ** Register a collation sequence factory callback with the database handle
3619 ** db. Replace any previously installed collation sequence factory.
3620 */
3621 int sqlite3_collation_needed(
3622   sqlite3 *db,
3623   void *pCollNeededArg,
3624   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
3625 ){
3626 #ifdef SQLITE_ENABLE_API_ARMOR
3627   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3628 #endif
3629   sqlite3_mutex_enter(db->mutex);
3630   db->xCollNeeded = xCollNeeded;
3631   db->xCollNeeded16 = 0;
3632   db->pCollNeededArg = pCollNeededArg;
3633   sqlite3_mutex_leave(db->mutex);
3634   return SQLITE_OK;
3635 }
3636 
3637 #ifndef SQLITE_OMIT_UTF16
3638 /*
3639 ** Register a collation sequence factory callback with the database handle
3640 ** db. Replace any previously installed collation sequence factory.
3641 */
3642 int sqlite3_collation_needed16(
3643   sqlite3 *db,
3644   void *pCollNeededArg,
3645   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
3646 ){
3647 #ifdef SQLITE_ENABLE_API_ARMOR
3648   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3649 #endif
3650   sqlite3_mutex_enter(db->mutex);
3651   db->xCollNeeded = 0;
3652   db->xCollNeeded16 = xCollNeeded16;
3653   db->pCollNeededArg = pCollNeededArg;
3654   sqlite3_mutex_leave(db->mutex);
3655   return SQLITE_OK;
3656 }
3657 #endif /* SQLITE_OMIT_UTF16 */
3658 
3659 #ifndef SQLITE_OMIT_DEPRECATED
3660 /*
3661 ** This function is now an anachronism. It used to be used to recover from a
3662 ** malloc() failure, but SQLite now does this automatically.
3663 */
3664 int sqlite3_global_recover(void){
3665   return SQLITE_OK;
3666 }
3667 #endif
3668 
3669 /*
3670 ** Test to see whether or not the database connection is in autocommit
3671 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
3672 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
3673 ** by the next COMMIT or ROLLBACK.
3674 */
3675 int sqlite3_get_autocommit(sqlite3 *db){
3676 #ifdef SQLITE_ENABLE_API_ARMOR
3677   if( !sqlite3SafetyCheckOk(db) ){
3678     (void)SQLITE_MISUSE_BKPT;
3679     return 0;
3680   }
3681 #endif
3682   return db->autoCommit;
3683 }
3684 
3685 /*
3686 ** The following routines are substitutes for constants SQLITE_CORRUPT,
3687 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
3688 ** constants.  They serve two purposes:
3689 **
3690 **   1.  Serve as a convenient place to set a breakpoint in a debugger
3691 **       to detect when version error conditions occurs.
3692 **
3693 **   2.  Invoke sqlite3_log() to provide the source code location where
3694 **       a low-level error is first detected.
3695 */
3696 int sqlite3ReportError(int iErr, int lineno, const char *zType){
3697   sqlite3_log(iErr, "%s at line %d of [%.10s]",
3698               zType, lineno, 20+sqlite3_sourceid());
3699   return iErr;
3700 }
3701 int sqlite3CorruptError(int lineno){
3702   testcase( sqlite3GlobalConfig.xLog!=0 );
3703   return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
3704 }
3705 int sqlite3MisuseError(int lineno){
3706   testcase( sqlite3GlobalConfig.xLog!=0 );
3707   return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
3708 }
3709 int sqlite3CantopenError(int lineno){
3710   testcase( sqlite3GlobalConfig.xLog!=0 );
3711   return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
3712 }
3713 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
3714 int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
3715   char zMsg[100];
3716   sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
3717   testcase( sqlite3GlobalConfig.xLog!=0 );
3718   return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
3719 }
3720 #endif
3721 #ifdef SQLITE_DEBUG
3722 int sqlite3NomemError(int lineno){
3723   testcase( sqlite3GlobalConfig.xLog!=0 );
3724   return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
3725 }
3726 int sqlite3IoerrnomemError(int lineno){
3727   testcase( sqlite3GlobalConfig.xLog!=0 );
3728   return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
3729 }
3730 #endif
3731 
3732 #ifndef SQLITE_OMIT_DEPRECATED
3733 /*
3734 ** This is a convenience routine that makes sure that all thread-specific
3735 ** data for this thread has been deallocated.
3736 **
3737 ** SQLite no longer uses thread-specific data so this routine is now a
3738 ** no-op.  It is retained for historical compatibility.
3739 */
3740 void sqlite3_thread_cleanup(void){
3741 }
3742 #endif
3743 
3744 /*
3745 ** Return meta information about a specific column of a database table.
3746 ** See comment in sqlite3.h (sqlite.h.in) for details.
3747 */
3748 int sqlite3_table_column_metadata(
3749   sqlite3 *db,                /* Connection handle */
3750   const char *zDbName,        /* Database name or NULL */
3751   const char *zTableName,     /* Table name */
3752   const char *zColumnName,    /* Column name */
3753   char const **pzDataType,    /* OUTPUT: Declared data type */
3754   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
3755   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
3756   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
3757   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
3758 ){
3759   int rc;
3760   char *zErrMsg = 0;
3761   Table *pTab = 0;
3762   Column *pCol = 0;
3763   int iCol = 0;
3764   char const *zDataType = 0;
3765   char const *zCollSeq = 0;
3766   int notnull = 0;
3767   int primarykey = 0;
3768   int autoinc = 0;
3769 
3770 
3771 #ifdef SQLITE_ENABLE_API_ARMOR
3772   if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
3773     return SQLITE_MISUSE_BKPT;
3774   }
3775 #endif
3776 
3777   /* Ensure the database schema has been loaded */
3778   sqlite3_mutex_enter(db->mutex);
3779   sqlite3BtreeEnterAll(db);
3780   rc = sqlite3Init(db, &zErrMsg);
3781   if( SQLITE_OK!=rc ){
3782     goto error_out;
3783   }
3784 
3785   /* Locate the table in question */
3786   pTab = sqlite3FindTable(db, zTableName, zDbName);
3787   if( !pTab || IsView(pTab) ){
3788     pTab = 0;
3789     goto error_out;
3790   }
3791 
3792   /* Find the column for which info is requested */
3793   if( zColumnName==0 ){
3794     /* Query for existance of table only */
3795   }else{
3796     for(iCol=0; iCol<pTab->nCol; iCol++){
3797       pCol = &pTab->aCol[iCol];
3798       if( 0==sqlite3StrICmp(pCol->zCnName, zColumnName) ){
3799         break;
3800       }
3801     }
3802     if( iCol==pTab->nCol ){
3803       if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
3804         iCol = pTab->iPKey;
3805         pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
3806       }else{
3807         pTab = 0;
3808         goto error_out;
3809       }
3810     }
3811   }
3812 
3813   /* The following block stores the meta information that will be returned
3814   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
3815   ** and autoinc. At this point there are two possibilities:
3816   **
3817   **     1. The specified column name was rowid", "oid" or "_rowid_"
3818   **        and there is no explicitly declared IPK column.
3819   **
3820   **     2. The table is not a view and the column name identified an
3821   **        explicitly declared column. Copy meta information from *pCol.
3822   */
3823   if( pCol ){
3824     zDataType = sqlite3ColumnType(pCol,0);
3825     zCollSeq = sqlite3ColumnColl(pCol);
3826     notnull = pCol->notNull!=0;
3827     primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
3828     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
3829   }else{
3830     zDataType = "INTEGER";
3831     primarykey = 1;
3832   }
3833   if( !zCollSeq ){
3834     zCollSeq = sqlite3StrBINARY;
3835   }
3836 
3837 error_out:
3838   sqlite3BtreeLeaveAll(db);
3839 
3840   /* Whether the function call succeeded or failed, set the output parameters
3841   ** to whatever their local counterparts contain. If an error did occur,
3842   ** this has the effect of zeroing all output parameters.
3843   */
3844   if( pzDataType ) *pzDataType = zDataType;
3845   if( pzCollSeq ) *pzCollSeq = zCollSeq;
3846   if( pNotNull ) *pNotNull = notnull;
3847   if( pPrimaryKey ) *pPrimaryKey = primarykey;
3848   if( pAutoinc ) *pAutoinc = autoinc;
3849 
3850   if( SQLITE_OK==rc && !pTab ){
3851     sqlite3DbFree(db, zErrMsg);
3852     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
3853         zColumnName);
3854     rc = SQLITE_ERROR;
3855   }
3856   sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
3857   sqlite3DbFree(db, zErrMsg);
3858   rc = sqlite3ApiExit(db, rc);
3859   sqlite3_mutex_leave(db->mutex);
3860   return rc;
3861 }
3862 
3863 /*
3864 ** Sleep for a little while.  Return the amount of time slept.
3865 */
3866 int sqlite3_sleep(int ms){
3867   sqlite3_vfs *pVfs;
3868   int rc;
3869   pVfs = sqlite3_vfs_find(0);
3870   if( pVfs==0 ) return 0;
3871 
3872   /* This function works in milliseconds, but the underlying OsSleep()
3873   ** API uses microseconds. Hence the 1000's.
3874   */
3875   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
3876   return rc;
3877 }
3878 
3879 /*
3880 ** Enable or disable the extended result codes.
3881 */
3882 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
3883 #ifdef SQLITE_ENABLE_API_ARMOR
3884   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3885 #endif
3886   sqlite3_mutex_enter(db->mutex);
3887   db->errMask = onoff ? 0xffffffff : 0xff;
3888   sqlite3_mutex_leave(db->mutex);
3889   return SQLITE_OK;
3890 }
3891 
3892 /*
3893 ** Invoke the xFileControl method on a particular database.
3894 */
3895 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
3896   int rc = SQLITE_ERROR;
3897   Btree *pBtree;
3898 
3899 #ifdef SQLITE_ENABLE_API_ARMOR
3900   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3901 #endif
3902   sqlite3_mutex_enter(db->mutex);
3903   pBtree = sqlite3DbNameToBtree(db, zDbName);
3904   if( pBtree ){
3905     Pager *pPager;
3906     sqlite3_file *fd;
3907     sqlite3BtreeEnter(pBtree);
3908     pPager = sqlite3BtreePager(pBtree);
3909     assert( pPager!=0 );
3910     fd = sqlite3PagerFile(pPager);
3911     assert( fd!=0 );
3912     if( op==SQLITE_FCNTL_FILE_POINTER ){
3913       *(sqlite3_file**)pArg = fd;
3914       rc = SQLITE_OK;
3915     }else if( op==SQLITE_FCNTL_VFS_POINTER ){
3916       *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
3917       rc = SQLITE_OK;
3918     }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
3919       *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
3920       rc = SQLITE_OK;
3921     }else if( op==SQLITE_FCNTL_DATA_VERSION ){
3922       *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager);
3923       rc = SQLITE_OK;
3924     }else if( op==SQLITE_FCNTL_RESERVE_BYTES ){
3925       int iNew = *(int*)pArg;
3926       *(int*)pArg = sqlite3BtreeGetRequestedReserve(pBtree);
3927       if( iNew>=0 && iNew<=255 ){
3928         sqlite3BtreeSetPageSize(pBtree, 0, iNew, 0);
3929       }
3930       rc = SQLITE_OK;
3931     }else{
3932       int nSave = db->busyHandler.nBusy;
3933       rc = sqlite3OsFileControl(fd, op, pArg);
3934       db->busyHandler.nBusy = nSave;
3935     }
3936     sqlite3BtreeLeave(pBtree);
3937   }
3938   sqlite3_mutex_leave(db->mutex);
3939   return rc;
3940 }
3941 
3942 /*
3943 ** Interface to the testing logic.
3944 */
3945 int sqlite3_test_control(int op, ...){
3946   int rc = 0;
3947 #ifdef SQLITE_UNTESTABLE
3948   UNUSED_PARAMETER(op);
3949 #else
3950   va_list ap;
3951   va_start(ap, op);
3952   switch( op ){
3953 
3954     /*
3955     ** Save the current state of the PRNG.
3956     */
3957     case SQLITE_TESTCTRL_PRNG_SAVE: {
3958       sqlite3PrngSaveState();
3959       break;
3960     }
3961 
3962     /*
3963     ** Restore the state of the PRNG to the last state saved using
3964     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
3965     ** this verb acts like PRNG_RESET.
3966     */
3967     case SQLITE_TESTCTRL_PRNG_RESTORE: {
3968       sqlite3PrngRestoreState();
3969       break;
3970     }
3971 
3972     /*  sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, int x, sqlite3 *db);
3973     **
3974     ** Control the seed for the pseudo-random number generator (PRNG) that
3975     ** is built into SQLite.  Cases:
3976     **
3977     **    x!=0 && db!=0       Seed the PRNG to the current value of the
3978     **                        schema cookie in the main database for db, or
3979     **                        x if the schema cookie is zero.  This case
3980     **                        is convenient to use with database fuzzers
3981     **                        as it allows the fuzzer some control over the
3982     **                        the PRNG seed.
3983     **
3984     **    x!=0 && db==0       Seed the PRNG to the value of x.
3985     **
3986     **    x==0 && db==0       Revert to default behavior of using the
3987     **                        xRandomness method on the primary VFS.
3988     **
3989     ** This test-control also resets the PRNG so that the new seed will
3990     ** be used for the next call to sqlite3_randomness().
3991     */
3992 #ifndef SQLITE_OMIT_WSD
3993     case SQLITE_TESTCTRL_PRNG_SEED: {
3994       int x = va_arg(ap, int);
3995       int y;
3996       sqlite3 *db = va_arg(ap, sqlite3*);
3997       assert( db==0 || db->aDb[0].pSchema!=0 );
3998       if( db && (y = db->aDb[0].pSchema->schema_cookie)!=0 ){ x = y; }
3999       sqlite3Config.iPrngSeed = x;
4000       sqlite3_randomness(0,0);
4001       break;
4002     }
4003 #endif
4004 
4005     /*
4006     **  sqlite3_test_control(BITVEC_TEST, size, program)
4007     **
4008     ** Run a test against a Bitvec object of size.  The program argument
4009     ** is an array of integers that defines the test.  Return -1 on a
4010     ** memory allocation error, 0 on success, or non-zero for an error.
4011     ** See the sqlite3BitvecBuiltinTest() for additional information.
4012     */
4013     case SQLITE_TESTCTRL_BITVEC_TEST: {
4014       int sz = va_arg(ap, int);
4015       int *aProg = va_arg(ap, int*);
4016       rc = sqlite3BitvecBuiltinTest(sz, aProg);
4017       break;
4018     }
4019 
4020     /*
4021     **  sqlite3_test_control(FAULT_INSTALL, xCallback)
4022     **
4023     ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
4024     ** if xCallback is not NULL.
4025     **
4026     ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
4027     ** is called immediately after installing the new callback and the return
4028     ** value from sqlite3FaultSim(0) becomes the return from
4029     ** sqlite3_test_control().
4030     */
4031     case SQLITE_TESTCTRL_FAULT_INSTALL: {
4032       /* A bug in MSVC prevents it from understanding pointers to functions
4033       ** types in the second argument to va_arg().  Work around the problem
4034       ** using a typedef.
4035       ** http://support.microsoft.com/kb/47961  <-- dead hyperlink
4036       ** Search at http://web.archive.org/ to find the 2015-03-16 archive
4037       ** of the link above to see the original text.
4038       ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
4039       */
4040       typedef int(*sqlite3FaultFuncType)(int);
4041       sqlite3GlobalConfig.xTestCallback = va_arg(ap, sqlite3FaultFuncType);
4042       rc = sqlite3FaultSim(0);
4043       break;
4044     }
4045 
4046     /*
4047     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
4048     **
4049     ** Register hooks to call to indicate which malloc() failures
4050     ** are benign.
4051     */
4052     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
4053       typedef void (*void_function)(void);
4054       void_function xBenignBegin;
4055       void_function xBenignEnd;
4056       xBenignBegin = va_arg(ap, void_function);
4057       xBenignEnd = va_arg(ap, void_function);
4058       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
4059       break;
4060     }
4061 
4062     /*
4063     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
4064     **
4065     ** Set the PENDING byte to the value in the argument, if X>0.
4066     ** Make no changes if X==0.  Return the value of the pending byte
4067     ** as it existing before this routine was called.
4068     **
4069     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
4070     ** an incompatible database file format.  Changing the PENDING byte
4071     ** while any database connection is open results in undefined and
4072     ** deleterious behavior.
4073     */
4074     case SQLITE_TESTCTRL_PENDING_BYTE: {
4075       rc = PENDING_BYTE;
4076 #ifndef SQLITE_OMIT_WSD
4077       {
4078         unsigned int newVal = va_arg(ap, unsigned int);
4079         if( newVal ) sqlite3PendingByte = newVal;
4080       }
4081 #endif
4082       break;
4083     }
4084 
4085     /*
4086     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
4087     **
4088     ** This action provides a run-time test to see whether or not
4089     ** assert() was enabled at compile-time.  If X is true and assert()
4090     ** is enabled, then the return value is true.  If X is true and
4091     ** assert() is disabled, then the return value is zero.  If X is
4092     ** false and assert() is enabled, then the assertion fires and the
4093     ** process aborts.  If X is false and assert() is disabled, then the
4094     ** return value is zero.
4095     */
4096     case SQLITE_TESTCTRL_ASSERT: {
4097       volatile int x = 0;
4098       assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
4099       rc = x;
4100 #if defined(SQLITE_DEBUG)
4101       /* Invoke these debugging routines so that the compiler does not
4102       ** issue "defined but not used" warnings. */
4103       if( x==9999 ){
4104         sqlite3ShowExpr(0);
4105         sqlite3ShowExpr(0);
4106         sqlite3ShowExprList(0);
4107         sqlite3ShowIdList(0);
4108         sqlite3ShowSrcList(0);
4109         sqlite3ShowWith(0);
4110         sqlite3ShowUpsert(0);
4111         sqlite3ShowTriggerStep(0);
4112         sqlite3ShowTriggerStepList(0);
4113         sqlite3ShowTrigger(0);
4114         sqlite3ShowTriggerList(0);
4115 #ifndef SQLITE_OMIT_WINDOWFUNC
4116         sqlite3ShowWindow(0);
4117         sqlite3ShowWinFunc(0);
4118 #endif
4119         sqlite3ShowSelect(0);
4120       }
4121 #endif
4122       break;
4123     }
4124 
4125 
4126     /*
4127     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
4128     **
4129     ** This action provides a run-time test to see how the ALWAYS and
4130     ** NEVER macros were defined at compile-time.
4131     **
4132     ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
4133     **
4134     ** The recommended test is X==2.  If the return value is 2, that means
4135     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
4136     ** default setting.  If the return value is 1, then ALWAYS() is either
4137     ** hard-coded to true or else it asserts if its argument is false.
4138     ** The first behavior (hard-coded to true) is the case if
4139     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
4140     ** behavior (assert if the argument to ALWAYS() is false) is the case if
4141     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
4142     **
4143     ** The run-time test procedure might look something like this:
4144     **
4145     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
4146     **      // ALWAYS() and NEVER() are no-op pass-through macros
4147     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
4148     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
4149     **    }else{
4150     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
4151     **    }
4152     */
4153     case SQLITE_TESTCTRL_ALWAYS: {
4154       int x = va_arg(ap,int);
4155       rc = x ? ALWAYS(x) : 0;
4156       break;
4157     }
4158 
4159     /*
4160     **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
4161     **
4162     ** The integer returned reveals the byte-order of the computer on which
4163     ** SQLite is running:
4164     **
4165     **       1     big-endian,    determined at run-time
4166     **      10     little-endian, determined at run-time
4167     **  432101     big-endian,    determined at compile-time
4168     **  123410     little-endian, determined at compile-time
4169     */
4170     case SQLITE_TESTCTRL_BYTEORDER: {
4171       rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
4172       break;
4173     }
4174 
4175     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
4176     **
4177     ** Enable or disable various optimizations for testing purposes.  The
4178     ** argument N is a bitmask of optimizations to be disabled.  For normal
4179     ** operation N should be 0.  The idea is that a test program (like the
4180     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
4181     ** with various optimizations disabled to verify that the same answer
4182     ** is obtained in every case.
4183     */
4184     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
4185       sqlite3 *db = va_arg(ap, sqlite3*);
4186       db->dbOptFlags = va_arg(ap, u32);
4187       break;
4188     }
4189 
4190     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, onoff, xAlt);
4191     **
4192     ** If parameter onoff is 1, subsequent calls to localtime() fail.
4193     ** If 2, then invoke xAlt() instead of localtime().  If 0, normal
4194     ** processing.
4195     **
4196     ** xAlt arguments are void pointers, but they really want to be:
4197     **
4198     **    int xAlt(const time_t*, struct tm*);
4199     **
4200     ** xAlt should write results in to struct tm object of its 2nd argument
4201     ** and return zero on success, or return non-zero on failure.
4202     */
4203     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
4204       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
4205       if( sqlite3GlobalConfig.bLocaltimeFault==2 ){
4206         typedef int(*sqlite3LocaltimeType)(const void*,void*);
4207         sqlite3GlobalConfig.xAltLocaltime = va_arg(ap, sqlite3LocaltimeType);
4208       }else{
4209         sqlite3GlobalConfig.xAltLocaltime = 0;
4210       }
4211       break;
4212     }
4213 
4214     /*   sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, sqlite3*);
4215     **
4216     ** Toggle the ability to use internal functions on or off for
4217     ** the database connection given in the argument.
4218     */
4219     case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: {
4220       sqlite3 *db = va_arg(ap, sqlite3*);
4221       db->mDbFlags ^= DBFLAG_InternalFunc;
4222       break;
4223     }
4224 
4225     /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
4226     **
4227     ** Set or clear a flag that indicates that the database file is always well-
4228     ** formed and never corrupt.  This flag is clear by default, indicating that
4229     ** database files might have arbitrary corruption.  Setting the flag during
4230     ** testing causes certain assert() statements in the code to be activated
4231     ** that demonstrat invariants on well-formed database files.
4232     */
4233     case SQLITE_TESTCTRL_NEVER_CORRUPT: {
4234       sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
4235       break;
4236     }
4237 
4238     /*   sqlite3_test_control(SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS, int);
4239     **
4240     ** Set or clear a flag that causes SQLite to verify that type, name,
4241     ** and tbl_name fields of the sqlite_schema table.  This is normally
4242     ** on, but it is sometimes useful to turn it off for testing.
4243     **
4244     ** 2020-07-22:  Disabling EXTRA_SCHEMA_CHECKS also disables the
4245     ** verification of rootpage numbers when parsing the schema.  This
4246     ** is useful to make it easier to reach strange internal error states
4247     ** during testing.  The EXTRA_SCHEMA_CHECKS setting is always enabled
4248     ** in production.
4249     */
4250     case SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS: {
4251       sqlite3GlobalConfig.bExtraSchemaChecks = va_arg(ap, int);
4252       break;
4253     }
4254 
4255     /* Set the threshold at which OP_Once counters reset back to zero.
4256     ** By default this is 0x7ffffffe (over 2 billion), but that value is
4257     ** too big to test in a reasonable amount of time, so this control is
4258     ** provided to set a small and easily reachable reset value.
4259     */
4260     case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
4261       sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
4262       break;
4263     }
4264 
4265     /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
4266     **
4267     ** Set the VDBE coverage callback function to xCallback with context
4268     ** pointer ptr.
4269     */
4270     case SQLITE_TESTCTRL_VDBE_COVERAGE: {
4271 #ifdef SQLITE_VDBE_COVERAGE
4272       typedef void (*branch_callback)(void*,unsigned int,
4273                                       unsigned char,unsigned char);
4274       sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
4275       sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
4276 #endif
4277       break;
4278     }
4279 
4280     /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
4281     case SQLITE_TESTCTRL_SORTER_MMAP: {
4282       sqlite3 *db = va_arg(ap, sqlite3*);
4283       db->nMaxSorterMmap = va_arg(ap, int);
4284       break;
4285     }
4286 
4287     /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
4288     **
4289     ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
4290     ** not.
4291     */
4292     case SQLITE_TESTCTRL_ISINIT: {
4293       if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
4294       break;
4295     }
4296 
4297     /*  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
4298     **
4299     ** This test control is used to create imposter tables.  "db" is a pointer
4300     ** to the database connection.  dbName is the database name (ex: "main" or
4301     ** "temp") which will receive the imposter.  "onOff" turns imposter mode on
4302     ** or off.  "tnum" is the root page of the b-tree to which the imposter
4303     ** table should connect.
4304     **
4305     ** Enable imposter mode only when the schema has already been parsed.  Then
4306     ** run a single CREATE TABLE statement to construct the imposter table in
4307     ** the parsed schema.  Then turn imposter mode back off again.
4308     **
4309     ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
4310     ** the schema to be reparsed the next time it is needed.  This has the
4311     ** effect of erasing all imposter tables.
4312     */
4313     case SQLITE_TESTCTRL_IMPOSTER: {
4314       sqlite3 *db = va_arg(ap, sqlite3*);
4315       int iDb;
4316       sqlite3_mutex_enter(db->mutex);
4317       iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
4318       if( iDb>=0 ){
4319         db->init.iDb = iDb;
4320         db->init.busy = db->init.imposterTable = va_arg(ap,int);
4321         db->init.newTnum = va_arg(ap,int);
4322         if( db->init.busy==0 && db->init.newTnum>0 ){
4323           sqlite3ResetAllSchemasOfConnection(db);
4324         }
4325       }
4326       sqlite3_mutex_leave(db->mutex);
4327       break;
4328     }
4329 
4330 #if defined(YYCOVERAGE)
4331     /*  sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
4332     **
4333     ** This test control (only available when SQLite is compiled with
4334     ** -DYYCOVERAGE) writes a report onto "out" that shows all
4335     ** state/lookahead combinations in the parser state machine
4336     ** which are never exercised.  If any state is missed, make the
4337     ** return code SQLITE_ERROR.
4338     */
4339     case SQLITE_TESTCTRL_PARSER_COVERAGE: {
4340       FILE *out = va_arg(ap, FILE*);
4341       if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
4342       break;
4343     }
4344 #endif /* defined(YYCOVERAGE) */
4345 
4346     /*  sqlite3_test_control(SQLITE_TESTCTRL_RESULT_INTREAL, sqlite3_context*);
4347     **
4348     ** This test-control causes the most recent sqlite3_result_int64() value
4349     ** to be interpreted as a MEM_IntReal instead of as an MEM_Int.  Normally,
4350     ** MEM_IntReal values only arise during an INSERT operation of integer
4351     ** values into a REAL column, so they can be challenging to test.  This
4352     ** test-control enables us to write an intreal() SQL function that can
4353     ** inject an intreal() value at arbitrary places in an SQL statement,
4354     ** for testing purposes.
4355     */
4356     case SQLITE_TESTCTRL_RESULT_INTREAL: {
4357       sqlite3_context *pCtx = va_arg(ap, sqlite3_context*);
4358       sqlite3ResultIntReal(pCtx);
4359       break;
4360     }
4361 
4362     /*  sqlite3_test_control(SQLITE_TESTCTRL_SEEK_COUNT,
4363     **    sqlite3 *db,    // Database connection
4364     **    u64 *pnSeek     // Write seek count here
4365     **  );
4366     **
4367     ** This test-control queries the seek-counter on the "main" database
4368     ** file.  The seek-counter is written into *pnSeek and is then reset.
4369     ** The seek-count is only available if compiled with SQLITE_DEBUG.
4370     */
4371     case SQLITE_TESTCTRL_SEEK_COUNT: {
4372       sqlite3 *db = va_arg(ap, sqlite3*);
4373       u64 *pn = va_arg(ap, sqlite3_uint64*);
4374       *pn = sqlite3BtreeSeekCount(db->aDb->pBt);
4375       (void)db;  /* Silence harmless unused variable warning */
4376       break;
4377     }
4378 
4379     /*  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, op, ptr)
4380     **
4381     **  "ptr" is a pointer to a u32.
4382     **
4383     **   op==0       Store the current sqlite3TreeTrace in *ptr
4384     **   op==1       Set sqlite3TreeTrace to the value *ptr
4385     **   op==3       Store the current sqlite3WhereTrace in *ptr
4386     **   op==3       Set sqlite3WhereTrace to the value *ptr
4387     */
4388     case SQLITE_TESTCTRL_TRACEFLAGS: {
4389        int opTrace = va_arg(ap, int);
4390        u32 *ptr = va_arg(ap, u32*);
4391        switch( opTrace ){
4392          case 0:   *ptr = sqlite3TreeTrace;      break;
4393          case 1:   sqlite3TreeTrace = *ptr;      break;
4394          case 2:   *ptr = sqlite3WhereTrace;     break;
4395          case 3:   sqlite3WhereTrace = *ptr;     break;
4396        }
4397        break;
4398     }
4399 
4400     /* sqlite3_test_control(SQLITE_TESTCTRL_LOGEST,
4401     **      double fIn,     // Input value
4402     **      int *pLogEst,   // sqlite3LogEstFromDouble(fIn)
4403     **      u64 *pInt,      // sqlite3LogEstToInt(*pLogEst)
4404     **      int *pLogEst2   // sqlite3LogEst(*pInt)
4405     ** );
4406     **
4407     ** Test access for the LogEst conversion routines.
4408     */
4409     case SQLITE_TESTCTRL_LOGEST: {
4410       double rIn = va_arg(ap, double);
4411       LogEst rLogEst = sqlite3LogEstFromDouble(rIn);
4412       int *pI1 = va_arg(ap,int*);
4413       u64 *pU64 = va_arg(ap,u64*);
4414       int *pI2 = va_arg(ap,int*);
4415       *pI1 = rLogEst;
4416       *pU64 = sqlite3LogEstToInt(rLogEst);
4417       *pI2 = sqlite3LogEst(*pU64);
4418       break;
4419     }
4420 
4421 
4422 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
4423     /* sqlite3_test_control(SQLITE_TESTCTRL_TUNE, id, *piValue)
4424     **
4425     ** If "id" is an integer between 1 and SQLITE_NTUNE then set the value
4426     ** of the id-th tuning parameter to *piValue.  If "id" is between -1
4427     ** and -SQLITE_NTUNE, then write the current value of the (-id)-th
4428     ** tuning parameter into *piValue.
4429     **
4430     ** Tuning parameters are for use during transient development builds,
4431     ** to help find the best values for constants in the query planner.
4432     ** Access tuning parameters using the Tuning(ID) macro.  Set the
4433     ** parameters in the CLI using ".testctrl tune ID VALUE".
4434     **
4435     ** Transient use only.  Tuning parameters should not be used in
4436     ** checked-in code.
4437     */
4438     case SQLITE_TESTCTRL_TUNE: {
4439       int id = va_arg(ap, int);
4440       int *piValue = va_arg(ap, int*);
4441       if( id>0 && id<=SQLITE_NTUNE ){
4442         Tuning(id) = *piValue;
4443       }else if( id<0 && id>=-SQLITE_NTUNE ){
4444         *piValue = Tuning(-id);
4445       }else{
4446         rc = SQLITE_NOTFOUND;
4447       }
4448       break;
4449     }
4450 #endif
4451   }
4452   va_end(ap);
4453 #endif /* SQLITE_UNTESTABLE */
4454   return rc;
4455 }
4456 
4457 /*
4458 ** The Pager stores the Database filename, Journal filename, and WAL filename
4459 ** consecutively in memory, in that order.  The database filename is prefixed
4460 ** by four zero bytes.  Locate the start of the database filename by searching
4461 ** backwards for the first byte following four consecutive zero bytes.
4462 **
4463 ** This only works if the filename passed in was obtained from the Pager.
4464 */
4465 static const char *databaseName(const char *zName){
4466   while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
4467     zName--;
4468   }
4469   return zName;
4470 }
4471 
4472 /*
4473 ** Append text z[] to the end of p[].  Return a pointer to the first
4474 ** character after then zero terminator on the new text in p[].
4475 */
4476 static char *appendText(char *p, const char *z){
4477   size_t n = strlen(z);
4478   memcpy(p, z, n+1);
4479   return p+n+1;
4480 }
4481 
4482 /*
4483 ** Allocate memory to hold names for a database, journal file, WAL file,
4484 ** and query parameters.  The pointer returned is valid for use by
4485 ** sqlite3_filename_database() and sqlite3_uri_parameter() and related
4486 ** functions.
4487 **
4488 ** Memory layout must be compatible with that generated by the pager
4489 ** and expected by sqlite3_uri_parameter() and databaseName().
4490 */
4491 char *sqlite3_create_filename(
4492   const char *zDatabase,
4493   const char *zJournal,
4494   const char *zWal,
4495   int nParam,
4496   const char **azParam
4497 ){
4498   sqlite3_int64 nByte;
4499   int i;
4500   char *pResult, *p;
4501   nByte = strlen(zDatabase) + strlen(zJournal) + strlen(zWal) + 10;
4502   for(i=0; i<nParam*2; i++){
4503     nByte += strlen(azParam[i])+1;
4504   }
4505   pResult = p = sqlite3_malloc64( nByte );
4506   if( p==0 ) return 0;
4507   memset(p, 0, 4);
4508   p += 4;
4509   p = appendText(p, zDatabase);
4510   for(i=0; i<nParam*2; i++){
4511     p = appendText(p, azParam[i]);
4512   }
4513   *(p++) = 0;
4514   p = appendText(p, zJournal);
4515   p = appendText(p, zWal);
4516   *(p++) = 0;
4517   *(p++) = 0;
4518   assert( (sqlite3_int64)(p - pResult)==nByte );
4519   return pResult + 4;
4520 }
4521 
4522 /*
4523 ** Free memory obtained from sqlite3_create_filename().  It is a severe
4524 ** error to call this routine with any parameter other than a pointer
4525 ** previously obtained from sqlite3_create_filename() or a NULL pointer.
4526 */
4527 void sqlite3_free_filename(char *p){
4528   if( p==0 ) return;
4529   p = (char*)databaseName(p);
4530   sqlite3_free(p - 4);
4531 }
4532 
4533 
4534 /*
4535 ** This is a utility routine, useful to VFS implementations, that checks
4536 ** to see if a database file was a URI that contained a specific query
4537 ** parameter, and if so obtains the value of the query parameter.
4538 **
4539 ** The zFilename argument is the filename pointer passed into the xOpen()
4540 ** method of a VFS implementation.  The zParam argument is the name of the
4541 ** query parameter we seek.  This routine returns the value of the zParam
4542 ** parameter if it exists.  If the parameter does not exist, this routine
4543 ** returns a NULL pointer.
4544 */
4545 const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
4546   if( zFilename==0 || zParam==0 ) return 0;
4547   zFilename = databaseName(zFilename);
4548   return uriParameter(zFilename, zParam);
4549 }
4550 
4551 /*
4552 ** Return a pointer to the name of Nth query parameter of the filename.
4553 */
4554 const char *sqlite3_uri_key(const char *zFilename, int N){
4555   if( zFilename==0 || N<0 ) return 0;
4556   zFilename = databaseName(zFilename);
4557   zFilename += sqlite3Strlen30(zFilename) + 1;
4558   while( ALWAYS(zFilename) && zFilename[0] && (N--)>0 ){
4559     zFilename += sqlite3Strlen30(zFilename) + 1;
4560     zFilename += sqlite3Strlen30(zFilename) + 1;
4561   }
4562   return zFilename[0] ? zFilename : 0;
4563 }
4564 
4565 /*
4566 ** Return a boolean value for a query parameter.
4567 */
4568 int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
4569   const char *z = sqlite3_uri_parameter(zFilename, zParam);
4570   bDflt = bDflt!=0;
4571   return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
4572 }
4573 
4574 /*
4575 ** Return a 64-bit integer value for a query parameter.
4576 */
4577 sqlite3_int64 sqlite3_uri_int64(
4578   const char *zFilename,    /* Filename as passed to xOpen */
4579   const char *zParam,       /* URI parameter sought */
4580   sqlite3_int64 bDflt       /* return if parameter is missing */
4581 ){
4582   const char *z = sqlite3_uri_parameter(zFilename, zParam);
4583   sqlite3_int64 v;
4584   if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
4585     bDflt = v;
4586   }
4587   return bDflt;
4588 }
4589 
4590 /*
4591 ** Translate a filename that was handed to a VFS routine into the corresponding
4592 ** database, journal, or WAL file.
4593 **
4594 ** It is an error to pass this routine a filename string that was not
4595 ** passed into the VFS from the SQLite core.  Doing so is similar to
4596 ** passing free() a pointer that was not obtained from malloc() - it is
4597 ** an error that we cannot easily detect but that will likely cause memory
4598 ** corruption.
4599 */
4600 const char *sqlite3_filename_database(const char *zFilename){
4601   if( zFilename==0 ) return 0;
4602   return databaseName(zFilename);
4603 }
4604 const char *sqlite3_filename_journal(const char *zFilename){
4605   if( zFilename==0 ) return 0;
4606   zFilename = databaseName(zFilename);
4607   zFilename += sqlite3Strlen30(zFilename) + 1;
4608   while( ALWAYS(zFilename) && zFilename[0] ){
4609     zFilename += sqlite3Strlen30(zFilename) + 1;
4610     zFilename += sqlite3Strlen30(zFilename) + 1;
4611   }
4612   return zFilename + 1;
4613 }
4614 const char *sqlite3_filename_wal(const char *zFilename){
4615 #ifdef SQLITE_OMIT_WAL
4616   return 0;
4617 #else
4618   zFilename = sqlite3_filename_journal(zFilename);
4619   if( zFilename ) zFilename += sqlite3Strlen30(zFilename) + 1;
4620   return zFilename;
4621 #endif
4622 }
4623 
4624 /*
4625 ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
4626 */
4627 Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
4628   int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
4629   return iDb<0 ? 0 : db->aDb[iDb].pBt;
4630 }
4631 
4632 /*
4633 ** Return the name of the N-th database schema.  Return NULL if N is out
4634 ** of range.
4635 */
4636 const char *sqlite3_db_name(sqlite3 *db, int N){
4637 #ifdef SQLITE_ENABLE_API_ARMOR
4638   if( !sqlite3SafetyCheckOk(db) ){
4639     (void)SQLITE_MISUSE_BKPT;
4640     return 0;
4641   }
4642 #endif
4643   if( N<0 || N>=db->nDb ){
4644     return 0;
4645   }else{
4646     return db->aDb[N].zDbSName;
4647   }
4648 }
4649 
4650 /*
4651 ** Return the filename of the database associated with a database
4652 ** connection.
4653 */
4654 const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
4655   Btree *pBt;
4656 #ifdef SQLITE_ENABLE_API_ARMOR
4657   if( !sqlite3SafetyCheckOk(db) ){
4658     (void)SQLITE_MISUSE_BKPT;
4659     return 0;
4660   }
4661 #endif
4662   pBt = sqlite3DbNameToBtree(db, zDbName);
4663   return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
4664 }
4665 
4666 /*
4667 ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
4668 ** no such database exists.
4669 */
4670 int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
4671   Btree *pBt;
4672 #ifdef SQLITE_ENABLE_API_ARMOR
4673   if( !sqlite3SafetyCheckOk(db) ){
4674     (void)SQLITE_MISUSE_BKPT;
4675     return -1;
4676   }
4677 #endif
4678   pBt = sqlite3DbNameToBtree(db, zDbName);
4679   return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
4680 }
4681 
4682 #ifdef SQLITE_ENABLE_SNAPSHOT
4683 /*
4684 ** Obtain a snapshot handle for the snapshot of database zDb currently
4685 ** being read by handle db.
4686 */
4687 int sqlite3_snapshot_get(
4688   sqlite3 *db,
4689   const char *zDb,
4690   sqlite3_snapshot **ppSnapshot
4691 ){
4692   int rc = SQLITE_ERROR;
4693 #ifndef SQLITE_OMIT_WAL
4694 
4695 #ifdef SQLITE_ENABLE_API_ARMOR
4696   if( !sqlite3SafetyCheckOk(db) ){
4697     return SQLITE_MISUSE_BKPT;
4698   }
4699 #endif
4700   sqlite3_mutex_enter(db->mutex);
4701 
4702   if( db->autoCommit==0 ){
4703     int iDb = sqlite3FindDbName(db, zDb);
4704     if( iDb==0 || iDb>1 ){
4705       Btree *pBt = db->aDb[iDb].pBt;
4706       if( SQLITE_TXN_WRITE!=sqlite3BtreeTxnState(pBt) ){
4707         rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
4708         if( rc==SQLITE_OK ){
4709           rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
4710         }
4711       }
4712     }
4713   }
4714 
4715   sqlite3_mutex_leave(db->mutex);
4716 #endif   /* SQLITE_OMIT_WAL */
4717   return rc;
4718 }
4719 
4720 /*
4721 ** Open a read-transaction on the snapshot idendified by pSnapshot.
4722 */
4723 int sqlite3_snapshot_open(
4724   sqlite3 *db,
4725   const char *zDb,
4726   sqlite3_snapshot *pSnapshot
4727 ){
4728   int rc = SQLITE_ERROR;
4729 #ifndef SQLITE_OMIT_WAL
4730 
4731 #ifdef SQLITE_ENABLE_API_ARMOR
4732   if( !sqlite3SafetyCheckOk(db) ){
4733     return SQLITE_MISUSE_BKPT;
4734   }
4735 #endif
4736   sqlite3_mutex_enter(db->mutex);
4737   if( db->autoCommit==0 ){
4738     int iDb;
4739     iDb = sqlite3FindDbName(db, zDb);
4740     if( iDb==0 || iDb>1 ){
4741       Btree *pBt = db->aDb[iDb].pBt;
4742       if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE ){
4743         Pager *pPager = sqlite3BtreePager(pBt);
4744         int bUnlock = 0;
4745         if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_NONE ){
4746           if( db->nVdbeActive==0 ){
4747             rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot);
4748             if( rc==SQLITE_OK ){
4749               bUnlock = 1;
4750               rc = sqlite3BtreeCommit(pBt);
4751             }
4752           }
4753         }else{
4754           rc = SQLITE_OK;
4755         }
4756         if( rc==SQLITE_OK ){
4757           rc = sqlite3PagerSnapshotOpen(pPager, pSnapshot);
4758         }
4759         if( rc==SQLITE_OK ){
4760           rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
4761           sqlite3PagerSnapshotOpen(pPager, 0);
4762         }
4763         if( bUnlock ){
4764           sqlite3PagerSnapshotUnlock(pPager);
4765         }
4766       }
4767     }
4768   }
4769 
4770   sqlite3_mutex_leave(db->mutex);
4771 #endif   /* SQLITE_OMIT_WAL */
4772   return rc;
4773 }
4774 
4775 /*
4776 ** Recover as many snapshots as possible from the wal file associated with
4777 ** schema zDb of database db.
4778 */
4779 int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
4780   int rc = SQLITE_ERROR;
4781   int iDb;
4782 #ifndef SQLITE_OMIT_WAL
4783 
4784 #ifdef SQLITE_ENABLE_API_ARMOR
4785   if( !sqlite3SafetyCheckOk(db) ){
4786     return SQLITE_MISUSE_BKPT;
4787   }
4788 #endif
4789 
4790   sqlite3_mutex_enter(db->mutex);
4791   iDb = sqlite3FindDbName(db, zDb);
4792   if( iDb==0 || iDb>1 ){
4793     Btree *pBt = db->aDb[iDb].pBt;
4794     if( SQLITE_TXN_NONE==sqlite3BtreeTxnState(pBt) ){
4795       rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
4796       if( rc==SQLITE_OK ){
4797         rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
4798         sqlite3BtreeCommit(pBt);
4799       }
4800     }
4801   }
4802   sqlite3_mutex_leave(db->mutex);
4803 #endif   /* SQLITE_OMIT_WAL */
4804   return rc;
4805 }
4806 
4807 /*
4808 ** Free a snapshot handle obtained from sqlite3_snapshot_get().
4809 */
4810 void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
4811   sqlite3_free(pSnapshot);
4812 }
4813 #endif /* SQLITE_ENABLE_SNAPSHOT */
4814 
4815 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
4816 /*
4817 ** Given the name of a compile-time option, return true if that option
4818 ** was used and false if not.
4819 **
4820 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
4821 ** is not required for a match.
4822 */
4823 int sqlite3_compileoption_used(const char *zOptName){
4824   int i, n;
4825   int nOpt;
4826   const char **azCompileOpt;
4827 
4828 #if SQLITE_ENABLE_API_ARMOR
4829   if( zOptName==0 ){
4830     (void)SQLITE_MISUSE_BKPT;
4831     return 0;
4832   }
4833 #endif
4834 
4835   azCompileOpt = sqlite3CompileOptions(&nOpt);
4836 
4837   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
4838   n = sqlite3Strlen30(zOptName);
4839 
4840   /* Since nOpt is normally in single digits, a linear search is
4841   ** adequate. No need for a binary search. */
4842   for(i=0; i<nOpt; i++){
4843     if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
4844      && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
4845     ){
4846       return 1;
4847     }
4848   }
4849   return 0;
4850 }
4851 
4852 /*
4853 ** Return the N-th compile-time option string.  If N is out of range,
4854 ** return a NULL pointer.
4855 */
4856 const char *sqlite3_compileoption_get(int N){
4857   int nOpt;
4858   const char **azCompileOpt;
4859   azCompileOpt = sqlite3CompileOptions(&nOpt);
4860   if( N>=0 && N<nOpt ){
4861     return azCompileOpt[N];
4862   }
4863   return 0;
4864 }
4865 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
4866