interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / src / main.c

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