1/******************************************************************************
2** This file is an amalgamation of many separate C source files from SQLite
3** version 3.37.2. By combining all the individual C code files into this
4** single large file, the entire code can be compiled as a single translation
5** unit. This allows many compilers to do optimizations that would not be
6** possible if the files were compiled separately. Performance improvements
7** of 5% or more are commonly seen when SQLite is compiled as a single
8** translation unit.
9**
10** This file is all you need to compile SQLite. To use SQLite in other
11** programs, you need this file and the "sqlite3.h" header file that defines
12** the programming interface to the SQLite library. (If you do not have
13** the "sqlite3.h" header file at hand, you will find a copy embedded within
14** the text of this file. Search for "Begin file sqlite3.h" to find the start
15** of the embedded sqlite3.h header file.) Additional code files may be needed
16** if you want a wrapper to interface SQLite with your choice of programming
17** language. The code for the "sqlite3" command-line shell is also in a
18** separate file. This file contains only code for the core SQLite library.
19*/
20#define SQLITE_CORE 1
21#define SQLITE_AMALGAMATION 1
22#ifndef SQLITE_PRIVATE
23# define SQLITE_PRIVATE static
24#endif
25/************** Begin file sqliteInt.h ***************************************/
26/*
27** 2001 September 15
28**
29** The author disclaims copyright to this source code. In place of
30** a legal notice, here is a blessing:
31**
32** May you do good and not evil.
33** May you find forgiveness for yourself and forgive others.
34** May you share freely, never taking more than you give.
35**
36*************************************************************************
37** Internal interface definitions for SQLite.
38**
39*/
40#ifndef SQLITEINT_H
41#define SQLITEINT_H
42
43/* Special Comments:
44**
45** Some comments have special meaning to the tools that measure test
46** coverage:
47**
48** NO_TEST - The branches on this line are not
49** measured by branch coverage. This is
50** used on lines of code that actually
51** implement parts of coverage testing.
52**
53** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false
54** and the correct answer is still obtained,
55** though perhaps more slowly.
56**
57** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true
58** and the correct answer is still obtained,
59** though perhaps more slowly.
60**
61** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
62** that would be harmless and undetectable
63** if it did occur.
64**
65** In all cases, the special comment must be enclosed in the usual
66** slash-asterisk...asterisk-slash comment marks, with no spaces between the
67** asterisks and the comment text.
68*/
69
70/*
71** Make sure the Tcl calling convention macro is defined. This macro is
72** only used by test code and Tcl integration code.
73*/
74#ifndef SQLITE_TCLAPI
75# define SQLITE_TCLAPI
76#endif
77
78/*
79** Include the header file used to customize the compiler options for MSVC.
80** This should be done first so that it can successfully prevent spurious
81** compiler warnings due to subsequent content in this file and other files
82** that are included by this file.
83*/
84/************** Include msvc.h in the middle of sqliteInt.h ******************/
85/************** Begin file msvc.h ********************************************/
86/*
87** 2015 January 12
88**
89** The author disclaims copyright to this source code. In place of
90** a legal notice, here is a blessing:
91**
92** May you do good and not evil.
93** May you find forgiveness for yourself and forgive others.
94** May you share freely, never taking more than you give.
95**
96******************************************************************************
97**
98** This file contains code that is specific to MSVC.
99*/
100#ifndef SQLITE_MSVC_H
101#define SQLITE_MSVC_H
102
103#if defined(_MSC_VER)
104#pragma warning(disable : 4054)
105#pragma warning(disable : 4055)
106#pragma warning(disable : 4100)
107#pragma warning(disable : 4127)
108#pragma warning(disable : 4130)
109#pragma warning(disable : 4152)
110#pragma warning(disable : 4189)
111#pragma warning(disable : 4206)
112#pragma warning(disable : 4210)
113#pragma warning(disable : 4232)
114#pragma warning(disable : 4244)
115#pragma warning(disable : 4305)
116#pragma warning(disable : 4306)
117#pragma warning(disable : 4702)
118#pragma warning(disable : 4706)
119#endif /* defined(_MSC_VER) */
120
121#if defined(_MSC_VER) && !defined(_WIN64)
122#undef SQLITE_4_BYTE_ALIGNED_MALLOC
123#define SQLITE_4_BYTE_ALIGNED_MALLOC
124#endif /* defined(_MSC_VER) && !defined(_WIN64) */
125
126#endif /* SQLITE_MSVC_H */
127
128/************** End of msvc.h ************************************************/
129/************** Continuing where we left off in sqliteInt.h ******************/
130
131/*
132** Special setup for VxWorks
133*/
134/************** Include vxworks.h in the middle of sqliteInt.h ***************/
135/************** Begin file vxworks.h *****************************************/
136/*
137** 2015-03-02
138**
139** The author disclaims copyright to this source code. In place of
140** a legal notice, here is a blessing:
141**
142** May you do good and not evil.
143** May you find forgiveness for yourself and forgive others.
144** May you share freely, never taking more than you give.
145**
146******************************************************************************
147**
148** This file contains code that is specific to Wind River's VxWorks
149*/
150#if defined(__RTP__) || defined(_WRS_KERNEL)
151/* This is VxWorks. Set up things specially for that OS
152*/
153#include <vxWorks.h>
154#include <pthread.h> /* amalgamator: dontcache */
155#define OS_VXWORKS 1
156#define SQLITE_OS_OTHER 0
157#define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
158#define SQLITE_OMIT_LOAD_EXTENSION 1
159#define SQLITE_ENABLE_LOCKING_STYLE 0
160#define HAVE_UTIME 1
161#else
162/* This is not VxWorks. */
163#define OS_VXWORKS 0
164#define HAVE_FCHOWN 1
165#define HAVE_READLINK 1
166#define HAVE_LSTAT 1
167#endif /* defined(_WRS_KERNEL) */
168
169/************** End of vxworks.h *********************************************/
170/************** Continuing where we left off in sqliteInt.h ******************/
171
172/*
173** These #defines should enable >2GB file support on POSIX if the
174** underlying operating system supports it. If the OS lacks
175** large file support, or if the OS is windows, these should be no-ops.
176**
177** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
178** system #includes. Hence, this block of code must be the very first
179** code in all source files.
180**
181** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
182** on the compiler command line. This is necessary if you are compiling
183** on a recent machine (ex: Red Hat 7.2) but you want your code to work
184** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
185** without this option, LFS is enable. But LFS does not exist in the kernel
186** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
187** portability you should omit LFS.
188**
189** The previous paragraph was written in 2005. (This paragraph is written
190** on 2008-11-28.) These days, all Linux kernels support large files, so
191** you should probably leave LFS enabled. But some embedded platforms might
192** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
193**
194** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
195*/
196#ifndef SQLITE_DISABLE_LFS
197# define _LARGE_FILE 1
198# ifndef _FILE_OFFSET_BITS
199# define _FILE_OFFSET_BITS 64
200# endif
201# define _LARGEFILE_SOURCE 1
202#endif
203
204/* The GCC_VERSION and MSVC_VERSION macros are used to
205** conditionally include optimizations for each of these compilers. A
206** value of 0 means that compiler is not being used. The
207** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
208** optimizations, and hence set all compiler macros to 0
209**
210** There was once also a CLANG_VERSION macro. However, we learn that the
211** version numbers in clang are for "marketing" only and are inconsistent
212** and unreliable. Fortunately, all versions of clang also recognize the
213** gcc version numbers and have reasonable settings for gcc version numbers,
214** so the GCC_VERSION macro will be set to a correct non-zero value even
215** when compiling with clang.
216*/
217#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
218# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
219#else
220# define GCC_VERSION 0
221#endif
222#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
223# define MSVC_VERSION _MSC_VER
224#else
225# define MSVC_VERSION 0
226#endif
227
228/*
229** Some C99 functions in "math.h" are only present for MSVC when its version
230** is associated with Visual Studio 2013 or higher.
231*/
232#ifndef SQLITE_HAVE_C99_MATH_FUNCS
233# if MSVC_VERSION==0 || MSVC_VERSION>=1800
234# define SQLITE_HAVE_C99_MATH_FUNCS (1)
235# else
236# define SQLITE_HAVE_C99_MATH_FUNCS (0)
237# endif
238#endif
239
240/* Needed for various definitions... */
241#if defined(__GNUC__) && !defined(_GNU_SOURCE)
242# define _GNU_SOURCE
243#endif
244
245#if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
246# define _BSD_SOURCE
247#endif
248
249/*
250** Macro to disable warnings about missing "break" at the end of a "case".
251*/
252#if GCC_VERSION>=7000000
253# define deliberate_fall_through __attribute__((fallthrough));
254#else
255# define deliberate_fall_through
256#endif
257
258/*
259** For MinGW, check to see if we can include the header file containing its
260** version information, among other things. Normally, this internal MinGW
261** header file would [only] be included automatically by other MinGW header
262** files; however, the contained version information is now required by this
263** header file to work around binary compatibility issues (see below) and
264** this is the only known way to reliably obtain it. This entire #if block
265** would be completely unnecessary if there was any other way of detecting
266** MinGW via their preprocessor (e.g. if they customized their GCC to define
267** some MinGW-specific macros). When compiling for MinGW, either the
268** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
269** defined; otherwise, detection of conditions specific to MinGW will be
270** disabled.
271*/
272#if defined(_HAVE_MINGW_H)
273# include "mingw.h"
274#elif defined(_HAVE__MINGW_H)
275# include "_mingw.h"
276#endif
277
278/*
279** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
280** define is required to maintain binary compatibility with the MSVC runtime
281** library in use (e.g. for Windows XP).
282*/
283#if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
284 defined(_WIN32) && !defined(_WIN64) && \
285 defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
286 defined(__MSVCRT__)
287# define _USE_32BIT_TIME_T
288#endif
289
290/* Optionally #include a user-defined header, whereby compilation options
291** may be set prior to where they take effect, but after platform setup.
292** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
293** file.
294*/
295#ifdef SQLITE_CUSTOM_INCLUDE
296# define INC_STRINGIFY_(f) #f
297# define INC_STRINGIFY(f) INC_STRINGIFY_(f)
298# include INC_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
299#endif
300
301/* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
302** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
303** MinGW.
304*/
305/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
306/************** Begin file sqlite3.h *****************************************/
307/*
308** 2001-09-15
309**
310** The author disclaims copyright to this source code. In place of
311** a legal notice, here is a blessing:
312**
313** May you do good and not evil.
314** May you find forgiveness for yourself and forgive others.
315** May you share freely, never taking more than you give.
316**
317*************************************************************************
318** This header file defines the interface that the SQLite library
319** presents to client programs. If a C-function, structure, datatype,
320** or constant definition does not appear in this file, then it is
321** not a published API of SQLite, is subject to change without
322** notice, and should not be referenced by programs that use SQLite.
323**
324** Some of the definitions that are in this file are marked as
325** "experimental". Experimental interfaces are normally new
326** features recently added to SQLite. We do not anticipate changes
327** to experimental interfaces but reserve the right to make minor changes
328** if experience from use "in the wild" suggest such changes are prudent.
329**
330** The official C-language API documentation for SQLite is derived
331** from comments in this file. This file is the authoritative source
332** on how SQLite interfaces are supposed to operate.
333**
334** The name of this file under configuration management is "sqlite.h.in".
335** The makefile makes some minor changes to this file (such as inserting
336** the version number) and changes its name to "sqlite3.h" as
337** part of the build process.
338*/
339#ifndef SQLITE3_H
340#define SQLITE3_H
341#include <stdarg.h> /* Needed for the definition of va_list */
342
343/*
344** Make sure we can call this stuff from C++.
345*/
346#if 0
347extern "C" {
348#endif
349
350
351/*
352** Facilitate override of interface linkage and calling conventions.
353** Be aware that these macros may not be used within this particular
354** translation of the amalgamation and its associated header file.
355**
356** The SQLITE_EXTERN and SQLITE_API macros are used to instruct the
357** compiler that the target identifier should have external linkage.
358**
359** The SQLITE_CDECL macro is used to set the calling convention for
360** public functions that accept a variable number of arguments.
361**
362** The SQLITE_APICALL macro is used to set the calling convention for
363** public functions that accept a fixed number of arguments.
364**
365** The SQLITE_STDCALL macro is no longer used and is now deprecated.
366**
367** The SQLITE_CALLBACK macro is used to set the calling convention for
368** function pointers.
369**
370** The SQLITE_SYSAPI macro is used to set the calling convention for
371** functions provided by the operating system.
372**
373** Currently, the SQLITE_CDECL, SQLITE_APICALL, SQLITE_CALLBACK, and
374** SQLITE_SYSAPI macros are used only when building for environments
375** that require non-default calling conventions.
376*/
377#ifndef SQLITE_EXTERN
378# define SQLITE_EXTERN extern
379#endif
380#ifndef SQLITE_API
381# define SQLITE_API
382#endif
383#ifndef SQLITE_CDECL
384# define SQLITE_CDECL
385#endif
386#ifndef SQLITE_APICALL
387# define SQLITE_APICALL
388#endif
389#ifndef SQLITE_STDCALL
390# define SQLITE_STDCALL SQLITE_APICALL
391#endif
392#ifndef SQLITE_CALLBACK
393# define SQLITE_CALLBACK
394#endif
395#ifndef SQLITE_SYSAPI
396# define SQLITE_SYSAPI
397#endif
398
399/*
400** These no-op macros are used in front of interfaces to mark those
401** interfaces as either deprecated or experimental. New applications
402** should not use deprecated interfaces - they are supported for backwards
403** compatibility only. Application writers should be aware that
404** experimental interfaces are subject to change in point releases.
405**
406** These macros used to resolve to various kinds of compiler magic that
407** would generate warning messages when they were used. But that
408** compiler magic ended up generating such a flurry of bug reports
409** that we have taken it all out and gone back to using simple
410** noop macros.
411*/
412#define SQLITE_DEPRECATED
413#define SQLITE_EXPERIMENTAL
414
415/*
416** Ensure these symbols were not defined by some previous header file.
417*/
418#ifdef SQLITE_VERSION
419# undef SQLITE_VERSION
420#endif
421#ifdef SQLITE_VERSION_NUMBER
422# undef SQLITE_VERSION_NUMBER
423#endif
424
425/*
426** CAPI3REF: Compile-Time Library Version Numbers
427**
428** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
429** evaluates to a string literal that is the SQLite version in the
430** format "X.Y.Z" where X is the major version number (always 3 for
431** SQLite3) and Y is the minor version number and Z is the release number.)^
432** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
433** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
434** numbers used in [SQLITE_VERSION].)^
435** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
436** be larger than the release from which it is derived. Either Y will
437** be held constant and Z will be incremented or else Y will be incremented
438** and Z will be reset to zero.
439**
440** Since [version 3.6.18] ([dateof:3.6.18]),
441** SQLite source code has been stored in the
442** <a href="http://www.fossil-scm.org/">Fossil configuration management
443** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
444** a string which identifies a particular check-in of SQLite
445** within its configuration management system. ^The SQLITE_SOURCE_ID
446** string contains the date and time of the check-in (UTC) and a SHA1
447** or SHA3-256 hash of the entire source tree. If the source code has
448** been edited in any way since it was last checked in, then the last
449** four hexadecimal digits of the hash may be modified.
450**
451** See also: [sqlite3_libversion()],
452** [sqlite3_libversion_number()], [sqlite3_sourceid()],
453** [sqlite_version()] and [sqlite_source_id()].
454*/
455#define SQLITE_VERSION "3.37.2"
456#define SQLITE_VERSION_NUMBER 3037002
457#define SQLITE_SOURCE_ID "2022-01-06 13:25:41 872ba256cbf61d9290b571c0e6d82a20c224ca3ad82971edc46b29818d5d17a0"
458
459/*
460** CAPI3REF: Run-Time Library Version Numbers
461** KEYWORDS: sqlite3_version sqlite3_sourceid
462**
463** These interfaces provide the same information as the [SQLITE_VERSION],
464** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
465** but are associated with the library instead of the header file. ^(Cautious
466** programmers might include assert() statements in their application to
467** verify that values returned by these interfaces match the macros in
468** the header, and thus ensure that the application is
469** compiled with matching library and header files.
470**
471** <blockquote><pre>
472** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
473** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );
474** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
475** </pre></blockquote>)^
476**
477** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
478** macro. ^The sqlite3_libversion() function returns a pointer to the
479** to the sqlite3_version[] string constant. The sqlite3_libversion()
480** function is provided for use in DLLs since DLL users usually do not have
481** direct access to string constants within the DLL. ^The
482** sqlite3_libversion_number() function returns an integer equal to
483** [SQLITE_VERSION_NUMBER]. ^(The sqlite3_sourceid() function returns
484** a pointer to a string constant whose value is the same as the
485** [SQLITE_SOURCE_ID] C preprocessor macro. Except if SQLite is built
486** using an edited copy of [the amalgamation], then the last four characters
487** of the hash might be different from [SQLITE_SOURCE_ID].)^
488**
489** See also: [sqlite_version()] and [sqlite_source_id()].
490*/
491SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
492SQLITE_API const char *sqlite3_libversion(void);
493SQLITE_API const char *sqlite3_sourceid(void);
494SQLITE_API int sqlite3_libversion_number(void);
495
496/*
497** CAPI3REF: Run-Time Library Compilation Options Diagnostics
498**
499** ^The sqlite3_compileoption_used() function returns 0 or 1
500** indicating whether the specified option was defined at
501** compile time. ^The SQLITE_ prefix may be omitted from the
502** option name passed to sqlite3_compileoption_used().
503**
504** ^The sqlite3_compileoption_get() function allows iterating
505** over the list of options that were defined at compile time by
506** returning the N-th compile time option string. ^If N is out of range,
507** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
508** prefix is omitted from any strings returned by
509** sqlite3_compileoption_get().
510**
511** ^Support for the diagnostic functions sqlite3_compileoption_used()
512** and sqlite3_compileoption_get() may be omitted by specifying the
513** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
514**
515** See also: SQL functions [sqlite_compileoption_used()] and
516** [sqlite_compileoption_get()] and the [compile_options pragma].
517*/
518#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
519SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
520SQLITE_API const char *sqlite3_compileoption_get(int N);
521#else
522# define sqlite3_compileoption_used(X) 0
523# define sqlite3_compileoption_get(X) ((void*)0)
524#endif
525
526/*
527** CAPI3REF: Test To See If The Library Is Threadsafe
528**
529** ^The sqlite3_threadsafe() function returns zero if and only if
530** SQLite was compiled with mutexing code omitted due to the
531** [SQLITE_THREADSAFE] compile-time option being set to 0.
532**
533** SQLite can be compiled with or without mutexes. When
534** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
535** are enabled and SQLite is threadsafe. When the
536** [SQLITE_THREADSAFE] macro is 0,
537** the mutexes are omitted. Without the mutexes, it is not safe
538** to use SQLite concurrently from more than one thread.
539**
540** Enabling mutexes incurs a measurable performance penalty.
541** So if speed is of utmost importance, it makes sense to disable
542** the mutexes. But for maximum safety, mutexes should be enabled.
543** ^The default behavior is for mutexes to be enabled.
544**
545** This interface can be used by an application to make sure that the
546** version of SQLite that it is linking against was compiled with
547** the desired setting of the [SQLITE_THREADSAFE] macro.
548**
549** This interface only reports on the compile-time mutex setting
550** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
551** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
552** can be fully or partially disabled using a call to [sqlite3_config()]
553** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
554** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
555** sqlite3_threadsafe() function shows only the compile-time setting of
556** thread safety, not any run-time changes to that setting made by
557** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
558** is unchanged by calls to sqlite3_config().)^
559**
560** See the [threading mode] documentation for additional information.
561*/
562SQLITE_API int sqlite3_threadsafe(void);
563
564/*
565** CAPI3REF: Database Connection Handle
566** KEYWORDS: {database connection} {database connections}
567**
568** Each open SQLite database is represented by a pointer to an instance of
569** the opaque structure named "sqlite3". It is useful to think of an sqlite3
570** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
571** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
572** and [sqlite3_close_v2()] are its destructors. There are many other
573** interfaces (such as
574** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
575** [sqlite3_busy_timeout()] to name but three) that are methods on an
576** sqlite3 object.
577*/
578typedef struct sqlite3 sqlite3;
579
580/*
581** CAPI3REF: 64-Bit Integer Types
582** KEYWORDS: sqlite_int64 sqlite_uint64
583**
584** Because there is no cross-platform way to specify 64-bit integer types
585** SQLite includes typedefs for 64-bit signed and unsigned integers.
586**
587** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
588** The sqlite_int64 and sqlite_uint64 types are supported for backwards
589** compatibility only.
590**
591** ^The sqlite3_int64 and sqlite_int64 types can store integer values
592** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
593** sqlite3_uint64 and sqlite_uint64 types can store integer values
594** between 0 and +18446744073709551615 inclusive.
595*/
596#ifdef SQLITE_INT64_TYPE
597 typedef SQLITE_INT64_TYPE sqlite_int64;
598# ifdef SQLITE_UINT64_TYPE
599 typedef SQLITE_UINT64_TYPE sqlite_uint64;
600# else
601 typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
602# endif
603#elif defined(_MSC_VER) || defined(__BORLANDC__)
604 typedef __int64 sqlite_int64;
605 typedef unsigned __int64 sqlite_uint64;
606#else
607 typedef long long int sqlite_int64;
608 typedef unsigned long long int sqlite_uint64;
609#endif
610typedef sqlite_int64 sqlite3_int64;
611typedef sqlite_uint64 sqlite3_uint64;
612
613/*
614** If compiling for a processor that lacks floating point support,
615** substitute integer for floating-point.
616*/
617#ifdef SQLITE_OMIT_FLOATING_POINT
618# define double sqlite3_int64
619#endif
620
621/*
622** CAPI3REF: Closing A Database Connection
623** DESTRUCTOR: sqlite3
624**
625** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
626** for the [sqlite3] object.
627** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
628** the [sqlite3] object is successfully destroyed and all associated
629** resources are deallocated.
630**
631** Ideally, applications should [sqlite3_finalize | finalize] all
632** [prepared statements], [sqlite3_blob_close | close] all [BLOB handles], and
633** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
634** with the [sqlite3] object prior to attempting to close the object.
635** ^If the database connection is associated with unfinalized prepared
636** statements, BLOB handlers, and/or unfinished sqlite3_backup objects then
637** sqlite3_close() will leave the database connection open and return
638** [SQLITE_BUSY]. ^If sqlite3_close_v2() is called with unfinalized prepared
639** statements, unclosed BLOB handlers, and/or unfinished sqlite3_backups,
640** it returns [SQLITE_OK] regardless, but instead of deallocating the database
641** connection immediately, it marks the database connection as an unusable
642** "zombie" and makes arrangements to automatically deallocate the database
643** connection after all prepared statements are finalized, all BLOB handles
644** are closed, and all backups have finished. The sqlite3_close_v2() interface
645** is intended for use with host languages that are garbage collected, and
646** where the order in which destructors are called is arbitrary.
647**
648** ^If an [sqlite3] object is destroyed while a transaction is open,
649** the transaction is automatically rolled back.
650**
651** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
652** must be either a NULL
653** pointer or an [sqlite3] object pointer obtained
654** from [sqlite3_open()], [sqlite3_open16()], or
655** [sqlite3_open_v2()], and not previously closed.
656** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
657** argument is a harmless no-op.
658*/
659SQLITE_API int sqlite3_close(sqlite3*);
660SQLITE_API int sqlite3_close_v2(sqlite3*);
661
662/*
663** The type for a callback function.
664** This is legacy and deprecated. It is included for historical
665** compatibility and is not documented.
666*/
667typedef int (*sqlite3_callback)(void*,int,char**, char**);
668
669/*
670** CAPI3REF: One-Step Query Execution Interface
671** METHOD: sqlite3
672**
673** The sqlite3_exec() interface is a convenience wrapper around
674** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
675** that allows an application to run multiple statements of SQL
676** without having to use a lot of C code.
677**
678** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
679** semicolon-separate SQL statements passed into its 2nd argument,
680** in the context of the [database connection] passed in as its 1st
681** argument. ^If the callback function of the 3rd argument to
682** sqlite3_exec() is not NULL, then it is invoked for each result row
683** coming out of the evaluated SQL statements. ^The 4th argument to
684** sqlite3_exec() is relayed through to the 1st argument of each
685** callback invocation. ^If the callback pointer to sqlite3_exec()
686** is NULL, then no callback is ever invoked and result rows are
687** ignored.
688**
689** ^If an error occurs while evaluating the SQL statements passed into
690** sqlite3_exec(), then execution of the current statement stops and
691** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
692** is not NULL then any error message is written into memory obtained
693** from [sqlite3_malloc()] and passed back through the 5th parameter.
694** To avoid memory leaks, the application should invoke [sqlite3_free()]
695** on error message strings returned through the 5th parameter of
696** sqlite3_exec() after the error message string is no longer needed.
697** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
698** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
699** NULL before returning.
700**
701** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
702** routine returns SQLITE_ABORT without invoking the callback again and
703** without running any subsequent SQL statements.
704**
705** ^The 2nd argument to the sqlite3_exec() callback function is the
706** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
707** callback is an array of pointers to strings obtained as if from
708** [sqlite3_column_text()], one for each column. ^If an element of a
709** result row is NULL then the corresponding string pointer for the
710** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
711** sqlite3_exec() callback is an array of pointers to strings where each
712** entry represents the name of corresponding result column as obtained
713** from [sqlite3_column_name()].
714**
715** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
716** to an empty string, or a pointer that contains only whitespace and/or
717** SQL comments, then no SQL statements are evaluated and the database
718** is not changed.
719**
720** Restrictions:
721**
722** <ul>
723** <li> The application must ensure that the 1st parameter to sqlite3_exec()
724** is a valid and open [database connection].
725** <li> The application must not close the [database connection] specified by
726** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
727** <li> The application must not modify the SQL statement text passed into
728** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
729** </ul>
730*/
731SQLITE_API int sqlite3_exec(
732 sqlite3*, /* An open database */
733 const char *sql, /* SQL to be evaluated */
734 int (*callback)(void*,int,char**,char**), /* Callback function */
735 void *, /* 1st argument to callback */
736 char **errmsg /* Error msg written here */
737);
738
739/*
740** CAPI3REF: Result Codes
741** KEYWORDS: {result code definitions}
742**
743** Many SQLite functions return an integer result code from the set shown
744** here in order to indicate success or failure.
745**
746** New error codes may be added in future versions of SQLite.
747**
748** See also: [extended result code definitions]
749*/
750#define SQLITE_OK 0 /* Successful result */
751/* beginning-of-error-codes */
752#define SQLITE_ERROR 1 /* Generic error */
753#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
754#define SQLITE_PERM 3 /* Access permission denied */
755#define SQLITE_ABORT 4 /* Callback routine requested an abort */
756#define SQLITE_BUSY 5 /* The database file is locked */
757#define SQLITE_LOCKED 6 /* A table in the database is locked */
758#define SQLITE_NOMEM 7 /* A malloc() failed */
759#define SQLITE_READONLY 8 /* Attempt to write a readonly database */
760#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
761#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
762#define SQLITE_CORRUPT 11 /* The database disk image is malformed */
763#define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
764#define SQLITE_FULL 13 /* Insertion failed because database is full */
765#define SQLITE_CANTOPEN 14 /* Unable to open the database file */
766#define SQLITE_PROTOCOL 15 /* Database lock protocol error */
767#define SQLITE_EMPTY 16 /* Internal use only */
768#define SQLITE_SCHEMA 17 /* The database schema changed */
769#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
770#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
771#define SQLITE_MISMATCH 20 /* Data type mismatch */
772#define SQLITE_MISUSE 21 /* Library used incorrectly */
773#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
774#define SQLITE_AUTH 23 /* Authorization denied */
775#define SQLITE_FORMAT 24 /* Not used */
776#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
777#define SQLITE_NOTADB 26 /* File opened that is not a database file */
778#define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
779#define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
780#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
781#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
782/* end-of-error-codes */
783
784/*
785** CAPI3REF: Extended Result Codes
786** KEYWORDS: {extended result code definitions}
787**
788** In its default configuration, SQLite API routines return one of 30 integer
789** [result codes]. However, experience has shown that many of
790** these result codes are too coarse-grained. They do not provide as
791** much information about problems as programmers might like. In an effort to
792** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
793** and later) include
794** support for additional result codes that provide more detailed information
795** about errors. These [extended result codes] are enabled or disabled
796** on a per database connection basis using the
797** [sqlite3_extended_result_codes()] API. Or, the extended code for
798** the most recent error can be obtained using
799** [sqlite3_extended_errcode()].
800*/
801#define SQLITE_ERROR_MISSING_COLLSEQ (SQLITE_ERROR | (1<<8))
802#define SQLITE_ERROR_RETRY (SQLITE_ERROR | (2<<8))
803#define SQLITE_ERROR_SNAPSHOT (SQLITE_ERROR | (3<<8))
804#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
805#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
806#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
807#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
808#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
809#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
810#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
811#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
812#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
813#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
814#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
815#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
816#define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
817#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
818#define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
819#define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
820#define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
821#define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
822#define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
823#define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
824#define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
825#define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
826#define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
827#define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
828#define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
829#define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
830#define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
831#define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
832#define SQLITE_IOERR_BEGIN_ATOMIC (SQLITE_IOERR | (29<<8))
833#define SQLITE_IOERR_COMMIT_ATOMIC (SQLITE_IOERR | (30<<8))
834#define SQLITE_IOERR_ROLLBACK_ATOMIC (SQLITE_IOERR | (31<<8))
835#define SQLITE_IOERR_DATA (SQLITE_IOERR | (32<<8))
836#define SQLITE_IOERR_CORRUPTFS (SQLITE_IOERR | (33<<8))
837#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
838#define SQLITE_LOCKED_VTAB (SQLITE_LOCKED | (2<<8))
839#define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
840#define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
841#define SQLITE_BUSY_TIMEOUT (SQLITE_BUSY | (3<<8))
842#define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
843#define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
844#define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
845#define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
846#define SQLITE_CANTOPEN_DIRTYWAL (SQLITE_CANTOPEN | (5<<8)) /* Not Used */
847#define SQLITE_CANTOPEN_SYMLINK (SQLITE_CANTOPEN | (6<<8))
848#define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
849#define SQLITE_CORRUPT_SEQUENCE (SQLITE_CORRUPT | (2<<8))
850#define SQLITE_CORRUPT_INDEX (SQLITE_CORRUPT | (3<<8))
851#define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
852#define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
853#define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
854#define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
855#define SQLITE_READONLY_CANTINIT (SQLITE_READONLY | (5<<8))
856#define SQLITE_READONLY_DIRECTORY (SQLITE_READONLY | (6<<8))
857#define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
858#define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
859#define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
860#define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
861#define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
862#define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
863#define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
864#define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
865#define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
866#define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
867#define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
868#define SQLITE_CONSTRAINT_PINNED (SQLITE_CONSTRAINT |(11<<8))
869#define SQLITE_CONSTRAINT_DATATYPE (SQLITE_CONSTRAINT |(12<<8))
870#define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
871#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
872#define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
873#define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
874#define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8))
875#define SQLITE_OK_SYMLINK (SQLITE_OK | (2<<8))
876
877/*
878** CAPI3REF: Flags For File Open Operations
879**
880** These bit values are intended for use in the
881** 3rd parameter to the [sqlite3_open_v2()] interface and
882** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
883**
884** Only those flags marked as "Ok for sqlite3_open_v2()" may be
885** used as the third argument to the [sqlite3_open_v2()] interface.
886** The other flags have historically been ignored by sqlite3_open_v2(),
887** though future versions of SQLite might change so that an error is
888** raised if any of the disallowed bits are passed into sqlite3_open_v2().
889** Applications should not depend on the historical behavior.
890**
891** Note in particular that passing the SQLITE_OPEN_EXCLUSIVE flag into
892** [sqlite3_open_v2()] does *not* cause the underlying database file
893** to be opened using O_EXCL. Passing SQLITE_OPEN_EXCLUSIVE into
894** [sqlite3_open_v2()] has historically be a no-op and might become an
895** error in future versions of SQLite.
896*/
897#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
898#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
899#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
900#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
901#define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
902#define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
903#define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
904#define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
905#define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
906#define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
907#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
908#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
909#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
910#define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
911#define SQLITE_OPEN_SUPER_JOURNAL 0x00004000 /* VFS only */
912#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
913#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
914#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
915#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
916#define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
917#define SQLITE_OPEN_NOFOLLOW 0x01000000 /* Ok for sqlite3_open_v2() */
918#define SQLITE_OPEN_EXRESCODE 0x02000000 /* Extended result codes */
919
920/* Reserved: 0x00F00000 */
921/* Legacy compatibility: */
922#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
923
924
925/*
926** CAPI3REF: Device Characteristics
927**
928** The xDeviceCharacteristics method of the [sqlite3_io_methods]
929** object returns an integer which is a vector of these
930** bit values expressing I/O characteristics of the mass storage
931** device that holds the file that the [sqlite3_io_methods]
932** refers to.
933**
934** The SQLITE_IOCAP_ATOMIC property means that all writes of
935** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
936** mean that writes of blocks that are nnn bytes in size and
937** are aligned to an address which is an integer multiple of
938** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
939** that when data is appended to a file, the data is appended
940** first then the size of the file is extended, never the other
941** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
942** information is written to disk in the same order as calls
943** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
944** after reboot following a crash or power loss, the only bytes in a
945** file that were written at the application level might have changed
946** and that adjacent bytes, even bytes within the same sector are
947** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
948** flag indicates that a file cannot be deleted when open. The
949** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
950** read-only media and cannot be changed even by processes with
951** elevated privileges.
952**
953** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
954** filesystem supports doing multiple write operations atomically when those
955** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and
956** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].
957*/
958#define SQLITE_IOCAP_ATOMIC 0x00000001
959#define SQLITE_IOCAP_ATOMIC512 0x00000002
960#define SQLITE_IOCAP_ATOMIC1K 0x00000004
961#define SQLITE_IOCAP_ATOMIC2K 0x00000008
962#define SQLITE_IOCAP_ATOMIC4K 0x00000010
963#define SQLITE_IOCAP_ATOMIC8K 0x00000020
964#define SQLITE_IOCAP_ATOMIC16K 0x00000040
965#define SQLITE_IOCAP_ATOMIC32K 0x00000080
966#define SQLITE_IOCAP_ATOMIC64K 0x00000100
967#define SQLITE_IOCAP_SAFE_APPEND 0x00000200
968#define SQLITE_IOCAP_SEQUENTIAL 0x00000400
969#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
970#define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
971#define SQLITE_IOCAP_IMMUTABLE 0x00002000
972#define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000
973
974/*
975** CAPI3REF: File Locking Levels
976**
977** SQLite uses one of these integer values as the second
978** argument to calls it makes to the xLock() and xUnlock() methods
979** of an [sqlite3_io_methods] object.
980*/
981#define SQLITE_LOCK_NONE 0
982#define SQLITE_LOCK_SHARED 1
983#define SQLITE_LOCK_RESERVED 2
984#define SQLITE_LOCK_PENDING 3
985#define SQLITE_LOCK_EXCLUSIVE 4
986
987/*
988** CAPI3REF: Synchronization Type Flags
989**
990** When SQLite invokes the xSync() method of an
991** [sqlite3_io_methods] object it uses a combination of
992** these integer values as the second argument.
993**
994** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
995** sync operation only needs to flush data to mass storage. Inode
996** information need not be flushed. If the lower four bits of the flag
997** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
998** If the lower four bits equal SQLITE_SYNC_FULL, that means
999** to use Mac OS X style fullsync instead of fsync().
1000**
1001** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1002** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1003** settings. The [synchronous pragma] determines when calls to the
1004** xSync VFS method occur and applies uniformly across all platforms.
1005** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1006** energetic or rigorous or forceful the sync operations are and
1007** only make a difference on Mac OSX for the default SQLite code.
1008** (Third-party VFS implementations might also make the distinction
1009** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1010** operating systems natively supported by SQLite, only Mac OSX
1011** cares about the difference.)
1012*/
1013#define SQLITE_SYNC_NORMAL 0x00002
1014#define SQLITE_SYNC_FULL 0x00003
1015#define SQLITE_SYNC_DATAONLY 0x00010
1016
1017/*
1018** CAPI3REF: OS Interface Open File Handle
1019**
1020** An [sqlite3_file] object represents an open file in the
1021** [sqlite3_vfs | OS interface layer]. Individual OS interface
1022** implementations will
1023** want to subclass this object by appending additional fields
1024** for their own use. The pMethods entry is a pointer to an
1025** [sqlite3_io_methods] object that defines methods for performing
1026** I/O operations on the open file.
1027*/
1028typedef struct sqlite3_file sqlite3_file;
1029struct sqlite3_file {
1030 const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
1031};
1032
1033/*
1034** CAPI3REF: OS Interface File Virtual Methods Object
1035**
1036** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1037** [sqlite3_file] object (or, more commonly, a subclass of the
1038** [sqlite3_file] object) with a pointer to an instance of this object.
1039** This object defines the methods used to perform various operations
1040** against the open file represented by the [sqlite3_file] object.
1041**
1042** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
1043** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1044** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
1045** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
1046** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
1047** to NULL.
1048**
1049** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1050** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
1051** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
1052** flag may be ORed in to indicate that only the data of the file
1053** and not its inode needs to be synced.
1054**
1055** The integer values to xLock() and xUnlock() are one of
1056** <ul>
1057** <li> [SQLITE_LOCK_NONE],
1058** <li> [SQLITE_LOCK_SHARED],
1059** <li> [SQLITE_LOCK_RESERVED],
1060** <li> [SQLITE_LOCK_PENDING], or
1061** <li> [SQLITE_LOCK_EXCLUSIVE].
1062** </ul>
1063** xLock() increases the lock. xUnlock() decreases the lock.
1064** The xCheckReservedLock() method checks whether any database connection,
1065** either in this process or in some other process, is holding a RESERVED,
1066** PENDING, or EXCLUSIVE lock on the file. It returns true
1067** if such a lock exists and false otherwise.
1068**
1069** The xFileControl() method is a generic interface that allows custom
1070** VFS implementations to directly control an open file using the
1071** [sqlite3_file_control()] interface. The second "op" argument is an
1072** integer opcode. The third argument is a generic pointer intended to
1073** point to a structure that may contain arguments or space in which to
1074** write return values. Potential uses for xFileControl() might be
1075** functions to enable blocking locks with timeouts, to change the
1076** locking strategy (for example to use dot-file locks), to inquire
1077** about the status of a lock, or to break stale locks. The SQLite
1078** core reserves all opcodes less than 100 for its own use.
1079** A [file control opcodes | list of opcodes] less than 100 is available.
1080** Applications that define a custom xFileControl method should use opcodes
1081** greater than 100 to avoid conflicts. VFS implementations should
1082** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1083** recognize.
1084**
1085** The xSectorSize() method returns the sector size of the
1086** device that underlies the file. The sector size is the
1087** minimum write that can be performed without disturbing
1088** other bytes in the file. The xDeviceCharacteristics()
1089** method returns a bit vector describing behaviors of the
1090** underlying device:
1091**
1092** <ul>
1093** <li> [SQLITE_IOCAP_ATOMIC]
1094** <li> [SQLITE_IOCAP_ATOMIC512]
1095** <li> [SQLITE_IOCAP_ATOMIC1K]
1096** <li> [SQLITE_IOCAP_ATOMIC2K]
1097** <li> [SQLITE_IOCAP_ATOMIC4K]
1098** <li> [SQLITE_IOCAP_ATOMIC8K]
1099** <li> [SQLITE_IOCAP_ATOMIC16K]
1100** <li> [SQLITE_IOCAP_ATOMIC32K]
1101** <li> [SQLITE_IOCAP_ATOMIC64K]
1102** <li> [SQLITE_IOCAP_SAFE_APPEND]
1103** <li> [SQLITE_IOCAP_SEQUENTIAL]
1104** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
1105** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
1106** <li> [SQLITE_IOCAP_IMMUTABLE]
1107** <li> [SQLITE_IOCAP_BATCH_ATOMIC]
1108** </ul>
1109**
1110** The SQLITE_IOCAP_ATOMIC property means that all writes of
1111** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
1112** mean that writes of blocks that are nnn bytes in size and
1113** are aligned to an address which is an integer multiple of
1114** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
1115** that when data is appended to a file, the data is appended
1116** first then the size of the file is extended, never the other
1117** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
1118** information is written to disk in the same order as calls
1119** to xWrite().
1120**
1121** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1122** in the unread portions of the buffer with zeros. A VFS that
1123** fails to zero-fill short reads might seem to work. However,
1124** failure to zero-fill short reads will eventually lead to
1125** database corruption.
1126*/
1127typedef struct sqlite3_io_methods sqlite3_io_methods;
1128struct sqlite3_io_methods {
1129 int iVersion;
1130 int (*xClose)(sqlite3_file*);
1131 int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1132 int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1133 int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1134 int (*xSync)(sqlite3_file*, int flags);
1135 int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1136 int (*xLock)(sqlite3_file*, int);
1137 int (*xUnlock)(sqlite3_file*, int);
1138 int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1139 int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1140 int (*xSectorSize)(sqlite3_file*);
1141 int (*xDeviceCharacteristics)(sqlite3_file*);
1142 /* Methods above are valid for version 1 */
1143 int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1144 int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1145 void (*xShmBarrier)(sqlite3_file*);
1146 int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1147 /* Methods above are valid for version 2 */
1148 int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
1149 int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
1150 /* Methods above are valid for version 3 */
1151 /* Additional methods may be added in future releases */
1152};
1153
1154/*
1155** CAPI3REF: Standard File Control Opcodes
1156** KEYWORDS: {file control opcodes} {file control opcode}
1157**
1158** These integer constants are opcodes for the xFileControl method
1159** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1160** interface.
1161**
1162** <ul>
1163** <li>[[SQLITE_FCNTL_LOCKSTATE]]
1164** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
1165** opcode causes the xFileControl method to write the current state of
1166** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1167** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1168** into an integer that the pArg argument points to. This capability
1169** is used during testing and is only available when the SQLITE_TEST
1170** compile-time option is used.
1171**
1172** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1173** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1174** layer a hint of how large the database file will grow to be during the
1175** current transaction. This hint is not guaranteed to be accurate but it
1176** is often close. The underlying VFS might choose to preallocate database
1177** file space based on this hint in order to help writes to the database
1178** file run faster.
1179**
1180** <li>[[SQLITE_FCNTL_SIZE_LIMIT]]
1181** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that
1182** implements [sqlite3_deserialize()] to set an upper bound on the size
1183** of the in-memory database. The argument is a pointer to a [sqlite3_int64].
1184** If the integer pointed to is negative, then it is filled in with the
1185** current limit. Otherwise the limit is set to the larger of the value
1186** of the integer pointed to and the current database size. The integer
1187** pointed to is set to the new limit.
1188**
1189** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1190** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1191** extends and truncates the database file in chunks of a size specified
1192** by the user. The fourth argument to [sqlite3_file_control()] should
1193** point to an integer (type int) containing the new chunk-size to use
1194** for the nominated database. Allocating database file space in large
1195** chunks (say 1MB at a time), may reduce file-system fragmentation and
1196** improve performance on some systems.
1197**
1198** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1199** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1200** to the [sqlite3_file] object associated with a particular database
1201** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
1202**
1203** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
1204** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
1205** to the [sqlite3_file] object associated with the journal file (either
1206** the [rollback journal] or the [write-ahead log]) for a particular database
1207** connection. See also [SQLITE_FCNTL_FILE_POINTER].
1208**
1209** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1210** No longer in use.
1211**
1212** <li>[[SQLITE_FCNTL_SYNC]]
1213** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
1214** sent to the VFS immediately before the xSync method is invoked on a
1215** database file descriptor. Or, if the xSync method is not invoked
1216** because the user has configured SQLite with
1217** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
1218** of the xSync method. In most cases, the pointer argument passed with
1219** this file-control is NULL. However, if the database file is being synced
1220** as part of a multi-database commit, the argument points to a nul-terminated
1221** string containing the transactions super-journal file name. VFSes that
1222** do not need this signal should silently ignore this opcode. Applications
1223** should not call [sqlite3_file_control()] with this opcode as doing so may
1224** disrupt the operation of the specialized VFSes that do require it.
1225**
1226** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
1227** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
1228** and sent to the VFS after a transaction has been committed immediately
1229** but before the database is unlocked. VFSes that do not need this signal
1230** should silently ignore this opcode. Applications should not call
1231** [sqlite3_file_control()] with this opcode as doing so may disrupt the
1232** operation of the specialized VFSes that do require it.
1233**
1234** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1235** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1236** retry counts and intervals for certain disk I/O operations for the
1237** windows [VFS] in order to provide robustness in the presence of
1238** anti-virus programs. By default, the windows VFS will retry file read,
1239** file write, and file delete operations up to 10 times, with a delay
1240** of 25 milliseconds before the first retry and with the delay increasing
1241** by an additional 25 milliseconds with each subsequent retry. This
1242** opcode allows these two values (10 retries and 25 milliseconds of delay)
1243** to be adjusted. The values are changed for all database connections
1244** within the same process. The argument is a pointer to an array of two
1245** integers where the first integer is the new retry count and the second
1246** integer is the delay. If either integer is negative, then the setting
1247** is not changed but instead the prior value of that setting is written
1248** into the array entry, allowing the current retry settings to be
1249** interrogated. The zDbName parameter is ignored.
1250**
1251** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1252** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1253** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
1254** write ahead log ([WAL file]) and shared memory
1255** files used for transaction control
1256** are automatically deleted when the latest connection to the database
1257** closes. Setting persistent WAL mode causes those files to persist after
1258** close. Persisting the files is useful when other processes that do not
1259** have write permission on the directory containing the database file want
1260** to read the database file, as the WAL and shared memory files must exist
1261** in order for the database to be readable. The fourth parameter to
1262** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1263** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1264** WAL mode. If the integer is -1, then it is overwritten with the current
1265** WAL persistence setting.
1266**
1267** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1268** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1269** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
1270** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1271** xDeviceCharacteristics methods. The fourth parameter to
1272** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1273** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1274** mode. If the integer is -1, then it is overwritten with the current
1275** zero-damage mode setting.
1276**
1277** <li>[[SQLITE_FCNTL_OVERWRITE]]
1278** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1279** a write transaction to indicate that, unless it is rolled back for some
1280** reason, the entire database file will be overwritten by the current
1281** transaction. This is used by VACUUM operations.
1282**
1283** <li>[[SQLITE_FCNTL_VFSNAME]]
1284** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1285** all [VFSes] in the VFS stack. The names are of all VFS shims and the
1286** final bottom-level VFS are written into memory obtained from
1287** [sqlite3_malloc()] and the result is stored in the char* variable
1288** that the fourth parameter of [sqlite3_file_control()] points to.
1289** The caller is responsible for freeing the memory when done. As with
1290** all file-control actions, there is no guarantee that this will actually
1291** do anything. Callers should initialize the char* variable to a NULL
1292** pointer in case this file-control is not implemented. This file-control
1293** is intended for diagnostic use only.
1294**
1295** <li>[[SQLITE_FCNTL_VFS_POINTER]]
1296** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
1297** [VFSes] currently in use. ^(The argument X in
1298** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
1299** of type "[sqlite3_vfs] **". This opcodes will set *X
1300** to a pointer to the top-level VFS.)^
1301** ^When there are multiple VFS shims in the stack, this opcode finds the
1302** upper-most shim only.
1303**
1304** <li>[[SQLITE_FCNTL_PRAGMA]]
1305** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1306** file control is sent to the open [sqlite3_file] object corresponding
1307** to the database file to which the pragma statement refers. ^The argument
1308** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1309** pointers to strings (char**) in which the second element of the array
1310** is the name of the pragma and the third element is the argument to the
1311** pragma or NULL if the pragma has no argument. ^The handler for an
1312** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1313** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1314** or the equivalent and that string will become the result of the pragma or
1315** the error message if the pragma fails. ^If the
1316** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1317** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
1318** file control returns [SQLITE_OK], then the parser assumes that the
1319** VFS has handled the PRAGMA itself and the parser generates a no-op
1320** prepared statement if result string is NULL, or that returns a copy
1321** of the result string if the string is non-NULL.
1322** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1323** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1324** that the VFS encountered an error while handling the [PRAGMA] and the
1325** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
1326** file control occurs at the beginning of pragma statement analysis and so
1327** it is able to override built-in [PRAGMA] statements.
1328**
1329** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1330** ^The [SQLITE_FCNTL_BUSYHANDLER]
1331** file-control may be invoked by SQLite on the database file handle
1332** shortly after it is opened in order to provide a custom VFS with access
1333** to the connection's busy-handler callback. The argument is of type (void**)
1334** - an array of two (void *) values. The first (void *) actually points
1335** to a function of type (int (*)(void *)). In order to invoke the connection's
1336** busy-handler, this function should be invoked with the second (void *) in
1337** the array as the only argument. If it returns non-zero, then the operation
1338** should be retried. If it returns zero, the custom VFS should abandon the
1339** current operation.
1340**
1341** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1342** ^Applications can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1343** to have SQLite generate a
1344** temporary filename using the same algorithm that is followed to generate
1345** temporary filenames for TEMP tables and other internal uses. The
1346** argument should be a char** which will be filled with the filename
1347** written into memory obtained from [sqlite3_malloc()]. The caller should
1348** invoke [sqlite3_free()] on the result to avoid a memory leak.
1349**
1350** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1351** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1352** maximum number of bytes that will be used for memory-mapped I/O.
1353** The argument is a pointer to a value of type sqlite3_int64 that
1354** is an advisory maximum number of bytes in the file to memory map. The
1355** pointer is overwritten with the old value. The limit is not changed if
1356** the value originally pointed to is negative, and so the current limit
1357** can be queried by passing in a pointer to a negative number. This
1358** file-control is used internally to implement [PRAGMA mmap_size].
1359**
1360** <li>[[SQLITE_FCNTL_TRACE]]
1361** The [SQLITE_FCNTL_TRACE] file control provides advisory information
1362** to the VFS about what the higher layers of the SQLite stack are doing.
1363** This file control is used by some VFS activity tracing [shims].
1364** The argument is a zero-terminated string. Higher layers in the
1365** SQLite stack may generate instances of this file control if
1366** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
1367**
1368** <li>[[SQLITE_FCNTL_HAS_MOVED]]
1369** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
1370** pointer to an integer and it writes a boolean into that integer depending
1371** on whether or not the file has been renamed, moved, or deleted since it
1372** was first opened.
1373**
1374** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
1375** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
1376** underlying native file handle associated with a file handle. This file
1377** control interprets its argument as a pointer to a native file handle and
1378** writes the resulting value there.
1379**
1380** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
1381** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
1382** opcode causes the xFileControl method to swap the file handle with the one
1383** pointed to by the pArg argument. This capability is used during testing
1384** and only needs to be supported when SQLITE_TEST is defined.
1385**
1386** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
1387** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
1388** be advantageous to block on the next WAL lock if the lock is not immediately
1389** available. The WAL subsystem issues this signal during rare
1390** circumstances in order to fix a problem with priority inversion.
1391** Applications should <em>not</em> use this file-control.
1392**
1393** <li>[[SQLITE_FCNTL_ZIPVFS]]
1394** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
1395** VFS should return SQLITE_NOTFOUND for this opcode.
1396**
1397** <li>[[SQLITE_FCNTL_RBU]]
1398** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
1399** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
1400** this opcode.
1401**
1402** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
1403** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
1404** the file descriptor is placed in "batch write mode", which
1405** means all subsequent write operations will be deferred and done
1406** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems
1407** that do not support batch atomic writes will return SQLITE_NOTFOUND.
1408** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to
1409** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or
1410** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make
1411** no VFS interface calls on the same [sqlite3_file] file descriptor
1412** except for calls to the xWrite method and the xFileControl method
1413** with [SQLITE_FCNTL_SIZE_HINT].
1414**
1415** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
1416** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
1417** operations since the previous successful call to
1418** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
1419** This file control returns [SQLITE_OK] if and only if the writes were
1420** all performed successfully and have been committed to persistent storage.
1421** ^Regardless of whether or not it is successful, this file control takes
1422** the file descriptor out of batch write mode so that all subsequent
1423** write operations are independent.
1424** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without
1425** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
1426**
1427** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
1428** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
1429** operations since the previous successful call to
1430** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
1431** ^This file control takes the file descriptor out of batch write mode
1432** so that all subsequent write operations are independent.
1433** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without
1434** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
1435**
1436** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]]
1437** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode is used to configure a VFS
1438** to block for up to M milliseconds before failing when attempting to
1439** obtain a file lock using the xLock or xShmLock methods of the VFS.
1440** The parameter is a pointer to a 32-bit signed integer that contains
1441** the value that M is to be set to. Before returning, the 32-bit signed
1442** integer is overwritten with the previous value of M.
1443**
1444** <li>[[SQLITE_FCNTL_DATA_VERSION]]
1445** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to
1446** a database file. The argument is a pointer to a 32-bit unsigned integer.
1447** The "data version" for the pager is written into the pointer. The
1448** "data version" changes whenever any change occurs to the corresponding
1449** database file, either through SQL statements on the same database
1450** connection or through transactions committed by separate database
1451** connections possibly in other processes. The [sqlite3_total_changes()]
1452** interface can be used to find if any database on the connection has changed,
1453** but that interface responds to changes on TEMP as well as MAIN and does
1454** not provide a mechanism to detect changes to MAIN only. Also, the
1455** [sqlite3_total_changes()] interface responds to internal changes only and
1456** omits changes made by other database connections. The
1457** [PRAGMA data_version] command provides a mechanism to detect changes to
1458** a single attached database that occur due to other database connections,
1459** but omits changes implemented by the database connection on which it is
1460** called. This file control is the only mechanism to detect changes that
1461** happen either internally or externally and that are associated with
1462** a particular attached database.
1463**
1464** <li>[[SQLITE_FCNTL_CKPT_START]]
1465** The [SQLITE_FCNTL_CKPT_START] opcode is invoked from within a checkpoint
1466** in wal mode before the client starts to copy pages from the wal
1467** file to the database file.
1468**
1469** <li>[[SQLITE_FCNTL_CKPT_DONE]]
1470** The [SQLITE_FCNTL_CKPT_DONE] opcode is invoked from within a checkpoint
1471** in wal mode after the client has finished copying pages from the wal
1472** file to the database file, but before the *-shm file is updated to
1473** record the fact that the pages have been checkpointed.
1474** </ul>
1475**
1476** <li>[[SQLITE_FCNTL_EXTERNAL_READER]]
1477** The EXPERIMENTAL [SQLITE_FCNTL_EXTERNAL_READER] opcode is used to detect
1478** whether or not there is a database client in another process with a wal-mode
1479** transaction open on the database or not. It is only available on unix.The
1480** (void*) argument passed with this file-control should be a pointer to a
1481** value of type (int). The integer value is set to 1 if the database is a wal
1482** mode database and there exists at least one client in another process that
1483** currently has an SQL transaction open on the database. It is set to 0 if
1484** the database is not a wal-mode db, or if there is no such connection in any
1485** other process. This opcode cannot be used to detect transactions opened
1486** by clients within the current process, only within other processes.
1487** </ul>
1488**
1489** <li>[[SQLITE_FCNTL_CKSM_FILE]]
1490** Used by the cksmvfs VFS module only.
1491** </ul>
1492*/
1493#define SQLITE_FCNTL_LOCKSTATE 1
1494#define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
1495#define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
1496#define SQLITE_FCNTL_LAST_ERRNO 4
1497#define SQLITE_FCNTL_SIZE_HINT 5
1498#define SQLITE_FCNTL_CHUNK_SIZE 6
1499#define SQLITE_FCNTL_FILE_POINTER 7
1500#define SQLITE_FCNTL_SYNC_OMITTED 8
1501#define SQLITE_FCNTL_WIN32_AV_RETRY 9
1502#define SQLITE_FCNTL_PERSIST_WAL 10
1503#define SQLITE_FCNTL_OVERWRITE 11
1504#define SQLITE_FCNTL_VFSNAME 12
1505#define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
1506#define SQLITE_FCNTL_PRAGMA 14
1507#define SQLITE_FCNTL_BUSYHANDLER 15
1508#define SQLITE_FCNTL_TEMPFILENAME 16
1509#define SQLITE_FCNTL_MMAP_SIZE 18
1510#define SQLITE_FCNTL_TRACE 19
1511#define SQLITE_FCNTL_HAS_MOVED 20
1512#define SQLITE_FCNTL_SYNC 21
1513#define SQLITE_FCNTL_COMMIT_PHASETWO 22
1514#define SQLITE_FCNTL_WIN32_SET_HANDLE 23
1515#define SQLITE_FCNTL_WAL_BLOCK 24
1516#define SQLITE_FCNTL_ZIPVFS 25
1517#define SQLITE_FCNTL_RBU 26
1518#define SQLITE_FCNTL_VFS_POINTER 27
1519#define SQLITE_FCNTL_JOURNAL_POINTER 28
1520#define SQLITE_FCNTL_WIN32_GET_HANDLE 29
1521#define SQLITE_FCNTL_PDB 30
1522#define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE 31
1523#define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE 32
1524#define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE 33
1525#define SQLITE_FCNTL_LOCK_TIMEOUT 34
1526#define SQLITE_FCNTL_DATA_VERSION 35
1527#define SQLITE_FCNTL_SIZE_LIMIT 36
1528#define SQLITE_FCNTL_CKPT_DONE 37
1529#define SQLITE_FCNTL_RESERVE_BYTES 38
1530#define SQLITE_FCNTL_CKPT_START 39
1531#define SQLITE_FCNTL_EXTERNAL_READER 40
1532#define SQLITE_FCNTL_CKSM_FILE 41
1533
1534/* deprecated names */
1535#define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
1536#define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
1537#define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
1538
1539
1540/*
1541** CAPI3REF: Mutex Handle
1542**
1543** The mutex module within SQLite defines [sqlite3_mutex] to be an
1544** abstract type for a mutex object. The SQLite core never looks
1545** at the internal representation of an [sqlite3_mutex]. It only
1546** deals with pointers to the [sqlite3_mutex] object.
1547**
1548** Mutexes are created using [sqlite3_mutex_alloc()].
1549*/
1550typedef struct sqlite3_mutex sqlite3_mutex;
1551
1552/*
1553** CAPI3REF: Loadable Extension Thunk
1554**
1555** A pointer to the opaque sqlite3_api_routines structure is passed as
1556** the third parameter to entry points of [loadable extensions]. This
1557** structure must be typedefed in order to work around compiler warnings
1558** on some platforms.
1559*/
1560typedef struct sqlite3_api_routines sqlite3_api_routines;
1561
1562/*
1563** CAPI3REF: OS Interface Object
1564**
1565** An instance of the sqlite3_vfs object defines the interface between
1566** the SQLite core and the underlying operating system. The "vfs"
1567** in the name of the object stands for "virtual file system". See
1568** the [VFS | VFS documentation] for further information.
1569**
1570** The VFS interface is sometimes extended by adding new methods onto
1571** the end. Each time such an extension occurs, the iVersion field
1572** is incremented. The iVersion value started out as 1 in
1573** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 2
1574** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased
1575** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6]. Additional fields
1576** may be appended to the sqlite3_vfs object and the iVersion value
1577** may increase again in future versions of SQLite.
1578** Note that due to an oversight, the structure
1579** of the sqlite3_vfs object changed in the transition from
1580** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0]
1581** and yet the iVersion field was not increased.
1582**
1583** The szOsFile field is the size of the subclassed [sqlite3_file]
1584** structure used by this VFS. mxPathname is the maximum length of
1585** a pathname in this VFS.
1586**
1587** Registered sqlite3_vfs objects are kept on a linked list formed by
1588** the pNext pointer. The [sqlite3_vfs_register()]
1589** and [sqlite3_vfs_unregister()] interfaces manage this list
1590** in a thread-safe way. The [sqlite3_vfs_find()] interface
1591** searches the list. Neither the application code nor the VFS
1592** implementation should use the pNext pointer.
1593**
1594** The pNext field is the only field in the sqlite3_vfs
1595** structure that SQLite will ever modify. SQLite will only access
1596** or modify this field while holding a particular static mutex.
1597** The application should never modify anything within the sqlite3_vfs
1598** object once the object has been registered.
1599**
1600** The zName field holds the name of the VFS module. The name must
1601** be unique across all VFS modules.
1602**
1603** [[sqlite3_vfs.xOpen]]
1604** ^SQLite guarantees that the zFilename parameter to xOpen
1605** is either a NULL pointer or string obtained
1606** from xFullPathname() with an optional suffix added.
1607** ^If a suffix is added to the zFilename parameter, it will
1608** consist of a single "-" character followed by no more than
1609** 11 alphanumeric and/or "-" characters.
1610** ^SQLite further guarantees that
1611** the string will be valid and unchanged until xClose() is
1612** called. Because of the previous sentence,
1613** the [sqlite3_file] can safely store a pointer to the
1614** filename if it needs to remember the filename for some reason.
1615** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1616** must invent its own temporary name for the file. ^Whenever the
1617** xFilename parameter is NULL it will also be the case that the
1618** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1619**
1620** The flags argument to xOpen() includes all bits set in
1621** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
1622** or [sqlite3_open16()] is used, then flags includes at least
1623** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1624** If xOpen() opens a file read-only then it sets *pOutFlags to
1625** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
1626**
1627** ^(SQLite will also add one of the following flags to the xOpen()
1628** call, depending on the object being opened:
1629**
1630** <ul>
1631** <li> [SQLITE_OPEN_MAIN_DB]
1632** <li> [SQLITE_OPEN_MAIN_JOURNAL]
1633** <li> [SQLITE_OPEN_TEMP_DB]
1634** <li> [SQLITE_OPEN_TEMP_JOURNAL]
1635** <li> [SQLITE_OPEN_TRANSIENT_DB]
1636** <li> [SQLITE_OPEN_SUBJOURNAL]
1637** <li> [SQLITE_OPEN_SUPER_JOURNAL]
1638** <li> [SQLITE_OPEN_WAL]
1639** </ul>)^
1640**
1641** The file I/O implementation can use the object type flags to
1642** change the way it deals with files. For example, an application
1643** that does not care about crash recovery or rollback might make
1644** the open of a journal file a no-op. Writes to this journal would
1645** also be no-ops, and any attempt to read the journal would return
1646** SQLITE_IOERR. Or the implementation might recognize that a database
1647** file will be doing page-aligned sector reads and writes in a random
1648** order and set up its I/O subsystem accordingly.
1649**
1650** SQLite might also add one of the following flags to the xOpen method:
1651**
1652** <ul>
1653** <li> [SQLITE_OPEN_DELETEONCLOSE]
1654** <li> [SQLITE_OPEN_EXCLUSIVE]
1655** </ul>
1656**
1657** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1658** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
1659** will be set for TEMP databases and their journals, transient
1660** databases, and subjournals.
1661**
1662** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1663** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1664** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1665** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1666** SQLITE_OPEN_CREATE, is used to indicate that file should always
1667** be created, and that it is an error if it already exists.
1668** It is <i>not</i> used to indicate the file should be opened
1669** for exclusive access.
1670**
1671** ^At least szOsFile bytes of memory are allocated by SQLite
1672** to hold the [sqlite3_file] structure passed as the third
1673** argument to xOpen. The xOpen method does not have to
1674** allocate the structure; it should just fill it in. Note that
1675** the xOpen method must set the sqlite3_file.pMethods to either
1676** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
1677** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
1678** element will be valid after xOpen returns regardless of the success
1679** or failure of the xOpen call.
1680**
1681** [[sqlite3_vfs.xAccess]]
1682** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1683** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1684** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1685** to test whether a file is at least readable. The SQLITE_ACCESS_READ
1686** flag is never actually used and is not implemented in the built-in
1687** VFSes of SQLite. The file is named by the second argument and can be a
1688** directory. The xAccess method returns [SQLITE_OK] on success or some
1689** non-zero error code if there is an I/O error or if the name of
1690** the file given in the second argument is illegal. If SQLITE_OK
1691** is returned, then non-zero or zero is written into *pResOut to indicate
1692** whether or not the file is accessible.
1693**
1694** ^SQLite will always allocate at least mxPathname+1 bytes for the
1695** output buffer xFullPathname. The exact size of the output buffer
1696** is also passed as a parameter to both methods. If the output buffer
1697** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1698** handled as a fatal error by SQLite, vfs implementations should endeavor
1699** to prevent this by setting mxPathname to a sufficiently large value.
1700**
1701** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1702** interfaces are not strictly a part of the filesystem, but they are
1703** included in the VFS structure for completeness.
1704** The xRandomness() function attempts to return nBytes bytes
1705** of good-quality randomness into zOut. The return value is
1706** the actual number of bytes of randomness obtained.
1707** The xSleep() method causes the calling thread to sleep for at
1708** least the number of microseconds given. ^The xCurrentTime()
1709** method returns a Julian Day Number for the current date and time as
1710** a floating point value.
1711** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1712** Day Number multiplied by 86400000 (the number of milliseconds in
1713** a 24-hour day).
1714** ^SQLite will use the xCurrentTimeInt64() method to get the current
1715** date and time if that method is available (if iVersion is 2 or
1716** greater and the function pointer is not NULL) and will fall back
1717** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1718**
1719** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1720** are not used by the SQLite core. These optional interfaces are provided
1721** by some VFSes to facilitate testing of the VFS code. By overriding
1722** system calls with functions under its control, a test program can
1723** simulate faults and error conditions that would otherwise be difficult
1724** or impossible to induce. The set of system calls that can be overridden
1725** varies from one VFS to another, and from one version of the same VFS to the
1726** next. Applications that use these interfaces must be prepared for any
1727** or all of these interfaces to be NULL or for their behavior to change
1728** from one release to the next. Applications must not attempt to access
1729** any of these methods if the iVersion of the VFS is less than 3.
1730*/
1731typedef struct sqlite3_vfs sqlite3_vfs;
1732typedef void (*sqlite3_syscall_ptr)(void);
1733struct sqlite3_vfs {
1734 int iVersion; /* Structure version number (currently 3) */
1735 int szOsFile; /* Size of subclassed sqlite3_file */
1736 int mxPathname; /* Maximum file pathname length */
1737 sqlite3_vfs *pNext; /* Next registered VFS */
1738 const char *zName; /* Name of this virtual file system */
1739 void *pAppData; /* Pointer to application-specific data */
1740 int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1741 int flags, int *pOutFlags);
1742 int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1743 int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1744 int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1745 void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1746 void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1747 void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1748 void (*xDlClose)(sqlite3_vfs*, void*);
1749 int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1750 int (*xSleep)(sqlite3_vfs*, int microseconds);
1751 int (*xCurrentTime)(sqlite3_vfs*, double*);
1752 int (*xGetLastError)(sqlite3_vfs*, int, char *);
1753 /*
1754 ** The methods above are in version 1 of the sqlite_vfs object
1755 ** definition. Those that follow are added in version 2 or later
1756 */
1757 int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1758 /*
1759 ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1760 ** Those below are for version 3 and greater.
1761 */
1762 int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1763 sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1764 const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1765 /*
1766 ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1767 ** New fields may be appended in future versions. The iVersion
1768 ** value will increment whenever this happens.
1769 */
1770};
1771
1772/*
1773** CAPI3REF: Flags for the xAccess VFS method
1774**
1775** These integer constants can be used as the third parameter to
1776** the xAccess method of an [sqlite3_vfs] object. They determine
1777** what kind of permissions the xAccess method is looking for.
1778** With SQLITE_ACCESS_EXISTS, the xAccess method
1779** simply checks whether the file exists.
1780** With SQLITE_ACCESS_READWRITE, the xAccess method
1781** checks whether the named directory is both readable and writable
1782** (in other words, if files can be added, removed, and renamed within
1783** the directory).
1784** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1785** [temp_store_directory pragma], though this could change in a future
1786** release of SQLite.
1787** With SQLITE_ACCESS_READ, the xAccess method
1788** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
1789** currently unused, though it might be used in a future release of
1790** SQLite.
1791*/
1792#define SQLITE_ACCESS_EXISTS 0
1793#define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
1794#define SQLITE_ACCESS_READ 2 /* Unused */
1795
1796/*
1797** CAPI3REF: Flags for the xShmLock VFS method
1798**
1799** These integer constants define the various locking operations
1800** allowed by the xShmLock method of [sqlite3_io_methods]. The
1801** following are the only legal combinations of flags to the
1802** xShmLock method:
1803**
1804** <ul>
1805** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1806** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1807** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1808** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1809** </ul>
1810**
1811** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1812** was given on the corresponding lock.
1813**
1814** The xShmLock method can transition between unlocked and SHARED or
1815** between unlocked and EXCLUSIVE. It cannot transition between SHARED
1816** and EXCLUSIVE.
1817*/
1818#define SQLITE_SHM_UNLOCK 1
1819#define SQLITE_SHM_LOCK 2
1820#define SQLITE_SHM_SHARED 4
1821#define SQLITE_SHM_EXCLUSIVE 8
1822
1823/*
1824** CAPI3REF: Maximum xShmLock index
1825**
1826** The xShmLock method on [sqlite3_io_methods] may use values
1827** between 0 and this upper bound as its "offset" argument.
1828** The SQLite core will never attempt to acquire or release a
1829** lock outside of this range
1830*/
1831#define SQLITE_SHM_NLOCK 8
1832
1833
1834/*
1835** CAPI3REF: Initialize The SQLite Library
1836**
1837** ^The sqlite3_initialize() routine initializes the
1838** SQLite library. ^The sqlite3_shutdown() routine
1839** deallocates any resources that were allocated by sqlite3_initialize().
1840** These routines are designed to aid in process initialization and
1841** shutdown on embedded systems. Workstation applications using
1842** SQLite normally do not need to invoke either of these routines.
1843**
1844** A call to sqlite3_initialize() is an "effective" call if it is
1845** the first time sqlite3_initialize() is invoked during the lifetime of
1846** the process, or if it is the first time sqlite3_initialize() is invoked
1847** following a call to sqlite3_shutdown(). ^(Only an effective call
1848** of sqlite3_initialize() does any initialization. All other calls
1849** are harmless no-ops.)^
1850**
1851** A call to sqlite3_shutdown() is an "effective" call if it is the first
1852** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
1853** an effective call to sqlite3_shutdown() does any deinitialization.
1854** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1855**
1856** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1857** is not. The sqlite3_shutdown() interface must only be called from a
1858** single thread. All open [database connections] must be closed and all
1859** other SQLite resources must be deallocated prior to invoking
1860** sqlite3_shutdown().
1861**
1862** Among other things, ^sqlite3_initialize() will invoke
1863** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
1864** will invoke sqlite3_os_end().
1865**
1866** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1867** ^If for some reason, sqlite3_initialize() is unable to initialize
1868** the library (perhaps it is unable to allocate a needed resource such
1869** as a mutex) it returns an [error code] other than [SQLITE_OK].
1870**
1871** ^The sqlite3_initialize() routine is called internally by many other
1872** SQLite interfaces so that an application usually does not need to
1873** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
1874** calls sqlite3_initialize() so the SQLite library will be automatically
1875** initialized when [sqlite3_open()] is called if it has not be initialized
1876** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1877** compile-time option, then the automatic calls to sqlite3_initialize()
1878** are omitted and the application must call sqlite3_initialize() directly
1879** prior to using any other SQLite interface. For maximum portability,
1880** it is recommended that applications always invoke sqlite3_initialize()
1881** directly prior to using any other SQLite interface. Future releases
1882** of SQLite may require this. In other words, the behavior exhibited
1883** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1884** default behavior in some future release of SQLite.
1885**
1886** The sqlite3_os_init() routine does operating-system specific
1887** initialization of the SQLite library. The sqlite3_os_end()
1888** routine undoes the effect of sqlite3_os_init(). Typical tasks
1889** performed by these routines include allocation or deallocation
1890** of static resources, initialization of global variables,
1891** setting up a default [sqlite3_vfs] module, or setting up
1892** a default configuration using [sqlite3_config()].
1893**
1894** The application should never invoke either sqlite3_os_init()
1895** or sqlite3_os_end() directly. The application should only invoke
1896** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
1897** interface is called automatically by sqlite3_initialize() and
1898** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
1899** implementations for sqlite3_os_init() and sqlite3_os_end()
1900** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1901** When [custom builds | built for other platforms]
1902** (using the [SQLITE_OS_OTHER=1] compile-time
1903** option) the application must supply a suitable implementation for
1904** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
1905** implementation of sqlite3_os_init() or sqlite3_os_end()
1906** must return [SQLITE_OK] on success and some other [error code] upon
1907** failure.
1908*/
1909SQLITE_API int sqlite3_initialize(void);
1910SQLITE_API int sqlite3_shutdown(void);
1911SQLITE_API int sqlite3_os_init(void);
1912SQLITE_API int sqlite3_os_end(void);
1913
1914/*
1915** CAPI3REF: Configuring The SQLite Library
1916**
1917** The sqlite3_config() interface is used to make global configuration
1918** changes to SQLite in order to tune SQLite to the specific needs of
1919** the application. The default configuration is recommended for most
1920** applications and so this routine is usually not necessary. It is
1921** provided to support rare applications with unusual needs.
1922**
1923** <b>The sqlite3_config() interface is not threadsafe. The application
1924** must ensure that no other SQLite interfaces are invoked by other
1925** threads while sqlite3_config() is running.</b>
1926**
1927** The sqlite3_config() interface
1928** may only be invoked prior to library initialization using
1929** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1930** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1931** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1932** Note, however, that ^sqlite3_config() can be called as part of the
1933** implementation of an application-defined [sqlite3_os_init()].
1934**
1935** The first argument to sqlite3_config() is an integer
1936** [configuration option] that determines
1937** what property of SQLite is to be configured. Subsequent arguments
1938** vary depending on the [configuration option]
1939** in the first argument.
1940**
1941** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1942** ^If the option is unknown or SQLite is unable to set the option
1943** then this routine returns a non-zero [error code].
1944*/
1945SQLITE_API int sqlite3_config(int, ...);
1946
1947/*
1948** CAPI3REF: Configure database connections
1949** METHOD: sqlite3
1950**
1951** The sqlite3_db_config() interface is used to make configuration
1952** changes to a [database connection]. The interface is similar to
1953** [sqlite3_config()] except that the changes apply to a single
1954** [database connection] (specified in the first argument).
1955**
1956** The second argument to sqlite3_db_config(D,V,...) is the
1957** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1958** that indicates what aspect of the [database connection] is being configured.
1959** Subsequent arguments vary depending on the configuration verb.
1960**
1961** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1962** the call is considered successful.
1963*/
1964SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1965
1966/*
1967** CAPI3REF: Memory Allocation Routines
1968**
1969** An instance of this object defines the interface between SQLite
1970** and low-level memory allocation routines.
1971**
1972** This object is used in only one place in the SQLite interface.
1973** A pointer to an instance of this object is the argument to
1974** [sqlite3_config()] when the configuration option is
1975** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1976** By creating an instance of this object
1977** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1978** during configuration, an application can specify an alternative
1979** memory allocation subsystem for SQLite to use for all of its
1980** dynamic memory needs.
1981**
1982** Note that SQLite comes with several [built-in memory allocators]
1983** that are perfectly adequate for the overwhelming majority of applications
1984** and that this object is only useful to a tiny minority of applications
1985** with specialized memory allocation requirements. This object is
1986** also used during testing of SQLite in order to specify an alternative
1987** memory allocator that simulates memory out-of-memory conditions in
1988** order to verify that SQLite recovers gracefully from such
1989** conditions.
1990**
1991** The xMalloc, xRealloc, and xFree methods must work like the
1992** malloc(), realloc() and free() functions from the standard C library.
1993** ^SQLite guarantees that the second argument to
1994** xRealloc is always a value returned by a prior call to xRoundup.
1995**
1996** xSize should return the allocated size of a memory allocation
1997** previously obtained from xMalloc or xRealloc. The allocated size
1998** is always at least as big as the requested size but may be larger.
1999**
2000** The xRoundup method returns what would be the allocated size of
2001** a memory allocation given a particular requested size. Most memory
2002** allocators round up memory allocations at least to the next multiple
2003** of 8. Some allocators round up to a larger multiple or to a power of 2.
2004** Every memory allocation request coming in through [sqlite3_malloc()]
2005** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
2006** that causes the corresponding memory allocation to fail.
2007**
2008** The xInit method initializes the memory allocator. For example,
2009** it might allocate any required mutexes or initialize internal data
2010** structures. The xShutdown method is invoked (indirectly) by
2011** [sqlite3_shutdown()] and should deallocate any resources acquired
2012** by xInit. The pAppData pointer is used as the only parameter to
2013** xInit and xShutdown.
2014**
2015** SQLite holds the [SQLITE_MUTEX_STATIC_MAIN] mutex when it invokes
2016** the xInit method, so the xInit method need not be threadsafe. The
2017** xShutdown method is only called from [sqlite3_shutdown()] so it does
2018** not need to be threadsafe either. For all other methods, SQLite
2019** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
2020** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
2021** it is by default) and so the methods are automatically serialized.
2022** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
2023** methods must be threadsafe or else make their own arrangements for
2024** serialization.
2025**
2026** SQLite will never invoke xInit() more than once without an intervening
2027** call to xShutdown().
2028*/
2029typedef struct sqlite3_mem_methods sqlite3_mem_methods;
2030struct sqlite3_mem_methods {
2031 void *(*xMalloc)(int); /* Memory allocation function */
2032 void (*xFree)(void*); /* Free a prior allocation */
2033 void *(*xRealloc)(void*,int); /* Resize an allocation */
2034 int (*xSize)(void*); /* Return the size of an allocation */
2035 int (*xRoundup)(int); /* Round up request size to allocation size */
2036 int (*xInit)(void*); /* Initialize the memory allocator */
2037 void (*xShutdown)(void*); /* Deinitialize the memory allocator */
2038 void *pAppData; /* Argument to xInit() and xShutdown() */
2039};
2040
2041/*
2042** CAPI3REF: Configuration Options
2043** KEYWORDS: {configuration option}
2044**
2045** These constants are the available integer configuration options that
2046** can be passed as the first argument to the [sqlite3_config()] interface.
2047**
2048** New configuration options may be added in future releases of SQLite.
2049** Existing configuration options might be discontinued. Applications
2050** should check the return code from [sqlite3_config()] to make sure that
2051** the call worked. The [sqlite3_config()] interface will return a
2052** non-zero [error code] if a discontinued or unsupported configuration option
2053** is invoked.
2054**
2055** <dl>
2056** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
2057** <dd>There are no arguments to this option. ^This option sets the
2058** [threading mode] to Single-thread. In other words, it disables
2059** all mutexing and puts SQLite into a mode where it can only be used
2060** by a single thread. ^If SQLite is compiled with
2061** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2062** it is not possible to change the [threading mode] from its default
2063** value of Single-thread and so [sqlite3_config()] will return
2064** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
2065** configuration option.</dd>
2066**
2067** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
2068** <dd>There are no arguments to this option. ^This option sets the
2069** [threading mode] to Multi-thread. In other words, it disables
2070** mutexing on [database connection] and [prepared statement] objects.
2071** The application is responsible for serializing access to
2072** [database connections] and [prepared statements]. But other mutexes
2073** are enabled so that SQLite will be safe to use in a multi-threaded
2074** environment as long as no two threads attempt to use the same
2075** [database connection] at the same time. ^If SQLite is compiled with
2076** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2077** it is not possible to set the Multi-thread [threading mode] and
2078** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
2079** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
2080**
2081** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
2082** <dd>There are no arguments to this option. ^This option sets the
2083** [threading mode] to Serialized. In other words, this option enables
2084** all mutexes including the recursive
2085** mutexes on [database connection] and [prepared statement] objects.
2086** In this mode (which is the default when SQLite is compiled with
2087** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
2088** to [database connections] and [prepared statements] so that the
2089** application is free to use the same [database connection] or the
2090** same [prepared statement] in different threads at the same time.
2091** ^If SQLite is compiled with
2092** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2093** it is not possible to set the Serialized [threading mode] and
2094** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
2095** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
2096**
2097** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
2098** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
2099** a pointer to an instance of the [sqlite3_mem_methods] structure.
2100** The argument specifies
2101** alternative low-level memory allocation routines to be used in place of
2102** the memory allocation routines built into SQLite.)^ ^SQLite makes
2103** its own private copy of the content of the [sqlite3_mem_methods] structure
2104** before the [sqlite3_config()] call returns.</dd>
2105**
2106** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
2107** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
2108** is a pointer to an instance of the [sqlite3_mem_methods] structure.
2109** The [sqlite3_mem_methods]
2110** structure is filled with the currently defined memory allocation routines.)^
2111** This option can be used to overload the default memory allocation
2112** routines with a wrapper that simulations memory allocation failure or
2113** tracks memory usage, for example. </dd>
2114**
2115** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>
2116** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of
2117** type int, interpreted as a boolean, which if true provides a hint to
2118** SQLite that it should avoid large memory allocations if possible.
2119** SQLite will run faster if it is free to make large memory allocations,
2120** but some application might prefer to run slower in exchange for
2121** guarantees about memory fragmentation that are possible if large
2122** allocations are avoided. This hint is normally off.
2123** </dd>
2124**
2125** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
2126** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
2127** interpreted as a boolean, which enables or disables the collection of
2128** memory allocation statistics. ^(When memory allocation statistics are
2129** disabled, the following SQLite interfaces become non-operational:
2130** <ul>
2131** <li> [sqlite3_hard_heap_limit64()]
2132** <li> [sqlite3_memory_used()]
2133** <li> [sqlite3_memory_highwater()]
2134** <li> [sqlite3_soft_heap_limit64()]
2135** <li> [sqlite3_status64()]
2136** </ul>)^
2137** ^Memory allocation statistics are enabled by default unless SQLite is
2138** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
2139** allocation statistics are disabled by default.
2140** </dd>
2141**
2142** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
2143** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used.
2144** </dd>
2145**
2146** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
2147** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
2148** that SQLite can use for the database page cache with the default page
2149** cache implementation.
2150** This configuration option is a no-op if an application-defined page
2151** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
2152** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
2153** 8-byte aligned memory (pMem), the size of each page cache line (sz),
2154** and the number of cache lines (N).
2155** The sz argument should be the size of the largest database page
2156** (a power of two between 512 and 65536) plus some extra bytes for each
2157** page header. ^The number of extra bytes needed by the page header
2158** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
2159** ^It is harmless, apart from the wasted memory,
2160** for the sz parameter to be larger than necessary. The pMem
2161** argument must be either a NULL pointer or a pointer to an 8-byte
2162** aligned block of memory of at least sz*N bytes, otherwise
2163** subsequent behavior is undefined.
2164** ^When pMem is not NULL, SQLite will strive to use the memory provided
2165** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
2166** a page cache line is larger than sz bytes or if all of the pMem buffer
2167** is exhausted.
2168** ^If pMem is NULL and N is non-zero, then each database connection
2169** does an initial bulk allocation for page cache memory
2170** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
2171** of -1024*N bytes if N is negative, . ^If additional
2172** page cache memory is needed beyond what is provided by the initial
2173** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
2174** additional cache line. </dd>
2175**
2176** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
2177** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
2178** that SQLite will use for all of its dynamic memory allocation needs
2179** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].
2180** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
2181** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
2182** [SQLITE_ERROR] if invoked otherwise.
2183** ^There are three arguments to SQLITE_CONFIG_HEAP:
2184** An 8-byte aligned pointer to the memory,
2185** the number of bytes in the memory buffer, and the minimum allocation size.
2186** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
2187** to using its default memory allocator (the system malloc() implementation),
2188** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
2189** memory pointer is not NULL then the alternative memory
2190** allocator is engaged to handle all of SQLites memory allocation needs.
2191** The first pointer (the memory pointer) must be aligned to an 8-byte
2192** boundary or subsequent behavior of SQLite will be undefined.
2193** The minimum allocation size is capped at 2**12. Reasonable values
2194** for the minimum allocation size are 2**5 through 2**8.</dd>
2195**
2196** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
2197** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
2198** pointer to an instance of the [sqlite3_mutex_methods] structure.
2199** The argument specifies alternative low-level mutex routines to be used
2200** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
2201** the content of the [sqlite3_mutex_methods] structure before the call to
2202** [sqlite3_config()] returns. ^If SQLite is compiled with
2203** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2204** the entire mutexing subsystem is omitted from the build and hence calls to
2205** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
2206** return [SQLITE_ERROR].</dd>
2207**
2208** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
2209** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
2210** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
2211** [sqlite3_mutex_methods]
2212** structure is filled with the currently defined mutex routines.)^
2213** This option can be used to overload the default mutex allocation
2214** routines with a wrapper used to track mutex usage for performance
2215** profiling or testing, for example. ^If SQLite is compiled with
2216** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2217** the entire mutexing subsystem is omitted from the build and hence calls to
2218** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
2219** return [SQLITE_ERROR].</dd>
2220**
2221** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
2222** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
2223** the default size of lookaside memory on each [database connection].
2224** The first argument is the
2225** size of each lookaside buffer slot and the second is the number of
2226** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
2227** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
2228** option to [sqlite3_db_config()] can be used to change the lookaside
2229** configuration on individual connections.)^ </dd>
2230**
2231** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
2232** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
2233** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
2234** the interface to a custom page cache implementation.)^
2235** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
2236**
2237** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
2238** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
2239** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
2240** the current page cache implementation into that object.)^ </dd>
2241**
2242** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
2243** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
2244** global [error log].
2245** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
2246** function with a call signature of void(*)(void*,int,const char*),
2247** and a pointer to void. ^If the function pointer is not NULL, it is
2248** invoked by [sqlite3_log()] to process each logging event. ^If the
2249** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2250** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2251** passed through as the first parameter to the application-defined logger
2252** function whenever that function is invoked. ^The second parameter to
2253** the logger function is a copy of the first parameter to the corresponding
2254** [sqlite3_log()] call and is intended to be a [result code] or an
2255** [extended result code]. ^The third parameter passed to the logger is
2256** log message after formatting via [sqlite3_snprintf()].
2257** The SQLite logging interface is not reentrant; the logger function
2258** supplied by the application must not invoke any SQLite interface.
2259** In a multi-threaded application, the application-defined logger
2260** function must be threadsafe. </dd>
2261**
2262** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2263** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
2264** If non-zero, then URI handling is globally enabled. If the parameter is zero,
2265** then URI handling is globally disabled.)^ ^If URI handling is globally
2266** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
2267** [sqlite3_open16()] or
2268** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2269** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2270** connection is opened. ^If it is globally disabled, filenames are
2271** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2272** database connection is opened. ^(By default, URI handling is globally
2273** disabled. The default value may be changed by compiling with the
2274** [SQLITE_USE_URI] symbol defined.)^
2275**
2276** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
2277** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
2278** argument which is interpreted as a boolean in order to enable or disable
2279** the use of covering indices for full table scans in the query optimizer.
2280** ^The default setting is determined
2281** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
2282** if that compile-time option is omitted.
2283** The ability to disable the use of covering indices for full table scans
2284** is because some incorrectly coded legacy applications might malfunction
2285** when the optimization is enabled. Providing the ability to
2286** disable the optimization allows the older, buggy application code to work
2287** without change even with newer versions of SQLite.
2288**
2289** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2290** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
2291** <dd> These options are obsolete and should not be used by new code.
2292** They are retained for backwards compatibility but are now no-ops.
2293** </dd>
2294**
2295** [[SQLITE_CONFIG_SQLLOG]]
2296** <dt>SQLITE_CONFIG_SQLLOG
2297** <dd>This option is only available if sqlite is compiled with the
2298** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
2299** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
2300** The second should be of type (void*). The callback is invoked by the library
2301** in three separate circumstances, identified by the value passed as the
2302** fourth parameter. If the fourth parameter is 0, then the database connection
2303** passed as the second argument has just been opened. The third argument
2304** points to a buffer containing the name of the main database file. If the
2305** fourth parameter is 1, then the SQL statement that the third parameter
2306** points to has just been executed. Or, if the fourth parameter is 2, then
2307** the connection being passed as the second parameter is being closed. The
2308** third parameter is passed NULL In this case. An example of using this
2309** configuration option can be seen in the "test_sqllog.c" source file in
2310** the canonical SQLite source tree.</dd>
2311**
2312** [[SQLITE_CONFIG_MMAP_SIZE]]
2313** <dt>SQLITE_CONFIG_MMAP_SIZE
2314** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
2315** that are the default mmap size limit (the default setting for
2316** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
2317** ^The default setting can be overridden by each database connection using
2318** either the [PRAGMA mmap_size] command, or by using the
2319** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
2320** will be silently truncated if necessary so that it does not exceed the
2321** compile-time maximum mmap size set by the
2322** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
2323** ^If either argument to this option is negative, then that argument is
2324** changed to its compile-time default.
2325**
2326** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
2327** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
2328** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
2329** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
2330** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
2331** that specifies the maximum size of the created heap.
2332**
2333** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
2334** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
2335** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
2336** is a pointer to an integer and writes into that integer the number of extra
2337** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
2338** The amount of extra space required can change depending on the compiler,
2339** target platform, and SQLite version.
2340**
2341** [[SQLITE_CONFIG_PMASZ]]
2342** <dt>SQLITE_CONFIG_PMASZ
2343** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
2344** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
2345** sorter to that integer. The default minimum PMA Size is set by the
2346** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
2347** to help with sort operations when multithreaded sorting
2348** is enabled (using the [PRAGMA threads] command) and the amount of content
2349** to be sorted exceeds the page size times the minimum of the
2350** [PRAGMA cache_size] setting and this value.
2351**
2352** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
2353** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
2354** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
2355** becomes the [statement journal] spill-to-disk threshold.
2356** [Statement journals] are held in memory until their size (in bytes)
2357** exceeds this threshold, at which point they are written to disk.
2358** Or if the threshold is -1, statement journals are always held
2359** exclusively in memory.
2360** Since many statement journals never become large, setting the spill
2361** threshold to a value such as 64KiB can greatly reduce the amount of
2362** I/O required to support statement rollback.
2363** The default value for this setting is controlled by the
2364** [SQLITE_STMTJRNL_SPILL] compile-time option.
2365**
2366** [[SQLITE_CONFIG_SORTERREF_SIZE]]
2367** <dt>SQLITE_CONFIG_SORTERREF_SIZE
2368** <dd>The SQLITE_CONFIG_SORTERREF_SIZE option accepts a single parameter
2369** of type (int) - the new value of the sorter-reference size threshold.
2370** Usually, when SQLite uses an external sort to order records according
2371** to an ORDER BY clause, all fields required by the caller are present in the
2372** sorted records. However, if SQLite determines based on the declared type
2373** of a table column that its values are likely to be very large - larger
2374** than the configured sorter-reference size threshold - then a reference
2375** is stored in each sorted record and the required column values loaded
2376** from the database as records are returned in sorted order. The default
2377** value for this option is to never use this optimization. Specifying a
2378** negative value for this option restores the default behaviour.
2379** This option is only available if SQLite is compiled with the
2380** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.
2381**
2382** [[SQLITE_CONFIG_MEMDB_MAXSIZE]]
2383** <dt>SQLITE_CONFIG_MEMDB_MAXSIZE
2384** <dd>The SQLITE_CONFIG_MEMDB_MAXSIZE option accepts a single parameter
2385** [sqlite3_int64] parameter which is the default maximum size for an in-memory
2386** database created using [sqlite3_deserialize()]. This default maximum
2387** size can be adjusted up or down for individual databases using the
2388** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control]. If this
2389** configuration setting is never used, then the default maximum is determined
2390** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option. If that
2391** compile-time option is not set, then the default maximum is 1073741824.
2392** </dl>
2393*/
2394#define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
2395#define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
2396#define SQLITE_CONFIG_SERIALIZED 3 /* nil */
2397#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
2398#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
2399#define SQLITE_CONFIG_SCRATCH 6 /* No longer used */
2400#define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
2401#define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
2402#define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
2403#define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
2404#define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
2405/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2406#define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
2407#define SQLITE_CONFIG_PCACHE 14 /* no-op */
2408#define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
2409#define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
2410#define SQLITE_CONFIG_URI 17 /* int */
2411#define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
2412#define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
2413#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
2414#define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
2415#define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
2416#define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
2417#define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
2418#define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
2419#define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */
2420#define SQLITE_CONFIG_SMALL_MALLOC 27 /* boolean */
2421#define SQLITE_CONFIG_SORTERREF_SIZE 28 /* int nByte */
2422#define SQLITE_CONFIG_MEMDB_MAXSIZE 29 /* sqlite3_int64 */
2423
2424/*
2425** CAPI3REF: Database Connection Configuration Options
2426**
2427** These constants are the available integer configuration options that
2428** can be passed as the second argument to the [sqlite3_db_config()] interface.
2429**
2430** New configuration options may be added in future releases of SQLite.
2431** Existing configuration options might be discontinued. Applications
2432** should check the return code from [sqlite3_db_config()] to make sure that
2433** the call worked. ^The [sqlite3_db_config()] interface will return a
2434** non-zero [error code] if a discontinued or unsupported configuration option
2435** is invoked.
2436**
2437** <dl>
2438** [[SQLITE_DBCONFIG_LOOKASIDE]]
2439** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2440** <dd> ^This option takes three additional arguments that determine the
2441** [lookaside memory allocator] configuration for the [database connection].
2442** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2443** pointer to a memory buffer to use for lookaside memory.
2444** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2445** may be NULL in which case SQLite will allocate the
2446** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2447** size of each lookaside buffer slot. ^The third argument is the number of
2448** slots. The size of the buffer in the first argument must be greater than
2449** or equal to the product of the second and third arguments. The buffer
2450** must be aligned to an 8-byte boundary. ^If the second argument to
2451** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2452** rounded down to the next smaller multiple of 8. ^(The lookaside memory
2453** configuration for a database connection can only be changed when that
2454** connection is not currently using lookaside memory, or in other words
2455** when the "current value" returned by
2456** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2457** Any attempt to change the lookaside memory configuration when lookaside
2458** memory is in use leaves the configuration unchanged and returns
2459** [SQLITE_BUSY].)^</dd>
2460**
2461** [[SQLITE_DBCONFIG_ENABLE_FKEY]]
2462** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2463** <dd> ^This option is used to enable or disable the enforcement of
2464** [foreign key constraints]. There should be two additional arguments.
2465** The first argument is an integer which is 0 to disable FK enforcement,
2466** positive to enable FK enforcement or negative to leave FK enforcement
2467** unchanged. The second parameter is a pointer to an integer into which
2468** is written 0 or 1 to indicate whether FK enforcement is off or on
2469** following this call. The second parameter may be a NULL pointer, in
2470** which case the FK enforcement setting is not reported back. </dd>
2471**
2472** [[SQLITE_DBCONFIG_ENABLE_TRIGGER]]
2473** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2474** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2475** There should be two additional arguments.
2476** The first argument is an integer which is 0 to disable triggers,
2477** positive to enable triggers or negative to leave the setting unchanged.
2478** The second parameter is a pointer to an integer into which
2479** is written 0 or 1 to indicate whether triggers are disabled or enabled
2480** following this call. The second parameter may be a NULL pointer, in
2481** which case the trigger setting is not reported back.
2482**
2483** <p>Originally this option disabled all triggers. ^(However, since
2484** SQLite version 3.35.0, TEMP triggers are still allowed even if
2485** this option is off. So, in other words, this option now only disables
2486** triggers in the main database schema or in the schemas of ATTACH-ed
2487** databases.)^ </dd>
2488**
2489** [[SQLITE_DBCONFIG_ENABLE_VIEW]]
2490** <dt>SQLITE_DBCONFIG_ENABLE_VIEW</dt>
2491** <dd> ^This option is used to enable or disable [CREATE VIEW | views].
2492** There should be two additional arguments.
2493** The first argument is an integer which is 0 to disable views,
2494** positive to enable views or negative to leave the setting unchanged.
2495** The second parameter is a pointer to an integer into which
2496** is written 0 or 1 to indicate whether views are disabled or enabled
2497** following this call. The second parameter may be a NULL pointer, in
2498** which case the view setting is not reported back.
2499**
2500** <p>Originally this option disabled all views. ^(However, since
2501** SQLite version 3.35.0, TEMP views are still allowed even if
2502** this option is off. So, in other words, this option now only disables
2503** views in the main database schema or in the schemas of ATTACH-ed
2504** databases.)^ </dd>
2505**
2506** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]]
2507** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
2508** <dd> ^This option is used to enable or disable the
2509** [fts3_tokenizer()] function which is part of the
2510** [FTS3] full-text search engine extension.
2511** There should be two additional arguments.
2512** The first argument is an integer which is 0 to disable fts3_tokenizer() or
2513** positive to enable fts3_tokenizer() or negative to leave the setting
2514** unchanged.
2515** The second parameter is a pointer to an integer into which
2516** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
2517** following this call. The second parameter may be a NULL pointer, in
2518** which case the new setting is not reported back. </dd>
2519**
2520** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]]
2521** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
2522** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
2523** interface independently of the [load_extension()] SQL function.
2524** The [sqlite3_enable_load_extension()] API enables or disables both the
2525** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
2526** There should be two additional arguments.
2527** When the first argument to this interface is 1, then only the C-API is
2528** enabled and the SQL function remains disabled. If the first argument to
2529** this interface is 0, then both the C-API and the SQL function are disabled.
2530** If the first argument is -1, then no changes are made to state of either the
2531** C-API or the SQL function.
2532** The second parameter is a pointer to an integer into which
2533** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
2534** is disabled or enabled following this call. The second parameter may
2535** be a NULL pointer, in which case the new setting is not reported back.
2536** </dd>
2537**
2538** [[SQLITE_DBCONFIG_MAINDBNAME]] <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
2539** <dd> ^This option is used to change the name of the "main" database
2540** schema. ^The sole argument is a pointer to a constant UTF8 string
2541** which will become the new schema name in place of "main". ^SQLite
2542** does not make a copy of the new main schema name string, so the application
2543** must ensure that the argument passed into this DBCONFIG option is unchanged
2544** until after the database connection closes.
2545** </dd>
2546**
2547** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]]
2548** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
2549** <dd> Usually, when a database in wal mode is closed or detached from a
2550** database handle, SQLite checks if this will mean that there are now no
2551** connections at all to the database. If so, it performs a checkpoint
2552** operation before closing the connection. This option may be used to
2553** override this behaviour. The first parameter passed to this operation
2554** is an integer - positive to disable checkpoints-on-close, or zero (the
2555** default) to enable them, and negative to leave the setting unchanged.
2556** The second parameter is a pointer to an integer
2557** into which is written 0 or 1 to indicate whether checkpoints-on-close
2558** have been disabled - 0 if they are not disabled, 1 if they are.
2559** </dd>
2560**
2561** [[SQLITE_DBCONFIG_ENABLE_QPSG]] <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>
2562** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates
2563** the [query planner stability guarantee] (QPSG). When the QPSG is active,
2564** a single SQL query statement will always use the same algorithm regardless
2565** of values of [bound parameters].)^ The QPSG disables some query optimizations
2566** that look at the values of bound parameters, which can make some queries
2567** slower. But the QPSG has the advantage of more predictable behavior. With
2568** the QPSG active, SQLite will always use the same query plan in the field as
2569** was used during testing in the lab.
2570** The first argument to this setting is an integer which is 0 to disable
2571** the QPSG, positive to enable QPSG, or negative to leave the setting
2572** unchanged. The second parameter is a pointer to an integer into which
2573** is written 0 or 1 to indicate whether the QPSG is disabled or enabled
2574** following this call.
2575** </dd>
2576**
2577** [[SQLITE_DBCONFIG_TRIGGER_EQP]] <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt>
2578** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not
2579** include output for any operations performed by trigger programs. This
2580** option is used to set or clear (the default) a flag that governs this
2581** behavior. The first parameter passed to this operation is an integer -
2582** positive to enable output for trigger programs, or zero to disable it,
2583** or negative to leave the setting unchanged.
2584** The second parameter is a pointer to an integer into which is written
2585** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if
2586** it is not disabled, 1 if it is.
2587** </dd>
2588**
2589** [[SQLITE_DBCONFIG_RESET_DATABASE]] <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt>
2590** <dd> Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run
2591** [VACUUM] in order to reset a database back to an empty database
2592** with no schema and no content. The following process works even for
2593** a badly corrupted database file:
2594** <ol>
2595** <li> If the database connection is newly opened, make sure it has read the
2596** database schema by preparing then discarding some query against the
2597** database, or calling sqlite3_table_column_metadata(), ignoring any
2598** errors. This step is only necessary if the application desires to keep
2599** the database in WAL mode after the reset if it was in WAL mode before
2600** the reset.
2601** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
2602** <li> [sqlite3_exec](db, "[VACUUM]", 0, 0, 0);
2603** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
2604** </ol>
2605** Because resetting a database is destructive and irreversible, the
2606** process requires the use of this obscure API and multiple steps to help
2607** ensure that it does not happen by accident.
2608**
2609** [[SQLITE_DBCONFIG_DEFENSIVE]] <dt>SQLITE_DBCONFIG_DEFENSIVE</dt>
2610** <dd>The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the
2611** "defensive" flag for a database connection. When the defensive
2612** flag is enabled, language features that allow ordinary SQL to
2613** deliberately corrupt the database file are disabled. The disabled
2614** features include but are not limited to the following:
2615** <ul>
2616** <li> The [PRAGMA writable_schema=ON] statement.
2617** <li> The [PRAGMA journal_mode=OFF] statement.
2618** <li> Writes to the [sqlite_dbpage] virtual table.
2619** <li> Direct writes to [shadow tables].
2620** </ul>
2621** </dd>
2622**
2623** [[SQLITE_DBCONFIG_WRITABLE_SCHEMA]] <dt>SQLITE_DBCONFIG_WRITABLE_SCHEMA</dt>
2624** <dd>The SQLITE_DBCONFIG_WRITABLE_SCHEMA option activates or deactivates the
2625** "writable_schema" flag. This has the same effect and is logically equivalent
2626** to setting [PRAGMA writable_schema=ON] or [PRAGMA writable_schema=OFF].
2627** The first argument to this setting is an integer which is 0 to disable
2628** the writable_schema, positive to enable writable_schema, or negative to
2629** leave the setting unchanged. The second parameter is a pointer to an
2630** integer into which is written 0 or 1 to indicate whether the writable_schema
2631** is enabled or disabled following this call.
2632** </dd>
2633**
2634** [[SQLITE_DBCONFIG_LEGACY_ALTER_TABLE]]
2635** <dt>SQLITE_DBCONFIG_LEGACY_ALTER_TABLE</dt>
2636** <dd>The SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option activates or deactivates
2637** the legacy behavior of the [ALTER TABLE RENAME] command such it
2638** behaves as it did prior to [version 3.24.0] (2018-06-04). See the
2639** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for
2640** additional information. This feature can also be turned on and off
2641** using the [PRAGMA legacy_alter_table] statement.
2642** </dd>
2643**
2644** [[SQLITE_DBCONFIG_DQS_DML]]
2645** <dt>SQLITE_DBCONFIG_DQS_DML</td>
2646** <dd>The SQLITE_DBCONFIG_DQS_DML option activates or deactivates
2647** the legacy [double-quoted string literal] misfeature for DML statements
2648** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The
2649** default value of this setting is determined by the [-DSQLITE_DQS]
2650** compile-time option.
2651** </dd>
2652**
2653** [[SQLITE_DBCONFIG_DQS_DDL]]
2654** <dt>SQLITE_DBCONFIG_DQS_DDL</td>
2655** <dd>The SQLITE_DBCONFIG_DQS option activates or deactivates
2656** the legacy [double-quoted string literal] misfeature for DDL statements,
2657** such as CREATE TABLE and CREATE INDEX. The
2658** default value of this setting is determined by the [-DSQLITE_DQS]
2659** compile-time option.
2660** </dd>
2661**
2662** [[SQLITE_DBCONFIG_TRUSTED_SCHEMA]]
2663** <dt>SQLITE_DBCONFIG_TRUSTED_SCHEMA</td>
2664** <dd>The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to
2665** assume that database schemas are untainted by malicious content.
2666** When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite
2667** takes additional defensive steps to protect the application from harm
2668** including:
2669** <ul>
2670** <li> Prohibit the use of SQL functions inside triggers, views,
2671** CHECK constraints, DEFAULT clauses, expression indexes,
2672** partial indexes, or generated columns
2673** unless those functions are tagged with [SQLITE_INNOCUOUS].
2674** <li> Prohibit the use of virtual tables inside of triggers or views
2675** unless those virtual tables are tagged with [SQLITE_VTAB_INNOCUOUS].
2676** </ul>
2677** This setting defaults to "on" for legacy compatibility, however
2678** all applications are advised to turn it off if possible. This setting
2679** can also be controlled using the [PRAGMA trusted_schema] statement.
2680** </dd>
2681**
2682** [[SQLITE_DBCONFIG_LEGACY_FILE_FORMAT]]
2683** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</td>
2684** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates
2685** the legacy file format flag. When activated, this flag causes all newly
2686** created database file to have a schema format version number (the 4-byte
2687** integer found at offset 44 into the database header) of 1. This in turn
2688** means that the resulting database file will be readable and writable by
2689** any SQLite version back to 3.0.0 ([dateof:3.0.0]). Without this setting,
2690** newly created databases are generally not understandable by SQLite versions
2691** prior to 3.3.0 ([dateof:3.3.0]). As these words are written, there
2692** is now scarcely any need to generated database files that are compatible
2693** all the way back to version 3.0.0, and so this setting is of little
2694** practical use, but is provided so that SQLite can continue to claim the
2695** ability to generate new database files that are compatible with version
2696** 3.0.0.
2697** <p>Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on,
2698** the [VACUUM] command will fail with an obscure error when attempting to
2699** process a table with generated columns and a descending index. This is
2700** not considered a bug since SQLite versions 3.3.0 and earlier do not support
2701** either generated columns or decending indexes.
2702** </dd>
2703** </dl>
2704*/
2705#define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */
2706#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
2707#define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
2708#define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
2709#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
2710#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
2711#define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE 1006 /* int int* */
2712#define SQLITE_DBCONFIG_ENABLE_QPSG 1007 /* int int* */
2713#define SQLITE_DBCONFIG_TRIGGER_EQP 1008 /* int int* */
2714#define SQLITE_DBCONFIG_RESET_DATABASE 1009 /* int int* */
2715#define SQLITE_DBCONFIG_DEFENSIVE 1010 /* int int* */
2716#define SQLITE_DBCONFIG_WRITABLE_SCHEMA 1011 /* int int* */
2717#define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE 1012 /* int int* */
2718#define SQLITE_DBCONFIG_DQS_DML 1013 /* int int* */
2719#define SQLITE_DBCONFIG_DQS_DDL 1014 /* int int* */
2720#define SQLITE_DBCONFIG_ENABLE_VIEW 1015 /* int int* */
2721#define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT 1016 /* int int* */
2722#define SQLITE_DBCONFIG_TRUSTED_SCHEMA 1017 /* int int* */
2723#define SQLITE_DBCONFIG_MAX 1017 /* Largest DBCONFIG */
2724
2725/*
2726** CAPI3REF: Enable Or Disable Extended Result Codes
2727** METHOD: sqlite3
2728**
2729** ^The sqlite3_extended_result_codes() routine enables or disables the
2730** [extended result codes] feature of SQLite. ^The extended result
2731** codes are disabled by default for historical compatibility.
2732*/
2733SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2734
2735/*
2736** CAPI3REF: Last Insert Rowid
2737** METHOD: sqlite3
2738**
2739** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
2740** has a unique 64-bit signed
2741** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2742** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2743** names are not also used by explicitly declared columns. ^If
2744** the table has a column of type [INTEGER PRIMARY KEY] then that column
2745** is another alias for the rowid.
2746**
2747** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
2748** the most recent successful [INSERT] into a rowid table or [virtual table]
2749** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
2750** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
2751** on the database connection D, then sqlite3_last_insert_rowid(D) returns
2752** zero.
2753**
2754** As well as being set automatically as rows are inserted into database
2755** tables, the value returned by this function may be set explicitly by
2756** [sqlite3_set_last_insert_rowid()]
2757**
2758** Some virtual table implementations may INSERT rows into rowid tables as
2759** part of committing a transaction (e.g. to flush data accumulated in memory
2760** to disk). In this case subsequent calls to this function return the rowid
2761** associated with these internal INSERT operations, which leads to
2762** unintuitive results. Virtual table implementations that do write to rowid
2763** tables in this way can avoid this problem by restoring the original
2764** rowid value using [sqlite3_set_last_insert_rowid()] before returning
2765** control to the user.
2766**
2767** ^(If an [INSERT] occurs within a trigger then this routine will
2768** return the [rowid] of the inserted row as long as the trigger is
2769** running. Once the trigger program ends, the value returned
2770** by this routine reverts to what it was before the trigger was fired.)^
2771**
2772** ^An [INSERT] that fails due to a constraint violation is not a
2773** successful [INSERT] and does not change the value returned by this
2774** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2775** and INSERT OR ABORT make no changes to the return value of this
2776** routine when their insertion fails. ^(When INSERT OR REPLACE
2777** encounters a constraint violation, it does not fail. The
2778** INSERT continues to completion after deleting rows that caused
2779** the constraint problem so INSERT OR REPLACE will always change
2780** the return value of this interface.)^
2781**
2782** ^For the purposes of this routine, an [INSERT] is considered to
2783** be successful even if it is subsequently rolled back.
2784**
2785** This function is accessible to SQL statements via the
2786** [last_insert_rowid() SQL function].
2787**
2788** If a separate thread performs a new [INSERT] on the same
2789** database connection while the [sqlite3_last_insert_rowid()]
2790** function is running and thus changes the last insert [rowid],
2791** then the value returned by [sqlite3_last_insert_rowid()] is
2792** unpredictable and might not equal either the old or the new
2793** last insert [rowid].
2794*/
2795SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2796
2797/*
2798** CAPI3REF: Set the Last Insert Rowid value.
2799** METHOD: sqlite3
2800**
2801** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
2802** set the value returned by calling sqlite3_last_insert_rowid(D) to R
2803** without inserting a row into the database.
2804*/
2805SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
2806
2807/*
2808** CAPI3REF: Count The Number Of Rows Modified
2809** METHOD: sqlite3
2810**
2811** ^These functions return the number of rows modified, inserted or
2812** deleted by the most recently completed INSERT, UPDATE or DELETE
2813** statement on the database connection specified by the only parameter.
2814** The two functions are identical except for the type of the return value
2815** and that if the number of rows modified by the most recent INSERT, UPDATE
2816** or DELETE is greater than the maximum value supported by type "int", then
2817** the return value of sqlite3_changes() is undefined. ^Executing any other
2818** type of SQL statement does not modify the value returned by these functions.
2819**
2820** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
2821** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
2822** [foreign key actions] or [REPLACE] constraint resolution are not counted.
2823**
2824** Changes to a view that are intercepted by
2825** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
2826** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
2827** DELETE statement run on a view is always zero. Only changes made to real
2828** tables are counted.
2829**
2830** Things are more complicated if the sqlite3_changes() function is
2831** executed while a trigger program is running. This may happen if the
2832** program uses the [changes() SQL function], or if some other callback
2833** function invokes sqlite3_changes() directly. Essentially:
2834**
2835** <ul>
2836** <li> ^(Before entering a trigger program the value returned by
2837** sqlite3_changes() function is saved. After the trigger program
2838** has finished, the original value is restored.)^
2839**
2840** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
2841** statement sets the value returned by sqlite3_changes()
2842** upon completion as normal. Of course, this value will not include
2843** any changes performed by sub-triggers, as the sqlite3_changes()
2844** value will be saved and restored after each sub-trigger has run.)^
2845** </ul>
2846**
2847** ^This means that if the changes() SQL function (or similar) is used
2848** by the first INSERT, UPDATE or DELETE statement within a trigger, it
2849** returns the value as set when the calling statement began executing.
2850** ^If it is used by the second or subsequent such statement within a trigger
2851** program, the value returned reflects the number of rows modified by the
2852** previous INSERT, UPDATE or DELETE statement within the same trigger.
2853**
2854** If a separate thread makes changes on the same database connection
2855** while [sqlite3_changes()] is running then the value returned
2856** is unpredictable and not meaningful.
2857**
2858** See also:
2859** <ul>
2860** <li> the [sqlite3_total_changes()] interface
2861** <li> the [count_changes pragma]
2862** <li> the [changes() SQL function]
2863** <li> the [data_version pragma]
2864** </ul>
2865*/
2866SQLITE_API int sqlite3_changes(sqlite3*);
2867SQLITE_API sqlite3_int64 sqlite3_changes64(sqlite3*);
2868
2869/*
2870** CAPI3REF: Total Number Of Rows Modified
2871** METHOD: sqlite3
2872**
2873** ^These functions return the total number of rows inserted, modified or
2874** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
2875** since the database connection was opened, including those executed as
2876** part of trigger programs. The two functions are identical except for the
2877** type of the return value and that if the number of rows modified by the
2878** connection exceeds the maximum value supported by type "int", then
2879** the return value of sqlite3_total_changes() is undefined. ^Executing
2880** any other type of SQL statement does not affect the value returned by
2881** sqlite3_total_changes().
2882**
2883** ^Changes made as part of [foreign key actions] are included in the
2884** count, but those made as part of REPLACE constraint resolution are
2885** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
2886** are not counted.
2887**
2888** The [sqlite3_total_changes(D)] interface only reports the number
2889** of rows that changed due to SQL statement run against database
2890** connection D. Any changes by other database connections are ignored.
2891** To detect changes against a database file from other database
2892** connections use the [PRAGMA data_version] command or the
2893** [SQLITE_FCNTL_DATA_VERSION] [file control].
2894**
2895** If a separate thread makes changes on the same database connection
2896** while [sqlite3_total_changes()] is running then the value
2897** returned is unpredictable and not meaningful.
2898**
2899** See also:
2900** <ul>
2901** <li> the [sqlite3_changes()] interface
2902** <li> the [count_changes pragma]
2903** <li> the [changes() SQL function]
2904** <li> the [data_version pragma]
2905** <li> the [SQLITE_FCNTL_DATA_VERSION] [file control]
2906** </ul>
2907*/
2908SQLITE_API int sqlite3_total_changes(sqlite3*);
2909SQLITE_API sqlite3_int64 sqlite3_total_changes64(sqlite3*);
2910
2911/*
2912** CAPI3REF: Interrupt A Long-Running Query
2913** METHOD: sqlite3
2914**
2915** ^This function causes any pending database operation to abort and
2916** return at its earliest opportunity. This routine is typically
2917** called in response to a user action such as pressing "Cancel"
2918** or Ctrl-C where the user wants a long query operation to halt
2919** immediately.
2920**
2921** ^It is safe to call this routine from a thread different from the
2922** thread that is currently running the database operation. But it
2923** is not safe to call this routine with a [database connection] that
2924** is closed or might close before sqlite3_interrupt() returns.
2925**
2926** ^If an SQL operation is very nearly finished at the time when
2927** sqlite3_interrupt() is called, then it might not have an opportunity
2928** to be interrupted and might continue to completion.
2929**
2930** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2931** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2932** that is inside an explicit transaction, then the entire transaction
2933** will be rolled back automatically.
2934**
2935** ^The sqlite3_interrupt(D) call is in effect until all currently running
2936** SQL statements on [database connection] D complete. ^Any new SQL statements
2937** that are started after the sqlite3_interrupt() call and before the
2938** running statement count reaches zero are interrupted as if they had been
2939** running prior to the sqlite3_interrupt() call. ^New SQL statements
2940** that are started after the running statement count reaches zero are
2941** not effected by the sqlite3_interrupt().
2942** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2943** SQL statements is a no-op and has no effect on SQL statements
2944** that are started after the sqlite3_interrupt() call returns.
2945*/
2946SQLITE_API void sqlite3_interrupt(sqlite3*);
2947
2948/*
2949** CAPI3REF: Determine If An SQL Statement Is Complete
2950**
2951** These routines are useful during command-line input to determine if the
2952** currently entered text seems to form a complete SQL statement or
2953** if additional input is needed before sending the text into
2954** SQLite for parsing. ^These routines return 1 if the input string
2955** appears to be a complete SQL statement. ^A statement is judged to be
2956** complete if it ends with a semicolon token and is not a prefix of a
2957** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
2958** string literals or quoted identifier names or comments are not
2959** independent tokens (they are part of the token in which they are
2960** embedded) and thus do not count as a statement terminator. ^Whitespace
2961** and comments that follow the final semicolon are ignored.
2962**
2963** ^These routines return 0 if the statement is incomplete. ^If a
2964** memory allocation fails, then SQLITE_NOMEM is returned.
2965**
2966** ^These routines do not parse the SQL statements thus
2967** will not detect syntactically incorrect SQL.
2968**
2969** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2970** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2971** automatically by sqlite3_complete16(). If that initialization fails,
2972** then the return value from sqlite3_complete16() will be non-zero
2973** regardless of whether or not the input SQL is complete.)^
2974**
2975** The input to [sqlite3_complete()] must be a zero-terminated
2976** UTF-8 string.
2977**
2978** The input to [sqlite3_complete16()] must be a zero-terminated
2979** UTF-16 string in native byte order.
2980*/
2981SQLITE_API int sqlite3_complete(const char *sql);
2982SQLITE_API int sqlite3_complete16(const void *sql);
2983
2984/*
2985** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2986** KEYWORDS: {busy-handler callback} {busy handler}
2987** METHOD: sqlite3
2988**
2989** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
2990** that might be invoked with argument P whenever
2991** an attempt is made to access a database table associated with
2992** [database connection] D when another thread
2993** or process has the table locked.
2994** The sqlite3_busy_handler() interface is used to implement
2995** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
2996**
2997** ^If the busy callback is NULL, then [SQLITE_BUSY]
2998** is returned immediately upon encountering the lock. ^If the busy callback
2999** is not NULL, then the callback might be invoked with two arguments.
3000**
3001** ^The first argument to the busy handler is a copy of the void* pointer which
3002** is the third argument to sqlite3_busy_handler(). ^The second argument to
3003** the busy handler callback is the number of times that the busy handler has
3004** been invoked previously for the same locking event. ^If the
3005** busy callback returns 0, then no additional attempts are made to
3006** access the database and [SQLITE_BUSY] is returned
3007** to the application.
3008** ^If the callback returns non-zero, then another attempt
3009** is made to access the database and the cycle repeats.
3010**
3011** The presence of a busy handler does not guarantee that it will be invoked
3012** when there is lock contention. ^If SQLite determines that invoking the busy
3013** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
3014** to the application instead of invoking the
3015** busy handler.
3016** Consider a scenario where one process is holding a read lock that
3017** it is trying to promote to a reserved lock and
3018** a second process is holding a reserved lock that it is trying
3019** to promote to an exclusive lock. The first process cannot proceed
3020** because it is blocked by the second and the second process cannot
3021** proceed because it is blocked by the first. If both processes
3022** invoke the busy handlers, neither will make any progress. Therefore,
3023** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
3024** will induce the first process to release its read lock and allow
3025** the second process to proceed.
3026**
3027** ^The default busy callback is NULL.
3028**
3029** ^(There can only be a single busy handler defined for each
3030** [database connection]. Setting a new busy handler clears any
3031** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
3032** or evaluating [PRAGMA busy_timeout=N] will change the
3033** busy handler and thus clear any previously set busy handler.
3034**
3035** The busy callback should not take any actions which modify the
3036** database connection that invoked the busy handler. In other words,
3037** the busy handler is not reentrant. Any such actions
3038** result in undefined behavior.
3039**
3040** A busy handler must not close the database connection
3041** or [prepared statement] that invoked the busy handler.
3042*/
3043SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
3044
3045/*
3046** CAPI3REF: Set A Busy Timeout
3047** METHOD: sqlite3
3048**
3049** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
3050** for a specified amount of time when a table is locked. ^The handler
3051** will sleep multiple times until at least "ms" milliseconds of sleeping
3052** have accumulated. ^After at least "ms" milliseconds of sleeping,
3053** the handler returns 0 which causes [sqlite3_step()] to return
3054** [SQLITE_BUSY].
3055**
3056** ^Calling this routine with an argument less than or equal to zero
3057** turns off all busy handlers.
3058**
3059** ^(There can only be a single busy handler for a particular
3060** [database connection] at any given moment. If another busy handler
3061** was defined (using [sqlite3_busy_handler()]) prior to calling
3062** this routine, that other busy handler is cleared.)^
3063**
3064** See also: [PRAGMA busy_timeout]
3065*/
3066SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
3067
3068/*
3069** CAPI3REF: Convenience Routines For Running Queries
3070** METHOD: sqlite3
3071**
3072** This is a legacy interface that is preserved for backwards compatibility.
3073** Use of this interface is not recommended.
3074**
3075** Definition: A <b>result table</b> is memory data structure created by the
3076** [sqlite3_get_table()] interface. A result table records the
3077** complete query results from one or more queries.
3078**
3079** The table conceptually has a number of rows and columns. But
3080** these numbers are not part of the result table itself. These
3081** numbers are obtained separately. Let N be the number of rows
3082** and M be the number of columns.
3083**
3084** A result table is an array of pointers to zero-terminated UTF-8 strings.
3085** There are (N+1)*M elements in the array. The first M pointers point
3086** to zero-terminated strings that contain the names of the columns.
3087** The remaining entries all point to query results. NULL values result
3088** in NULL pointers. All other values are in their UTF-8 zero-terminated
3089** string representation as returned by [sqlite3_column_text()].
3090**
3091** A result table might consist of one or more memory allocations.
3092** It is not safe to pass a result table directly to [sqlite3_free()].
3093** A result table should be deallocated using [sqlite3_free_table()].
3094**
3095** ^(As an example of the result table format, suppose a query result
3096** is as follows:
3097**
3098** <blockquote><pre>
3099** Name | Age
3100** -----------------------
3101** Alice | 43
3102** Bob | 28
3103** Cindy | 21
3104** </pre></blockquote>
3105**
3106** There are two columns (M==2) and three rows (N==3). Thus the
3107** result table has 8 entries. Suppose the result table is stored
3108** in an array named azResult. Then azResult holds this content:
3109**
3110** <blockquote><pre>
3111** azResult&#91;0] = "Name";
3112** azResult&#91;1] = "Age";
3113** azResult&#91;2] = "Alice";
3114** azResult&#91;3] = "43";
3115** azResult&#91;4] = "Bob";
3116** azResult&#91;5] = "28";
3117** azResult&#91;6] = "Cindy";
3118** azResult&#91;7] = "21";
3119** </pre></blockquote>)^
3120**
3121** ^The sqlite3_get_table() function evaluates one or more
3122** semicolon-separated SQL statements in the zero-terminated UTF-8
3123** string of its 2nd parameter and returns a result table to the
3124** pointer given in its 3rd parameter.
3125**
3126** After the application has finished with the result from sqlite3_get_table(),
3127** it must pass the result table pointer to sqlite3_free_table() in order to
3128** release the memory that was malloced. Because of the way the
3129** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
3130** function must not try to call [sqlite3_free()] directly. Only
3131** [sqlite3_free_table()] is able to release the memory properly and safely.
3132**
3133** The sqlite3_get_table() interface is implemented as a wrapper around
3134** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
3135** to any internal data structures of SQLite. It uses only the public
3136** interface defined here. As a consequence, errors that occur in the
3137** wrapper layer outside of the internal [sqlite3_exec()] call are not
3138** reflected in subsequent calls to [sqlite3_errcode()] or
3139** [sqlite3_errmsg()].
3140*/
3141SQLITE_API int sqlite3_get_table(
3142 sqlite3 *db, /* An open database */
3143 const char *zSql, /* SQL to be evaluated */
3144 char ***pazResult, /* Results of the query */
3145 int *pnRow, /* Number of result rows written here */
3146 int *pnColumn, /* Number of result columns written here */
3147 char **pzErrmsg /* Error msg written here */
3148);
3149SQLITE_API void sqlite3_free_table(char **result);
3150
3151/*
3152** CAPI3REF: Formatted String Printing Functions
3153**
3154** These routines are work-alikes of the "printf()" family of functions
3155** from the standard C library.
3156** These routines understand most of the common formatting options from
3157** the standard library printf()
3158** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]).
3159** See the [built-in printf()] documentation for details.
3160**
3161** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
3162** results into memory obtained from [sqlite3_malloc64()].
3163** The strings returned by these two routines should be
3164** released by [sqlite3_free()]. ^Both routines return a
3165** NULL pointer if [sqlite3_malloc64()] is unable to allocate enough
3166** memory to hold the resulting string.
3167**
3168** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
3169** the standard C library. The result is written into the
3170** buffer supplied as the second parameter whose size is given by
3171** the first parameter. Note that the order of the
3172** first two parameters is reversed from snprintf().)^ This is an
3173** historical accident that cannot be fixed without breaking
3174** backwards compatibility. ^(Note also that sqlite3_snprintf()
3175** returns a pointer to its buffer instead of the number of
3176** characters actually written into the buffer.)^ We admit that
3177** the number of characters written would be a more useful return
3178** value but we cannot change the implementation of sqlite3_snprintf()
3179** now without breaking compatibility.
3180**
3181** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
3182** guarantees that the buffer is always zero-terminated. ^The first
3183** parameter "n" is the total size of the buffer, including space for
3184** the zero terminator. So the longest string that can be completely
3185** written will be n-1 characters.
3186**
3187** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
3188**
3189** See also: [built-in printf()], [printf() SQL function]
3190*/
3191SQLITE_API char *sqlite3_mprintf(const char*,...);
3192SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
3193SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
3194SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
3195
3196/*
3197** CAPI3REF: Memory Allocation Subsystem
3198**
3199** The SQLite core uses these three routines for all of its own
3200** internal memory allocation needs. "Core" in the previous sentence
3201** does not include operating-system specific [VFS] implementation. The
3202** Windows VFS uses native malloc() and free() for some operations.
3203**
3204** ^The sqlite3_malloc() routine returns a pointer to a block
3205** of memory at least N bytes in length, where N is the parameter.
3206** ^If sqlite3_malloc() is unable to obtain sufficient free
3207** memory, it returns a NULL pointer. ^If the parameter N to
3208** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
3209** a NULL pointer.
3210**
3211** ^The sqlite3_malloc64(N) routine works just like
3212** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
3213** of a signed 32-bit integer.
3214**
3215** ^Calling sqlite3_free() with a pointer previously returned
3216** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
3217** that it might be reused. ^The sqlite3_free() routine is
3218** a no-op if is called with a NULL pointer. Passing a NULL pointer
3219** to sqlite3_free() is harmless. After being freed, memory
3220** should neither be read nor written. Even reading previously freed
3221** memory might result in a segmentation fault or other severe error.
3222** Memory corruption, a segmentation fault, or other severe error
3223** might result if sqlite3_free() is called with a non-NULL pointer that
3224** was not obtained from sqlite3_malloc() or sqlite3_realloc().
3225**
3226** ^The sqlite3_realloc(X,N) interface attempts to resize a
3227** prior memory allocation X to be at least N bytes.
3228** ^If the X parameter to sqlite3_realloc(X,N)
3229** is a NULL pointer then its behavior is identical to calling
3230** sqlite3_malloc(N).
3231** ^If the N parameter to sqlite3_realloc(X,N) is zero or
3232** negative then the behavior is exactly the same as calling
3233** sqlite3_free(X).
3234** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
3235** of at least N bytes in size or NULL if insufficient memory is available.
3236** ^If M is the size of the prior allocation, then min(N,M) bytes
3237** of the prior allocation are copied into the beginning of buffer returned
3238** by sqlite3_realloc(X,N) and the prior allocation is freed.
3239** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
3240** prior allocation is not freed.
3241**
3242** ^The sqlite3_realloc64(X,N) interfaces works the same as
3243** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
3244** of a 32-bit signed integer.
3245**
3246** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
3247** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
3248** sqlite3_msize(X) returns the size of that memory allocation in bytes.
3249** ^The value returned by sqlite3_msize(X) might be larger than the number
3250** of bytes requested when X was allocated. ^If X is a NULL pointer then
3251** sqlite3_msize(X) returns zero. If X points to something that is not
3252** the beginning of memory allocation, or if it points to a formerly
3253** valid memory allocation that has now been freed, then the behavior
3254** of sqlite3_msize(X) is undefined and possibly harmful.
3255**
3256** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
3257** sqlite3_malloc64(), and sqlite3_realloc64()
3258** is always aligned to at least an 8 byte boundary, or to a
3259** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
3260** option is used.
3261**
3262** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
3263** must be either NULL or else pointers obtained from a prior
3264** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
3265** not yet been released.
3266**
3267** The application must not read or write any part of
3268** a block of memory after it has been released using
3269** [sqlite3_free()] or [sqlite3_realloc()].
3270*/
3271SQLITE_API void *sqlite3_malloc(int);
3272SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
3273SQLITE_API void *sqlite3_realloc(void*, int);
3274SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
3275SQLITE_API void sqlite3_free(void*);
3276SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
3277
3278/*
3279** CAPI3REF: Memory Allocator Statistics
3280**
3281** SQLite provides these two interfaces for reporting on the status
3282** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
3283** routines, which form the built-in memory allocation subsystem.
3284**
3285** ^The [sqlite3_memory_used()] routine returns the number of bytes
3286** of memory currently outstanding (malloced but not freed).
3287** ^The [sqlite3_memory_highwater()] routine returns the maximum
3288** value of [sqlite3_memory_used()] since the high-water mark
3289** was last reset. ^The values returned by [sqlite3_memory_used()] and
3290** [sqlite3_memory_highwater()] include any overhead
3291** added by SQLite in its implementation of [sqlite3_malloc()],
3292** but not overhead added by the any underlying system library
3293** routines that [sqlite3_malloc()] may call.
3294**
3295** ^The memory high-water mark is reset to the current value of
3296** [sqlite3_memory_used()] if and only if the parameter to
3297** [sqlite3_memory_highwater()] is true. ^The value returned
3298** by [sqlite3_memory_highwater(1)] is the high-water mark
3299** prior to the reset.
3300*/
3301SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
3302SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
3303
3304/*
3305** CAPI3REF: Pseudo-Random Number Generator
3306**
3307** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
3308** select random [ROWID | ROWIDs] when inserting new records into a table that
3309** already uses the largest possible [ROWID]. The PRNG is also used for
3310** the built-in random() and randomblob() SQL functions. This interface allows
3311** applications to access the same PRNG for other purposes.
3312**
3313** ^A call to this routine stores N bytes of randomness into buffer P.
3314** ^The P parameter can be a NULL pointer.
3315**
3316** ^If this routine has not been previously called or if the previous
3317** call had N less than one or a NULL pointer for P, then the PRNG is
3318** seeded using randomness obtained from the xRandomness method of
3319** the default [sqlite3_vfs] object.
3320** ^If the previous call to this routine had an N of 1 or more and a
3321** non-NULL P then the pseudo-randomness is generated
3322** internally and without recourse to the [sqlite3_vfs] xRandomness
3323** method.
3324*/
3325SQLITE_API void sqlite3_randomness(int N, void *P);
3326
3327/*
3328** CAPI3REF: Compile-Time Authorization Callbacks
3329** METHOD: sqlite3
3330** KEYWORDS: {authorizer callback}
3331**
3332** ^This routine registers an authorizer callback with a particular
3333** [database connection], supplied in the first argument.
3334** ^The authorizer callback is invoked as SQL statements are being compiled
3335** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
3336** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],
3337** and [sqlite3_prepare16_v3()]. ^At various
3338** points during the compilation process, as logic is being created
3339** to perform various actions, the authorizer callback is invoked to
3340** see if those actions are allowed. ^The authorizer callback should
3341** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
3342** specific action but allow the SQL statement to continue to be
3343** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
3344** rejected with an error. ^If the authorizer callback returns
3345** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
3346** then the [sqlite3_prepare_v2()] or equivalent call that triggered
3347** the authorizer will fail with an error message.
3348**
3349** When the callback returns [SQLITE_OK], that means the operation
3350** requested is ok. ^When the callback returns [SQLITE_DENY], the
3351** [sqlite3_prepare_v2()] or equivalent call that triggered the
3352** authorizer will fail with an error message explaining that
3353** access is denied.
3354**
3355** ^The first parameter to the authorizer callback is a copy of the third
3356** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
3357** to the callback is an integer [SQLITE_COPY | action code] that specifies
3358** the particular action to be authorized. ^The third through sixth parameters
3359** to the callback are either NULL pointers or zero-terminated strings
3360** that contain additional details about the action to be authorized.
3361** Applications must always be prepared to encounter a NULL pointer in any
3362** of the third through the sixth parameters of the authorization callback.
3363**
3364** ^If the action code is [SQLITE_READ]
3365** and the callback returns [SQLITE_IGNORE] then the
3366** [prepared statement] statement is constructed to substitute
3367** a NULL value in place of the table column that would have
3368** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
3369** return can be used to deny an untrusted user access to individual
3370** columns of a table.
3371** ^When a table is referenced by a [SELECT] but no column values are
3372** extracted from that table (for example in a query like
3373** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback
3374** is invoked once for that table with a column name that is an empty string.
3375** ^If the action code is [SQLITE_DELETE] and the callback returns
3376** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
3377** [truncate optimization] is disabled and all rows are deleted individually.
3378**
3379** An authorizer is used when [sqlite3_prepare | preparing]
3380** SQL statements from an untrusted source, to ensure that the SQL statements
3381** do not try to access data they are not allowed to see, or that they do not
3382** try to execute malicious statements that damage the database. For
3383** example, an application may allow a user to enter arbitrary
3384** SQL queries for evaluation by a database. But the application does
3385** not want the user to be able to make arbitrary changes to the
3386** database. An authorizer could then be put in place while the
3387** user-entered SQL is being [sqlite3_prepare | prepared] that
3388** disallows everything except [SELECT] statements.
3389**
3390** Applications that need to process SQL from untrusted sources
3391** might also consider lowering resource limits using [sqlite3_limit()]
3392** and limiting database size using the [max_page_count] [PRAGMA]
3393** in addition to using an authorizer.
3394**
3395** ^(Only a single authorizer can be in place on a database connection
3396** at a time. Each call to sqlite3_set_authorizer overrides the
3397** previous call.)^ ^Disable the authorizer by installing a NULL callback.
3398** The authorizer is disabled by default.
3399**
3400** The authorizer callback must not do anything that will modify
3401** the database connection that invoked the authorizer callback.
3402** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3403** database connections for the meaning of "modify" in this paragraph.
3404**
3405** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
3406** statement might be re-prepared during [sqlite3_step()] due to a
3407** schema change. Hence, the application should ensure that the
3408** correct authorizer callback remains in place during the [sqlite3_step()].
3409**
3410** ^Note that the authorizer callback is invoked only during
3411** [sqlite3_prepare()] or its variants. Authorization is not
3412** performed during statement evaluation in [sqlite3_step()], unless
3413** as stated in the previous paragraph, sqlite3_step() invokes
3414** sqlite3_prepare_v2() to reprepare a statement after a schema change.
3415*/
3416SQLITE_API int sqlite3_set_authorizer(
3417 sqlite3*,
3418 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
3419 void *pUserData
3420);
3421
3422/*
3423** CAPI3REF: Authorizer Return Codes
3424**
3425** The [sqlite3_set_authorizer | authorizer callback function] must
3426** return either [SQLITE_OK] or one of these two constants in order
3427** to signal SQLite whether or not the action is permitted. See the
3428** [sqlite3_set_authorizer | authorizer documentation] for additional
3429** information.
3430**
3431** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
3432** returned from the [sqlite3_vtab_on_conflict()] interface.
3433*/
3434#define SQLITE_DENY 1 /* Abort the SQL statement with an error */
3435#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
3436
3437/*
3438** CAPI3REF: Authorizer Action Codes
3439**
3440** The [sqlite3_set_authorizer()] interface registers a callback function
3441** that is invoked to authorize certain SQL statement actions. The
3442** second parameter to the callback is an integer code that specifies
3443** what action is being authorized. These are the integer action codes that
3444** the authorizer callback may be passed.
3445**
3446** These action code values signify what kind of operation is to be
3447** authorized. The 3rd and 4th parameters to the authorization
3448** callback function will be parameters or NULL depending on which of these
3449** codes is used as the second parameter. ^(The 5th parameter to the
3450** authorizer callback is the name of the database ("main", "temp",
3451** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
3452** is the name of the inner-most trigger or view that is responsible for
3453** the access attempt or NULL if this access attempt is directly from
3454** top-level SQL code.
3455*/
3456/******************************************* 3rd ************ 4th ***********/
3457#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
3458#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
3459#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
3460#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
3461#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
3462#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
3463#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
3464#define SQLITE_CREATE_VIEW 8 /* View Name NULL */
3465#define SQLITE_DELETE 9 /* Table Name NULL */
3466#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
3467#define SQLITE_DROP_TABLE 11 /* Table Name NULL */
3468#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
3469#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
3470#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
3471#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
3472#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
3473#define SQLITE_DROP_VIEW 17 /* View Name NULL */
3474#define SQLITE_INSERT 18 /* Table Name NULL */
3475#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
3476#define SQLITE_READ 20 /* Table Name Column Name */
3477#define SQLITE_SELECT 21 /* NULL NULL */
3478#define SQLITE_TRANSACTION 22 /* Operation NULL */
3479#define SQLITE_UPDATE 23 /* Table Name Column Name */
3480#define SQLITE_ATTACH 24 /* Filename NULL */
3481#define SQLITE_DETACH 25 /* Database Name NULL */
3482#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
3483#define SQLITE_REINDEX 27 /* Index Name NULL */
3484#define SQLITE_ANALYZE 28 /* Table Name NULL */
3485#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
3486#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
3487#define SQLITE_FUNCTION 31 /* NULL Function Name */
3488#define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
3489#define SQLITE_COPY 0 /* No longer used */
3490#define SQLITE_RECURSIVE 33 /* NULL NULL */
3491
3492/*
3493** CAPI3REF: Tracing And Profiling Functions
3494** METHOD: sqlite3
3495**
3496** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
3497** instead of the routines described here.
3498**
3499** These routines register callback functions that can be used for
3500** tracing and profiling the execution of SQL statements.
3501**
3502** ^The callback function registered by sqlite3_trace() is invoked at
3503** various times when an SQL statement is being run by [sqlite3_step()].
3504** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
3505** SQL statement text as the statement first begins executing.
3506** ^(Additional sqlite3_trace() callbacks might occur
3507** as each triggered subprogram is entered. The callbacks for triggers
3508** contain a UTF-8 SQL comment that identifies the trigger.)^
3509**
3510** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
3511** the length of [bound parameter] expansion in the output of sqlite3_trace().
3512**
3513** ^The callback function registered by sqlite3_profile() is invoked
3514** as each SQL statement finishes. ^The profile callback contains
3515** the original statement text and an estimate of wall-clock time
3516** of how long that statement took to run. ^The profile callback
3517** time is in units of nanoseconds, however the current implementation
3518** is only capable of millisecond resolution so the six least significant
3519** digits in the time are meaningless. Future versions of SQLite
3520** might provide greater resolution on the profiler callback. Invoking
3521** either [sqlite3_trace()] or [sqlite3_trace_v2()] will cancel the
3522** profile callback.
3523*/
3524SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
3525 void(*xTrace)(void*,const char*), void*);
3526SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
3527 void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
3528
3529/*
3530** CAPI3REF: SQL Trace Event Codes
3531** KEYWORDS: SQLITE_TRACE
3532**
3533** These constants identify classes of events that can be monitored
3534** using the [sqlite3_trace_v2()] tracing logic. The M argument
3535** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of
3536** the following constants. ^The first argument to the trace callback
3537** is one of the following constants.
3538**
3539** New tracing constants may be added in future releases.
3540**
3541** ^A trace callback has four arguments: xCallback(T,C,P,X).
3542** ^The T argument is one of the integer type codes above.
3543** ^The C argument is a copy of the context pointer passed in as the
3544** fourth argument to [sqlite3_trace_v2()].
3545** The P and X arguments are pointers whose meanings depend on T.
3546**
3547** <dl>
3548** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
3549** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
3550** first begins running and possibly at other times during the
3551** execution of the prepared statement, such as at the start of each
3552** trigger subprogram. ^The P argument is a pointer to the
3553** [prepared statement]. ^The X argument is a pointer to a string which
3554** is the unexpanded SQL text of the prepared statement or an SQL comment
3555** that indicates the invocation of a trigger. ^The callback can compute
3556** the same text that would have been returned by the legacy [sqlite3_trace()]
3557** interface by using the X argument when X begins with "--" and invoking
3558** [sqlite3_expanded_sql(P)] otherwise.
3559**
3560** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
3561** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
3562** information as is provided by the [sqlite3_profile()] callback.
3563** ^The P argument is a pointer to the [prepared statement] and the
3564** X argument points to a 64-bit integer which is the estimated of
3565** the number of nanosecond that the prepared statement took to run.
3566** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
3567**
3568** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
3569** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
3570** statement generates a single row of result.
3571** ^The P argument is a pointer to the [prepared statement] and the
3572** X argument is unused.
3573**
3574** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
3575** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
3576** connection closes.
3577** ^The P argument is a pointer to the [database connection] object
3578** and the X argument is unused.
3579** </dl>
3580*/
3581#define SQLITE_TRACE_STMT 0x01
3582#define SQLITE_TRACE_PROFILE 0x02
3583#define SQLITE_TRACE_ROW 0x04
3584#define SQLITE_TRACE_CLOSE 0x08
3585
3586/*
3587** CAPI3REF: SQL Trace Hook
3588** METHOD: sqlite3
3589**
3590** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
3591** function X against [database connection] D, using property mask M
3592** and context pointer P. ^If the X callback is
3593** NULL or if the M mask is zero, then tracing is disabled. The
3594** M argument should be the bitwise OR-ed combination of
3595** zero or more [SQLITE_TRACE] constants.
3596**
3597** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
3598** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
3599**
3600** ^The X callback is invoked whenever any of the events identified by
3601** mask M occur. ^The integer return value from the callback is currently
3602** ignored, though this may change in future releases. Callback
3603** implementations should return zero to ensure future compatibility.
3604**
3605** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
3606** ^The T argument is one of the [SQLITE_TRACE]
3607** constants to indicate why the callback was invoked.
3608** ^The C argument is a copy of the context pointer.
3609** The P and X arguments are pointers whose meanings depend on T.
3610**
3611** The sqlite3_trace_v2() interface is intended to replace the legacy
3612** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
3613** are deprecated.
3614*/
3615SQLITE_API int sqlite3_trace_v2(
3616 sqlite3*,
3617 unsigned uMask,
3618 int(*xCallback)(unsigned,void*,void*,void*),
3619 void *pCtx
3620);
3621
3622/*
3623** CAPI3REF: Query Progress Callbacks
3624** METHOD: sqlite3
3625**
3626** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
3627** function X to be invoked periodically during long running calls to
3628** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
3629** database connection D. An example use for this
3630** interface is to keep a GUI updated during a large query.
3631**
3632** ^The parameter P is passed through as the only parameter to the
3633** callback function X. ^The parameter N is the approximate number of
3634** [virtual machine instructions] that are evaluated between successive
3635** invocations of the callback X. ^If N is less than one then the progress
3636** handler is disabled.
3637**
3638** ^Only a single progress handler may be defined at one time per
3639** [database connection]; setting a new progress handler cancels the
3640** old one. ^Setting parameter X to NULL disables the progress handler.
3641** ^The progress handler is also disabled by setting N to a value less
3642** than 1.
3643**
3644** ^If the progress callback returns non-zero, the operation is
3645** interrupted. This feature can be used to implement a
3646** "Cancel" button on a GUI progress dialog box.
3647**
3648** The progress handler callback must not do anything that will modify
3649** the database connection that invoked the progress handler.
3650** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3651** database connections for the meaning of "modify" in this paragraph.
3652**
3653*/
3654SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
3655
3656/*
3657** CAPI3REF: Opening A New Database Connection
3658** CONSTRUCTOR: sqlite3
3659**
3660** ^These routines open an SQLite database file as specified by the
3661** filename argument. ^The filename argument is interpreted as UTF-8 for
3662** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3663** order for sqlite3_open16(). ^(A [database connection] handle is usually
3664** returned in *ppDb, even if an error occurs. The only exception is that
3665** if SQLite is unable to allocate memory to hold the [sqlite3] object,
3666** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
3667** object.)^ ^(If the database is opened (and/or created) successfully, then
3668** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
3669** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3670** an English language description of the error following a failure of any
3671** of the sqlite3_open() routines.
3672**
3673** ^The default encoding will be UTF-8 for databases created using
3674** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
3675** created using sqlite3_open16() will be UTF-16 in the native byte order.
3676**
3677** Whether or not an error occurs when it is opened, resources
3678** associated with the [database connection] handle should be released by
3679** passing it to [sqlite3_close()] when it is no longer required.
3680**
3681** The sqlite3_open_v2() interface works like sqlite3_open()
3682** except that it accepts two additional parameters for additional control
3683** over the new database connection. ^(The flags parameter to
3684** sqlite3_open_v2() must include, at a minimum, one of the following
3685** three flag combinations:)^
3686**
3687** <dl>
3688** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
3689** <dd>The database is opened in read-only mode. If the database does not
3690** already exist, an error is returned.</dd>)^
3691**
3692** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
3693** <dd>The database is opened for reading and writing if possible, or reading
3694** only if the file is write protected by the operating system. In either
3695** case the database must already exist, otherwise an error is returned.</dd>)^
3696**
3697** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3698** <dd>The database is opened for reading and writing, and is created if
3699** it does not already exist. This is the behavior that is always used for
3700** sqlite3_open() and sqlite3_open16().</dd>)^
3701** </dl>
3702**
3703** In addition to the required flags, the following optional flags are
3704** also supported:
3705**
3706** <dl>
3707** ^(<dt>[SQLITE_OPEN_URI]</dt>
3708** <dd>The filename can be interpreted as a URI if this flag is set.</dd>)^
3709**
3710** ^(<dt>[SQLITE_OPEN_MEMORY]</dt>
3711** <dd>The database will be opened as an in-memory database. The database
3712** is named by the "filename" argument for the purposes of cache-sharing,
3713** if shared cache mode is enabled, but the "filename" is otherwise ignored.
3714** </dd>)^
3715**
3716** ^(<dt>[SQLITE_OPEN_NOMUTEX]</dt>
3717** <dd>The new database connection will use the "multi-thread"
3718** [threading mode].)^ This means that separate threads are allowed
3719** to use SQLite at the same time, as long as each thread is using
3720** a different [database connection].
3721**
3722** ^(<dt>[SQLITE_OPEN_FULLMUTEX]</dt>
3723** <dd>The new database connection will use the "serialized"
3724** [threading mode].)^ This means the multiple threads can safely
3725** attempt to use the same database connection at the same time.
3726** (Mutexes will block any actual concurrency, but in this mode
3727** there is no harm in trying.)
3728**
3729** ^(<dt>[SQLITE_OPEN_SHAREDCACHE]</dt>
3730** <dd>The database is opened [shared cache] enabled, overriding
3731** the default shared cache setting provided by
3732** [sqlite3_enable_shared_cache()].)^
3733**
3734** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt>
3735** <dd>The database is opened [shared cache] disabled, overriding
3736** the default shared cache setting provided by
3737** [sqlite3_enable_shared_cache()].)^
3738**
3739** [[OPEN_EXRESCODE]] ^(<dt>[SQLITE_OPEN_EXRESCODE]</dt>
3740** <dd>The database connection comes up in "extended result code mode".
3741** In other words, the database behaves has if
3742** [sqlite3_extended_result_codes(db,1)] where called on the database
3743** connection as soon as the connection is created. In addition to setting
3744** the extended result code mode, this flag also causes [sqlite3_open_v2()]
3745** to return an extended result code.</dd>
3746**
3747** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt>
3748** <dd>The database filename is not allowed to be a symbolic link</dd>
3749** </dl>)^
3750**
3751** If the 3rd parameter to sqlite3_open_v2() is not one of the
3752** required combinations shown above optionally combined with other
3753** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
3754** then the behavior is undefined. Historic versions of SQLite
3755** have silently ignored surplus bits in the flags parameter to
3756** sqlite3_open_v2(), however that behavior might not be carried through
3757** into future versions of SQLite and so applications should not rely
3758** upon it. Note in particular that the SQLITE_OPEN_EXCLUSIVE flag is a no-op
3759** for sqlite3_open_v2(). The SQLITE_OPEN_EXCLUSIVE does *not* cause
3760** the open to fail if the database already exists. The SQLITE_OPEN_EXCLUSIVE
3761** flag is intended for use by the [sqlite3_vfs|VFS interface] only, and not
3762** by sqlite3_open_v2().
3763**
3764** ^The fourth parameter to sqlite3_open_v2() is the name of the
3765** [sqlite3_vfs] object that defines the operating system interface that
3766** the new database connection should use. ^If the fourth parameter is
3767** a NULL pointer then the default [sqlite3_vfs] object is used.
3768**
3769** ^If the filename is ":memory:", then a private, temporary in-memory database
3770** is created for the connection. ^This in-memory database will vanish when
3771** the database connection is closed. Future versions of SQLite might
3772** make use of additional special filenames that begin with the ":" character.
3773** It is recommended that when a database filename actually does begin with
3774** a ":" character you should prefix the filename with a pathname such as
3775** "./" to avoid ambiguity.
3776**
3777** ^If the filename is an empty string, then a private, temporary
3778** on-disk database will be created. ^This private database will be
3779** automatically deleted as soon as the database connection is closed.
3780**
3781** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3782**
3783** ^If [URI filename] interpretation is enabled, and the filename argument
3784** begins with "file:", then the filename is interpreted as a URI. ^URI
3785** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3786** set in the third argument to sqlite3_open_v2(), or if it has
3787** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3788** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3789** URI filename interpretation is turned off
3790** by default, but future releases of SQLite might enable URI filename
3791** interpretation by default. See "[URI filenames]" for additional
3792** information.
3793**
3794** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3795** authority, then it must be either an empty string or the string
3796** "localhost". ^If the authority is not an empty string or "localhost", an
3797** error is returned to the caller. ^The fragment component of a URI, if
3798** present, is ignored.
3799**
3800** ^SQLite uses the path component of the URI as the name of the disk file
3801** which contains the database. ^If the path begins with a '/' character,
3802** then it is interpreted as an absolute path. ^If the path does not begin
3803** with a '/' (meaning that the authority section is omitted from the URI)
3804** then the path is interpreted as a relative path.
3805** ^(On windows, the first component of an absolute path
3806** is a drive specification (e.g. "C:").)^
3807**
3808** [[core URI query parameters]]
3809** The query component of a URI may contain parameters that are interpreted
3810** either by SQLite itself, or by a [VFS | custom VFS implementation].
3811** SQLite and its built-in [VFSes] interpret the
3812** following query parameters:
3813**
3814** <ul>
3815** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3816** a VFS object that provides the operating system interface that should
3817** be used to access the database file on disk. ^If this option is set to
3818** an empty string the default VFS object is used. ^Specifying an unknown
3819** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3820** present, then the VFS specified by the option takes precedence over
3821** the value passed as the fourth parameter to sqlite3_open_v2().
3822**
3823** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
3824** "rwc", or "memory". Attempting to set it to any other value is
3825** an error)^.
3826** ^If "ro" is specified, then the database is opened for read-only
3827** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
3828** third argument to sqlite3_open_v2(). ^If the mode option is set to
3829** "rw", then the database is opened for read-write (but not create)
3830** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
3831** been set. ^Value "rwc" is equivalent to setting both
3832** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
3833** set to "memory" then a pure [in-memory database] that never reads
3834** or writes from disk is used. ^It is an error to specify a value for
3835** the mode parameter that is less restrictive than that specified by
3836** the flags passed in the third parameter to sqlite3_open_v2().
3837**
3838** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3839** "private". ^Setting it to "shared" is equivalent to setting the
3840** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3841** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
3842** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3843** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3844** a URI filename, its value overrides any behavior requested by setting
3845** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3846**
3847** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
3848** [powersafe overwrite] property does or does not apply to the
3849** storage media on which the database file resides.
3850**
3851** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
3852** which if set disables file locking in rollback journal modes. This
3853** is useful for accessing a database on a filesystem that does not
3854** support locking. Caution: Database corruption might result if two
3855** or more processes write to the same database and any one of those
3856** processes uses nolock=1.
3857**
3858** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
3859** parameter that indicates that the database file is stored on
3860** read-only media. ^When immutable is set, SQLite assumes that the
3861** database file cannot be changed, even by a process with higher
3862** privilege, and so the database is opened read-only and all locking
3863** and change detection is disabled. Caution: Setting the immutable
3864** property on a database file that does in fact change can result
3865** in incorrect query results and/or [SQLITE_CORRUPT] errors.
3866** See also: [SQLITE_IOCAP_IMMUTABLE].
3867**
3868** </ul>
3869**
3870** ^Specifying an unknown parameter in the query component of a URI is not an
3871** error. Future versions of SQLite might understand additional query
3872** parameters. See "[query parameters with special meaning to SQLite]" for
3873** additional information.
3874**
3875** [[URI filename examples]] <h3>URI filename examples</h3>
3876**
3877** <table border="1" align=center cellpadding=5>
3878** <tr><th> URI filenames <th> Results
3879** <tr><td> file:data.db <td>
3880** Open the file "data.db" in the current directory.
3881** <tr><td> file:/home/fred/data.db<br>
3882** file:///home/fred/data.db <br>
3883** file://localhost/home/fred/data.db <br> <td>
3884** Open the database file "/home/fred/data.db".
3885** <tr><td> file://darkstar/home/fred/data.db <td>
3886** An error. "darkstar" is not a recognized authority.
3887** <tr><td style="white-space:nowrap">
3888** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3889** <td> Windows only: Open the file "data.db" on fred's desktop on drive
3890** C:. Note that the %20 escaping in this example is not strictly
3891** necessary - space characters can be used literally
3892** in URI filenames.
3893** <tr><td> file:data.db?mode=ro&cache=private <td>
3894** Open file "data.db" in the current directory for read-only access.
3895** Regardless of whether or not shared-cache mode is enabled by
3896** default, use a private cache.
3897** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
3898** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
3899** that uses dot-files in place of posix advisory locking.
3900** <tr><td> file:data.db?mode=readonly <td>
3901** An error. "readonly" is not a valid option for the "mode" parameter.
3902** Use "ro" instead: "file:data.db?mode=ro".
3903** </table>
3904**
3905** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3906** query components of a URI. A hexadecimal escape sequence consists of a
3907** percent sign - "%" - followed by exactly two hexadecimal digits
3908** specifying an octet value. ^Before the path or query components of a
3909** URI filename are interpreted, they are encoded using UTF-8 and all
3910** hexadecimal escape sequences replaced by a single byte containing the
3911** corresponding octet. If this process generates an invalid UTF-8 encoding,
3912** the results are undefined.
3913**
3914** <b>Note to Windows users:</b> The encoding used for the filename argument
3915** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3916** codepage is currently defined. Filenames containing international
3917** characters must be converted to UTF-8 prior to passing them into
3918** sqlite3_open() or sqlite3_open_v2().
3919**
3920** <b>Note to Windows Runtime users:</b> The temporary directory must be set
3921** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
3922** features that require the use of temporary files may fail.
3923**
3924** See also: [sqlite3_temp_directory]
3925*/
3926SQLITE_API int sqlite3_open(
3927 const char *filename, /* Database filename (UTF-8) */
3928 sqlite3 **ppDb /* OUT: SQLite db handle */
3929);
3930SQLITE_API int sqlite3_open16(
3931 const void *filename, /* Database filename (UTF-16) */
3932 sqlite3 **ppDb /* OUT: SQLite db handle */
3933);
3934SQLITE_API int sqlite3_open_v2(
3935 const char *filename, /* Database filename (UTF-8) */
3936 sqlite3 **ppDb, /* OUT: SQLite db handle */
3937 int flags, /* Flags */
3938 const char *zVfs /* Name of VFS module to use */
3939);
3940
3941/*
3942** CAPI3REF: Obtain Values For URI Parameters
3943**
3944** These are utility routines, useful to [VFS|custom VFS implementations],
3945** that check if a database file was a URI that contained a specific query
3946** parameter, and if so obtains the value of that query parameter.
3947**
3948** The first parameter to these interfaces (hereafter referred to
3949** as F) must be one of:
3950** <ul>
3951** <li> A database filename pointer created by the SQLite core and
3952** passed into the xOpen() method of a VFS implemention, or
3953** <li> A filename obtained from [sqlite3_db_filename()], or
3954** <li> A new filename constructed using [sqlite3_create_filename()].
3955** </ul>
3956** If the F parameter is not one of the above, then the behavior is
3957** undefined and probably undesirable. Older versions of SQLite were
3958** more tolerant of invalid F parameters than newer versions.
3959**
3960** If F is a suitable filename (as described in the previous paragraph)
3961** and if P is the name of the query parameter, then
3962** sqlite3_uri_parameter(F,P) returns the value of the P
3963** parameter if it exists or a NULL pointer if P does not appear as a
3964** query parameter on F. If P is a query parameter of F and it
3965** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3966** a pointer to an empty string.
3967**
3968** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3969** parameter and returns true (1) or false (0) according to the value
3970** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3971** value of query parameter P is one of "yes", "true", or "on" in any
3972** case or if the value begins with a non-zero number. The
3973** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3974** query parameter P is one of "no", "false", or "off" in any case or
3975** if the value begins with a numeric zero. If P is not a query
3976** parameter on F or if the value of P does not match any of the
3977** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3978**
3979** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3980** 64-bit signed integer and returns that integer, or D if P does not
3981** exist. If the value of P is something other than an integer, then
3982** zero is returned.
3983**
3984** The sqlite3_uri_key(F,N) returns a pointer to the name (not
3985** the value) of the N-th query parameter for filename F, or a NULL
3986** pointer if N is less than zero or greater than the number of query
3987** parameters minus 1. The N value is zero-based so N should be 0 to obtain
3988** the name of the first query parameter, 1 for the second parameter, and
3989** so forth.
3990**
3991** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3992** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
3993** is not a database file pathname pointer that the SQLite core passed
3994** into the xOpen VFS method, then the behavior of this routine is undefined
3995** and probably undesirable.
3996**
3997** Beginning with SQLite [version 3.31.0] ([dateof:3.31.0]) the input F
3998** parameter can also be the name of a rollback journal file or WAL file
3999** in addition to the main database file. Prior to version 3.31.0, these
4000** routines would only work if F was the name of the main database file.
4001** When the F parameter is the name of the rollback journal or WAL file,
4002** it has access to all the same query parameters as were found on the
4003** main database file.
4004**
4005** See the [URI filename] documentation for additional information.
4006*/
4007SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
4008SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
4009SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
4010SQLITE_API const char *sqlite3_uri_key(const char *zFilename, int N);
4011
4012/*
4013** CAPI3REF: Translate filenames
4014**
4015** These routines are available to [VFS|custom VFS implementations] for
4016** translating filenames between the main database file, the journal file,
4017** and the WAL file.
4018**
4019** If F is the name of an sqlite database file, journal file, or WAL file
4020** passed by the SQLite core into the VFS, then sqlite3_filename_database(F)
4021** returns the name of the corresponding database file.
4022**
4023** If F is the name of an sqlite database file, journal file, or WAL file
4024** passed by the SQLite core into the VFS, or if F is a database filename
4025** obtained from [sqlite3_db_filename()], then sqlite3_filename_journal(F)
4026** returns the name of the corresponding rollback journal file.
4027**
4028** If F is the name of an sqlite database file, journal file, or WAL file
4029** that was passed by the SQLite core into the VFS, or if F is a database
4030** filename obtained from [sqlite3_db_filename()], then
4031** sqlite3_filename_wal(F) returns the name of the corresponding
4032** WAL file.
4033**
4034** In all of the above, if F is not the name of a database, journal or WAL
4035** filename passed into the VFS from the SQLite core and F is not the
4036** return value from [sqlite3_db_filename()], then the result is
4037** undefined and is likely a memory access violation.
4038*/
4039SQLITE_API const char *sqlite3_filename_database(const char*);
4040SQLITE_API const char *sqlite3_filename_journal(const char*);
4041SQLITE_API const char *sqlite3_filename_wal(const char*);
4042
4043/*
4044** CAPI3REF: Database File Corresponding To A Journal
4045**
4046** ^If X is the name of a rollback or WAL-mode journal file that is
4047** passed into the xOpen method of [sqlite3_vfs], then
4048** sqlite3_database_file_object(X) returns a pointer to the [sqlite3_file]
4049** object that represents the main database file.
4050**
4051** This routine is intended for use in custom [VFS] implementations
4052** only. It is not a general-purpose interface.
4053** The argument sqlite3_file_object(X) must be a filename pointer that
4054** has been passed into [sqlite3_vfs].xOpen method where the
4055** flags parameter to xOpen contains one of the bits
4056** [SQLITE_OPEN_MAIN_JOURNAL] or [SQLITE_OPEN_WAL]. Any other use
4057** of this routine results in undefined and probably undesirable
4058** behavior.
4059*/
4060SQLITE_API sqlite3_file *sqlite3_database_file_object(const char*);
4061
4062/*
4063** CAPI3REF: Create and Destroy VFS Filenames
4064**
4065** These interfces are provided for use by [VFS shim] implementations and
4066** are not useful outside of that context.
4067**
4068** The sqlite3_create_filename(D,J,W,N,P) allocates memory to hold a version of
4069** database filename D with corresponding journal file J and WAL file W and
4070** with N URI parameters key/values pairs in the array P. The result from
4071** sqlite3_create_filename(D,J,W,N,P) is a pointer to a database filename that
4072** is safe to pass to routines like:
4073** <ul>
4074** <li> [sqlite3_uri_parameter()],
4075** <li> [sqlite3_uri_boolean()],
4076** <li> [sqlite3_uri_int64()],
4077** <li> [sqlite3_uri_key()],
4078** <li> [sqlite3_filename_database()],
4079** <li> [sqlite3_filename_journal()], or
4080** <li> [sqlite3_filename_wal()].
4081** </ul>
4082** If a memory allocation error occurs, sqlite3_create_filename() might
4083** return a NULL pointer. The memory obtained from sqlite3_create_filename(X)
4084** must be released by a corresponding call to sqlite3_free_filename(Y).
4085**
4086** The P parameter in sqlite3_create_filename(D,J,W,N,P) should be an array
4087** of 2*N pointers to strings. Each pair of pointers in this array corresponds
4088** to a key and value for a query parameter. The P parameter may be a NULL
4089** pointer if N is zero. None of the 2*N pointers in the P array may be
4090** NULL pointers and key pointers should not be empty strings.
4091** None of the D, J, or W parameters to sqlite3_create_filename(D,J,W,N,P) may
4092** be NULL pointers, though they can be empty strings.
4093**
4094** The sqlite3_free_filename(Y) routine releases a memory allocation
4095** previously obtained from sqlite3_create_filename(). Invoking
4096** sqlite3_free_filename(Y) where Y is a NULL pointer is a harmless no-op.
4097**
4098** If the Y parameter to sqlite3_free_filename(Y) is anything other
4099** than a NULL pointer or a pointer previously acquired from
4100** sqlite3_create_filename(), then bad things such as heap
4101** corruption or segfaults may occur. The value Y should not be
4102** used again after sqlite3_free_filename(Y) has been called. This means
4103** that if the [sqlite3_vfs.xOpen()] method of a VFS has been called using Y,
4104** then the corresponding [sqlite3_module.xClose() method should also be
4105** invoked prior to calling sqlite3_free_filename(Y).
4106*/
4107SQLITE_API char *sqlite3_create_filename(
4108 const char *zDatabase,
4109 const char *zJournal,
4110 const char *zWal,
4111 int nParam,
4112 const char **azParam
4113);
4114SQLITE_API void sqlite3_free_filename(char*);
4115
4116/*
4117** CAPI3REF: Error Codes And Messages
4118** METHOD: sqlite3
4119**
4120** ^If the most recent sqlite3_* API call associated with
4121** [database connection] D failed, then the sqlite3_errcode(D) interface
4122** returns the numeric [result code] or [extended result code] for that
4123** API call.
4124** ^The sqlite3_extended_errcode()
4125** interface is the same except that it always returns the
4126** [extended result code] even when extended result codes are
4127** disabled.
4128**
4129** The values returned by sqlite3_errcode() and/or
4130** sqlite3_extended_errcode() might change with each API call.
4131** Except, there are some interfaces that are guaranteed to never
4132** change the value of the error code. The error-code preserving
4133** interfaces are:
4134**
4135** <ul>
4136** <li> sqlite3_errcode()
4137** <li> sqlite3_extended_errcode()
4138** <li> sqlite3_errmsg()
4139** <li> sqlite3_errmsg16()
4140** </ul>
4141**
4142** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
4143** text that describes the error, as either UTF-8 or UTF-16 respectively.
4144** ^(Memory to hold the error message string is managed internally.
4145** The application does not need to worry about freeing the result.
4146** However, the error string might be overwritten or deallocated by
4147** subsequent calls to other SQLite interface functions.)^
4148**
4149** ^The sqlite3_errstr() interface returns the English-language text
4150** that describes the [result code], as UTF-8.
4151** ^(Memory to hold the error message string is managed internally
4152** and must not be freed by the application)^.
4153**
4154** When the serialized [threading mode] is in use, it might be the
4155** case that a second error occurs on a separate thread in between
4156** the time of the first error and the call to these interfaces.
4157** When that happens, the second error will be reported since these
4158** interfaces always report the most recent result. To avoid
4159** this, each thread can obtain exclusive use of the [database connection] D
4160** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
4161** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
4162** all calls to the interfaces listed here are completed.
4163**
4164** If an interface fails with SQLITE_MISUSE, that means the interface
4165** was invoked incorrectly by the application. In that case, the
4166** error code and message may or may not be set.
4167*/
4168SQLITE_API int sqlite3_errcode(sqlite3 *db);
4169SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
4170SQLITE_API const char *sqlite3_errmsg(sqlite3*);
4171SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
4172SQLITE_API const char *sqlite3_errstr(int);
4173
4174/*
4175** CAPI3REF: Prepared Statement Object
4176** KEYWORDS: {prepared statement} {prepared statements}
4177**
4178** An instance of this object represents a single SQL statement that
4179** has been compiled into binary form and is ready to be evaluated.
4180**
4181** Think of each SQL statement as a separate computer program. The
4182** original SQL text is source code. A prepared statement object
4183** is the compiled object code. All SQL must be converted into a
4184** prepared statement before it can be run.
4185**
4186** The life-cycle of a prepared statement object usually goes like this:
4187**
4188** <ol>
4189** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
4190** <li> Bind values to [parameters] using the sqlite3_bind_*()
4191** interfaces.
4192** <li> Run the SQL by calling [sqlite3_step()] one or more times.
4193** <li> Reset the prepared statement using [sqlite3_reset()] then go back
4194** to step 2. Do this zero or more times.
4195** <li> Destroy the object using [sqlite3_finalize()].
4196** </ol>
4197*/
4198typedef struct sqlite3_stmt sqlite3_stmt;
4199
4200/*
4201** CAPI3REF: Run-time Limits
4202** METHOD: sqlite3
4203**
4204** ^(This interface allows the size of various constructs to be limited
4205** on a connection by connection basis. The first parameter is the
4206** [database connection] whose limit is to be set or queried. The
4207** second parameter is one of the [limit categories] that define a
4208** class of constructs to be size limited. The third parameter is the
4209** new limit for that construct.)^
4210**
4211** ^If the new limit is a negative number, the limit is unchanged.
4212** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
4213** [limits | hard upper bound]
4214** set at compile-time by a C preprocessor macro called
4215** [limits | SQLITE_MAX_<i>NAME</i>].
4216** (The "_LIMIT_" in the name is changed to "_MAX_".))^
4217** ^Attempts to increase a limit above its hard upper bound are
4218** silently truncated to the hard upper bound.
4219**
4220** ^Regardless of whether or not the limit was changed, the
4221** [sqlite3_limit()] interface returns the prior value of the limit.
4222** ^Hence, to find the current value of a limit without changing it,
4223** simply invoke this interface with the third parameter set to -1.
4224**
4225** Run-time limits are intended for use in applications that manage
4226** both their own internal database and also databases that are controlled
4227** by untrusted external sources. An example application might be a
4228** web browser that has its own databases for storing history and
4229** separate databases controlled by JavaScript applications downloaded
4230** off the Internet. The internal databases can be given the
4231** large, default limits. Databases managed by external sources can
4232** be given much smaller limits designed to prevent a denial of service
4233** attack. Developers might also want to use the [sqlite3_set_authorizer()]
4234** interface to further control untrusted SQL. The size of the database
4235** created by an untrusted script can be contained using the
4236** [max_page_count] [PRAGMA].
4237**
4238** New run-time limit categories may be added in future releases.
4239*/
4240SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
4241
4242/*
4243** CAPI3REF: Run-Time Limit Categories
4244** KEYWORDS: {limit category} {*limit categories}
4245**
4246** These constants define various performance limits
4247** that can be lowered at run-time using [sqlite3_limit()].
4248** The synopsis of the meanings of the various limits is shown below.
4249** Additional information is available at [limits | Limits in SQLite].
4250**
4251** <dl>
4252** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
4253** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
4254**
4255** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
4256** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
4257**
4258** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
4259** <dd>The maximum number of columns in a table definition or in the
4260** result set of a [SELECT] or the maximum number of columns in an index
4261** or in an ORDER BY or GROUP BY clause.</dd>)^
4262**
4263** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
4264** <dd>The maximum depth of the parse tree on any expression.</dd>)^
4265**
4266** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
4267** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
4268**
4269** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
4270** <dd>The maximum number of instructions in a virtual machine program
4271** used to implement an SQL statement. If [sqlite3_prepare_v2()] or
4272** the equivalent tries to allocate space for more than this many opcodes
4273** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
4274**
4275** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
4276** <dd>The maximum number of arguments on a function.</dd>)^
4277**
4278** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
4279** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
4280**
4281** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
4282** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
4283** <dd>The maximum length of the pattern argument to the [LIKE] or
4284** [GLOB] operators.</dd>)^
4285**
4286** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
4287** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
4288** <dd>The maximum index number of any [parameter] in an SQL statement.)^
4289**
4290** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
4291** <dd>The maximum depth of recursion for triggers.</dd>)^
4292**
4293** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
4294** <dd>The maximum number of auxiliary worker threads that a single
4295** [prepared statement] may start.</dd>)^
4296** </dl>
4297*/
4298#define SQLITE_LIMIT_LENGTH 0
4299#define SQLITE_LIMIT_SQL_LENGTH 1
4300#define SQLITE_LIMIT_COLUMN 2
4301#define SQLITE_LIMIT_EXPR_DEPTH 3
4302#define SQLITE_LIMIT_COMPOUND_SELECT 4
4303#define SQLITE_LIMIT_VDBE_OP 5
4304#define SQLITE_LIMIT_FUNCTION_ARG 6
4305#define SQLITE_LIMIT_ATTACHED 7
4306#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
4307#define SQLITE_LIMIT_VARIABLE_NUMBER 9
4308#define SQLITE_LIMIT_TRIGGER_DEPTH 10
4309#define SQLITE_LIMIT_WORKER_THREADS 11
4310
4311/*
4312** CAPI3REF: Prepare Flags
4313**
4314** These constants define various flags that can be passed into
4315** "prepFlags" parameter of the [sqlite3_prepare_v3()] and
4316** [sqlite3_prepare16_v3()] interfaces.
4317**
4318** New flags may be added in future releases of SQLite.
4319**
4320** <dl>
4321** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt>
4322** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
4323** that the prepared statement will be retained for a long time and
4324** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
4325** and [sqlite3_prepare16_v3()] assume that the prepared statement will
4326** be used just once or at most a few times and then destroyed using
4327** [sqlite3_finalize()] relatively soon. The current implementation acts
4328** on this hint by avoiding the use of [lookaside memory] so as not to
4329** deplete the limited store of lookaside memory. Future versions of
4330** SQLite may act on this hint differently.
4331**
4332** [[SQLITE_PREPARE_NORMALIZE]] <dt>SQLITE_PREPARE_NORMALIZE</dt>
4333** <dd>The SQLITE_PREPARE_NORMALIZE flag is a no-op. This flag used
4334** to be required for any prepared statement that wanted to use the
4335** [sqlite3_normalized_sql()] interface. However, the
4336** [sqlite3_normalized_sql()] interface is now available to all
4337** prepared statements, regardless of whether or not they use this
4338** flag.
4339**
4340** [[SQLITE_PREPARE_NO_VTAB]] <dt>SQLITE_PREPARE_NO_VTAB</dt>
4341** <dd>The SQLITE_PREPARE_NO_VTAB flag causes the SQL compiler
4342** to return an error (error code SQLITE_ERROR) if the statement uses
4343** any virtual tables.
4344** </dl>
4345*/
4346#define SQLITE_PREPARE_PERSISTENT 0x01
4347#define SQLITE_PREPARE_NORMALIZE 0x02
4348#define SQLITE_PREPARE_NO_VTAB 0x04
4349
4350/*
4351** CAPI3REF: Compiling An SQL Statement
4352** KEYWORDS: {SQL statement compiler}
4353** METHOD: sqlite3
4354** CONSTRUCTOR: sqlite3_stmt
4355**
4356** To execute an SQL statement, it must first be compiled into a byte-code
4357** program using one of these routines. Or, in other words, these routines
4358** are constructors for the [prepared statement] object.
4359**
4360** The preferred routine to use is [sqlite3_prepare_v2()]. The
4361** [sqlite3_prepare()] interface is legacy and should be avoided.
4362** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used
4363** for special purposes.
4364**
4365** The use of the UTF-8 interfaces is preferred, as SQLite currently
4366** does all parsing using UTF-8. The UTF-16 interfaces are provided
4367** as a convenience. The UTF-16 interfaces work by converting the
4368** input text into UTF-8, then invoking the corresponding UTF-8 interface.
4369**
4370** The first argument, "db", is a [database connection] obtained from a
4371** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
4372** [sqlite3_open16()]. The database connection must not have been closed.
4373**
4374** The second argument, "zSql", is the statement to be compiled, encoded
4375** as either UTF-8 or UTF-16. The sqlite3_prepare(), sqlite3_prepare_v2(),
4376** and sqlite3_prepare_v3()
4377** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
4378** and sqlite3_prepare16_v3() use UTF-16.
4379**
4380** ^If the nByte argument is negative, then zSql is read up to the
4381** first zero terminator. ^If nByte is positive, then it is the
4382** number of bytes read from zSql. ^If nByte is zero, then no prepared
4383** statement is generated.
4384** If the caller knows that the supplied string is nul-terminated, then
4385** there is a small performance advantage to passing an nByte parameter that
4386** is the number of bytes in the input string <i>including</i>
4387** the nul-terminator.
4388**
4389** ^If pzTail is not NULL then *pzTail is made to point to the first byte
4390** past the end of the first SQL statement in zSql. These routines only
4391** compile the first statement in zSql, so *pzTail is left pointing to
4392** what remains uncompiled.
4393**
4394** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
4395** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
4396** to NULL. ^If the input text contains no SQL (if the input is an empty
4397** string or a comment) then *ppStmt is set to NULL.
4398** The calling procedure is responsible for deleting the compiled
4399** SQL statement using [sqlite3_finalize()] after it has finished with it.
4400** ppStmt may not be NULL.
4401**
4402** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
4403** otherwise an [error code] is returned.
4404**
4405** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),
4406** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.
4407** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())
4408** are retained for backwards compatibility, but their use is discouraged.
4409** ^In the "vX" interfaces, the prepared statement
4410** that is returned (the [sqlite3_stmt] object) contains a copy of the
4411** original SQL text. This causes the [sqlite3_step()] interface to
4412** behave differently in three ways:
4413**
4414** <ol>
4415** <li>
4416** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
4417** always used to do, [sqlite3_step()] will automatically recompile the SQL
4418** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
4419** retries will occur before sqlite3_step() gives up and returns an error.
4420** </li>
4421**
4422** <li>
4423** ^When an error occurs, [sqlite3_step()] will return one of the detailed
4424** [error codes] or [extended error codes]. ^The legacy behavior was that
4425** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
4426** and the application would have to make a second call to [sqlite3_reset()]
4427** in order to find the underlying cause of the problem. With the "v2" prepare
4428** interfaces, the underlying reason for the error is returned immediately.
4429** </li>
4430**
4431** <li>
4432** ^If the specific value bound to a [parameter | host parameter] in the
4433** WHERE clause might influence the choice of query plan for a statement,
4434** then the statement will be automatically recompiled, as if there had been
4435** a schema change, on the first [sqlite3_step()] call following any change
4436** to the [sqlite3_bind_text | bindings] of that [parameter].
4437** ^The specific value of a WHERE-clause [parameter] might influence the
4438** choice of query plan if the parameter is the left-hand side of a [LIKE]
4439** or [GLOB] operator or if the parameter is compared to an indexed column
4440** and the [SQLITE_ENABLE_STAT4] compile-time option is enabled.
4441** </li>
4442** </ol>
4443**
4444** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having
4445** the extra prepFlags parameter, which is a bit array consisting of zero or
4446** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags. ^The
4447** sqlite3_prepare_v2() interface works exactly the same as
4448** sqlite3_prepare_v3() with a zero prepFlags parameter.
4449*/
4450SQLITE_API int sqlite3_prepare(
4451 sqlite3 *db, /* Database handle */
4452 const char *zSql, /* SQL statement, UTF-8 encoded */
4453 int nByte, /* Maximum length of zSql in bytes. */
4454 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
4455 const char **pzTail /* OUT: Pointer to unused portion of zSql */
4456);
4457SQLITE_API int sqlite3_prepare_v2(
4458 sqlite3 *db, /* Database handle */
4459 const char *zSql, /* SQL statement, UTF-8 encoded */
4460 int nByte, /* Maximum length of zSql in bytes. */
4461 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
4462 const char **pzTail /* OUT: Pointer to unused portion of zSql */
4463);
4464SQLITE_API int sqlite3_prepare_v3(
4465 sqlite3 *db, /* Database handle */
4466 const char *zSql, /* SQL statement, UTF-8 encoded */
4467 int nByte, /* Maximum length of zSql in bytes. */
4468 unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
4469 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
4470 const char **pzTail /* OUT: Pointer to unused portion of zSql */
4471);
4472SQLITE_API int sqlite3_prepare16(
4473 sqlite3 *db, /* Database handle */
4474 const void *zSql, /* SQL statement, UTF-16 encoded */
4475 int nByte, /* Maximum length of zSql in bytes. */
4476 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
4477 const void **pzTail /* OUT: Pointer to unused portion of zSql */
4478);
4479SQLITE_API int sqlite3_prepare16_v2(
4480 sqlite3 *db, /* Database handle */
4481 const void *zSql, /* SQL statement, UTF-16 encoded */
4482 int nByte, /* Maximum length of zSql in bytes. */
4483 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
4484 const void **pzTail /* OUT: Pointer to unused portion of zSql */
4485);
4486SQLITE_API int sqlite3_prepare16_v3(
4487 sqlite3 *db, /* Database handle */
4488 const void *zSql, /* SQL statement, UTF-16 encoded */
4489 int nByte, /* Maximum length of zSql in bytes. */
4490 unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
4491 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
4492 const void **pzTail /* OUT: Pointer to unused portion of zSql */
4493);
4494
4495/*
4496** CAPI3REF: Retrieving Statement SQL
4497** METHOD: sqlite3_stmt
4498**
4499** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
4500** SQL text used to create [prepared statement] P if P was
4501** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],
4502** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
4503** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
4504** string containing the SQL text of prepared statement P with
4505** [bound parameters] expanded.
4506** ^The sqlite3_normalized_sql(P) interface returns a pointer to a UTF-8
4507** string containing the normalized SQL text of prepared statement P. The
4508** semantics used to normalize a SQL statement are unspecified and subject
4509** to change. At a minimum, literal values will be replaced with suitable
4510** placeholders.
4511**
4512** ^(For example, if a prepared statement is created using the SQL
4513** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
4514** and parameter :xyz is unbound, then sqlite3_sql() will return
4515** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
4516** will return "SELECT 2345,NULL".)^
4517**
4518** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
4519** is available to hold the result, or if the result would exceed the
4520** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
4521**
4522** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
4523** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time
4524** option causes sqlite3_expanded_sql() to always return NULL.
4525**
4526** ^The strings returned by sqlite3_sql(P) and sqlite3_normalized_sql(P)
4527** are managed by SQLite and are automatically freed when the prepared
4528** statement is finalized.
4529** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
4530** is obtained from [sqlite3_malloc()] and must be freed by the application
4531** by passing it to [sqlite3_free()].
4532**
4533** ^The sqlite3_normalized_sql() interface is only available if
4534** the [SQLITE_ENABLE_NORMALIZE] compile-time option is defined.
4535*/
4536SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
4537SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
4538#ifdef SQLITE_ENABLE_NORMALIZE
4539SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
4540#endif
4541
4542/*
4543** CAPI3REF: Determine If An SQL Statement Writes The Database
4544** METHOD: sqlite3_stmt
4545**
4546** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
4547** and only if the [prepared statement] X makes no direct changes to
4548** the content of the database file.
4549**
4550** Note that [application-defined SQL functions] or
4551** [virtual tables] might change the database indirectly as a side effect.
4552** ^(For example, if an application defines a function "eval()" that
4553** calls [sqlite3_exec()], then the following SQL statement would
4554** change the database file through side-effects:
4555**
4556** <blockquote><pre>
4557** SELECT eval('DELETE FROM t1') FROM t2;
4558** </pre></blockquote>
4559**
4560** But because the [SELECT] statement does not change the database file
4561** directly, sqlite3_stmt_readonly() would still return true.)^
4562**
4563** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
4564** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
4565** since the statements themselves do not actually modify the database but
4566** rather they control the timing of when other statements modify the
4567** database. ^The [ATTACH] and [DETACH] statements also cause
4568** sqlite3_stmt_readonly() to return true since, while those statements
4569** change the configuration of a database connection, they do not make
4570** changes to the content of the database files on disk.
4571** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
4572** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
4573** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
4574** sqlite3_stmt_readonly() returns false for those commands.
4575**
4576** ^This routine returns false if there is any possibility that the
4577** statement might change the database file. ^A false return does
4578** not guarantee that the statement will change the database file.
4579** ^For example, an UPDATE statement might have a WHERE clause that
4580** makes it a no-op, but the sqlite3_stmt_readonly() result would still
4581** be false. ^Similarly, a CREATE TABLE IF NOT EXISTS statement is a
4582** read-only no-op if the table already exists, but
4583** sqlite3_stmt_readonly() still returns false for such a statement.
4584*/
4585SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
4586
4587/*
4588** CAPI3REF: Query The EXPLAIN Setting For A Prepared Statement
4589** METHOD: sqlite3_stmt
4590**
4591** ^The sqlite3_stmt_isexplain(S) interface returns 1 if the
4592** prepared statement S is an EXPLAIN statement, or 2 if the
4593** statement S is an EXPLAIN QUERY PLAN.
4594** ^The sqlite3_stmt_isexplain(S) interface returns 0 if S is
4595** an ordinary statement or a NULL pointer.
4596*/
4597SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt);
4598
4599/*
4600** CAPI3REF: Determine If A Prepared Statement Has Been Reset
4601** METHOD: sqlite3_stmt
4602**
4603** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
4604** [prepared statement] S has been stepped at least once using
4605** [sqlite3_step(S)] but has neither run to completion (returned
4606** [SQLITE_DONE] from [sqlite3_step(S)]) nor
4607** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
4608** interface returns false if S is a NULL pointer. If S is not a
4609** NULL pointer and is not a pointer to a valid [prepared statement]
4610** object, then the behavior is undefined and probably undesirable.
4611**
4612** This interface can be used in combination [sqlite3_next_stmt()]
4613** to locate all prepared statements associated with a database
4614** connection that are in need of being reset. This can be used,
4615** for example, in diagnostic routines to search for prepared
4616** statements that are holding a transaction open.
4617*/
4618SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
4619
4620/*
4621** CAPI3REF: Dynamically Typed Value Object
4622** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
4623**
4624** SQLite uses the sqlite3_value object to represent all values
4625** that can be stored in a database table. SQLite uses dynamic typing
4626** for the values it stores. ^Values stored in sqlite3_value objects
4627** can be integers, floating point values, strings, BLOBs, or NULL.
4628**
4629** An sqlite3_value object may be either "protected" or "unprotected".
4630** Some interfaces require a protected sqlite3_value. Other interfaces
4631** will accept either a protected or an unprotected sqlite3_value.
4632** Every interface that accepts sqlite3_value arguments specifies
4633** whether or not it requires a protected sqlite3_value. The
4634** [sqlite3_value_dup()] interface can be used to construct a new
4635** protected sqlite3_value from an unprotected sqlite3_value.
4636**
4637** The terms "protected" and "unprotected" refer to whether or not
4638** a mutex is held. An internal mutex is held for a protected
4639** sqlite3_value object but no mutex is held for an unprotected
4640** sqlite3_value object. If SQLite is compiled to be single-threaded
4641** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
4642** or if SQLite is run in one of reduced mutex modes
4643** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
4644** then there is no distinction between protected and unprotected
4645** sqlite3_value objects and they can be used interchangeably. However,
4646** for maximum code portability it is recommended that applications
4647** still make the distinction between protected and unprotected
4648** sqlite3_value objects even when not strictly required.
4649**
4650** ^The sqlite3_value objects that are passed as parameters into the
4651** implementation of [application-defined SQL functions] are protected.
4652** ^The sqlite3_value object returned by
4653** [sqlite3_column_value()] is unprotected.
4654** Unprotected sqlite3_value objects may only be used as arguments
4655** to [sqlite3_result_value()], [sqlite3_bind_value()], and
4656** [sqlite3_value_dup()].
4657** The [sqlite3_value_blob | sqlite3_value_type()] family of
4658** interfaces require protected sqlite3_value objects.
4659*/
4660typedef struct sqlite3_value sqlite3_value;
4661
4662/*
4663** CAPI3REF: SQL Function Context Object
4664**
4665** The context in which an SQL function executes is stored in an
4666** sqlite3_context object. ^A pointer to an sqlite3_context object
4667** is always first parameter to [application-defined SQL functions].
4668** The application-defined SQL function implementation will pass this
4669** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
4670** [sqlite3_aggregate_context()], [sqlite3_user_data()],
4671** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
4672** and/or [sqlite3_set_auxdata()].
4673*/
4674typedef struct sqlite3_context sqlite3_context;
4675
4676/*
4677** CAPI3REF: Binding Values To Prepared Statements
4678** KEYWORDS: {host parameter} {host parameters} {host parameter name}
4679** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
4680** METHOD: sqlite3_stmt
4681**
4682** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
4683** literals may be replaced by a [parameter] that matches one of following
4684** templates:
4685**
4686** <ul>
4687** <li> ?
4688** <li> ?NNN
4689** <li> :VVV
4690** <li> @VVV
4691** <li> $VVV
4692** </ul>
4693**
4694** In the templates above, NNN represents an integer literal,
4695** and VVV represents an alphanumeric identifier.)^ ^The values of these
4696** parameters (also called "host parameter names" or "SQL parameters")
4697** can be set using the sqlite3_bind_*() routines defined here.
4698**
4699** ^The first argument to the sqlite3_bind_*() routines is always
4700** a pointer to the [sqlite3_stmt] object returned from
4701** [sqlite3_prepare_v2()] or its variants.
4702**
4703** ^The second argument is the index of the SQL parameter to be set.
4704** ^The leftmost SQL parameter has an index of 1. ^When the same named
4705** SQL parameter is used more than once, second and subsequent
4706** occurrences have the same index as the first occurrence.
4707** ^The index for named parameters can be looked up using the
4708** [sqlite3_bind_parameter_index()] API if desired. ^The index
4709** for "?NNN" parameters is the value of NNN.
4710** ^The NNN value must be between 1 and the [sqlite3_limit()]
4711** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 32766).
4712**
4713** ^The third argument is the value to bind to the parameter.
4714** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
4715** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
4716** is ignored and the end result is the same as sqlite3_bind_null().
4717** ^If the third parameter to sqlite3_bind_text() is not NULL, then
4718** it should be a pointer to well-formed UTF8 text.
4719** ^If the third parameter to sqlite3_bind_text16() is not NULL, then
4720** it should be a pointer to well-formed UTF16 text.
4721** ^If the third parameter to sqlite3_bind_text64() is not NULL, then
4722** it should be a pointer to a well-formed unicode string that is
4723** either UTF8 if the sixth parameter is SQLITE_UTF8, or UTF16
4724** otherwise.
4725**
4726** [[byte-order determination rules]] ^The byte-order of
4727** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF)
4728** found in first character, which is removed, or in the absence of a BOM
4729** the byte order is the native byte order of the host
4730** machine for sqlite3_bind_text16() or the byte order specified in
4731** the 6th parameter for sqlite3_bind_text64().)^
4732** ^If UTF16 input text contains invalid unicode
4733** characters, then SQLite might change those invalid characters
4734** into the unicode replacement character: U+FFFD.
4735**
4736** ^(In those routines that have a fourth argument, its value is the
4737** number of bytes in the parameter. To be clear: the value is the
4738** number of <u>bytes</u> in the value, not the number of characters.)^
4739** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
4740** is negative, then the length of the string is
4741** the number of bytes up to the first zero terminator.
4742** If the fourth parameter to sqlite3_bind_blob() is negative, then
4743** the behavior is undefined.
4744** If a non-negative fourth parameter is provided to sqlite3_bind_text()
4745** or sqlite3_bind_text16() or sqlite3_bind_text64() then
4746** that parameter must be the byte offset
4747** where the NUL terminator would occur assuming the string were NUL
4748** terminated. If any NUL characters occurs at byte offsets less than
4749** the value of the fourth parameter then the resulting string value will
4750** contain embedded NULs. The result of expressions involving strings
4751** with embedded NULs is undefined.
4752**
4753** ^The fifth argument to the BLOB and string binding interfaces controls
4754** or indicates the lifetime of the object referenced by the third parameter.
4755** These three options exist:
4756** ^ (1) A destructor to dispose of the BLOB or string after SQLite has finished
4757** with it may be passed. ^It is called to dispose of the BLOB or string even
4758** if the call to the bind API fails, except the destructor is not called if
4759** the third parameter is a NULL pointer or the fourth parameter is negative.
4760** ^ (2) The special constant, [SQLITE_STATIC], may be passsed to indicate that
4761** the application remains responsible for disposing of the object. ^In this
4762** case, the object and the provided pointer to it must remain valid until
4763** either the prepared statement is finalized or the same SQL parameter is
4764** bound to something else, whichever occurs sooner.
4765** ^ (3) The constant, [SQLITE_TRANSIENT], may be passed to indicate that the
4766** object is to be copied prior to the return from sqlite3_bind_*(). ^The
4767** object and pointer to it must remain valid until then. ^SQLite will then
4768** manage the lifetime of its private copy.
4769**
4770** ^The sixth argument to sqlite3_bind_text64() must be one of
4771** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
4772** to specify the encoding of the text in the third parameter. If
4773** the sixth argument to sqlite3_bind_text64() is not one of the
4774** allowed values shown above, or if the text encoding is different
4775** from the encoding specified by the sixth parameter, then the behavior
4776** is undefined.
4777**
4778** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
4779** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
4780** (just an integer to hold its size) while it is being processed.
4781** Zeroblobs are intended to serve as placeholders for BLOBs whose
4782** content is later written using
4783** [sqlite3_blob_open | incremental BLOB I/O] routines.
4784** ^A negative value for the zeroblob results in a zero-length BLOB.
4785**
4786** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in
4787** [prepared statement] S to have an SQL value of NULL, but to also be
4788** associated with the pointer P of type T. ^D is either a NULL pointer or
4789** a pointer to a destructor function for P. ^SQLite will invoke the
4790** destructor D with a single argument of P when it is finished using
4791** P. The T parameter should be a static string, preferably a string
4792** literal. The sqlite3_bind_pointer() routine is part of the
4793** [pointer passing interface] added for SQLite 3.20.0.
4794**
4795** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
4796** for the [prepared statement] or with a prepared statement for which
4797** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
4798** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
4799** routine is passed a [prepared statement] that has been finalized, the
4800** result is undefined and probably harmful.
4801**
4802** ^Bindings are not cleared by the [sqlite3_reset()] routine.
4803** ^Unbound parameters are interpreted as NULL.
4804**
4805** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
4806** [error code] if anything goes wrong.
4807** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
4808** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
4809** [SQLITE_MAX_LENGTH].
4810** ^[SQLITE_RANGE] is returned if the parameter
4811** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
4812**
4813** See also: [sqlite3_bind_parameter_count()],
4814** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
4815*/
4816SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
4817SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
4818 void(*)(void*));
4819SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
4820SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
4821SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
4822SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
4823SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
4824SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
4825SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
4826 void(*)(void*), unsigned char encoding);
4827SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
4828SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));
4829SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
4830SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
4831
4832/*
4833** CAPI3REF: Number Of SQL Parameters
4834** METHOD: sqlite3_stmt
4835**
4836** ^This routine can be used to find the number of [SQL parameters]
4837** in a [prepared statement]. SQL parameters are tokens of the
4838** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
4839** placeholders for values that are [sqlite3_bind_blob | bound]
4840** to the parameters at a later time.
4841**
4842** ^(This routine actually returns the index of the largest (rightmost)
4843** parameter. For all forms except ?NNN, this will correspond to the
4844** number of unique parameters. If parameters of the ?NNN form are used,
4845** there may be gaps in the list.)^
4846**
4847** See also: [sqlite3_bind_blob|sqlite3_bind()],
4848** [sqlite3_bind_parameter_name()], and
4849** [sqlite3_bind_parameter_index()].
4850*/
4851SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
4852
4853/*
4854** CAPI3REF: Name Of A Host Parameter
4855** METHOD: sqlite3_stmt
4856**
4857** ^The sqlite3_bind_parameter_name(P,N) interface returns
4858** the name of the N-th [SQL parameter] in the [prepared statement] P.
4859** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
4860** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
4861** respectively.
4862** In other words, the initial ":" or "$" or "@" or "?"
4863** is included as part of the name.)^
4864** ^Parameters of the form "?" without a following integer have no name
4865** and are referred to as "nameless" or "anonymous parameters".
4866**
4867** ^The first host parameter has an index of 1, not 0.
4868**
4869** ^If the value N is out of range or if the N-th parameter is
4870** nameless, then NULL is returned. ^The returned string is
4871** always in UTF-8 encoding even if the named parameter was
4872** originally specified as UTF-16 in [sqlite3_prepare16()],
4873** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
4874**
4875** See also: [sqlite3_bind_blob|sqlite3_bind()],
4876** [sqlite3_bind_parameter_count()], and
4877** [sqlite3_bind_parameter_index()].
4878*/
4879SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
4880
4881/*
4882** CAPI3REF: Index Of A Parameter With A Given Name
4883** METHOD: sqlite3_stmt
4884**
4885** ^Return the index of an SQL parameter given its name. ^The
4886** index value returned is suitable for use as the second
4887** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
4888** is returned if no matching parameter is found. ^The parameter
4889** name must be given in UTF-8 even if the original statement
4890** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or
4891** [sqlite3_prepare16_v3()].
4892**
4893** See also: [sqlite3_bind_blob|sqlite3_bind()],
4894** [sqlite3_bind_parameter_count()], and
4895** [sqlite3_bind_parameter_name()].
4896*/
4897SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
4898
4899/*
4900** CAPI3REF: Reset All Bindings On A Prepared Statement
4901** METHOD: sqlite3_stmt
4902**
4903** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
4904** the [sqlite3_bind_blob | bindings] on a [prepared statement].
4905** ^Use this routine to reset all host parameters to NULL.
4906*/
4907SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
4908
4909/*
4910** CAPI3REF: Number Of Columns In A Result Set
4911** METHOD: sqlite3_stmt
4912**
4913** ^Return the number of columns in the result set returned by the
4914** [prepared statement]. ^If this routine returns 0, that means the
4915** [prepared statement] returns no data (for example an [UPDATE]).
4916** ^However, just because this routine returns a positive number does not
4917** mean that one or more rows of data will be returned. ^A SELECT statement
4918** will always have a positive sqlite3_column_count() but depending on the
4919** WHERE clause constraints and the table content, it might return no rows.
4920**
4921** See also: [sqlite3_data_count()]
4922*/
4923SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
4924
4925/*
4926** CAPI3REF: Column Names In A Result Set
4927** METHOD: sqlite3_stmt
4928**
4929** ^These routines return the name assigned to a particular column
4930** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
4931** interface returns a pointer to a zero-terminated UTF-8 string
4932** and sqlite3_column_name16() returns a pointer to a zero-terminated
4933** UTF-16 string. ^The first parameter is the [prepared statement]
4934** that implements the [SELECT] statement. ^The second parameter is the
4935** column number. ^The leftmost column is number 0.
4936**
4937** ^The returned string pointer is valid until either the [prepared statement]
4938** is destroyed by [sqlite3_finalize()] or until the statement is automatically
4939** reprepared by the first call to [sqlite3_step()] for a particular run
4940** or until the next call to
4941** sqlite3_column_name() or sqlite3_column_name16() on the same column.
4942**
4943** ^If sqlite3_malloc() fails during the processing of either routine
4944** (for example during a conversion from UTF-8 to UTF-16) then a
4945** NULL pointer is returned.
4946**
4947** ^The name of a result column is the value of the "AS" clause for
4948** that column, if there is an AS clause. If there is no AS clause
4949** then the name of the column is unspecified and may change from
4950** one release of SQLite to the next.
4951*/
4952SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
4953SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
4954
4955/*
4956** CAPI3REF: Source Of Data In A Query Result
4957** METHOD: sqlite3_stmt
4958**
4959** ^These routines provide a means to determine the database, table, and
4960** table column that is the origin of a particular result column in
4961** [SELECT] statement.
4962** ^The name of the database or table or column can be returned as
4963** either a UTF-8 or UTF-16 string. ^The _database_ routines return
4964** the database name, the _table_ routines return the table name, and
4965** the origin_ routines return the column name.
4966** ^The returned string is valid until the [prepared statement] is destroyed
4967** using [sqlite3_finalize()] or until the statement is automatically
4968** reprepared by the first call to [sqlite3_step()] for a particular run
4969** or until the same information is requested
4970** again in a different encoding.
4971**
4972** ^The names returned are the original un-aliased names of the
4973** database, table, and column.
4974**
4975** ^The first argument to these interfaces is a [prepared statement].
4976** ^These functions return information about the Nth result column returned by
4977** the statement, where N is the second function argument.
4978** ^The left-most column is column 0 for these routines.
4979**
4980** ^If the Nth column returned by the statement is an expression or
4981** subquery and is not a column value, then all of these functions return
4982** NULL. ^These routines might also return NULL if a memory allocation error
4983** occurs. ^Otherwise, they return the name of the attached database, table,
4984** or column that query result column was extracted from.
4985**
4986** ^As with all other SQLite APIs, those whose names end with "16" return
4987** UTF-16 encoded strings and the other functions return UTF-8.
4988**
4989** ^These APIs are only available if the library was compiled with the
4990** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
4991**
4992** If two or more threads call one or more
4993** [sqlite3_column_database_name | column metadata interfaces]
4994** for the same [prepared statement] and result column
4995** at the same time then the results are undefined.
4996*/
4997SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
4998SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
4999SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
5000SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
5001SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
5002SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
5003
5004/*
5005** CAPI3REF: Declared Datatype Of A Query Result
5006** METHOD: sqlite3_stmt
5007**
5008** ^(The first parameter is a [prepared statement].
5009** If this statement is a [SELECT] statement and the Nth column of the
5010** returned result set of that [SELECT] is a table column (not an
5011** expression or subquery) then the declared type of the table
5012** column is returned.)^ ^If the Nth column of the result set is an
5013** expression or subquery, then a NULL pointer is returned.
5014** ^The returned string is always UTF-8 encoded.
5015**
5016** ^(For example, given the database schema:
5017**
5018** CREATE TABLE t1(c1 VARIANT);
5019**
5020** and the following statement to be compiled:
5021**
5022** SELECT c1 + 1, c1 FROM t1;
5023**
5024** this routine would return the string "VARIANT" for the second result
5025** column (i==1), and a NULL pointer for the first result column (i==0).)^
5026**
5027** ^SQLite uses dynamic run-time typing. ^So just because a column
5028** is declared to contain a particular type does not mean that the
5029** data stored in that column is of the declared type. SQLite is
5030** strongly typed, but the typing is dynamic not static. ^Type
5031** is associated with individual values, not with the containers
5032** used to hold those values.
5033*/
5034SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
5035SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
5036
5037/*
5038** CAPI3REF: Evaluate An SQL Statement
5039** METHOD: sqlite3_stmt
5040**
5041** After a [prepared statement] has been prepared using any of
5042** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],
5043** or [sqlite3_prepare16_v3()] or one of the legacy
5044** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
5045** must be called one or more times to evaluate the statement.
5046**
5047** The details of the behavior of the sqlite3_step() interface depend
5048** on whether the statement was prepared using the newer "vX" interfaces
5049** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],
5050** [sqlite3_prepare16_v2()] or the older legacy
5051** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
5052** new "vX" interface is recommended for new applications but the legacy
5053** interface will continue to be supported.
5054**
5055** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
5056** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
5057** ^With the "v2" interface, any of the other [result codes] or
5058** [extended result codes] might be returned as well.
5059**
5060** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
5061** database locks it needs to do its job. ^If the statement is a [COMMIT]
5062** or occurs outside of an explicit transaction, then you can retry the
5063** statement. If the statement is not a [COMMIT] and occurs within an
5064** explicit transaction then you should rollback the transaction before
5065** continuing.
5066**
5067** ^[SQLITE_DONE] means that the statement has finished executing
5068** successfully. sqlite3_step() should not be called again on this virtual
5069** machine without first calling [sqlite3_reset()] to reset the virtual
5070** machine back to its initial state.
5071**
5072** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
5073** is returned each time a new row of data is ready for processing by the
5074** caller. The values may be accessed using the [column access functions].
5075** sqlite3_step() is called again to retrieve the next row of data.
5076**
5077** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
5078** violation) has occurred. sqlite3_step() should not be called again on
5079** the VM. More information may be found by calling [sqlite3_errmsg()].
5080** ^With the legacy interface, a more specific error code (for example,
5081** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
5082** can be obtained by calling [sqlite3_reset()] on the
5083** [prepared statement]. ^In the "v2" interface,
5084** the more specific error code is returned directly by sqlite3_step().
5085**
5086** [SQLITE_MISUSE] means that the this routine was called inappropriately.
5087** Perhaps it was called on a [prepared statement] that has
5088** already been [sqlite3_finalize | finalized] or on one that had
5089** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
5090** be the case that the same database connection is being used by two or
5091** more threads at the same moment in time.
5092**
5093** For all versions of SQLite up to and including 3.6.23.1, a call to
5094** [sqlite3_reset()] was required after sqlite3_step() returned anything
5095** other than [SQLITE_ROW] before any subsequent invocation of
5096** sqlite3_step(). Failure to reset the prepared statement using
5097** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
5098** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1],
5099** sqlite3_step() began
5100** calling [sqlite3_reset()] automatically in this circumstance rather
5101** than returning [SQLITE_MISUSE]. This is not considered a compatibility
5102** break because any application that ever receives an SQLITE_MISUSE error
5103** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
5104** can be used to restore the legacy behavior.
5105**
5106** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
5107** API always returns a generic error code, [SQLITE_ERROR], following any
5108** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
5109** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
5110** specific [error codes] that better describes the error.
5111** We admit that this is a goofy design. The problem has been fixed
5112** with the "v2" interface. If you prepare all of your SQL statements
5113** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]
5114** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead
5115** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
5116** then the more specific [error codes] are returned directly
5117** by sqlite3_step(). The use of the "vX" interfaces is recommended.
5118*/
5119SQLITE_API int sqlite3_step(sqlite3_stmt*);
5120
5121/*
5122** CAPI3REF: Number of columns in a result set
5123** METHOD: sqlite3_stmt
5124**
5125** ^The sqlite3_data_count(P) interface returns the number of columns in the
5126** current row of the result set of [prepared statement] P.
5127** ^If prepared statement P does not have results ready to return
5128** (via calls to the [sqlite3_column_int | sqlite3_column()] family of
5129** interfaces) then sqlite3_data_count(P) returns 0.
5130** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
5131** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
5132** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
5133** will return non-zero if previous call to [sqlite3_step](P) returned
5134** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
5135** where it always returns zero since each step of that multi-step
5136** pragma returns 0 columns of data.
5137**
5138** See also: [sqlite3_column_count()]
5139*/
5140SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
5141
5142/*
5143** CAPI3REF: Fundamental Datatypes
5144** KEYWORDS: SQLITE_TEXT
5145**
5146** ^(Every value in SQLite has one of five fundamental datatypes:
5147**
5148** <ul>
5149** <li> 64-bit signed integer
5150** <li> 64-bit IEEE floating point number
5151** <li> string
5152** <li> BLOB
5153** <li> NULL
5154** </ul>)^
5155**
5156** These constants are codes for each of those types.
5157**
5158** Note that the SQLITE_TEXT constant was also used in SQLite version 2
5159** for a completely different meaning. Software that links against both
5160** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
5161** SQLITE_TEXT.
5162*/
5163#define SQLITE_INTEGER 1
5164#define SQLITE_FLOAT 2
5165#define SQLITE_BLOB 4
5166#define SQLITE_NULL 5
5167#ifdef SQLITE_TEXT
5168# undef SQLITE_TEXT
5169#else
5170# define SQLITE_TEXT 3
5171#endif
5172#define SQLITE3_TEXT 3
5173
5174/*
5175** CAPI3REF: Result Values From A Query
5176** KEYWORDS: {column access functions}
5177** METHOD: sqlite3_stmt
5178**
5179** <b>Summary:</b>
5180** <blockquote><table border=0 cellpadding=0 cellspacing=0>
5181** <tr><td><b>sqlite3_column_blob</b><td>&rarr;<td>BLOB result
5182** <tr><td><b>sqlite3_column_double</b><td>&rarr;<td>REAL result
5183** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result
5184** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result
5185** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result
5186** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result
5187** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an
5188** [sqlite3_value|unprotected sqlite3_value] object.
5189** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
5190** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB
5191** or a UTF-8 TEXT result in bytes
5192** <tr><td><b>sqlite3_column_bytes16&nbsp;&nbsp;</b>
5193** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
5194** TEXT in bytes
5195** <tr><td><b>sqlite3_column_type</b><td>&rarr;<td>Default
5196** datatype of the result
5197** </table></blockquote>
5198**
5199** <b>Details:</b>
5200**
5201** ^These routines return information about a single column of the current
5202** result row of a query. ^In every case the first argument is a pointer
5203** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
5204** that was returned from [sqlite3_prepare_v2()] or one of its variants)
5205** and the second argument is the index of the column for which information
5206** should be returned. ^The leftmost column of the result set has the index 0.
5207** ^The number of columns in the result can be determined using
5208** [sqlite3_column_count()].
5209**
5210** If the SQL statement does not currently point to a valid row, or if the
5211** column index is out of range, the result is undefined.
5212** These routines may only be called when the most recent call to
5213** [sqlite3_step()] has returned [SQLITE_ROW] and neither
5214** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
5215** If any of these routines are called after [sqlite3_reset()] or
5216** [sqlite3_finalize()] or after [sqlite3_step()] has returned
5217** something other than [SQLITE_ROW], the results are undefined.
5218** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
5219** are called from a different thread while any of these routines
5220** are pending, then the results are undefined.
5221**
5222** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)
5223** each return the value of a result column in a specific data format. If
5224** the result column is not initially in the requested format (for example,
5225** if the query returns an integer but the sqlite3_column_text() interface
5226** is used to extract the value) then an automatic type conversion is performed.
5227**
5228** ^The sqlite3_column_type() routine returns the
5229** [SQLITE_INTEGER | datatype code] for the initial data type
5230** of the result column. ^The returned value is one of [SQLITE_INTEGER],
5231** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].
5232** The return value of sqlite3_column_type() can be used to decide which
5233** of the first six interface should be used to extract the column value.
5234** The value returned by sqlite3_column_type() is only meaningful if no
5235** automatic type conversions have occurred for the value in question.
5236** After a type conversion, the result of calling sqlite3_column_type()
5237** is undefined, though harmless. Future
5238** versions of SQLite may change the behavior of sqlite3_column_type()
5239** following a type conversion.
5240**
5241** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()
5242** or sqlite3_column_bytes16() interfaces can be used to determine the size
5243** of that BLOB or string.
5244**
5245** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
5246** routine returns the number of bytes in that BLOB or string.
5247** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
5248** the string to UTF-8 and then returns the number of bytes.
5249** ^If the result is a numeric value then sqlite3_column_bytes() uses
5250** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
5251** the number of bytes in that string.
5252** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
5253**
5254** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
5255** routine returns the number of bytes in that BLOB or string.
5256** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
5257** the string to UTF-16 and then returns the number of bytes.
5258** ^If the result is a numeric value then sqlite3_column_bytes16() uses
5259** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
5260** the number of bytes in that string.
5261** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
5262**
5263** ^The values returned by [sqlite3_column_bytes()] and
5264** [sqlite3_column_bytes16()] do not include the zero terminators at the end
5265** of the string. ^For clarity: the values returned by
5266** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
5267** bytes in the string, not the number of characters.
5268**
5269** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
5270** even empty strings, are always zero-terminated. ^The return
5271** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
5272**
5273** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
5274** [unprotected sqlite3_value] object. In a multithreaded environment,
5275** an unprotected sqlite3_value object may only be used safely with
5276** [sqlite3_bind_value()] and [sqlite3_result_value()].
5277** If the [unprotected sqlite3_value] object returned by
5278** [sqlite3_column_value()] is used in any other way, including calls
5279** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
5280** or [sqlite3_value_bytes()], the behavior is not threadsafe.
5281** Hence, the sqlite3_column_value() interface
5282** is normally only useful within the implementation of
5283** [application-defined SQL functions] or [virtual tables], not within
5284** top-level application code.
5285**
5286** The these routines may attempt to convert the datatype of the result.
5287** ^For example, if the internal representation is FLOAT and a text result
5288** is requested, [sqlite3_snprintf()] is used internally to perform the
5289** conversion automatically. ^(The following table details the conversions
5290** that are applied:
5291**
5292** <blockquote>
5293** <table border="1">
5294** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
5295**
5296** <tr><td> NULL <td> INTEGER <td> Result is 0
5297** <tr><td> NULL <td> FLOAT <td> Result is 0.0
5298** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
5299** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
5300** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
5301** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
5302** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
5303** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
5304** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
5305** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
5306** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
5307** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
5308** <tr><td> TEXT <td> BLOB <td> No change
5309** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
5310** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
5311** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
5312** </table>
5313** </blockquote>)^
5314**
5315** Note that when type conversions occur, pointers returned by prior
5316** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
5317** sqlite3_column_text16() may be invalidated.
5318** Type conversions and pointer invalidations might occur
5319** in the following cases:
5320**
5321** <ul>
5322** <li> The initial content is a BLOB and sqlite3_column_text() or
5323** sqlite3_column_text16() is called. A zero-terminator might
5324** need to be added to the string.</li>
5325** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
5326** sqlite3_column_text16() is called. The content must be converted
5327** to UTF-16.</li>
5328** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
5329** sqlite3_column_text() is called. The content must be converted
5330** to UTF-8.</li>
5331** </ul>
5332**
5333** ^Conversions between UTF-16be and UTF-16le are always done in place and do
5334** not invalidate a prior pointer, though of course the content of the buffer
5335** that the prior pointer references will have been modified. Other kinds
5336** of conversion are done in place when it is possible, but sometimes they
5337** are not possible and in those cases prior pointers are invalidated.
5338**
5339** The safest policy is to invoke these routines
5340** in one of the following ways:
5341**
5342** <ul>
5343** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
5344** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
5345** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
5346** </ul>
5347**
5348** In other words, you should call sqlite3_column_text(),
5349** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
5350** into the desired format, then invoke sqlite3_column_bytes() or
5351** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
5352** to sqlite3_column_text() or sqlite3_column_blob() with calls to
5353** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
5354** with calls to sqlite3_column_bytes().
5355**
5356** ^The pointers returned are valid until a type conversion occurs as
5357** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
5358** [sqlite3_finalize()] is called. ^The memory space used to hold strings
5359** and BLOBs is freed automatically. Do not pass the pointers returned
5360** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
5361** [sqlite3_free()].
5362**
5363** As long as the input parameters are correct, these routines will only
5364** fail if an out-of-memory error occurs during a format conversion.
5365** Only the following subset of interfaces are subject to out-of-memory
5366** errors:
5367**
5368** <ul>
5369** <li> sqlite3_column_blob()
5370** <li> sqlite3_column_text()
5371** <li> sqlite3_column_text16()
5372** <li> sqlite3_column_bytes()
5373** <li> sqlite3_column_bytes16()
5374** </ul>
5375**
5376** If an out-of-memory error occurs, then the return value from these
5377** routines is the same as if the column had contained an SQL NULL value.
5378** Valid SQL NULL returns can be distinguished from out-of-memory errors
5379** by invoking the [sqlite3_errcode()] immediately after the suspect
5380** return value is obtained and before any
5381** other SQLite interface is called on the same [database connection].
5382*/
5383SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
5384SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
5385SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
5386SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
5387SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
5388SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
5389SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
5390SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
5391SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
5392SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
5393
5394/*
5395** CAPI3REF: Destroy A Prepared Statement Object
5396** DESTRUCTOR: sqlite3_stmt
5397**
5398** ^The sqlite3_finalize() function is called to delete a [prepared statement].
5399** ^If the most recent evaluation of the statement encountered no errors
5400** or if the statement is never been evaluated, then sqlite3_finalize() returns
5401** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
5402** sqlite3_finalize(S) returns the appropriate [error code] or
5403** [extended error code].
5404**
5405** ^The sqlite3_finalize(S) routine can be called at any point during
5406** the life cycle of [prepared statement] S:
5407** before statement S is ever evaluated, after
5408** one or more calls to [sqlite3_reset()], or after any call
5409** to [sqlite3_step()] regardless of whether or not the statement has
5410** completed execution.
5411**
5412** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
5413**
5414** The application must finalize every [prepared statement] in order to avoid
5415** resource leaks. It is a grievous error for the application to try to use
5416** a prepared statement after it has been finalized. Any use of a prepared
5417** statement after it has been finalized can result in undefined and
5418** undesirable behavior such as segfaults and heap corruption.
5419*/
5420SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
5421
5422/*
5423** CAPI3REF: Reset A Prepared Statement Object
5424** METHOD: sqlite3_stmt
5425**
5426** The sqlite3_reset() function is called to reset a [prepared statement]
5427** object back to its initial state, ready to be re-executed.
5428** ^Any SQL statement variables that had values bound to them using
5429** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
5430** Use [sqlite3_clear_bindings()] to reset the bindings.
5431**
5432** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
5433** back to the beginning of its program.
5434**
5435** ^If the most recent call to [sqlite3_step(S)] for the
5436** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
5437** or if [sqlite3_step(S)] has never before been called on S,
5438** then [sqlite3_reset(S)] returns [SQLITE_OK].
5439**
5440** ^If the most recent call to [sqlite3_step(S)] for the
5441** [prepared statement] S indicated an error, then
5442** [sqlite3_reset(S)] returns an appropriate [error code].
5443**
5444** ^The [sqlite3_reset(S)] interface does not change the values
5445** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
5446*/
5447SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
5448
5449/*
5450** CAPI3REF: Create Or Redefine SQL Functions
5451** KEYWORDS: {function creation routines}
5452** METHOD: sqlite3
5453**
5454** ^These functions (collectively known as "function creation routines")
5455** are used to add SQL functions or aggregates or to redefine the behavior
5456** of existing SQL functions or aggregates. The only differences between
5457** the three "sqlite3_create_function*" routines are the text encoding
5458** expected for the second parameter (the name of the function being
5459** created) and the presence or absence of a destructor callback for
5460** the application data pointer. Function sqlite3_create_window_function()
5461** is similar, but allows the user to supply the extra callback functions
5462** needed by [aggregate window functions].
5463**
5464** ^The first parameter is the [database connection] to which the SQL
5465** function is to be added. ^If an application uses more than one database
5466** connection then application-defined SQL functions must be added
5467** to each database connection separately.
5468**
5469** ^The second parameter is the name of the SQL function to be created or
5470** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
5471** representation, exclusive of the zero-terminator. ^Note that the name
5472** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
5473** ^Any attempt to create a function with a longer name
5474** will result in [SQLITE_MISUSE] being returned.
5475**
5476** ^The third parameter (nArg)
5477** is the number of arguments that the SQL function or
5478** aggregate takes. ^If this parameter is -1, then the SQL function or
5479** aggregate may take any number of arguments between 0 and the limit
5480** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
5481** parameter is less than -1 or greater than 127 then the behavior is
5482** undefined.
5483**
5484** ^The fourth parameter, eTextRep, specifies what
5485** [SQLITE_UTF8 | text encoding] this SQL function prefers for
5486** its parameters. The application should set this parameter to
5487** [SQLITE_UTF16LE] if the function implementation invokes
5488** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
5489** implementation invokes [sqlite3_value_text16be()] on an input, or
5490** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
5491** otherwise. ^The same SQL function may be registered multiple times using
5492** different preferred text encodings, with different implementations for
5493** each encoding.
5494** ^When multiple implementations of the same function are available, SQLite
5495** will pick the one that involves the least amount of data conversion.
5496**
5497** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
5498** to signal that the function will always return the same result given
5499** the same inputs within a single SQL statement. Most SQL functions are
5500** deterministic. The built-in [random()] SQL function is an example of a
5501** function that is not deterministic. The SQLite query planner is able to
5502** perform additional optimizations on deterministic functions, so use
5503** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
5504**
5505** ^The fourth parameter may also optionally include the [SQLITE_DIRECTONLY]
5506** flag, which if present prevents the function from being invoked from
5507** within VIEWs, TRIGGERs, CHECK constraints, generated column expressions,
5508** index expressions, or the WHERE clause of partial indexes.
5509**
5510** For best security, the [SQLITE_DIRECTONLY] flag is recommended for
5511** all application-defined SQL functions that do not need to be
5512** used inside of triggers, view, CHECK constraints, or other elements of
5513** the database schema. This flags is especially recommended for SQL
5514** functions that have side effects or reveal internal application state.
5515** Without this flag, an attacker might be able to modify the schema of
5516** a database file to include invocations of the function with parameters
5517** chosen by the attacker, which the application will then execute when
5518** the database file is opened and read.
5519**
5520** ^(The fifth parameter is an arbitrary pointer. The implementation of the
5521** function can gain access to this pointer using [sqlite3_user_data()].)^
5522**
5523** ^The sixth, seventh and eighth parameters passed to the three
5524** "sqlite3_create_function*" functions, xFunc, xStep and xFinal, are
5525** pointers to C-language functions that implement the SQL function or
5526** aggregate. ^A scalar SQL function requires an implementation of the xFunc
5527** callback only; NULL pointers must be passed as the xStep and xFinal
5528** parameters. ^An aggregate SQL function requires an implementation of xStep
5529** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
5530** SQL function or aggregate, pass NULL pointers for all three function
5531** callbacks.
5532**
5533** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue
5534** and xInverse) passed to sqlite3_create_window_function are pointers to
5535** C-language callbacks that implement the new function. xStep and xFinal
5536** must both be non-NULL. xValue and xInverse may either both be NULL, in
5537** which case a regular aggregate function is created, or must both be
5538** non-NULL, in which case the new function may be used as either an aggregate
5539** or aggregate window function. More details regarding the implementation
5540** of aggregate window functions are
5541** [user-defined window functions|available here].
5542**
5543** ^(If the final parameter to sqlite3_create_function_v2() or
5544** sqlite3_create_window_function() is not NULL, then it is destructor for
5545** the application data pointer. The destructor is invoked when the function
5546** is deleted, either by being overloaded or when the database connection
5547** closes.)^ ^The destructor is also invoked if the call to
5548** sqlite3_create_function_v2() fails. ^When the destructor callback is
5549** invoked, it is passed a single argument which is a copy of the application
5550** data pointer which was the fifth parameter to sqlite3_create_function_v2().
5551**
5552** ^It is permitted to register multiple implementations of the same
5553** functions with the same name but with either differing numbers of
5554** arguments or differing preferred text encodings. ^SQLite will use
5555** the implementation that most closely matches the way in which the
5556** SQL function is used. ^A function implementation with a non-negative
5557** nArg parameter is a better match than a function implementation with
5558** a negative nArg. ^A function where the preferred text encoding
5559** matches the database encoding is a better
5560** match than a function where the encoding is different.
5561** ^A function where the encoding difference is between UTF16le and UTF16be
5562** is a closer match than a function where the encoding difference is
5563** between UTF8 and UTF16.
5564**
5565** ^Built-in functions may be overloaded by new application-defined functions.
5566**
5567** ^An application-defined function is permitted to call other
5568** SQLite interfaces. However, such calls must not
5569** close the database connection nor finalize or reset the prepared
5570** statement in which the function is running.
5571*/
5572SQLITE_API int sqlite3_create_function(
5573 sqlite3 *db,
5574 const char *zFunctionName,
5575 int nArg,
5576 int eTextRep,
5577 void *pApp,
5578 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
5579 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
5580 void (*xFinal)(sqlite3_context*)
5581);
5582SQLITE_API int sqlite3_create_function16(
5583 sqlite3 *db,
5584 const void *zFunctionName,
5585 int nArg,
5586 int eTextRep,
5587 void *pApp,
5588 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
5589 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
5590 void (*xFinal)(sqlite3_context*)
5591);
5592SQLITE_API int sqlite3_create_function_v2(
5593 sqlite3 *db,
5594 const char *zFunctionName,
5595 int nArg,
5596 int eTextRep,
5597 void *pApp,
5598 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
5599 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
5600 void (*xFinal)(sqlite3_context*),
5601 void(*xDestroy)(void*)
5602);
5603SQLITE_API int sqlite3_create_window_function(
5604 sqlite3 *db,
5605 const char *zFunctionName,
5606 int nArg,
5607 int eTextRep,
5608 void *pApp,
5609 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
5610 void (*xFinal)(sqlite3_context*),
5611 void (*xValue)(sqlite3_context*),
5612 void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
5613 void(*xDestroy)(void*)
5614);
5615
5616/*
5617** CAPI3REF: Text Encodings
5618**
5619** These constant define integer codes that represent the various
5620** text encodings supported by SQLite.
5621*/
5622#define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
5623#define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
5624#define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
5625#define SQLITE_UTF16 4 /* Use native byte order */
5626#define SQLITE_ANY 5 /* Deprecated */
5627#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
5628
5629/*
5630** CAPI3REF: Function Flags
5631**
5632** These constants may be ORed together with the
5633** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
5634** to [sqlite3_create_function()], [sqlite3_create_function16()], or
5635** [sqlite3_create_function_v2()].
5636**
5637** <dl>
5638** [[SQLITE_DETERMINISTIC]] <dt>SQLITE_DETERMINISTIC</dt><dd>
5639** The SQLITE_DETERMINISTIC flag means that the new function always gives
5640** the same output when the input parameters are the same.
5641** The [abs|abs() function] is deterministic, for example, but
5642** [randomblob|randomblob()] is not. Functions must
5643** be deterministic in order to be used in certain contexts such as
5644** with the WHERE clause of [partial indexes] or in [generated columns].
5645** SQLite might also optimize deterministic functions by factoring them
5646** out of inner loops.
5647** </dd>
5648**
5649** [[SQLITE_DIRECTONLY]] <dt>SQLITE_DIRECTONLY</dt><dd>
5650** The SQLITE_DIRECTONLY flag means that the function may only be invoked
5651** from top-level SQL, and cannot be used in VIEWs or TRIGGERs nor in
5652** schema structures such as [CHECK constraints], [DEFAULT clauses],
5653** [expression indexes], [partial indexes], or [generated columns].
5654** The SQLITE_DIRECTONLY flags is a security feature which is recommended
5655** for all [application-defined SQL functions], and especially for functions
5656** that have side-effects or that could potentially leak sensitive
5657** information.
5658** </dd>
5659**
5660** [[SQLITE_INNOCUOUS]] <dt>SQLITE_INNOCUOUS</dt><dd>
5661** The SQLITE_INNOCUOUS flag means that the function is unlikely
5662** to cause problems even if misused. An innocuous function should have
5663** no side effects and should not depend on any values other than its
5664** input parameters. The [abs|abs() function] is an example of an
5665** innocuous function.
5666** The [load_extension() SQL function] is not innocuous because of its
5667** side effects.
5668** <p> SQLITE_INNOCUOUS is similar to SQLITE_DETERMINISTIC, but is not
5669** exactly the same. The [random|random() function] is an example of a
5670** function that is innocuous but not deterministic.
5671** <p>Some heightened security settings
5672** ([SQLITE_DBCONFIG_TRUSTED_SCHEMA] and [PRAGMA trusted_schema=OFF])
5673** disable the use of SQL functions inside views and triggers and in
5674** schema structures such as [CHECK constraints], [DEFAULT clauses],
5675** [expression indexes], [partial indexes], and [generated columns] unless
5676** the function is tagged with SQLITE_INNOCUOUS. Most built-in functions
5677** are innocuous. Developers are advised to avoid using the
5678** SQLITE_INNOCUOUS flag for application-defined functions unless the
5679** function has been carefully audited and found to be free of potentially
5680** security-adverse side-effects and information-leaks.
5681** </dd>
5682**
5683** [[SQLITE_SUBTYPE]] <dt>SQLITE_SUBTYPE</dt><dd>
5684** The SQLITE_SUBTYPE flag indicates to SQLite that a function may call
5685** [sqlite3_value_subtype()] to inspect the sub-types of its arguments.
5686** Specifying this flag makes no difference for scalar or aggregate user
5687** functions. However, if it is not specified for a user-defined window
5688** function, then any sub-types belonging to arguments passed to the window
5689** function may be discarded before the window function is called (i.e.
5690** sqlite3_value_subtype() will always return 0).
5691** </dd>
5692** </dl>
5693*/
5694#define SQLITE_DETERMINISTIC 0x000000800
5695#define SQLITE_DIRECTONLY 0x000080000
5696#define SQLITE_SUBTYPE 0x000100000
5697#define SQLITE_INNOCUOUS 0x000200000
5698
5699/*
5700** CAPI3REF: Deprecated Functions
5701** DEPRECATED
5702**
5703** These functions are [deprecated]. In order to maintain
5704** backwards compatibility with older code, these functions continue
5705** to be supported. However, new applications should avoid
5706** the use of these functions. To encourage programmers to avoid
5707** these functions, we will not explain what they do.
5708*/
5709#ifndef SQLITE_OMIT_DEPRECATED
5710SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
5711SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
5712SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
5713SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
5714SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
5715SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
5716 void*,sqlite3_int64);
5717#endif
5718
5719/*
5720** CAPI3REF: Obtaining SQL Values
5721** METHOD: sqlite3_value
5722**
5723** <b>Summary:</b>
5724** <blockquote><table border=0 cellpadding=0 cellspacing=0>
5725** <tr><td><b>sqlite3_value_blob</b><td>&rarr;<td>BLOB value
5726** <tr><td><b>sqlite3_value_double</b><td>&rarr;<td>REAL value
5727** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value
5728** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value
5729** <tr><td><b>sqlite3_value_pointer</b><td>&rarr;<td>Pointer value
5730** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value
5731** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in
5732** the native byteorder
5733** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value
5734** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value
5735** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
5736** <tr><td><b>sqlite3_value_bytes</b><td>&rarr;<td>Size of a BLOB
5737** or a UTF-8 TEXT in bytes
5738** <tr><td><b>sqlite3_value_bytes16&nbsp;&nbsp;</b>
5739** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
5740** TEXT in bytes
5741** <tr><td><b>sqlite3_value_type</b><td>&rarr;<td>Default
5742** datatype of the value
5743** <tr><td><b>sqlite3_value_numeric_type&nbsp;&nbsp;</b>
5744** <td>&rarr;&nbsp;&nbsp;<td>Best numeric datatype of the value
5745** <tr><td><b>sqlite3_value_nochange&nbsp;&nbsp;</b>
5746** <td>&rarr;&nbsp;&nbsp;<td>True if the column is unchanged in an UPDATE
5747** against a virtual table.
5748** <tr><td><b>sqlite3_value_frombind&nbsp;&nbsp;</b>
5749** <td>&rarr;&nbsp;&nbsp;<td>True if value originated from a [bound parameter]
5750** </table></blockquote>
5751**
5752** <b>Details:</b>
5753**
5754** These routines extract type, size, and content information from
5755** [protected sqlite3_value] objects. Protected sqlite3_value objects
5756** are used to pass parameter information into the functions that
5757** implement [application-defined SQL functions] and [virtual tables].
5758**
5759** These routines work only with [protected sqlite3_value] objects.
5760** Any attempt to use these routines on an [unprotected sqlite3_value]
5761** is not threadsafe.
5762**
5763** ^These routines work just like the corresponding [column access functions]
5764** except that these routines take a single [protected sqlite3_value] object
5765** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
5766**
5767** ^The sqlite3_value_text16() interface extracts a UTF-16 string
5768** in the native byte-order of the host machine. ^The
5769** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
5770** extract UTF-16 strings as big-endian and little-endian respectively.
5771**
5772** ^If [sqlite3_value] object V was initialized
5773** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]
5774** and if X and Y are strings that compare equal according to strcmp(X,Y),
5775** then sqlite3_value_pointer(V,Y) will return the pointer P. ^Otherwise,
5776** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer()
5777** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
5778**
5779** ^(The sqlite3_value_type(V) interface returns the
5780** [SQLITE_INTEGER | datatype code] for the initial datatype of the
5781** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],
5782** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^
5783** Other interfaces might change the datatype for an sqlite3_value object.
5784** For example, if the datatype is initially SQLITE_INTEGER and
5785** sqlite3_value_text(V) is called to extract a text value for that
5786** integer, then subsequent calls to sqlite3_value_type(V) might return
5787** SQLITE_TEXT. Whether or not a persistent internal datatype conversion
5788** occurs is undefined and may change from one release of SQLite to the next.
5789**
5790** ^(The sqlite3_value_numeric_type() interface attempts to apply
5791** numeric affinity to the value. This means that an attempt is
5792** made to convert the value to an integer or floating point. If
5793** such a conversion is possible without loss of information (in other
5794** words, if the value is a string that looks like a number)
5795** then the conversion is performed. Otherwise no conversion occurs.
5796** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
5797**
5798** ^Within the [xUpdate] method of a [virtual table], the
5799** sqlite3_value_nochange(X) interface returns true if and only if
5800** the column corresponding to X is unchanged by the UPDATE operation
5801** that the xUpdate method call was invoked to implement and if
5802** and the prior [xColumn] method call that was invoked to extracted
5803** the value for that column returned without setting a result (probably
5804** because it queried [sqlite3_vtab_nochange()] and found that the column
5805** was unchanging). ^Within an [xUpdate] method, any value for which
5806** sqlite3_value_nochange(X) is true will in all other respects appear
5807** to be a NULL value. If sqlite3_value_nochange(X) is invoked anywhere other
5808** than within an [xUpdate] method call for an UPDATE statement, then
5809** the return value is arbitrary and meaningless.
5810**
5811** ^The sqlite3_value_frombind(X) interface returns non-zero if the
5812** value X originated from one of the [sqlite3_bind_int|sqlite3_bind()]
5813** interfaces. ^If X comes from an SQL literal value, or a table column,
5814** or an expression, then sqlite3_value_frombind(X) returns zero.
5815**
5816** Please pay particular attention to the fact that the pointer returned
5817** from [sqlite3_value_blob()], [sqlite3_value_text()], or
5818** [sqlite3_value_text16()] can be invalidated by a subsequent call to
5819** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
5820** or [sqlite3_value_text16()].
5821**
5822** These routines must be called from the same thread as
5823** the SQL function that supplied the [sqlite3_value*] parameters.
5824**
5825** As long as the input parameter is correct, these routines can only
5826** fail if an out-of-memory error occurs during a format conversion.
5827** Only the following subset of interfaces are subject to out-of-memory
5828** errors:
5829**
5830** <ul>
5831** <li> sqlite3_value_blob()
5832** <li> sqlite3_value_text()
5833** <li> sqlite3_value_text16()
5834** <li> sqlite3_value_text16le()
5835** <li> sqlite3_value_text16be()
5836** <li> sqlite3_value_bytes()
5837** <li> sqlite3_value_bytes16()
5838** </ul>
5839**
5840** If an out-of-memory error occurs, then the return value from these
5841** routines is the same as if the column had contained an SQL NULL value.
5842** Valid SQL NULL returns can be distinguished from out-of-memory errors
5843** by invoking the [sqlite3_errcode()] immediately after the suspect
5844** return value is obtained and before any
5845** other SQLite interface is called on the same [database connection].
5846*/
5847SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
5848SQLITE_API double sqlite3_value_double(sqlite3_value*);
5849SQLITE_API int sqlite3_value_int(sqlite3_value*);
5850SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
5851SQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*);
5852SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
5853SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
5854SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
5855SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
5856SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
5857SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
5858SQLITE_API int sqlite3_value_type(sqlite3_value*);
5859SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
5860SQLITE_API int sqlite3_value_nochange(sqlite3_value*);
5861SQLITE_API int sqlite3_value_frombind(sqlite3_value*);
5862
5863/*
5864** CAPI3REF: Finding The Subtype Of SQL Values
5865** METHOD: sqlite3_value
5866**
5867** The sqlite3_value_subtype(V) function returns the subtype for
5868** an [application-defined SQL function] argument V. The subtype
5869** information can be used to pass a limited amount of context from
5870** one SQL function to another. Use the [sqlite3_result_subtype()]
5871** routine to set the subtype for the return value of an SQL function.
5872*/
5873SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
5874
5875/*
5876** CAPI3REF: Copy And Free SQL Values
5877** METHOD: sqlite3_value
5878**
5879** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
5880** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
5881** is a [protected sqlite3_value] object even if the input is not.
5882** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
5883** memory allocation fails.
5884**
5885** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
5886** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
5887** then sqlite3_value_free(V) is a harmless no-op.
5888*/
5889SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
5890SQLITE_API void sqlite3_value_free(sqlite3_value*);
5891
5892/*
5893** CAPI3REF: Obtain Aggregate Function Context
5894** METHOD: sqlite3_context
5895**
5896** Implementations of aggregate SQL functions use this
5897** routine to allocate memory for storing their state.
5898**
5899** ^The first time the sqlite3_aggregate_context(C,N) routine is called
5900** for a particular aggregate function, SQLite allocates
5901** N bytes of memory, zeroes out that memory, and returns a pointer
5902** to the new memory. ^On second and subsequent calls to
5903** sqlite3_aggregate_context() for the same aggregate function instance,
5904** the same buffer is returned. Sqlite3_aggregate_context() is normally
5905** called once for each invocation of the xStep callback and then one
5906** last time when the xFinal callback is invoked. ^(When no rows match
5907** an aggregate query, the xStep() callback of the aggregate function
5908** implementation is never called and xFinal() is called exactly once.
5909** In those cases, sqlite3_aggregate_context() might be called for the
5910** first time from within xFinal().)^
5911**
5912** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
5913** when first called if N is less than or equal to zero or if a memory
5914** allocate error occurs.
5915**
5916** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
5917** determined by the N parameter on first successful call. Changing the
5918** value of N in any subsequent call to sqlite3_aggregate_context() within
5919** the same aggregate function instance will not resize the memory
5920** allocation.)^ Within the xFinal callback, it is customary to set
5921** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
5922** pointless memory allocations occur.
5923**
5924** ^SQLite automatically frees the memory allocated by
5925** sqlite3_aggregate_context() when the aggregate query concludes.
5926**
5927** The first parameter must be a copy of the
5928** [sqlite3_context | SQL function context] that is the first parameter
5929** to the xStep or xFinal callback routine that implements the aggregate
5930** function.
5931**
5932** This routine must be called from the same thread in which
5933** the aggregate SQL function is running.
5934*/
5935SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
5936
5937/*
5938** CAPI3REF: User Data For Functions
5939** METHOD: sqlite3_context
5940**
5941** ^The sqlite3_user_data() interface returns a copy of
5942** the pointer that was the pUserData parameter (the 5th parameter)
5943** of the [sqlite3_create_function()]
5944** and [sqlite3_create_function16()] routines that originally
5945** registered the application defined function.
5946**
5947** This routine must be called from the same thread in which
5948** the application-defined function is running.
5949*/
5950SQLITE_API void *sqlite3_user_data(sqlite3_context*);
5951
5952/*
5953** CAPI3REF: Database Connection For Functions
5954** METHOD: sqlite3_context
5955**
5956** ^The sqlite3_context_db_handle() interface returns a copy of
5957** the pointer to the [database connection] (the 1st parameter)
5958** of the [sqlite3_create_function()]
5959** and [sqlite3_create_function16()] routines that originally
5960** registered the application defined function.
5961*/
5962SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
5963
5964/*
5965** CAPI3REF: Function Auxiliary Data
5966** METHOD: sqlite3_context
5967**
5968** These functions may be used by (non-aggregate) SQL functions to
5969** associate metadata with argument values. If the same value is passed to
5970** multiple invocations of the same SQL function during query execution, under
5971** some circumstances the associated metadata may be preserved. An example
5972** of where this might be useful is in a regular-expression matching
5973** function. The compiled version of the regular expression can be stored as
5974** metadata associated with the pattern string.
5975** Then as long as the pattern string remains the same,
5976** the compiled regular expression can be reused on multiple
5977** invocations of the same function.
5978**
5979** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata
5980** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
5981** value to the application-defined function. ^N is zero for the left-most
5982** function argument. ^If there is no metadata
5983** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
5984** returns a NULL pointer.
5985**
5986** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
5987** argument of the application-defined function. ^Subsequent
5988** calls to sqlite3_get_auxdata(C,N) return P from the most recent
5989** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
5990** NULL if the metadata has been discarded.
5991** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
5992** SQLite will invoke the destructor function X with parameter P exactly
5993** once, when the metadata is discarded.
5994** SQLite is free to discard the metadata at any time, including: <ul>
5995** <li> ^(when the corresponding function parameter changes)^, or
5996** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
5997** SQL statement)^, or
5998** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
5999** parameter)^, or
6000** <li> ^(during the original sqlite3_set_auxdata() call when a memory
6001** allocation error occurs.)^ </ul>
6002**
6003** Note the last bullet in particular. The destructor X in
6004** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
6005** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
6006** should be called near the end of the function implementation and the
6007** function implementation should not make any use of P after
6008** sqlite3_set_auxdata() has been called.
6009**
6010** ^(In practice, metadata is preserved between function calls for
6011** function parameters that are compile-time constants, including literal
6012** values and [parameters] and expressions composed from the same.)^
6013**
6014** The value of the N parameter to these interfaces should be non-negative.
6015** Future enhancements may make use of negative N values to define new
6016** kinds of function caching behavior.
6017**
6018** These routines must be called from the same thread in which
6019** the SQL function is running.
6020*/
6021SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
6022SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
6023
6024
6025/*
6026** CAPI3REF: Constants Defining Special Destructor Behavior
6027**
6028** These are special values for the destructor that is passed in as the
6029** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
6030** argument is SQLITE_STATIC, it means that the content pointer is constant
6031** and will never change. It does not need to be destroyed. ^The
6032** SQLITE_TRANSIENT value means that the content will likely change in
6033** the near future and that SQLite should make its own private copy of
6034** the content before returning.
6035**
6036** The typedef is necessary to work around problems in certain
6037** C++ compilers.
6038*/
6039typedef void (*sqlite3_destructor_type)(void*);
6040#define SQLITE_STATIC ((sqlite3_destructor_type)0)
6041#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
6042
6043/*
6044** CAPI3REF: Setting The Result Of An SQL Function
6045** METHOD: sqlite3_context
6046**
6047** These routines are used by the xFunc or xFinal callbacks that
6048** implement SQL functions and aggregates. See
6049** [sqlite3_create_function()] and [sqlite3_create_function16()]
6050** for additional information.
6051**
6052** These functions work very much like the [parameter binding] family of
6053** functions used to bind values to host parameters in prepared statements.
6054** Refer to the [SQL parameter] documentation for additional information.
6055**
6056** ^The sqlite3_result_blob() interface sets the result from
6057** an application-defined function to be the BLOB whose content is pointed
6058** to by the second parameter and which is N bytes long where N is the
6059** third parameter.
6060**
6061** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
6062** interfaces set the result of the application-defined function to be
6063** a BLOB containing all zero bytes and N bytes in size.
6064**
6065** ^The sqlite3_result_double() interface sets the result from
6066** an application-defined function to be a floating point value specified
6067** by its 2nd argument.
6068**
6069** ^The sqlite3_result_error() and sqlite3_result_error16() functions
6070** cause the implemented SQL function to throw an exception.
6071** ^SQLite uses the string pointed to by the
6072** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
6073** as the text of an error message. ^SQLite interprets the error
6074** message string from sqlite3_result_error() as UTF-8. ^SQLite
6075** interprets the string from sqlite3_result_error16() as UTF-16 using
6076** the same [byte-order determination rules] as [sqlite3_bind_text16()].
6077** ^If the third parameter to sqlite3_result_error()
6078** or sqlite3_result_error16() is negative then SQLite takes as the error
6079** message all text up through the first zero character.
6080** ^If the third parameter to sqlite3_result_error() or
6081** sqlite3_result_error16() is non-negative then SQLite takes that many
6082** bytes (not characters) from the 2nd parameter as the error message.
6083** ^The sqlite3_result_error() and sqlite3_result_error16()
6084** routines make a private copy of the error message text before
6085** they return. Hence, the calling function can deallocate or
6086** modify the text after they return without harm.
6087** ^The sqlite3_result_error_code() function changes the error code
6088** returned by SQLite as a result of an error in a function. ^By default,
6089** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
6090** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
6091**
6092** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
6093** error indicating that a string or BLOB is too long to represent.
6094**
6095** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
6096** error indicating that a memory allocation failed.
6097**
6098** ^The sqlite3_result_int() interface sets the return value
6099** of the application-defined function to be the 32-bit signed integer
6100** value given in the 2nd argument.
6101** ^The sqlite3_result_int64() interface sets the return value
6102** of the application-defined function to be the 64-bit signed integer
6103** value given in the 2nd argument.
6104**
6105** ^The sqlite3_result_null() interface sets the return value
6106** of the application-defined function to be NULL.
6107**
6108** ^The sqlite3_result_text(), sqlite3_result_text16(),
6109** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
6110** set the return value of the application-defined function to be
6111** a text string which is represented as UTF-8, UTF-16 native byte order,
6112** UTF-16 little endian, or UTF-16 big endian, respectively.
6113** ^The sqlite3_result_text64() interface sets the return value of an
6114** application-defined function to be a text string in an encoding
6115** specified by the fifth (and last) parameter, which must be one
6116** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
6117** ^SQLite takes the text result from the application from
6118** the 2nd parameter of the sqlite3_result_text* interfaces.
6119** ^If the 3rd parameter to the sqlite3_result_text* interfaces
6120** is negative, then SQLite takes result text from the 2nd parameter
6121** through the first zero character.
6122** ^If the 3rd parameter to the sqlite3_result_text* interfaces
6123** is non-negative, then as many bytes (not characters) of the text
6124** pointed to by the 2nd parameter are taken as the application-defined
6125** function result. If the 3rd parameter is non-negative, then it
6126** must be the byte offset into the string where the NUL terminator would
6127** appear if the string where NUL terminated. If any NUL characters occur
6128** in the string at a byte offset that is less than the value of the 3rd
6129** parameter, then the resulting string will contain embedded NULs and the
6130** result of expressions operating on strings with embedded NULs is undefined.
6131** ^If the 4th parameter to the sqlite3_result_text* interfaces
6132** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
6133** function as the destructor on the text or BLOB result when it has
6134** finished using that result.
6135** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
6136** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
6137** assumes that the text or BLOB result is in constant space and does not
6138** copy the content of the parameter nor call a destructor on the content
6139** when it has finished using that result.
6140** ^If the 4th parameter to the sqlite3_result_text* interfaces
6141** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
6142** then SQLite makes a copy of the result into space obtained
6143** from [sqlite3_malloc()] before it returns.
6144**
6145** ^For the sqlite3_result_text16(), sqlite3_result_text16le(), and
6146** sqlite3_result_text16be() routines, and for sqlite3_result_text64()
6147** when the encoding is not UTF8, if the input UTF16 begins with a
6148** byte-order mark (BOM, U+FEFF) then the BOM is removed from the
6149** string and the rest of the string is interpreted according to the
6150** byte-order specified by the BOM. ^The byte-order specified by
6151** the BOM at the beginning of the text overrides the byte-order
6152** specified by the interface procedure. ^So, for example, if
6153** sqlite3_result_text16le() is invoked with text that begins
6154** with bytes 0xfe, 0xff (a big-endian byte-order mark) then the
6155** first two bytes of input are skipped and the remaining input
6156** is interpreted as UTF16BE text.
6157**
6158** ^For UTF16 input text to the sqlite3_result_text16(),
6159** sqlite3_result_text16be(), sqlite3_result_text16le(), and
6160** sqlite3_result_text64() routines, if the text contains invalid
6161** UTF16 characters, the invalid characters might be converted
6162** into the unicode replacement character, U+FFFD.
6163**
6164** ^The sqlite3_result_value() interface sets the result of
6165** the application-defined function to be a copy of the
6166** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
6167** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
6168** so that the [sqlite3_value] specified in the parameter may change or
6169** be deallocated after sqlite3_result_value() returns without harm.
6170** ^A [protected sqlite3_value] object may always be used where an
6171** [unprotected sqlite3_value] object is required, so either
6172** kind of [sqlite3_value] object can be used with this interface.
6173**
6174** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
6175** SQL NULL value, just like [sqlite3_result_null(C)], except that it
6176** also associates the host-language pointer P or type T with that
6177** NULL value such that the pointer can be retrieved within an
6178** [application-defined SQL function] using [sqlite3_value_pointer()].
6179** ^If the D parameter is not NULL, then it is a pointer to a destructor
6180** for the P parameter. ^SQLite invokes D with P as its only argument
6181** when SQLite is finished with P. The T parameter should be a static
6182** string and preferably a string literal. The sqlite3_result_pointer()
6183** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
6184**
6185** If these routines are called from within the different thread
6186** than the one containing the application-defined function that received
6187** the [sqlite3_context] pointer, the results are undefined.
6188*/
6189SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
6190SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
6191 sqlite3_uint64,void(*)(void*));
6192SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
6193SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
6194SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
6195SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
6196SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
6197SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
6198SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
6199SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
6200SQLITE_API void sqlite3_result_null(sqlite3_context*);
6201SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
6202SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
6203 void(*)(void*), unsigned char encoding);
6204SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
6205SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
6206SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
6207SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
6208SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*));
6209SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
6210SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
6211
6212
6213/*
6214** CAPI3REF: Setting The Subtype Of An SQL Function
6215** METHOD: sqlite3_context
6216**
6217** The sqlite3_result_subtype(C,T) function causes the subtype of
6218** the result from the [application-defined SQL function] with
6219** [sqlite3_context] C to be the value T. Only the lower 8 bits
6220** of the subtype T are preserved in current versions of SQLite;
6221** higher order bits are discarded.
6222** The number of subtype bytes preserved by SQLite might increase
6223** in future releases of SQLite.
6224*/
6225SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
6226
6227/*
6228** CAPI3REF: Define New Collating Sequences
6229** METHOD: sqlite3
6230**
6231** ^These functions add, remove, or modify a [collation] associated
6232** with the [database connection] specified as the first argument.
6233**
6234** ^The name of the collation is a UTF-8 string
6235** for sqlite3_create_collation() and sqlite3_create_collation_v2()
6236** and a UTF-16 string in native byte order for sqlite3_create_collation16().
6237** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
6238** considered to be the same name.
6239**
6240** ^(The third argument (eTextRep) must be one of the constants:
6241** <ul>
6242** <li> [SQLITE_UTF8],
6243** <li> [SQLITE_UTF16LE],
6244** <li> [SQLITE_UTF16BE],
6245** <li> [SQLITE_UTF16], or
6246** <li> [SQLITE_UTF16_ALIGNED].
6247** </ul>)^
6248** ^The eTextRep argument determines the encoding of strings passed
6249** to the collating function callback, xCompare.
6250** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
6251** force strings to be UTF16 with native byte order.
6252** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
6253** on an even byte address.
6254**
6255** ^The fourth argument, pArg, is an application data pointer that is passed
6256** through as the first argument to the collating function callback.
6257**
6258** ^The fifth argument, xCompare, is a pointer to the collating function.
6259** ^Multiple collating functions can be registered using the same name but
6260** with different eTextRep parameters and SQLite will use whichever
6261** function requires the least amount of data transformation.
6262** ^If the xCompare argument is NULL then the collating function is
6263** deleted. ^When all collating functions having the same name are deleted,
6264** that collation is no longer usable.
6265**
6266** ^The collating function callback is invoked with a copy of the pArg
6267** application data pointer and with two strings in the encoding specified
6268** by the eTextRep argument. The two integer parameters to the collating
6269** function callback are the length of the two strings, in bytes. The collating
6270** function must return an integer that is negative, zero, or positive
6271** if the first string is less than, equal to, or greater than the second,
6272** respectively. A collating function must always return the same answer
6273** given the same inputs. If two or more collating functions are registered
6274** to the same collation name (using different eTextRep values) then all
6275** must give an equivalent answer when invoked with equivalent strings.
6276** The collating function must obey the following properties for all
6277** strings A, B, and C:
6278**
6279** <ol>
6280** <li> If A==B then B==A.
6281** <li> If A==B and B==C then A==C.
6282** <li> If A&lt;B THEN B&gt;A.
6283** <li> If A&lt;B and B&lt;C then A&lt;C.
6284** </ol>
6285**
6286** If a collating function fails any of the above constraints and that
6287** collating function is registered and used, then the behavior of SQLite
6288** is undefined.
6289**
6290** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
6291** with the addition that the xDestroy callback is invoked on pArg when
6292** the collating function is deleted.
6293** ^Collating functions are deleted when they are overridden by later
6294** calls to the collation creation functions or when the
6295** [database connection] is closed using [sqlite3_close()].
6296**
6297** ^The xDestroy callback is <u>not</u> called if the
6298** sqlite3_create_collation_v2() function fails. Applications that invoke
6299** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
6300** check the return code and dispose of the application data pointer
6301** themselves rather than expecting SQLite to deal with it for them.
6302** This is different from every other SQLite interface. The inconsistency
6303** is unfortunate but cannot be changed without breaking backwards
6304** compatibility.
6305**
6306** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
6307*/
6308SQLITE_API int sqlite3_create_collation(
6309 sqlite3*,
6310 const char *zName,
6311 int eTextRep,
6312 void *pArg,
6313 int(*xCompare)(void*,int,const void*,int,const void*)
6314);
6315SQLITE_API int sqlite3_create_collation_v2(
6316 sqlite3*,
6317 const char *zName,
6318 int eTextRep,
6319 void *pArg,
6320 int(*xCompare)(void*,int,const void*,int,const void*),
6321 void(*xDestroy)(void*)
6322);
6323SQLITE_API int sqlite3_create_collation16(
6324 sqlite3*,
6325 const void *zName,
6326 int eTextRep,
6327 void *pArg,
6328 int(*xCompare)(void*,int,const void*,int,const void*)
6329);
6330
6331/*
6332** CAPI3REF: Collation Needed Callbacks
6333** METHOD: sqlite3
6334**
6335** ^To avoid having to register all collation sequences before a database
6336** can be used, a single callback function may be registered with the
6337** [database connection] to be invoked whenever an undefined collation
6338** sequence is required.
6339**
6340** ^If the function is registered using the sqlite3_collation_needed() API,
6341** then it is passed the names of undefined collation sequences as strings
6342** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
6343** the names are passed as UTF-16 in machine native byte order.
6344** ^A call to either function replaces the existing collation-needed callback.
6345**
6346** ^(When the callback is invoked, the first argument passed is a copy
6347** of the second argument to sqlite3_collation_needed() or
6348** sqlite3_collation_needed16(). The second argument is the database
6349** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
6350** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
6351** sequence function required. The fourth parameter is the name of the
6352** required collation sequence.)^
6353**
6354** The callback function should register the desired collation using
6355** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
6356** [sqlite3_create_collation_v2()].
6357*/
6358SQLITE_API int sqlite3_collation_needed(
6359 sqlite3*,
6360 void*,
6361 void(*)(void*,sqlite3*,int eTextRep,const char*)
6362);
6363SQLITE_API int sqlite3_collation_needed16(
6364 sqlite3*,
6365 void*,
6366 void(*)(void*,sqlite3*,int eTextRep,const void*)
6367);
6368
6369#ifdef SQLITE_ENABLE_CEROD
6370/*
6371** Specify the activation key for a CEROD database. Unless
6372** activated, none of the CEROD routines will work.
6373*/
6374SQLITE_API void sqlite3_activate_cerod(
6375 const char *zPassPhrase /* Activation phrase */
6376);
6377#endif
6378
6379/*
6380** CAPI3REF: Suspend Execution For A Short Time
6381**
6382** The sqlite3_sleep() function causes the current thread to suspend execution
6383** for at least a number of milliseconds specified in its parameter.
6384**
6385** If the operating system does not support sleep requests with
6386** millisecond time resolution, then the time will be rounded up to
6387** the nearest second. The number of milliseconds of sleep actually
6388** requested from the operating system is returned.
6389**
6390** ^SQLite implements this interface by calling the xSleep()
6391** method of the default [sqlite3_vfs] object. If the xSleep() method
6392** of the default VFS is not implemented correctly, or not implemented at
6393** all, then the behavior of sqlite3_sleep() may deviate from the description
6394** in the previous paragraphs.
6395*/
6396SQLITE_API int sqlite3_sleep(int);
6397
6398/*
6399** CAPI3REF: Name Of The Folder Holding Temporary Files
6400**
6401** ^(If this global variable is made to point to a string which is
6402** the name of a folder (a.k.a. directory), then all temporary files
6403** created by SQLite when using a built-in [sqlite3_vfs | VFS]
6404** will be placed in that directory.)^ ^If this variable
6405** is a NULL pointer, then SQLite performs a search for an appropriate
6406** temporary file directory.
6407**
6408** Applications are strongly discouraged from using this global variable.
6409** It is required to set a temporary folder on Windows Runtime (WinRT).
6410** But for all other platforms, it is highly recommended that applications
6411** neither read nor write this variable. This global variable is a relic
6412** that exists for backwards compatibility of legacy applications and should
6413** be avoided in new projects.
6414**
6415** It is not safe to read or modify this variable in more than one
6416** thread at a time. It is not safe to read or modify this variable
6417** if a [database connection] is being used at the same time in a separate
6418** thread.
6419** It is intended that this variable be set once
6420** as part of process initialization and before any SQLite interface
6421** routines have been called and that this variable remain unchanged
6422** thereafter.
6423**
6424** ^The [temp_store_directory pragma] may modify this variable and cause
6425** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
6426** the [temp_store_directory pragma] always assumes that any string
6427** that this variable points to is held in memory obtained from
6428** [sqlite3_malloc] and the pragma may attempt to free that memory
6429** using [sqlite3_free].
6430** Hence, if this variable is modified directly, either it should be
6431** made NULL or made to point to memory obtained from [sqlite3_malloc]
6432** or else the use of the [temp_store_directory pragma] should be avoided.
6433** Except when requested by the [temp_store_directory pragma], SQLite
6434** does not free the memory that sqlite3_temp_directory points to. If
6435** the application wants that memory to be freed, it must do
6436** so itself, taking care to only do so after all [database connection]
6437** objects have been destroyed.
6438**
6439** <b>Note to Windows Runtime users:</b> The temporary directory must be set
6440** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
6441** features that require the use of temporary files may fail. Here is an
6442** example of how to do this using C++ with the Windows Runtime:
6443**
6444** <blockquote><pre>
6445** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
6446** &nbsp; TemporaryFolder->Path->Data();
6447** char zPathBuf&#91;MAX_PATH + 1&#93;;
6448** memset(zPathBuf, 0, sizeof(zPathBuf));
6449** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
6450** &nbsp; NULL, NULL);
6451** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
6452** </pre></blockquote>
6453*/
6454SQLITE_API char *sqlite3_temp_directory;
6455
6456/*
6457** CAPI3REF: Name Of The Folder Holding Database Files
6458**
6459** ^(If this global variable is made to point to a string which is
6460** the name of a folder (a.k.a. directory), then all database files
6461** specified with a relative pathname and created or accessed by
6462** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
6463** to be relative to that directory.)^ ^If this variable is a NULL
6464** pointer, then SQLite assumes that all database files specified
6465** with a relative pathname are relative to the current directory
6466** for the process. Only the windows VFS makes use of this global
6467** variable; it is ignored by the unix VFS.
6468**
6469** Changing the value of this variable while a database connection is
6470** open can result in a corrupt database.
6471**
6472** It is not safe to read or modify this variable in more than one
6473** thread at a time. It is not safe to read or modify this variable
6474** if a [database connection] is being used at the same time in a separate
6475** thread.
6476** It is intended that this variable be set once
6477** as part of process initialization and before any SQLite interface
6478** routines have been called and that this variable remain unchanged
6479** thereafter.
6480**
6481** ^The [data_store_directory pragma] may modify this variable and cause
6482** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
6483** the [data_store_directory pragma] always assumes that any string
6484** that this variable points to is held in memory obtained from
6485** [sqlite3_malloc] and the pragma may attempt to free that memory
6486** using [sqlite3_free].
6487** Hence, if this variable is modified directly, either it should be
6488** made NULL or made to point to memory obtained from [sqlite3_malloc]
6489** or else the use of the [data_store_directory pragma] should be avoided.
6490*/
6491SQLITE_API char *sqlite3_data_directory;
6492
6493/*
6494** CAPI3REF: Win32 Specific Interface
6495**
6496** These interfaces are available only on Windows. The
6497** [sqlite3_win32_set_directory] interface is used to set the value associated
6498** with the [sqlite3_temp_directory] or [sqlite3_data_directory] variable, to
6499** zValue, depending on the value of the type parameter. The zValue parameter
6500** should be NULL to cause the previous value to be freed via [sqlite3_free];
6501** a non-NULL value will be copied into memory obtained from [sqlite3_malloc]
6502** prior to being used. The [sqlite3_win32_set_directory] interface returns
6503** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported,
6504** or [SQLITE_NOMEM] if memory could not be allocated. The value of the
6505** [sqlite3_data_directory] variable is intended to act as a replacement for
6506** the current directory on the sub-platforms of Win32 where that concept is
6507** not present, e.g. WinRT and UWP. The [sqlite3_win32_set_directory8] and
6508** [sqlite3_win32_set_directory16] interfaces behave exactly the same as the
6509** sqlite3_win32_set_directory interface except the string parameter must be
6510** UTF-8 or UTF-16, respectively.
6511*/
6512SQLITE_API int sqlite3_win32_set_directory(
6513 unsigned long type, /* Identifier for directory being set or reset */
6514 void *zValue /* New value for directory being set or reset */
6515);
6516SQLITE_API int sqlite3_win32_set_directory8(unsigned long type, const char *zValue);
6517SQLITE_API int sqlite3_win32_set_directory16(unsigned long type, const void *zValue);
6518
6519/*
6520** CAPI3REF: Win32 Directory Types
6521**
6522** These macros are only available on Windows. They define the allowed values
6523** for the type argument to the [sqlite3_win32_set_directory] interface.
6524*/
6525#define SQLITE_WIN32_DATA_DIRECTORY_TYPE 1
6526#define SQLITE_WIN32_TEMP_DIRECTORY_TYPE 2
6527
6528/*
6529** CAPI3REF: Test For Auto-Commit Mode
6530** KEYWORDS: {autocommit mode}
6531** METHOD: sqlite3
6532**
6533** ^The sqlite3_get_autocommit() interface returns non-zero or
6534** zero if the given database connection is or is not in autocommit mode,
6535** respectively. ^Autocommit mode is on by default.
6536** ^Autocommit mode is disabled by a [BEGIN] statement.
6537** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
6538**
6539** If certain kinds of errors occur on a statement within a multi-statement
6540** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
6541** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
6542** transaction might be rolled back automatically. The only way to
6543** find out whether SQLite automatically rolled back the transaction after
6544** an error is to use this function.
6545**
6546** If another thread changes the autocommit status of the database
6547** connection while this routine is running, then the return value
6548** is undefined.
6549*/
6550SQLITE_API int sqlite3_get_autocommit(sqlite3*);
6551
6552/*
6553** CAPI3REF: Find The Database Handle Of A Prepared Statement
6554** METHOD: sqlite3_stmt
6555**
6556** ^The sqlite3_db_handle interface returns the [database connection] handle
6557** to which a [prepared statement] belongs. ^The [database connection]
6558** returned by sqlite3_db_handle is the same [database connection]
6559** that was the first argument
6560** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
6561** create the statement in the first place.
6562*/
6563SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
6564
6565/*
6566** CAPI3REF: Return The Filename For A Database Connection
6567** METHOD: sqlite3
6568**
6569** ^The sqlite3_db_filename(D,N) interface returns a pointer to the filename
6570** associated with database N of connection D.
6571** ^If there is no attached database N on the database
6572** connection D, or if database N is a temporary or in-memory database, then
6573** this function will return either a NULL pointer or an empty string.
6574**
6575** ^The string value returned by this routine is owned and managed by
6576** the database connection. ^The value will be valid until the database N
6577** is [DETACH]-ed or until the database connection closes.
6578**
6579** ^The filename returned by this function is the output of the
6580** xFullPathname method of the [VFS]. ^In other words, the filename
6581** will be an absolute pathname, even if the filename used
6582** to open the database originally was a URI or relative pathname.
6583**
6584** If the filename pointer returned by this routine is not NULL, then it
6585** can be used as the filename input parameter to these routines:
6586** <ul>
6587** <li> [sqlite3_uri_parameter()]
6588** <li> [sqlite3_uri_boolean()]
6589** <li> [sqlite3_uri_int64()]
6590** <li> [sqlite3_filename_database()]
6591** <li> [sqlite3_filename_journal()]
6592** <li> [sqlite3_filename_wal()]
6593** </ul>
6594*/
6595SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
6596
6597/*
6598** CAPI3REF: Determine if a database is read-only
6599** METHOD: sqlite3
6600**
6601** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
6602** of connection D is read-only, 0 if it is read/write, or -1 if N is not
6603** the name of a database on connection D.
6604*/
6605SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
6606
6607/*
6608** CAPI3REF: Determine the transaction state of a database
6609** METHOD: sqlite3
6610**
6611** ^The sqlite3_txn_state(D,S) interface returns the current
6612** [transaction state] of schema S in database connection D. ^If S is NULL,
6613** then the highest transaction state of any schema on database connection D
6614** is returned. Transaction states are (in order of lowest to highest):
6615** <ol>
6616** <li value="0"> SQLITE_TXN_NONE
6617** <li value="1"> SQLITE_TXN_READ
6618** <li value="2"> SQLITE_TXN_WRITE
6619** </ol>
6620** ^If the S argument to sqlite3_txn_state(D,S) is not the name of
6621** a valid schema, then -1 is returned.
6622*/
6623SQLITE_API int sqlite3_txn_state(sqlite3*,const char *zSchema);
6624
6625/*
6626** CAPI3REF: Allowed return values from [sqlite3_txn_state()]
6627** KEYWORDS: {transaction state}
6628**
6629** These constants define the current transaction state of a database file.
6630** ^The [sqlite3_txn_state(D,S)] interface returns one of these
6631** constants in order to describe the transaction state of schema S
6632** in [database connection] D.
6633**
6634** <dl>
6635** [[SQLITE_TXN_NONE]] <dt>SQLITE_TXN_NONE</dt>
6636** <dd>The SQLITE_TXN_NONE state means that no transaction is currently
6637** pending.</dd>
6638**
6639** [[SQLITE_TXN_READ]] <dt>SQLITE_TXN_READ</dt>
6640** <dd>The SQLITE_TXN_READ state means that the database is currently
6641** in a read transaction. Content has been read from the database file
6642** but nothing in the database file has changed. The transaction state
6643** will advanced to SQLITE_TXN_WRITE if any changes occur and there are
6644** no other conflicting concurrent write transactions. The transaction
6645** state will revert to SQLITE_TXN_NONE following a [ROLLBACK] or
6646** [COMMIT].</dd>
6647**
6648** [[SQLITE_TXN_WRITE]] <dt>SQLITE_TXN_WRITE</dt>
6649** <dd>The SQLITE_TXN_WRITE state means that the database is currently
6650** in a write transaction. Content has been written to the database file
6651** but has not yet committed. The transaction state will change to
6652** to SQLITE_TXN_NONE at the next [ROLLBACK] or [COMMIT].</dd>
6653*/
6654#define SQLITE_TXN_NONE 0
6655#define SQLITE_TXN_READ 1
6656#define SQLITE_TXN_WRITE 2
6657
6658/*
6659** CAPI3REF: Find the next prepared statement
6660** METHOD: sqlite3
6661**
6662** ^This interface returns a pointer to the next [prepared statement] after
6663** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
6664** then this interface returns a pointer to the first prepared statement
6665** associated with the database connection pDb. ^If no prepared statement
6666** satisfies the conditions of this routine, it returns NULL.
6667**
6668** The [database connection] pointer D in a call to
6669** [sqlite3_next_stmt(D,S)] must refer to an open database
6670** connection and in particular must not be a NULL pointer.
6671*/
6672SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
6673
6674/*
6675** CAPI3REF: Commit And Rollback Notification Callbacks
6676** METHOD: sqlite3
6677**
6678** ^The sqlite3_commit_hook() interface registers a callback
6679** function to be invoked whenever a transaction is [COMMIT | committed].
6680** ^Any callback set by a previous call to sqlite3_commit_hook()
6681** for the same database connection is overridden.
6682** ^The sqlite3_rollback_hook() interface registers a callback
6683** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
6684** ^Any callback set by a previous call to sqlite3_rollback_hook()
6685** for the same database connection is overridden.
6686** ^The pArg argument is passed through to the callback.
6687** ^If the callback on a commit hook function returns non-zero,
6688** then the commit is converted into a rollback.
6689**
6690** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
6691** return the P argument from the previous call of the same function
6692** on the same [database connection] D, or NULL for
6693** the first call for each function on D.
6694**
6695** The commit and rollback hook callbacks are not reentrant.
6696** The callback implementation must not do anything that will modify
6697** the database connection that invoked the callback. Any actions
6698** to modify the database connection must be deferred until after the
6699** completion of the [sqlite3_step()] call that triggered the commit
6700** or rollback hook in the first place.
6701** Note that running any other SQL statements, including SELECT statements,
6702** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
6703** the database connections for the meaning of "modify" in this paragraph.
6704**
6705** ^Registering a NULL function disables the callback.
6706**
6707** ^When the commit hook callback routine returns zero, the [COMMIT]
6708** operation is allowed to continue normally. ^If the commit hook
6709** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
6710** ^The rollback hook is invoked on a rollback that results from a commit
6711** hook returning non-zero, just as it would be with any other rollback.
6712**
6713** ^For the purposes of this API, a transaction is said to have been
6714** rolled back if an explicit "ROLLBACK" statement is executed, or
6715** an error or constraint causes an implicit rollback to occur.
6716** ^The rollback callback is not invoked if a transaction is
6717** automatically rolled back because the database connection is closed.
6718**
6719** See also the [sqlite3_update_hook()] interface.
6720*/
6721SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
6722SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
6723
6724/*
6725** CAPI3REF: Autovacuum Compaction Amount Callback
6726** METHOD: sqlite3
6727**
6728** ^The sqlite3_autovacuum_pages(D,C,P,X) interface registers a callback
6729** function C that is invoked prior to each autovacuum of the database
6730** file. ^The callback is passed a copy of the generic data pointer (P),
6731** the schema-name of the attached database that is being autovacuumed,
6732** the the size of the database file in pages, the number of free pages,
6733** and the number of bytes per page, respectively. The callback should
6734** return the number of free pages that should be removed by the
6735** autovacuum. ^If the callback returns zero, then no autovacuum happens.
6736** ^If the value returned is greater than or equal to the number of
6737** free pages, then a complete autovacuum happens.
6738**
6739** <p>^If there are multiple ATTACH-ed database files that are being
6740** modified as part of a transaction commit, then the autovacuum pages
6741** callback is invoked separately for each file.
6742**
6743** <p><b>The callback is not reentrant.</b> The callback function should
6744** not attempt to invoke any other SQLite interface. If it does, bad
6745** things may happen, including segmentation faults and corrupt database
6746** files. The callback function should be a simple function that
6747** does some arithmetic on its input parameters and returns a result.
6748**
6749** ^The X parameter to sqlite3_autovacuum_pages(D,C,P,X) is an optional
6750** destructor for the P parameter. ^If X is not NULL, then X(P) is
6751** invoked whenever the database connection closes or when the callback
6752** is overwritten by another invocation of sqlite3_autovacuum_pages().
6753**
6754** <p>^There is only one autovacuum pages callback per database connection.
6755** ^Each call to the sqlite3_autovacuum_pages() interface overrides all
6756** previous invocations for that database connection. ^If the callback
6757** argument (C) to sqlite3_autovacuum_pages(D,C,P,X) is a NULL pointer,
6758** then the autovacuum steps callback is cancelled. The return value
6759** from sqlite3_autovacuum_pages() is normally SQLITE_OK, but might
6760** be some other error code if something goes wrong. The current
6761** implementation will only return SQLITE_OK or SQLITE_MISUSE, but other
6762** return codes might be added in future releases.
6763**
6764** <p>If no autovacuum pages callback is specified (the usual case) or
6765** a NULL pointer is provided for the callback,
6766** then the default behavior is to vacuum all free pages. So, in other
6767** words, the default behavior is the same as if the callback function
6768** were something like this:
6769**
6770** <blockquote><pre>
6771** &nbsp; unsigned int demonstration_autovac_pages_callback(
6772** &nbsp; void *pClientData,
6773** &nbsp; const char *zSchema,
6774** &nbsp; unsigned int nDbPage,
6775** &nbsp; unsigned int nFreePage,
6776** &nbsp; unsigned int nBytePerPage
6777** &nbsp; ){
6778** &nbsp; return nFreePage;
6779** &nbsp; }
6780** </pre></blockquote>
6781*/
6782SQLITE_API int sqlite3_autovacuum_pages(
6783 sqlite3 *db,
6784 unsigned int(*)(void*,const char*,unsigned int,unsigned int,unsigned int),
6785 void*,
6786 void(*)(void*)
6787);
6788
6789
6790/*
6791** CAPI3REF: Data Change Notification Callbacks
6792** METHOD: sqlite3
6793**
6794** ^The sqlite3_update_hook() interface registers a callback function
6795** with the [database connection] identified by the first argument
6796** to be invoked whenever a row is updated, inserted or deleted in
6797** a [rowid table].
6798** ^Any callback set by a previous call to this function
6799** for the same database connection is overridden.
6800**
6801** ^The second argument is a pointer to the function to invoke when a
6802** row is updated, inserted or deleted in a rowid table.
6803** ^The first argument to the callback is a copy of the third argument
6804** to sqlite3_update_hook().
6805** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
6806** or [SQLITE_UPDATE], depending on the operation that caused the callback
6807** to be invoked.
6808** ^The third and fourth arguments to the callback contain pointers to the
6809** database and table name containing the affected row.
6810** ^The final callback parameter is the [rowid] of the row.
6811** ^In the case of an update, this is the [rowid] after the update takes place.
6812**
6813** ^(The update hook is not invoked when internal system tables are
6814** modified (i.e. sqlite_sequence).)^
6815** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
6816**
6817** ^In the current implementation, the update hook
6818** is not invoked when conflicting rows are deleted because of an
6819** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
6820** invoked when rows are deleted using the [truncate optimization].
6821** The exceptions defined in this paragraph might change in a future
6822** release of SQLite.
6823**
6824** The update hook implementation must not do anything that will modify
6825** the database connection that invoked the update hook. Any actions
6826** to modify the database connection must be deferred until after the
6827** completion of the [sqlite3_step()] call that triggered the update hook.
6828** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
6829** database connections for the meaning of "modify" in this paragraph.
6830**
6831** ^The sqlite3_update_hook(D,C,P) function
6832** returns the P argument from the previous call
6833** on the same [database connection] D, or NULL for
6834** the first call on D.
6835**
6836** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
6837** and [sqlite3_preupdate_hook()] interfaces.
6838*/
6839SQLITE_API void *sqlite3_update_hook(
6840 sqlite3*,
6841 void(*)(void *,int ,char const *,char const *,sqlite3_int64),
6842 void*
6843);
6844
6845/*
6846** CAPI3REF: Enable Or Disable Shared Pager Cache
6847**
6848** ^(This routine enables or disables the sharing of the database cache
6849** and schema data structures between [database connection | connections]
6850** to the same database. Sharing is enabled if the argument is true
6851** and disabled if the argument is false.)^
6852**
6853** ^Cache sharing is enabled and disabled for an entire process.
6854** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
6855** In prior versions of SQLite,
6856** sharing was enabled or disabled for each thread separately.
6857**
6858** ^(The cache sharing mode set by this interface effects all subsequent
6859** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
6860** Existing database connections continue to use the sharing mode
6861** that was in effect at the time they were opened.)^
6862**
6863** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
6864** successfully. An [error code] is returned otherwise.)^
6865**
6866** ^Shared cache is disabled by default. It is recommended that it stay
6867** that way. In other words, do not use this routine. This interface
6868** continues to be provided for historical compatibility, but its use is
6869** discouraged. Any use of shared cache is discouraged. If shared cache
6870** must be used, it is recommended that shared cache only be enabled for
6871** individual database connections using the [sqlite3_open_v2()] interface
6872** with the [SQLITE_OPEN_SHAREDCACHE] flag.
6873**
6874** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
6875** and will always return SQLITE_MISUSE. On those systems,
6876** shared cache mode should be enabled per-database connection via
6877** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
6878**
6879** This interface is threadsafe on processors where writing a
6880** 32-bit integer is atomic.
6881**
6882** See Also: [SQLite Shared-Cache Mode]
6883*/
6884SQLITE_API int sqlite3_enable_shared_cache(int);
6885
6886/*
6887** CAPI3REF: Attempt To Free Heap Memory
6888**
6889** ^The sqlite3_release_memory() interface attempts to free N bytes
6890** of heap memory by deallocating non-essential memory allocations
6891** held by the database library. Memory used to cache database
6892** pages to improve performance is an example of non-essential memory.
6893** ^sqlite3_release_memory() returns the number of bytes actually freed,
6894** which might be more or less than the amount requested.
6895** ^The sqlite3_release_memory() routine is a no-op returning zero
6896** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
6897**
6898** See also: [sqlite3_db_release_memory()]
6899*/
6900SQLITE_API int sqlite3_release_memory(int);
6901
6902/*
6903** CAPI3REF: Free Memory Used By A Database Connection
6904** METHOD: sqlite3
6905**
6906** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
6907** memory as possible from database connection D. Unlike the
6908** [sqlite3_release_memory()] interface, this interface is in effect even
6909** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
6910** omitted.
6911**
6912** See also: [sqlite3_release_memory()]
6913*/
6914SQLITE_API int sqlite3_db_release_memory(sqlite3*);
6915
6916/*
6917** CAPI3REF: Impose A Limit On Heap Size
6918**
6919** These interfaces impose limits on the amount of heap memory that will be
6920** by all database connections within a single process.
6921**
6922** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
6923** soft limit on the amount of heap memory that may be allocated by SQLite.
6924** ^SQLite strives to keep heap memory utilization below the soft heap
6925** limit by reducing the number of pages held in the page cache
6926** as heap memory usages approaches the limit.
6927** ^The soft heap limit is "soft" because even though SQLite strives to stay
6928** below the limit, it will exceed the limit rather than generate
6929** an [SQLITE_NOMEM] error. In other words, the soft heap limit
6930** is advisory only.
6931**
6932** ^The sqlite3_hard_heap_limit64(N) interface sets a hard upper bound of
6933** N bytes on the amount of memory that will be allocated. ^The
6934** sqlite3_hard_heap_limit64(N) interface is similar to
6935** sqlite3_soft_heap_limit64(N) except that memory allocations will fail
6936** when the hard heap limit is reached.
6937**
6938** ^The return value from both sqlite3_soft_heap_limit64() and
6939** sqlite3_hard_heap_limit64() is the size of
6940** the heap limit prior to the call, or negative in the case of an
6941** error. ^If the argument N is negative
6942** then no change is made to the heap limit. Hence, the current
6943** size of heap limits can be determined by invoking
6944** sqlite3_soft_heap_limit64(-1) or sqlite3_hard_heap_limit(-1).
6945**
6946** ^Setting the heap limits to zero disables the heap limiter mechanism.
6947**
6948** ^The soft heap limit may not be greater than the hard heap limit.
6949** ^If the hard heap limit is enabled and if sqlite3_soft_heap_limit(N)
6950** is invoked with a value of N that is greater than the hard heap limit,
6951** the the soft heap limit is set to the value of the hard heap limit.
6952** ^The soft heap limit is automatically enabled whenever the hard heap
6953** limit is enabled. ^When sqlite3_hard_heap_limit64(N) is invoked and
6954** the soft heap limit is outside the range of 1..N, then the soft heap
6955** limit is set to N. ^Invoking sqlite3_soft_heap_limit64(0) when the
6956** hard heap limit is enabled makes the soft heap limit equal to the
6957** hard heap limit.
6958**
6959** The memory allocation limits can also be adjusted using
6960** [PRAGMA soft_heap_limit] and [PRAGMA hard_heap_limit].
6961**
6962** ^(The heap limits are not enforced in the current implementation
6963** if one or more of following conditions are true:
6964**
6965** <ul>
6966** <li> The limit value is set to zero.
6967** <li> Memory accounting is disabled using a combination of the
6968** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
6969** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
6970** <li> An alternative page cache implementation is specified using
6971** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
6972** <li> The page cache allocates from its own memory pool supplied
6973** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
6974** from the heap.
6975** </ul>)^
6976**
6977** The circumstances under which SQLite will enforce the heap limits may
6978** changes in future releases of SQLite.
6979*/
6980SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
6981SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 N);
6982
6983/*
6984** CAPI3REF: Deprecated Soft Heap Limit Interface
6985** DEPRECATED
6986**
6987** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
6988** interface. This routine is provided for historical compatibility
6989** only. All new applications should use the
6990** [sqlite3_soft_heap_limit64()] interface rather than this one.
6991*/
6992SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
6993
6994
6995/*
6996** CAPI3REF: Extract Metadata About A Column Of A Table
6997** METHOD: sqlite3
6998**
6999** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
7000** information about column C of table T in database D
7001** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
7002** interface returns SQLITE_OK and fills in the non-NULL pointers in
7003** the final five arguments with appropriate values if the specified
7004** column exists. ^The sqlite3_table_column_metadata() interface returns
7005** SQLITE_ERROR if the specified column does not exist.
7006** ^If the column-name parameter to sqlite3_table_column_metadata() is a
7007** NULL pointer, then this routine simply checks for the existence of the
7008** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
7009** does not. If the table name parameter T in a call to
7010** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is
7011** undefined behavior.
7012**
7013** ^The column is identified by the second, third and fourth parameters to
7014** this function. ^(The second parameter is either the name of the database
7015** (i.e. "main", "temp", or an attached database) containing the specified
7016** table or NULL.)^ ^If it is NULL, then all attached databases are searched
7017** for the table using the same algorithm used by the database engine to
7018** resolve unqualified table references.
7019**
7020** ^The third and fourth parameters to this function are the table and column
7021** name of the desired column, respectively.
7022**
7023** ^Metadata is returned by writing to the memory locations passed as the 5th
7024** and subsequent parameters to this function. ^Any of these arguments may be
7025** NULL, in which case the corresponding element of metadata is omitted.
7026**
7027** ^(<blockquote>
7028** <table border="1">
7029** <tr><th> Parameter <th> Output<br>Type <th> Description
7030**
7031** <tr><td> 5th <td> const char* <td> Data type
7032** <tr><td> 6th <td> const char* <td> Name of default collation sequence
7033** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
7034** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
7035** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
7036** </table>
7037** </blockquote>)^
7038**
7039** ^The memory pointed to by the character pointers returned for the
7040** declaration type and collation sequence is valid until the next
7041** call to any SQLite API function.
7042**
7043** ^If the specified table is actually a view, an [error code] is returned.
7044**
7045** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
7046** is not a [WITHOUT ROWID] table and an
7047** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
7048** parameters are set for the explicitly declared column. ^(If there is no
7049** [INTEGER PRIMARY KEY] column, then the outputs
7050** for the [rowid] are set as follows:
7051**
7052** <pre>
7053** data type: "INTEGER"
7054** collation sequence: "BINARY"
7055** not null: 0
7056** primary key: 1
7057** auto increment: 0
7058** </pre>)^
7059**
7060** ^This function causes all database schemas to be read from disk and
7061** parsed, if that has not already been done, and returns an error if
7062** any errors are encountered while loading the schema.
7063*/
7064SQLITE_API int sqlite3_table_column_metadata(
7065 sqlite3 *db, /* Connection handle */
7066 const char *zDbName, /* Database name or NULL */
7067 const char *zTableName, /* Table name */
7068 const char *zColumnName, /* Column name */
7069 char const **pzDataType, /* OUTPUT: Declared data type */
7070 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
7071 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
7072 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
7073 int *pAutoinc /* OUTPUT: True if column is auto-increment */
7074);
7075
7076/*
7077** CAPI3REF: Load An Extension
7078** METHOD: sqlite3
7079**
7080** ^This interface loads an SQLite extension library from the named file.
7081**
7082** ^The sqlite3_load_extension() interface attempts to load an
7083** [SQLite extension] library contained in the file zFile. If
7084** the file cannot be loaded directly, attempts are made to load
7085** with various operating-system specific extensions added.
7086** So for example, if "samplelib" cannot be loaded, then names like
7087** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
7088** be tried also.
7089**
7090** ^The entry point is zProc.
7091** ^(zProc may be 0, in which case SQLite will try to come up with an
7092** entry point name on its own. It first tries "sqlite3_extension_init".
7093** If that does not work, it constructs a name "sqlite3_X_init" where the
7094** X is consists of the lower-case equivalent of all ASCII alphabetic
7095** characters in the filename from the last "/" to the first following
7096** "." and omitting any initial "lib".)^
7097** ^The sqlite3_load_extension() interface returns
7098** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
7099** ^If an error occurs and pzErrMsg is not 0, then the
7100** [sqlite3_load_extension()] interface shall attempt to
7101** fill *pzErrMsg with error message text stored in memory
7102** obtained from [sqlite3_malloc()]. The calling function
7103** should free this memory by calling [sqlite3_free()].
7104**
7105** ^Extension loading must be enabled using
7106** [sqlite3_enable_load_extension()] or
7107** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
7108** prior to calling this API,
7109** otherwise an error will be returned.
7110**
7111** <b>Security warning:</b> It is recommended that the
7112** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
7113** interface. The use of the [sqlite3_enable_load_extension()] interface
7114** should be avoided. This will keep the SQL function [load_extension()]
7115** disabled and prevent SQL injections from giving attackers
7116** access to extension loading capabilities.
7117**
7118** See also the [load_extension() SQL function].
7119*/
7120SQLITE_API int sqlite3_load_extension(
7121 sqlite3 *db, /* Load the extension into this database connection */
7122 const char *zFile, /* Name of the shared library containing extension */
7123 const char *zProc, /* Entry point. Derived from zFile if 0 */
7124 char **pzErrMsg /* Put error message here if not 0 */
7125);
7126
7127/*
7128** CAPI3REF: Enable Or Disable Extension Loading
7129** METHOD: sqlite3
7130**
7131** ^So as not to open security holes in older applications that are
7132** unprepared to deal with [extension loading], and as a means of disabling
7133** [extension loading] while evaluating user-entered SQL, the following API
7134** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
7135**
7136** ^Extension loading is off by default.
7137** ^Call the sqlite3_enable_load_extension() routine with onoff==1
7138** to turn extension loading on and call it with onoff==0 to turn
7139** it back off again.
7140**
7141** ^This interface enables or disables both the C-API
7142** [sqlite3_load_extension()] and the SQL function [load_extension()].
7143** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
7144** to enable or disable only the C-API.)^
7145**
7146** <b>Security warning:</b> It is recommended that extension loading
7147** be enabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
7148** rather than this interface, so the [load_extension()] SQL function
7149** remains disabled. This will prevent SQL injections from giving attackers
7150** access to extension loading capabilities.
7151*/
7152SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
7153
7154/*
7155** CAPI3REF: Automatically Load Statically Linked Extensions
7156**
7157** ^This interface causes the xEntryPoint() function to be invoked for
7158** each new [database connection] that is created. The idea here is that
7159** xEntryPoint() is the entry point for a statically linked [SQLite extension]
7160** that is to be automatically loaded into all new database connections.
7161**
7162** ^(Even though the function prototype shows that xEntryPoint() takes
7163** no arguments and returns void, SQLite invokes xEntryPoint() with three
7164** arguments and expects an integer result as if the signature of the
7165** entry point where as follows:
7166**
7167** <blockquote><pre>
7168** &nbsp; int xEntryPoint(
7169** &nbsp; sqlite3 *db,
7170** &nbsp; const char **pzErrMsg,
7171** &nbsp; const struct sqlite3_api_routines *pThunk
7172** &nbsp; );
7173** </pre></blockquote>)^
7174**
7175** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
7176** point to an appropriate error message (obtained from [sqlite3_mprintf()])
7177** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
7178** is NULL before calling the xEntryPoint(). ^SQLite will invoke
7179** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
7180** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
7181** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
7182**
7183** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
7184** on the list of automatic extensions is a harmless no-op. ^No entry point
7185** will be called more than once for each database connection that is opened.
7186**
7187** See also: [sqlite3_reset_auto_extension()]
7188** and [sqlite3_cancel_auto_extension()]
7189*/
7190SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
7191
7192/*
7193** CAPI3REF: Cancel Automatic Extension Loading
7194**
7195** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
7196** initialization routine X that was registered using a prior call to
7197** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
7198** routine returns 1 if initialization routine X was successfully
7199** unregistered and it returns 0 if X was not on the list of initialization
7200** routines.
7201*/
7202SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
7203
7204/*
7205** CAPI3REF: Reset Automatic Extension Loading
7206**
7207** ^This interface disables all automatic extensions previously
7208** registered using [sqlite3_auto_extension()].
7209*/
7210SQLITE_API void sqlite3_reset_auto_extension(void);
7211
7212/*
7213** The interface to the virtual-table mechanism is currently considered
7214** to be experimental. The interface might change in incompatible ways.
7215** If this is a problem for you, do not use the interface at this time.
7216**
7217** When the virtual-table mechanism stabilizes, we will declare the
7218** interface fixed, support it indefinitely, and remove this comment.
7219*/
7220
7221/*
7222** Structures used by the virtual table interface
7223*/
7224typedef struct sqlite3_vtab sqlite3_vtab;
7225typedef struct sqlite3_index_info sqlite3_index_info;
7226typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
7227typedef struct sqlite3_module sqlite3_module;
7228
7229/*
7230** CAPI3REF: Virtual Table Object
7231** KEYWORDS: sqlite3_module {virtual table module}
7232**
7233** This structure, sometimes called a "virtual table module",
7234** defines the implementation of a [virtual table].
7235** This structure consists mostly of methods for the module.
7236**
7237** ^A virtual table module is created by filling in a persistent
7238** instance of this structure and passing a pointer to that instance
7239** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
7240** ^The registration remains valid until it is replaced by a different
7241** module or until the [database connection] closes. The content
7242** of this structure must not change while it is registered with
7243** any database connection.
7244*/
7245struct sqlite3_module {
7246 int iVersion;
7247 int (*xCreate)(sqlite3*, void *pAux,
7248 int argc, const char *const*argv,
7249 sqlite3_vtab **ppVTab, char**);
7250 int (*xConnect)(sqlite3*, void *pAux,
7251 int argc, const char *const*argv,
7252 sqlite3_vtab **ppVTab, char**);
7253 int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
7254 int (*xDisconnect)(sqlite3_vtab *pVTab);
7255 int (*xDestroy)(sqlite3_vtab *pVTab);
7256 int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
7257 int (*xClose)(sqlite3_vtab_cursor*);
7258 int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
7259 int argc, sqlite3_value **argv);
7260 int (*xNext)(sqlite3_vtab_cursor*);
7261 int (*xEof)(sqlite3_vtab_cursor*);
7262 int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
7263 int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
7264 int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
7265 int (*xBegin)(sqlite3_vtab *pVTab);
7266 int (*xSync)(sqlite3_vtab *pVTab);
7267 int (*xCommit)(sqlite3_vtab *pVTab);
7268 int (*xRollback)(sqlite3_vtab *pVTab);
7269 int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
7270 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
7271 void **ppArg);
7272 int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
7273 /* The methods above are in version 1 of the sqlite_module object. Those
7274 ** below are for version 2 and greater. */
7275 int (*xSavepoint)(sqlite3_vtab *pVTab, int);
7276 int (*xRelease)(sqlite3_vtab *pVTab, int);
7277 int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
7278 /* The methods above are in versions 1 and 2 of the sqlite_module object.
7279 ** Those below are for version 3 and greater. */
7280 int (*xShadowName)(const char*);
7281};
7282
7283/*
7284** CAPI3REF: Virtual Table Indexing Information
7285** KEYWORDS: sqlite3_index_info
7286**
7287** The sqlite3_index_info structure and its substructures is used as part
7288** of the [virtual table] interface to
7289** pass information into and receive the reply from the [xBestIndex]
7290** method of a [virtual table module]. The fields under **Inputs** are the
7291** inputs to xBestIndex and are read-only. xBestIndex inserts its
7292** results into the **Outputs** fields.
7293**
7294** ^(The aConstraint[] array records WHERE clause constraints of the form:
7295**
7296** <blockquote>column OP expr</blockquote>
7297**
7298** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
7299** stored in aConstraint[].op using one of the
7300** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
7301** ^(The index of the column is stored in
7302** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
7303** expr on the right-hand side can be evaluated (and thus the constraint
7304** is usable) and false if it cannot.)^
7305**
7306** ^The optimizer automatically inverts terms of the form "expr OP column"
7307** and makes other simplifications to the WHERE clause in an attempt to
7308** get as many WHERE clause terms into the form shown above as possible.
7309** ^The aConstraint[] array only reports WHERE clause terms that are
7310** relevant to the particular virtual table being queried.
7311**
7312** ^Information about the ORDER BY clause is stored in aOrderBy[].
7313** ^Each term of aOrderBy records a column of the ORDER BY clause.
7314**
7315** The colUsed field indicates which columns of the virtual table may be
7316** required by the current scan. Virtual table columns are numbered from
7317** zero in the order in which they appear within the CREATE TABLE statement
7318** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
7319** the corresponding bit is set within the colUsed mask if the column may be
7320** required by SQLite. If the table has at least 64 columns and any column
7321** to the right of the first 63 is required, then bit 63 of colUsed is also
7322** set. In other words, column iCol may be required if the expression
7323** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
7324** non-zero.
7325**
7326** The [xBestIndex] method must fill aConstraintUsage[] with information
7327** about what parameters to pass to xFilter. ^If argvIndex>0 then
7328** the right-hand side of the corresponding aConstraint[] is evaluated
7329** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
7330** is true, then the constraint is assumed to be fully handled by the
7331** virtual table and might not be checked again by the byte code.)^ ^(The
7332** aConstraintUsage[].omit flag is an optimization hint. When the omit flag
7333** is left in its default setting of false, the constraint will always be
7334** checked separately in byte code. If the omit flag is change to true, then
7335** the constraint may or may not be checked in byte code. In other words,
7336** when the omit flag is true there is no guarantee that the constraint will
7337** not be checked again using byte code.)^
7338**
7339** ^The idxNum and idxPtr values are recorded and passed into the
7340** [xFilter] method.
7341** ^[sqlite3_free()] is used to free idxPtr if and only if
7342** needToFreeIdxPtr is true.
7343**
7344** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
7345** the correct order to satisfy the ORDER BY clause so that no separate
7346** sorting step is required.
7347**
7348** ^The estimatedCost value is an estimate of the cost of a particular
7349** strategy. A cost of N indicates that the cost of the strategy is similar
7350** to a linear scan of an SQLite table with N rows. A cost of log(N)
7351** indicates that the expense of the operation is similar to that of a
7352** binary search on a unique indexed field of an SQLite table with N rows.
7353**
7354** ^The estimatedRows value is an estimate of the number of rows that
7355** will be returned by the strategy.
7356**
7357** The xBestIndex method may optionally populate the idxFlags field with a
7358** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
7359** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
7360** assumes that the strategy may visit at most one row.
7361**
7362** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
7363** SQLite also assumes that if a call to the xUpdate() method is made as
7364** part of the same statement to delete or update a virtual table row and the
7365** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
7366** any database changes. In other words, if the xUpdate() returns
7367** SQLITE_CONSTRAINT, the database contents must be exactly as they were
7368** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
7369** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
7370** the xUpdate method are automatically rolled back by SQLite.
7371**
7372** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
7373** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
7374** If a virtual table extension is
7375** used with an SQLite version earlier than 3.8.2, the results of attempting
7376** to read or write the estimatedRows field are undefined (but are likely
7377** to include crashing the application). The estimatedRows field should
7378** therefore only be used if [sqlite3_libversion_number()] returns a
7379** value greater than or equal to 3008002. Similarly, the idxFlags field
7380** was added for [version 3.9.0] ([dateof:3.9.0]).
7381** It may therefore only be used if
7382** sqlite3_libversion_number() returns a value greater than or equal to
7383** 3009000.
7384*/
7385struct sqlite3_index_info {
7386 /* Inputs */
7387 int nConstraint; /* Number of entries in aConstraint */
7388 struct sqlite3_index_constraint {
7389 int iColumn; /* Column constrained. -1 for ROWID */
7390 unsigned char op; /* Constraint operator */
7391 unsigned char usable; /* True if this constraint is usable */
7392 int iTermOffset; /* Used internally - xBestIndex should ignore */
7393 } *aConstraint; /* Table of WHERE clause constraints */
7394 int nOrderBy; /* Number of terms in the ORDER BY clause */
7395 struct sqlite3_index_orderby {
7396 int iColumn; /* Column number */
7397 unsigned char desc; /* True for DESC. False for ASC. */
7398 } *aOrderBy; /* The ORDER BY clause */
7399 /* Outputs */
7400 struct sqlite3_index_constraint_usage {
7401 int argvIndex; /* if >0, constraint is part of argv to xFilter */
7402 unsigned char omit; /* Do not code a test for this constraint */
7403 } *aConstraintUsage;
7404 int idxNum; /* Number used to identify the index */
7405 char *idxStr; /* String, possibly obtained from sqlite3_malloc */
7406 int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
7407 int orderByConsumed; /* True if output is already ordered */
7408 double estimatedCost; /* Estimated cost of using this index */
7409 /* Fields below are only available in SQLite 3.8.2 and later */
7410 sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
7411 /* Fields below are only available in SQLite 3.9.0 and later */
7412 int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
7413 /* Fields below are only available in SQLite 3.10.0 and later */
7414 sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
7415};
7416
7417/*
7418** CAPI3REF: Virtual Table Scan Flags
7419**
7420** Virtual table implementations are allowed to set the
7421** [sqlite3_index_info].idxFlags field to some combination of
7422** these bits.
7423*/
7424#define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
7425
7426/*
7427** CAPI3REF: Virtual Table Constraint Operator Codes
7428**
7429** These macros define the allowed values for the
7430** [sqlite3_index_info].aConstraint[].op field. Each value represents
7431** an operator that is part of a constraint term in the wHERE clause of
7432** a query that uses a [virtual table].
7433*/
7434#define SQLITE_INDEX_CONSTRAINT_EQ 2
7435#define SQLITE_INDEX_CONSTRAINT_GT 4
7436#define SQLITE_INDEX_CONSTRAINT_LE 8
7437#define SQLITE_INDEX_CONSTRAINT_LT 16
7438#define SQLITE_INDEX_CONSTRAINT_GE 32
7439#define SQLITE_INDEX_CONSTRAINT_MATCH 64
7440#define SQLITE_INDEX_CONSTRAINT_LIKE 65
7441#define SQLITE_INDEX_CONSTRAINT_GLOB 66
7442#define SQLITE_INDEX_CONSTRAINT_REGEXP 67
7443#define SQLITE_INDEX_CONSTRAINT_NE 68
7444#define SQLITE_INDEX_CONSTRAINT_ISNOT 69
7445#define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70
7446#define SQLITE_INDEX_CONSTRAINT_ISNULL 71
7447#define SQLITE_INDEX_CONSTRAINT_IS 72
7448#define SQLITE_INDEX_CONSTRAINT_FUNCTION 150
7449
7450/*
7451** CAPI3REF: Register A Virtual Table Implementation
7452** METHOD: sqlite3
7453**
7454** ^These routines are used to register a new [virtual table module] name.
7455** ^Module names must be registered before
7456** creating a new [virtual table] using the module and before using a
7457** preexisting [virtual table] for the module.
7458**
7459** ^The module name is registered on the [database connection] specified
7460** by the first parameter. ^The name of the module is given by the
7461** second parameter. ^The third parameter is a pointer to
7462** the implementation of the [virtual table module]. ^The fourth
7463** parameter is an arbitrary client data pointer that is passed through
7464** into the [xCreate] and [xConnect] methods of the virtual table module
7465** when a new virtual table is be being created or reinitialized.
7466**
7467** ^The sqlite3_create_module_v2() interface has a fifth parameter which
7468** is a pointer to a destructor for the pClientData. ^SQLite will
7469** invoke the destructor function (if it is not NULL) when SQLite
7470** no longer needs the pClientData pointer. ^The destructor will also
7471** be invoked if the call to sqlite3_create_module_v2() fails.
7472** ^The sqlite3_create_module()
7473** interface is equivalent to sqlite3_create_module_v2() with a NULL
7474** destructor.
7475**
7476** ^If the third parameter (the pointer to the sqlite3_module object) is
7477** NULL then no new module is create and any existing modules with the
7478** same name are dropped.
7479**
7480** See also: [sqlite3_drop_modules()]
7481*/
7482SQLITE_API int sqlite3_create_module(
7483 sqlite3 *db, /* SQLite connection to register module with */
7484 const char *zName, /* Name of the module */
7485 const sqlite3_module *p, /* Methods for the module */
7486 void *pClientData /* Client data for xCreate/xConnect */
7487);
7488SQLITE_API int sqlite3_create_module_v2(
7489 sqlite3 *db, /* SQLite connection to register module with */
7490 const char *zName, /* Name of the module */
7491 const sqlite3_module *p, /* Methods for the module */
7492 void *pClientData, /* Client data for xCreate/xConnect */
7493 void(*xDestroy)(void*) /* Module destructor function */
7494);
7495
7496/*
7497** CAPI3REF: Remove Unnecessary Virtual Table Implementations
7498** METHOD: sqlite3
7499**
7500** ^The sqlite3_drop_modules(D,L) interface removes all virtual
7501** table modules from database connection D except those named on list L.
7502** The L parameter must be either NULL or a pointer to an array of pointers
7503** to strings where the array is terminated by a single NULL pointer.
7504** ^If the L parameter is NULL, then all virtual table modules are removed.
7505**
7506** See also: [sqlite3_create_module()]
7507*/
7508SQLITE_API int sqlite3_drop_modules(
7509 sqlite3 *db, /* Remove modules from this connection */
7510 const char **azKeep /* Except, do not remove the ones named here */
7511);
7512
7513/*
7514** CAPI3REF: Virtual Table Instance Object
7515** KEYWORDS: sqlite3_vtab
7516**
7517** Every [virtual table module] implementation uses a subclass
7518** of this object to describe a particular instance
7519** of the [virtual table]. Each subclass will
7520** be tailored to the specific needs of the module implementation.
7521** The purpose of this superclass is to define certain fields that are
7522** common to all module implementations.
7523**
7524** ^Virtual tables methods can set an error message by assigning a
7525** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
7526** take care that any prior string is freed by a call to [sqlite3_free()]
7527** prior to assigning a new string to zErrMsg. ^After the error message
7528** is delivered up to the client application, the string will be automatically
7529** freed by sqlite3_free() and the zErrMsg field will be zeroed.
7530*/
7531struct sqlite3_vtab {
7532 const sqlite3_module *pModule; /* The module for this virtual table */
7533 int nRef; /* Number of open cursors */
7534 char *zErrMsg; /* Error message from sqlite3_mprintf() */
7535 /* Virtual table implementations will typically add additional fields */
7536};
7537
7538/*
7539** CAPI3REF: Virtual Table Cursor Object
7540** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
7541**
7542** Every [virtual table module] implementation uses a subclass of the
7543** following structure to describe cursors that point into the
7544** [virtual table] and are used
7545** to loop through the virtual table. Cursors are created using the
7546** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
7547** by the [sqlite3_module.xClose | xClose] method. Cursors are used
7548** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
7549** of the module. Each module implementation will define
7550** the content of a cursor structure to suit its own needs.
7551**
7552** This superclass exists in order to define fields of the cursor that
7553** are common to all implementations.
7554*/
7555struct sqlite3_vtab_cursor {
7556 sqlite3_vtab *pVtab; /* Virtual table of this cursor */
7557 /* Virtual table implementations will typically add additional fields */
7558};
7559
7560/*
7561** CAPI3REF: Declare The Schema Of A Virtual Table
7562**
7563** ^The [xCreate] and [xConnect] methods of a
7564** [virtual table module] call this interface
7565** to declare the format (the names and datatypes of the columns) of
7566** the virtual tables they implement.
7567*/
7568SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
7569
7570/*
7571** CAPI3REF: Overload A Function For A Virtual Table
7572** METHOD: sqlite3
7573**
7574** ^(Virtual tables can provide alternative implementations of functions
7575** using the [xFindFunction] method of the [virtual table module].
7576** But global versions of those functions
7577** must exist in order to be overloaded.)^
7578**
7579** ^(This API makes sure a global version of a function with a particular
7580** name and number of parameters exists. If no such function exists
7581** before this API is called, a new function is created.)^ ^The implementation
7582** of the new function always causes an exception to be thrown. So
7583** the new function is not good for anything by itself. Its only
7584** purpose is to be a placeholder function that can be overloaded
7585** by a [virtual table].
7586*/
7587SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
7588
7589/*
7590** The interface to the virtual-table mechanism defined above (back up
7591** to a comment remarkably similar to this one) is currently considered
7592** to be experimental. The interface might change in incompatible ways.
7593** If this is a problem for you, do not use the interface at this time.
7594**
7595** When the virtual-table mechanism stabilizes, we will declare the
7596** interface fixed, support it indefinitely, and remove this comment.
7597*/
7598
7599/*
7600** CAPI3REF: A Handle To An Open BLOB
7601** KEYWORDS: {BLOB handle} {BLOB handles}
7602**
7603** An instance of this object represents an open BLOB on which
7604** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
7605** ^Objects of this type are created by [sqlite3_blob_open()]
7606** and destroyed by [sqlite3_blob_close()].
7607** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
7608** can be used to read or write small subsections of the BLOB.
7609** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
7610*/
7611typedef struct sqlite3_blob sqlite3_blob;
7612
7613/*
7614** CAPI3REF: Open A BLOB For Incremental I/O
7615** METHOD: sqlite3
7616** CONSTRUCTOR: sqlite3_blob
7617**
7618** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
7619** in row iRow, column zColumn, table zTable in database zDb;
7620** in other words, the same BLOB that would be selected by:
7621**
7622** <pre>
7623** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
7624** </pre>)^
7625**
7626** ^(Parameter zDb is not the filename that contains the database, but
7627** rather the symbolic name of the database. For attached databases, this is
7628** the name that appears after the AS keyword in the [ATTACH] statement.
7629** For the main database file, the database name is "main". For TEMP
7630** tables, the database name is "temp".)^
7631**
7632** ^If the flags parameter is non-zero, then the BLOB is opened for read
7633** and write access. ^If the flags parameter is zero, the BLOB is opened for
7634** read-only access.
7635**
7636** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
7637** in *ppBlob. Otherwise an [error code] is returned and, unless the error
7638** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
7639** the API is not misused, it is always safe to call [sqlite3_blob_close()]
7640** on *ppBlob after this function it returns.
7641**
7642** This function fails with SQLITE_ERROR if any of the following are true:
7643** <ul>
7644** <li> ^(Database zDb does not exist)^,
7645** <li> ^(Table zTable does not exist within database zDb)^,
7646** <li> ^(Table zTable is a WITHOUT ROWID table)^,
7647** <li> ^(Column zColumn does not exist)^,
7648** <li> ^(Row iRow is not present in the table)^,
7649** <li> ^(The specified column of row iRow contains a value that is not
7650** a TEXT or BLOB value)^,
7651** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
7652** constraint and the blob is being opened for read/write access)^,
7653** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
7654** column zColumn is part of a [child key] definition and the blob is
7655** being opened for read/write access)^.
7656** </ul>
7657**
7658** ^Unless it returns SQLITE_MISUSE, this function sets the
7659** [database connection] error code and message accessible via
7660** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
7661**
7662** A BLOB referenced by sqlite3_blob_open() may be read using the
7663** [sqlite3_blob_read()] interface and modified by using
7664** [sqlite3_blob_write()]. The [BLOB handle] can be moved to a
7665** different row of the same table using the [sqlite3_blob_reopen()]
7666** interface. However, the column, table, or database of a [BLOB handle]
7667** cannot be changed after the [BLOB handle] is opened.
7668**
7669** ^(If the row that a BLOB handle points to is modified by an
7670** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
7671** then the BLOB handle is marked as "expired".
7672** This is true if any column of the row is changed, even a column
7673** other than the one the BLOB handle is open on.)^
7674** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
7675** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
7676** ^(Changes written into a BLOB prior to the BLOB expiring are not
7677** rolled back by the expiration of the BLOB. Such changes will eventually
7678** commit if the transaction continues to completion.)^
7679**
7680** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
7681** the opened blob. ^The size of a blob may not be changed by this
7682** interface. Use the [UPDATE] SQL command to change the size of a
7683** blob.
7684**
7685** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
7686** and the built-in [zeroblob] SQL function may be used to create a
7687** zero-filled blob to read or write using the incremental-blob interface.
7688**
7689** To avoid a resource leak, every open [BLOB handle] should eventually
7690** be released by a call to [sqlite3_blob_close()].
7691**
7692** See also: [sqlite3_blob_close()],
7693** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
7694** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
7695*/
7696SQLITE_API int sqlite3_blob_open(
7697 sqlite3*,
7698 const char *zDb,
7699 const char *zTable,
7700 const char *zColumn,
7701 sqlite3_int64 iRow,
7702 int flags,
7703 sqlite3_blob **ppBlob
7704);
7705
7706/*
7707** CAPI3REF: Move a BLOB Handle to a New Row
7708** METHOD: sqlite3_blob
7709**
7710** ^This function is used to move an existing [BLOB handle] so that it points
7711** to a different row of the same database table. ^The new row is identified
7712** by the rowid value passed as the second argument. Only the row can be
7713** changed. ^The database, table and column on which the blob handle is open
7714** remain the same. Moving an existing [BLOB handle] to a new row is
7715** faster than closing the existing handle and opening a new one.
7716**
7717** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
7718** it must exist and there must be either a blob or text value stored in
7719** the nominated column.)^ ^If the new row is not present in the table, or if
7720** it does not contain a blob or text value, or if another error occurs, an
7721** SQLite error code is returned and the blob handle is considered aborted.
7722** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
7723** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
7724** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
7725** always returns zero.
7726**
7727** ^This function sets the database handle error code and message.
7728*/
7729SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
7730
7731/*
7732** CAPI3REF: Close A BLOB Handle
7733** DESTRUCTOR: sqlite3_blob
7734**
7735** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
7736** unconditionally. Even if this routine returns an error code, the
7737** handle is still closed.)^
7738**
7739** ^If the blob handle being closed was opened for read-write access, and if
7740** the database is in auto-commit mode and there are no other open read-write
7741** blob handles or active write statements, the current transaction is
7742** committed. ^If an error occurs while committing the transaction, an error
7743** code is returned and the transaction rolled back.
7744**
7745** Calling this function with an argument that is not a NULL pointer or an
7746** open blob handle results in undefined behaviour. ^Calling this routine
7747** with a null pointer (such as would be returned by a failed call to
7748** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
7749** is passed a valid open blob handle, the values returned by the
7750** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
7751*/
7752SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
7753
7754/*
7755** CAPI3REF: Return The Size Of An Open BLOB
7756** METHOD: sqlite3_blob
7757**
7758** ^Returns the size in bytes of the BLOB accessible via the
7759** successfully opened [BLOB handle] in its only argument. ^The
7760** incremental blob I/O routines can only read or overwriting existing
7761** blob content; they cannot change the size of a blob.
7762**
7763** This routine only works on a [BLOB handle] which has been created
7764** by a prior successful call to [sqlite3_blob_open()] and which has not
7765** been closed by [sqlite3_blob_close()]. Passing any other pointer in
7766** to this routine results in undefined and probably undesirable behavior.
7767*/
7768SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
7769
7770/*
7771** CAPI3REF: Read Data From A BLOB Incrementally
7772** METHOD: sqlite3_blob
7773**
7774** ^(This function is used to read data from an open [BLOB handle] into a
7775** caller-supplied buffer. N bytes of data are copied into buffer Z
7776** from the open BLOB, starting at offset iOffset.)^
7777**
7778** ^If offset iOffset is less than N bytes from the end of the BLOB,
7779** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
7780** less than zero, [SQLITE_ERROR] is returned and no data is read.
7781** ^The size of the blob (and hence the maximum value of N+iOffset)
7782** can be determined using the [sqlite3_blob_bytes()] interface.
7783**
7784** ^An attempt to read from an expired [BLOB handle] fails with an
7785** error code of [SQLITE_ABORT].
7786**
7787** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
7788** Otherwise, an [error code] or an [extended error code] is returned.)^
7789**
7790** This routine only works on a [BLOB handle] which has been created
7791** by a prior successful call to [sqlite3_blob_open()] and which has not
7792** been closed by [sqlite3_blob_close()]. Passing any other pointer in
7793** to this routine results in undefined and probably undesirable behavior.
7794**
7795** See also: [sqlite3_blob_write()].
7796*/
7797SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
7798
7799/*
7800** CAPI3REF: Write Data Into A BLOB Incrementally
7801** METHOD: sqlite3_blob
7802**
7803** ^(This function is used to write data into an open [BLOB handle] from a
7804** caller-supplied buffer. N bytes of data are copied from the buffer Z
7805** into the open BLOB, starting at offset iOffset.)^
7806**
7807** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
7808** Otherwise, an [error code] or an [extended error code] is returned.)^
7809** ^Unless SQLITE_MISUSE is returned, this function sets the
7810** [database connection] error code and message accessible via
7811** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
7812**
7813** ^If the [BLOB handle] passed as the first argument was not opened for
7814** writing (the flags parameter to [sqlite3_blob_open()] was zero),
7815** this function returns [SQLITE_READONLY].
7816**
7817** This function may only modify the contents of the BLOB; it is
7818** not possible to increase the size of a BLOB using this API.
7819** ^If offset iOffset is less than N bytes from the end of the BLOB,
7820** [SQLITE_ERROR] is returned and no data is written. The size of the
7821** BLOB (and hence the maximum value of N+iOffset) can be determined
7822** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
7823** than zero [SQLITE_ERROR] is returned and no data is written.
7824**
7825** ^An attempt to write to an expired [BLOB handle] fails with an
7826** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
7827** before the [BLOB handle] expired are not rolled back by the
7828** expiration of the handle, though of course those changes might
7829** have been overwritten by the statement that expired the BLOB handle
7830** or by other independent statements.
7831**
7832** This routine only works on a [BLOB handle] which has been created
7833** by a prior successful call to [sqlite3_blob_open()] and which has not
7834** been closed by [sqlite3_blob_close()]. Passing any other pointer in
7835** to this routine results in undefined and probably undesirable behavior.
7836**
7837** See also: [sqlite3_blob_read()].
7838*/
7839SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
7840
7841/*
7842** CAPI3REF: Virtual File System Objects
7843**
7844** A virtual filesystem (VFS) is an [sqlite3_vfs] object
7845** that SQLite uses to interact
7846** with the underlying operating system. Most SQLite builds come with a
7847** single default VFS that is appropriate for the host computer.
7848** New VFSes can be registered and existing VFSes can be unregistered.
7849** The following interfaces are provided.
7850**
7851** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
7852** ^Names are case sensitive.
7853** ^Names are zero-terminated UTF-8 strings.
7854** ^If there is no match, a NULL pointer is returned.
7855** ^If zVfsName is NULL then the default VFS is returned.
7856**
7857** ^New VFSes are registered with sqlite3_vfs_register().
7858** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
7859** ^The same VFS can be registered multiple times without injury.
7860** ^To make an existing VFS into the default VFS, register it again
7861** with the makeDflt flag set. If two different VFSes with the
7862** same name are registered, the behavior is undefined. If a
7863** VFS is registered with a name that is NULL or an empty string,
7864** then the behavior is undefined.
7865**
7866** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
7867** ^(If the default VFS is unregistered, another VFS is chosen as
7868** the default. The choice for the new VFS is arbitrary.)^
7869*/
7870SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
7871SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
7872SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
7873
7874/*
7875** CAPI3REF: Mutexes
7876**
7877** The SQLite core uses these routines for thread
7878** synchronization. Though they are intended for internal
7879** use by SQLite, code that links against SQLite is
7880** permitted to use any of these routines.
7881**
7882** The SQLite source code contains multiple implementations
7883** of these mutex routines. An appropriate implementation
7884** is selected automatically at compile-time. The following
7885** implementations are available in the SQLite core:
7886**
7887** <ul>
7888** <li> SQLITE_MUTEX_PTHREADS
7889** <li> SQLITE_MUTEX_W32
7890** <li> SQLITE_MUTEX_NOOP
7891** </ul>
7892**
7893** The SQLITE_MUTEX_NOOP implementation is a set of routines
7894** that does no real locking and is appropriate for use in
7895** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
7896** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
7897** and Windows.
7898**
7899** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
7900** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
7901** implementation is included with the library. In this case the
7902** application must supply a custom mutex implementation using the
7903** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
7904** before calling sqlite3_initialize() or any other public sqlite3_
7905** function that calls sqlite3_initialize().
7906**
7907** ^The sqlite3_mutex_alloc() routine allocates a new
7908** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
7909** routine returns NULL if it is unable to allocate the requested
7910** mutex. The argument to sqlite3_mutex_alloc() must one of these
7911** integer constants:
7912**
7913** <ul>
7914** <li> SQLITE_MUTEX_FAST
7915** <li> SQLITE_MUTEX_RECURSIVE
7916** <li> SQLITE_MUTEX_STATIC_MAIN
7917** <li> SQLITE_MUTEX_STATIC_MEM
7918** <li> SQLITE_MUTEX_STATIC_OPEN
7919** <li> SQLITE_MUTEX_STATIC_PRNG
7920** <li> SQLITE_MUTEX_STATIC_LRU
7921** <li> SQLITE_MUTEX_STATIC_PMEM
7922** <li> SQLITE_MUTEX_STATIC_APP1
7923** <li> SQLITE_MUTEX_STATIC_APP2
7924** <li> SQLITE_MUTEX_STATIC_APP3
7925** <li> SQLITE_MUTEX_STATIC_VFS1
7926** <li> SQLITE_MUTEX_STATIC_VFS2
7927** <li> SQLITE_MUTEX_STATIC_VFS3
7928** </ul>
7929**
7930** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
7931** cause sqlite3_mutex_alloc() to create
7932** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
7933** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
7934** The mutex implementation does not need to make a distinction
7935** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
7936** not want to. SQLite will only request a recursive mutex in
7937** cases where it really needs one. If a faster non-recursive mutex
7938** implementation is available on the host platform, the mutex subsystem
7939** might return such a mutex in response to SQLITE_MUTEX_FAST.
7940**
7941** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
7942** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
7943** a pointer to a static preexisting mutex. ^Nine static mutexes are
7944** used by the current version of SQLite. Future versions of SQLite
7945** may add additional static mutexes. Static mutexes are for internal
7946** use by SQLite only. Applications that use SQLite mutexes should
7947** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
7948** SQLITE_MUTEX_RECURSIVE.
7949**
7950** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
7951** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
7952** returns a different mutex on every call. ^For the static
7953** mutex types, the same mutex is returned on every call that has
7954** the same type number.
7955**
7956** ^The sqlite3_mutex_free() routine deallocates a previously
7957** allocated dynamic mutex. Attempting to deallocate a static
7958** mutex results in undefined behavior.
7959**
7960** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
7961** to enter a mutex. ^If another thread is already within the mutex,
7962** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
7963** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
7964** upon successful entry. ^(Mutexes created using
7965** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
7966** In such cases, the
7967** mutex must be exited an equal number of times before another thread
7968** can enter.)^ If the same thread tries to enter any mutex other
7969** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
7970**
7971** ^(Some systems (for example, Windows 95) do not support the operation
7972** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
7973** will always return SQLITE_BUSY. The SQLite core only ever uses
7974** sqlite3_mutex_try() as an optimization so this is acceptable
7975** behavior.)^
7976**
7977** ^The sqlite3_mutex_leave() routine exits a mutex that was
7978** previously entered by the same thread. The behavior
7979** is undefined if the mutex is not currently entered by the
7980** calling thread or is not currently allocated.
7981**
7982** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
7983** sqlite3_mutex_leave() is a NULL pointer, then all three routines
7984** behave as no-ops.
7985**
7986** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
7987*/
7988SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
7989SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
7990SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
7991SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
7992SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
7993
7994/*
7995** CAPI3REF: Mutex Methods Object
7996**
7997** An instance of this structure defines the low-level routines
7998** used to allocate and use mutexes.
7999**
8000** Usually, the default mutex implementations provided by SQLite are
8001** sufficient, however the application has the option of substituting a custom
8002** implementation for specialized deployments or systems for which SQLite
8003** does not provide a suitable implementation. In this case, the application
8004** creates and populates an instance of this structure to pass
8005** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
8006** Additionally, an instance of this structure can be used as an
8007** output variable when querying the system for the current mutex
8008** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
8009**
8010** ^The xMutexInit method defined by this structure is invoked as
8011** part of system initialization by the sqlite3_initialize() function.
8012** ^The xMutexInit routine is called by SQLite exactly once for each
8013** effective call to [sqlite3_initialize()].
8014**
8015** ^The xMutexEnd method defined by this structure is invoked as
8016** part of system shutdown by the sqlite3_shutdown() function. The
8017** implementation of this method is expected to release all outstanding
8018** resources obtained by the mutex methods implementation, especially
8019** those obtained by the xMutexInit method. ^The xMutexEnd()
8020** interface is invoked exactly once for each call to [sqlite3_shutdown()].
8021**
8022** ^(The remaining seven methods defined by this structure (xMutexAlloc,
8023** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
8024** xMutexNotheld) implement the following interfaces (respectively):
8025**
8026** <ul>
8027** <li> [sqlite3_mutex_alloc()] </li>
8028** <li> [sqlite3_mutex_free()] </li>
8029** <li> [sqlite3_mutex_enter()] </li>
8030** <li> [sqlite3_mutex_try()] </li>
8031** <li> [sqlite3_mutex_leave()] </li>
8032** <li> [sqlite3_mutex_held()] </li>
8033** <li> [sqlite3_mutex_notheld()] </li>
8034** </ul>)^
8035**
8036** The only difference is that the public sqlite3_XXX functions enumerated
8037** above silently ignore any invocations that pass a NULL pointer instead
8038** of a valid mutex handle. The implementations of the methods defined
8039** by this structure are not required to handle this case. The results
8040** of passing a NULL pointer instead of a valid mutex handle are undefined
8041** (i.e. it is acceptable to provide an implementation that segfaults if
8042** it is passed a NULL pointer).
8043**
8044** The xMutexInit() method must be threadsafe. It must be harmless to
8045** invoke xMutexInit() multiple times within the same process and without
8046** intervening calls to xMutexEnd(). Second and subsequent calls to
8047** xMutexInit() must be no-ops.
8048**
8049** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
8050** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
8051** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
8052** memory allocation for a fast or recursive mutex.
8053**
8054** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
8055** called, but only if the prior call to xMutexInit returned SQLITE_OK.
8056** If xMutexInit fails in any way, it is expected to clean up after itself
8057** prior to returning.
8058*/
8059typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
8060struct sqlite3_mutex_methods {
8061 int (*xMutexInit)(void);
8062 int (*xMutexEnd)(void);
8063 sqlite3_mutex *(*xMutexAlloc)(int);
8064 void (*xMutexFree)(sqlite3_mutex *);
8065 void (*xMutexEnter)(sqlite3_mutex *);
8066 int (*xMutexTry)(sqlite3_mutex *);
8067 void (*xMutexLeave)(sqlite3_mutex *);
8068 int (*xMutexHeld)(sqlite3_mutex *);
8069 int (*xMutexNotheld)(sqlite3_mutex *);
8070};
8071
8072/*
8073** CAPI3REF: Mutex Verification Routines
8074**
8075** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
8076** are intended for use inside assert() statements. The SQLite core
8077** never uses these routines except inside an assert() and applications
8078** are advised to follow the lead of the core. The SQLite core only
8079** provides implementations for these routines when it is compiled
8080** with the SQLITE_DEBUG flag. External mutex implementations
8081** are only required to provide these routines if SQLITE_DEBUG is
8082** defined and if NDEBUG is not defined.
8083**
8084** These routines should return true if the mutex in their argument
8085** is held or not held, respectively, by the calling thread.
8086**
8087** The implementation is not required to provide versions of these
8088** routines that actually work. If the implementation does not provide working
8089** versions of these routines, it should at least provide stubs that always
8090** return true so that one does not get spurious assertion failures.
8091**
8092** If the argument to sqlite3_mutex_held() is a NULL pointer then
8093** the routine should return 1. This seems counter-intuitive since
8094** clearly the mutex cannot be held if it does not exist. But
8095** the reason the mutex does not exist is because the build is not
8096** using mutexes. And we do not want the assert() containing the
8097** call to sqlite3_mutex_held() to fail, so a non-zero return is
8098** the appropriate thing to do. The sqlite3_mutex_notheld()
8099** interface should also return 1 when given a NULL pointer.
8100*/
8101#ifndef NDEBUG
8102SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
8103SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
8104#endif
8105
8106/*
8107** CAPI3REF: Mutex Types
8108**
8109** The [sqlite3_mutex_alloc()] interface takes a single argument
8110** which is one of these integer constants.
8111**
8112** The set of static mutexes may change from one SQLite release to the
8113** next. Applications that override the built-in mutex logic must be
8114** prepared to accommodate additional static mutexes.
8115*/
8116#define SQLITE_MUTEX_FAST 0
8117#define SQLITE_MUTEX_RECURSIVE 1
8118#define SQLITE_MUTEX_STATIC_MAIN 2
8119#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
8120#define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
8121#define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
8122#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */
8123#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
8124#define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
8125#define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
8126#define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
8127#define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
8128#define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
8129#define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
8130#define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
8131#define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
8132
8133/* Legacy compatibility: */
8134#define SQLITE_MUTEX_STATIC_MASTER 2
8135
8136
8137/*
8138** CAPI3REF: Retrieve the mutex for a database connection
8139** METHOD: sqlite3
8140**
8141** ^This interface returns a pointer the [sqlite3_mutex] object that
8142** serializes access to the [database connection] given in the argument
8143** when the [threading mode] is Serialized.
8144** ^If the [threading mode] is Single-thread or Multi-thread then this
8145** routine returns a NULL pointer.
8146*/
8147SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
8148
8149/*
8150** CAPI3REF: Low-Level Control Of Database Files
8151** METHOD: sqlite3
8152** KEYWORDS: {file control}
8153**
8154** ^The [sqlite3_file_control()] interface makes a direct call to the
8155** xFileControl method for the [sqlite3_io_methods] object associated
8156** with a particular database identified by the second argument. ^The
8157** name of the database is "main" for the main database or "temp" for the
8158** TEMP database, or the name that appears after the AS keyword for
8159** databases that are added using the [ATTACH] SQL command.
8160** ^A NULL pointer can be used in place of "main" to refer to the
8161** main database file.
8162** ^The third and fourth parameters to this routine
8163** are passed directly through to the second and third parameters of
8164** the xFileControl method. ^The return value of the xFileControl
8165** method becomes the return value of this routine.
8166**
8167** A few opcodes for [sqlite3_file_control()] are handled directly
8168** by the SQLite core and never invoke the
8169** sqlite3_io_methods.xFileControl method.
8170** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes
8171** a pointer to the underlying [sqlite3_file] object to be written into
8172** the space pointed to by the 4th parameter. The
8173** [SQLITE_FCNTL_JOURNAL_POINTER] works similarly except that it returns
8174** the [sqlite3_file] object associated with the journal file instead of
8175** the main database. The [SQLITE_FCNTL_VFS_POINTER] opcode returns
8176** a pointer to the underlying [sqlite3_vfs] object for the file.
8177** The [SQLITE_FCNTL_DATA_VERSION] returns the data version counter
8178** from the pager.
8179**
8180** ^If the second parameter (zDbName) does not match the name of any
8181** open database file, then SQLITE_ERROR is returned. ^This error
8182** code is not remembered and will not be recalled by [sqlite3_errcode()]
8183** or [sqlite3_errmsg()]. The underlying xFileControl method might
8184** also return SQLITE_ERROR. There is no way to distinguish between
8185** an incorrect zDbName and an SQLITE_ERROR return from the underlying
8186** xFileControl method.
8187**
8188** See also: [file control opcodes]
8189*/
8190SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
8191
8192/*
8193** CAPI3REF: Testing Interface
8194**
8195** ^The sqlite3_test_control() interface is used to read out internal
8196** state of SQLite and to inject faults into SQLite for testing
8197** purposes. ^The first parameter is an operation code that determines
8198** the number, meaning, and operation of all subsequent parameters.
8199**
8200** This interface is not for use by applications. It exists solely
8201** for verifying the correct operation of the SQLite library. Depending
8202** on how the SQLite library is compiled, this interface might not exist.
8203**
8204** The details of the operation codes, their meanings, the parameters
8205** they take, and what they do are all subject to change without notice.
8206** Unlike most of the SQLite API, this function is not guaranteed to
8207** operate consistently from one release to the next.
8208*/
8209SQLITE_API int sqlite3_test_control(int op, ...);
8210
8211/*
8212** CAPI3REF: Testing Interface Operation Codes
8213**
8214** These constants are the valid operation code parameters used
8215** as the first argument to [sqlite3_test_control()].
8216**
8217** These parameters and their meanings are subject to change
8218** without notice. These values are for testing purposes only.
8219** Applications should not use any of these parameters or the
8220** [sqlite3_test_control()] interface.
8221*/
8222#define SQLITE_TESTCTRL_FIRST 5
8223#define SQLITE_TESTCTRL_PRNG_SAVE 5
8224#define SQLITE_TESTCTRL_PRNG_RESTORE 6
8225#define SQLITE_TESTCTRL_PRNG_RESET 7 /* NOT USED */
8226#define SQLITE_TESTCTRL_BITVEC_TEST 8
8227#define SQLITE_TESTCTRL_FAULT_INSTALL 9
8228#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
8229#define SQLITE_TESTCTRL_PENDING_BYTE 11
8230#define SQLITE_TESTCTRL_ASSERT 12
8231#define SQLITE_TESTCTRL_ALWAYS 13
8232#define SQLITE_TESTCTRL_RESERVE 14 /* NOT USED */
8233#define SQLITE_TESTCTRL_OPTIMIZATIONS 15
8234#define SQLITE_TESTCTRL_ISKEYWORD 16 /* NOT USED */
8235#define SQLITE_TESTCTRL_SCRATCHMALLOC 17 /* NOT USED */
8236#define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS 17
8237#define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
8238#define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
8239#define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19
8240#define SQLITE_TESTCTRL_NEVER_CORRUPT 20
8241#define SQLITE_TESTCTRL_VDBE_COVERAGE 21
8242#define SQLITE_TESTCTRL_BYTEORDER 22
8243#define SQLITE_TESTCTRL_ISINIT 23
8244#define SQLITE_TESTCTRL_SORTER_MMAP 24
8245#define SQLITE_TESTCTRL_IMPOSTER 25
8246#define SQLITE_TESTCTRL_PARSER_COVERAGE 26
8247#define SQLITE_TESTCTRL_RESULT_INTREAL 27
8248#define SQLITE_TESTCTRL_PRNG_SEED 28
8249#define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS 29
8250#define SQLITE_TESTCTRL_SEEK_COUNT 30
8251#define SQLITE_TESTCTRL_TRACEFLAGS 31
8252#define SQLITE_TESTCTRL_TUNE 32
8253#define SQLITE_TESTCTRL_LAST 32 /* Largest TESTCTRL */
8254
8255/*
8256** CAPI3REF: SQL Keyword Checking
8257**
8258** These routines provide access to the set of SQL language keywords
8259** recognized by SQLite. Applications can uses these routines to determine
8260** whether or not a specific identifier needs to be escaped (for example,
8261** by enclosing in double-quotes) so as not to confuse the parser.
8262**
8263** The sqlite3_keyword_count() interface returns the number of distinct
8264** keywords understood by SQLite.
8265**
8266** The sqlite3_keyword_name(N,Z,L) interface finds the N-th keyword and
8267** makes *Z point to that keyword expressed as UTF8 and writes the number
8268** of bytes in the keyword into *L. The string that *Z points to is not
8269** zero-terminated. The sqlite3_keyword_name(N,Z,L) routine returns
8270** SQLITE_OK if N is within bounds and SQLITE_ERROR if not. If either Z
8271** or L are NULL or invalid pointers then calls to
8272** sqlite3_keyword_name(N,Z,L) result in undefined behavior.
8273**
8274** The sqlite3_keyword_check(Z,L) interface checks to see whether or not
8275** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero
8276** if it is and zero if not.
8277**
8278** The parser used by SQLite is forgiving. It is often possible to use
8279** a keyword as an identifier as long as such use does not result in a
8280** parsing ambiguity. For example, the statement
8281** "CREATE TABLE BEGIN(REPLACE,PRAGMA,END);" is accepted by SQLite, and
8282** creates a new table named "BEGIN" with three columns named
8283** "REPLACE", "PRAGMA", and "END". Nevertheless, best practice is to avoid
8284** using keywords as identifiers. Common techniques used to avoid keyword
8285** name collisions include:
8286** <ul>
8287** <li> Put all identifier names inside double-quotes. This is the official
8288** SQL way to escape identifier names.
8289** <li> Put identifier names inside &#91;...&#93;. This is not standard SQL,
8290** but it is what SQL Server does and so lots of programmers use this
8291** technique.
8292** <li> Begin every identifier with the letter "Z" as no SQL keywords start
8293** with "Z".
8294** <li> Include a digit somewhere in every identifier name.
8295** </ul>
8296**
8297** Note that the number of keywords understood by SQLite can depend on
8298** compile-time options. For example, "VACUUM" is not a keyword if
8299** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option. Also,
8300** new keywords may be added to future releases of SQLite.
8301*/
8302SQLITE_API int sqlite3_keyword_count(void);
8303SQLITE_API int sqlite3_keyword_name(int,const char**,int*);
8304SQLITE_API int sqlite3_keyword_check(const char*,int);
8305
8306/*
8307** CAPI3REF: Dynamic String Object
8308** KEYWORDS: {dynamic string}
8309**
8310** An instance of the sqlite3_str object contains a dynamically-sized
8311** string under construction.
8312**
8313** The lifecycle of an sqlite3_str object is as follows:
8314** <ol>
8315** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].
8316** <li> ^Text is appended to the sqlite3_str object using various
8317** methods, such as [sqlite3_str_appendf()].
8318** <li> ^The sqlite3_str object is destroyed and the string it created
8319** is returned using the [sqlite3_str_finish()] interface.
8320** </ol>
8321*/
8322typedef struct sqlite3_str sqlite3_str;
8323
8324/*
8325** CAPI3REF: Create A New Dynamic String Object
8326** CONSTRUCTOR: sqlite3_str
8327**
8328** ^The [sqlite3_str_new(D)] interface allocates and initializes
8329** a new [sqlite3_str] object. To avoid memory leaks, the object returned by
8330** [sqlite3_str_new()] must be freed by a subsequent call to
8331** [sqlite3_str_finish(X)].
8332**
8333** ^The [sqlite3_str_new(D)] interface always returns a pointer to a
8334** valid [sqlite3_str] object, though in the event of an out-of-memory
8335** error the returned object might be a special singleton that will
8336** silently reject new text, always return SQLITE_NOMEM from
8337** [sqlite3_str_errcode()], always return 0 for
8338** [sqlite3_str_length()], and always return NULL from
8339** [sqlite3_str_finish(X)]. It is always safe to use the value
8340** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter
8341** to any of the other [sqlite3_str] methods.
8342**
8343** The D parameter to [sqlite3_str_new(D)] may be NULL. If the
8344** D parameter in [sqlite3_str_new(D)] is not NULL, then the maximum
8345** length of the string contained in the [sqlite3_str] object will be
8346** the value set for [sqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead
8347** of [SQLITE_MAX_LENGTH].
8348*/
8349SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*);
8350
8351/*
8352** CAPI3REF: Finalize A Dynamic String
8353** DESTRUCTOR: sqlite3_str
8354**
8355** ^The [sqlite3_str_finish(X)] interface destroys the sqlite3_str object X
8356** and returns a pointer to a memory buffer obtained from [sqlite3_malloc64()]
8357** that contains the constructed string. The calling application should
8358** pass the returned value to [sqlite3_free()] to avoid a memory leak.
8359** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any
8360** errors were encountered during construction of the string. ^The
8361** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the
8362** string in [sqlite3_str] object X is zero bytes long.
8363*/
8364SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
8365
8366/*
8367** CAPI3REF: Add Content To A Dynamic String
8368** METHOD: sqlite3_str
8369**
8370** These interfaces add content to an sqlite3_str object previously obtained
8371** from [sqlite3_str_new()].
8372**
8373** ^The [sqlite3_str_appendf(X,F,...)] and
8374** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]
8375** functionality of SQLite to append formatted text onto the end of
8376** [sqlite3_str] object X.
8377**
8378** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S
8379** onto the end of the [sqlite3_str] object X. N must be non-negative.
8380** S must contain at least N non-zero bytes of content. To append a
8381** zero-terminated string in its entirety, use the [sqlite3_str_appendall()]
8382** method instead.
8383**
8384** ^The [sqlite3_str_appendall(X,S)] method appends the complete content of
8385** zero-terminated string S onto the end of [sqlite3_str] object X.
8386**
8387** ^The [sqlite3_str_appendchar(X,N,C)] method appends N copies of the
8388** single-byte character C onto the end of [sqlite3_str] object X.
8389** ^This method can be used, for example, to add whitespace indentation.
8390**
8391** ^The [sqlite3_str_reset(X)] method resets the string under construction
8392** inside [sqlite3_str] object X back to zero bytes in length.
8393**
8394** These methods do not return a result code. ^If an error occurs, that fact
8395** is recorded in the [sqlite3_str] object and can be recovered by a
8396** subsequent call to [sqlite3_str_errcode(X)].
8397*/
8398SQLITE_API void sqlite3_str_appendf(sqlite3_str*, const char *zFormat, ...);
8399SQLITE_API void sqlite3_str_vappendf(sqlite3_str*, const char *zFormat, va_list);
8400SQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N);
8401SQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn);
8402SQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C);
8403SQLITE_API void sqlite3_str_reset(sqlite3_str*);
8404
8405/*
8406** CAPI3REF: Status Of A Dynamic String
8407** METHOD: sqlite3_str
8408**
8409** These interfaces return the current status of an [sqlite3_str] object.
8410**
8411** ^If any prior errors have occurred while constructing the dynamic string
8412** in sqlite3_str X, then the [sqlite3_str_errcode(X)] method will return
8413** an appropriate error code. ^The [sqlite3_str_errcode(X)] method returns
8414** [SQLITE_NOMEM] following any out-of-memory error, or
8415** [SQLITE_TOOBIG] if the size of the dynamic string exceeds
8416** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors.
8417**
8418** ^The [sqlite3_str_length(X)] method returns the current length, in bytes,
8419** of the dynamic string under construction in [sqlite3_str] object X.
8420** ^The length returned by [sqlite3_str_length(X)] does not include the
8421** zero-termination byte.
8422**
8423** ^The [sqlite3_str_value(X)] method returns a pointer to the current
8424** content of the dynamic string under construction in X. The value
8425** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X
8426** and might be freed or altered by any subsequent method on the same
8427** [sqlite3_str] object. Applications must not used the pointer returned
8428** [sqlite3_str_value(X)] after any subsequent method call on the same
8429** object. ^Applications may change the content of the string returned
8430** by [sqlite3_str_value(X)] as long as they do not write into any bytes
8431** outside the range of 0 to [sqlite3_str_length(X)] and do not read or
8432** write any byte after any subsequent sqlite3_str method call.
8433*/
8434SQLITE_API int sqlite3_str_errcode(sqlite3_str*);
8435SQLITE_API int sqlite3_str_length(sqlite3_str*);
8436SQLITE_API char *sqlite3_str_value(sqlite3_str*);
8437
8438/*
8439** CAPI3REF: SQLite Runtime Status
8440**
8441** ^These interfaces are used to retrieve runtime status information
8442** about the performance of SQLite, and optionally to reset various
8443** highwater marks. ^The first argument is an integer code for
8444** the specific parameter to measure. ^(Recognized integer codes
8445** are of the form [status parameters | SQLITE_STATUS_...].)^
8446** ^The current value of the parameter is returned into *pCurrent.
8447** ^The highest recorded value is returned in *pHighwater. ^If the
8448** resetFlag is true, then the highest record value is reset after
8449** *pHighwater is written. ^(Some parameters do not record the highest
8450** value. For those parameters
8451** nothing is written into *pHighwater and the resetFlag is ignored.)^
8452** ^(Other parameters record only the highwater mark and not the current
8453** value. For these latter parameters nothing is written into *pCurrent.)^
8454**
8455** ^The sqlite3_status() and sqlite3_status64() routines return
8456** SQLITE_OK on success and a non-zero [error code] on failure.
8457**
8458** If either the current value or the highwater mark is too large to
8459** be represented by a 32-bit integer, then the values returned by
8460** sqlite3_status() are undefined.
8461**
8462** See also: [sqlite3_db_status()]
8463*/
8464SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
8465SQLITE_API int sqlite3_status64(
8466 int op,
8467 sqlite3_int64 *pCurrent,
8468 sqlite3_int64 *pHighwater,
8469 int resetFlag
8470);
8471
8472
8473/*
8474** CAPI3REF: Status Parameters
8475** KEYWORDS: {status parameters}
8476**
8477** These integer constants designate various run-time status parameters
8478** that can be returned by [sqlite3_status()].
8479**
8480** <dl>
8481** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
8482** <dd>This parameter is the current amount of memory checked out
8483** using [sqlite3_malloc()], either directly or indirectly. The
8484** figure includes calls made to [sqlite3_malloc()] by the application
8485** and internal memory usage by the SQLite library. Auxiliary page-cache
8486** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
8487** this parameter. The amount returned is the sum of the allocation
8488** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
8489**
8490** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
8491** <dd>This parameter records the largest memory allocation request
8492** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
8493** internal equivalents). Only the value returned in the
8494** *pHighwater parameter to [sqlite3_status()] is of interest.
8495** The value written into the *pCurrent parameter is undefined.</dd>)^
8496**
8497** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
8498** <dd>This parameter records the number of separate memory allocations
8499** currently checked out.</dd>)^
8500**
8501** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
8502** <dd>This parameter returns the number of pages used out of the
8503** [pagecache memory allocator] that was configured using
8504** [SQLITE_CONFIG_PAGECACHE]. The
8505** value returned is in pages, not in bytes.</dd>)^
8506**
8507** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
8508** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
8509** <dd>This parameter returns the number of bytes of page cache
8510** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
8511** buffer and where forced to overflow to [sqlite3_malloc()]. The
8512** returned value includes allocations that overflowed because they
8513** where too large (they were larger than the "sz" parameter to
8514** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
8515** no space was left in the page cache.</dd>)^
8516**
8517** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
8518** <dd>This parameter records the largest memory allocation request
8519** handed to the [pagecache memory allocator]. Only the value returned in the
8520** *pHighwater parameter to [sqlite3_status()] is of interest.
8521** The value written into the *pCurrent parameter is undefined.</dd>)^
8522**
8523** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>
8524** <dd>No longer used.</dd>
8525**
8526** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
8527** <dd>No longer used.</dd>
8528**
8529** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
8530** <dd>No longer used.</dd>
8531**
8532** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
8533** <dd>The *pHighwater parameter records the deepest parser stack.
8534** The *pCurrent value is undefined. The *pHighwater value is only
8535** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
8536** </dl>
8537**
8538** New status parameters may be added from time to time.
8539*/
8540#define SQLITE_STATUS_MEMORY_USED 0
8541#define SQLITE_STATUS_PAGECACHE_USED 1
8542#define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
8543#define SQLITE_STATUS_SCRATCH_USED 3 /* NOT USED */
8544#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 /* NOT USED */
8545#define SQLITE_STATUS_MALLOC_SIZE 5
8546#define SQLITE_STATUS_PARSER_STACK 6
8547#define SQLITE_STATUS_PAGECACHE_SIZE 7
8548#define SQLITE_STATUS_SCRATCH_SIZE 8 /* NOT USED */
8549#define SQLITE_STATUS_MALLOC_COUNT 9
8550
8551/*
8552** CAPI3REF: Database Connection Status
8553** METHOD: sqlite3
8554**
8555** ^This interface is used to retrieve runtime status information
8556** about a single [database connection]. ^The first argument is the
8557** database connection object to be interrogated. ^The second argument
8558** is an integer constant, taken from the set of
8559** [SQLITE_DBSTATUS options], that
8560** determines the parameter to interrogate. The set of
8561** [SQLITE_DBSTATUS options] is likely
8562** to grow in future releases of SQLite.
8563**
8564** ^The current value of the requested parameter is written into *pCur
8565** and the highest instantaneous value is written into *pHiwtr. ^If
8566** the resetFlg is true, then the highest instantaneous value is
8567** reset back down to the current value.
8568**
8569** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
8570** non-zero [error code] on failure.
8571**
8572** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
8573*/
8574SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
8575
8576/*
8577** CAPI3REF: Status Parameters for database connections
8578** KEYWORDS: {SQLITE_DBSTATUS options}
8579**
8580** These constants are the available integer "verbs" that can be passed as
8581** the second argument to the [sqlite3_db_status()] interface.
8582**
8583** New verbs may be added in future releases of SQLite. Existing verbs
8584** might be discontinued. Applications should check the return code from
8585** [sqlite3_db_status()] to make sure that the call worked.
8586** The [sqlite3_db_status()] interface will return a non-zero error code
8587** if a discontinued or unsupported verb is invoked.
8588**
8589** <dl>
8590** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
8591** <dd>This parameter returns the number of lookaside memory slots currently
8592** checked out.</dd>)^
8593**
8594** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
8595** <dd>This parameter returns the number of malloc attempts that were
8596** satisfied using lookaside memory. Only the high-water value is meaningful;
8597** the current value is always zero.)^
8598**
8599** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
8600** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
8601** <dd>This parameter returns the number malloc attempts that might have
8602** been satisfied using lookaside memory but failed due to the amount of
8603** memory requested being larger than the lookaside slot size.
8604** Only the high-water value is meaningful;
8605** the current value is always zero.)^
8606**
8607** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
8608** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
8609** <dd>This parameter returns the number malloc attempts that might have
8610** been satisfied using lookaside memory but failed due to all lookaside
8611** memory already being in use.
8612** Only the high-water value is meaningful;
8613** the current value is always zero.)^
8614**
8615** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
8616** <dd>This parameter returns the approximate number of bytes of heap
8617** memory used by all pager caches associated with the database connection.)^
8618** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
8619**
8620** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
8621** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
8622** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
8623** pager cache is shared between two or more connections the bytes of heap
8624** memory used by that pager cache is divided evenly between the attached
8625** connections.)^ In other words, if none of the pager caches associated
8626** with the database connection are shared, this request returns the same
8627** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
8628** shared, the value returned by this call will be smaller than that returned
8629** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
8630** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
8631**
8632** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
8633** <dd>This parameter returns the approximate number of bytes of heap
8634** memory used to store the schema for all databases associated
8635** with the connection - main, temp, and any [ATTACH]-ed databases.)^
8636** ^The full amount of memory used by the schemas is reported, even if the
8637** schema memory is shared with other database connections due to
8638** [shared cache mode] being enabled.
8639** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
8640**
8641** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
8642** <dd>This parameter returns the approximate number of bytes of heap
8643** and lookaside memory used by all prepared statements associated with
8644** the database connection.)^
8645** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
8646** </dd>
8647**
8648** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
8649** <dd>This parameter returns the number of pager cache hits that have
8650** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
8651** is always 0.
8652** </dd>
8653**
8654** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
8655** <dd>This parameter returns the number of pager cache misses that have
8656** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
8657** is always 0.
8658** </dd>
8659**
8660** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
8661** <dd>This parameter returns the number of dirty cache entries that have
8662** been written to disk. Specifically, the number of pages written to the
8663** wal file in wal mode databases, or the number of pages written to the
8664** database file in rollback mode databases. Any pages written as part of
8665** transaction rollback or database recovery operations are not included.
8666** If an IO or other error occurs while writing a page to disk, the effect
8667** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
8668** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
8669** </dd>
8670**
8671** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt>
8672** <dd>This parameter returns the number of dirty cache entries that have
8673** been written to disk in the middle of a transaction due to the page
8674** cache overflowing. Transactions are more efficient if they are written
8675** to disk all at once. When pages spill mid-transaction, that introduces
8676** additional overhead. This parameter can be used help identify
8677** inefficiencies that can be resolved by increasing the cache size.
8678** </dd>
8679**
8680** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
8681** <dd>This parameter returns zero for the current value if and only if
8682** all foreign key constraints (deferred or immediate) have been
8683** resolved.)^ ^The highwater mark is always 0.
8684** </dd>
8685** </dl>
8686*/
8687#define SQLITE_DBSTATUS_LOOKASIDE_USED 0
8688#define SQLITE_DBSTATUS_CACHE_USED 1
8689#define SQLITE_DBSTATUS_SCHEMA_USED 2
8690#define SQLITE_DBSTATUS_STMT_USED 3
8691#define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
8692#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
8693#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
8694#define SQLITE_DBSTATUS_CACHE_HIT 7
8695#define SQLITE_DBSTATUS_CACHE_MISS 8
8696#define SQLITE_DBSTATUS_CACHE_WRITE 9
8697#define SQLITE_DBSTATUS_DEFERRED_FKS 10
8698#define SQLITE_DBSTATUS_CACHE_USED_SHARED 11
8699#define SQLITE_DBSTATUS_CACHE_SPILL 12
8700#define SQLITE_DBSTATUS_MAX 12 /* Largest defined DBSTATUS */
8701
8702
8703/*
8704** CAPI3REF: Prepared Statement Status
8705** METHOD: sqlite3_stmt
8706**
8707** ^(Each prepared statement maintains various
8708** [SQLITE_STMTSTATUS counters] that measure the number
8709** of times it has performed specific operations.)^ These counters can
8710** be used to monitor the performance characteristics of the prepared
8711** statements. For example, if the number of table steps greatly exceeds
8712** the number of table searches or result rows, that would tend to indicate
8713** that the prepared statement is using a full table scan rather than
8714** an index.
8715**
8716** ^(This interface is used to retrieve and reset counter values from
8717** a [prepared statement]. The first argument is the prepared statement
8718** object to be interrogated. The second argument
8719** is an integer code for a specific [SQLITE_STMTSTATUS counter]
8720** to be interrogated.)^
8721** ^The current value of the requested counter is returned.
8722** ^If the resetFlg is true, then the counter is reset to zero after this
8723** interface call returns.
8724**
8725** See also: [sqlite3_status()] and [sqlite3_db_status()].
8726*/
8727SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
8728
8729/*
8730** CAPI3REF: Status Parameters for prepared statements
8731** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
8732**
8733** These preprocessor macros define integer codes that name counter
8734** values associated with the [sqlite3_stmt_status()] interface.
8735** The meanings of the various counters are as follows:
8736**
8737** <dl>
8738** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
8739** <dd>^This is the number of times that SQLite has stepped forward in
8740** a table as part of a full table scan. Large numbers for this counter
8741** may indicate opportunities for performance improvement through
8742** careful use of indices.</dd>
8743**
8744** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
8745** <dd>^This is the number of sort operations that have occurred.
8746** A non-zero value in this counter may indicate an opportunity to
8747** improvement performance through careful use of indices.</dd>
8748**
8749** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
8750** <dd>^This is the number of rows inserted into transient indices that
8751** were created automatically in order to help joins run faster.
8752** A non-zero value in this counter may indicate an opportunity to
8753** improvement performance by adding permanent indices that do not
8754** need to be reinitialized each time the statement is run.</dd>
8755**
8756** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
8757** <dd>^This is the number of virtual machine operations executed
8758** by the prepared statement if that number is less than or equal
8759** to 2147483647. The number of virtual machine operations can be
8760** used as a proxy for the total work done by the prepared statement.
8761** If the number of virtual machine operations exceeds 2147483647
8762** then the value returned by this statement status code is undefined.
8763**
8764** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>
8765** <dd>^This is the number of times that the prepare statement has been
8766** automatically regenerated due to schema changes or changes to
8767** [bound parameters] that might affect the query plan.
8768**
8769** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
8770** <dd>^This is the number of times that the prepared statement has
8771** been run. A single "run" for the purposes of this counter is one
8772** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].
8773** The counter is incremented on the first [sqlite3_step()] call of each
8774** cycle.
8775**
8776** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
8777** <dd>^This is the approximate number of bytes of heap memory
8778** used to store the prepared statement. ^This value is not actually
8779** a counter, and so the resetFlg parameter to sqlite3_stmt_status()
8780** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.
8781** </dd>
8782** </dl>
8783*/
8784#define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
8785#define SQLITE_STMTSTATUS_SORT 2
8786#define SQLITE_STMTSTATUS_AUTOINDEX 3
8787#define SQLITE_STMTSTATUS_VM_STEP 4
8788#define SQLITE_STMTSTATUS_REPREPARE 5
8789#define SQLITE_STMTSTATUS_RUN 6
8790#define SQLITE_STMTSTATUS_MEMUSED 99
8791
8792/*
8793** CAPI3REF: Custom Page Cache Object
8794**
8795** The sqlite3_pcache type is opaque. It is implemented by
8796** the pluggable module. The SQLite core has no knowledge of
8797** its size or internal structure and never deals with the
8798** sqlite3_pcache object except by holding and passing pointers
8799** to the object.
8800**
8801** See [sqlite3_pcache_methods2] for additional information.
8802*/
8803typedef struct sqlite3_pcache sqlite3_pcache;
8804
8805/*
8806** CAPI3REF: Custom Page Cache Object
8807**
8808** The sqlite3_pcache_page object represents a single page in the
8809** page cache. The page cache will allocate instances of this
8810** object. Various methods of the page cache use pointers to instances
8811** of this object as parameters or as their return value.
8812**
8813** See [sqlite3_pcache_methods2] for additional information.
8814*/
8815typedef struct sqlite3_pcache_page sqlite3_pcache_page;
8816struct sqlite3_pcache_page {
8817 void *pBuf; /* The content of the page */
8818 void *pExtra; /* Extra information associated with the page */
8819};
8820
8821/*
8822** CAPI3REF: Application Defined Page Cache.
8823** KEYWORDS: {page cache}
8824**
8825** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
8826** register an alternative page cache implementation by passing in an
8827** instance of the sqlite3_pcache_methods2 structure.)^
8828** In many applications, most of the heap memory allocated by
8829** SQLite is used for the page cache.
8830** By implementing a
8831** custom page cache using this API, an application can better control
8832** the amount of memory consumed by SQLite, the way in which
8833** that memory is allocated and released, and the policies used to
8834** determine exactly which parts of a database file are cached and for
8835** how long.
8836**
8837** The alternative page cache mechanism is an
8838** extreme measure that is only needed by the most demanding applications.
8839** The built-in page cache is recommended for most uses.
8840**
8841** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
8842** internal buffer by SQLite within the call to [sqlite3_config]. Hence
8843** the application may discard the parameter after the call to
8844** [sqlite3_config()] returns.)^
8845**
8846** [[the xInit() page cache method]]
8847** ^(The xInit() method is called once for each effective
8848** call to [sqlite3_initialize()])^
8849** (usually only once during the lifetime of the process). ^(The xInit()
8850** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
8851** The intent of the xInit() method is to set up global data structures
8852** required by the custom page cache implementation.
8853** ^(If the xInit() method is NULL, then the
8854** built-in default page cache is used instead of the application defined
8855** page cache.)^
8856**
8857** [[the xShutdown() page cache method]]
8858** ^The xShutdown() method is called by [sqlite3_shutdown()].
8859** It can be used to clean up
8860** any outstanding resources before process shutdown, if required.
8861** ^The xShutdown() method may be NULL.
8862**
8863** ^SQLite automatically serializes calls to the xInit method,
8864** so the xInit method need not be threadsafe. ^The
8865** xShutdown method is only called from [sqlite3_shutdown()] so it does
8866** not need to be threadsafe either. All other methods must be threadsafe
8867** in multithreaded applications.
8868**
8869** ^SQLite will never invoke xInit() more than once without an intervening
8870** call to xShutdown().
8871**
8872** [[the xCreate() page cache methods]]
8873** ^SQLite invokes the xCreate() method to construct a new cache instance.
8874** SQLite will typically create one cache instance for each open database file,
8875** though this is not guaranteed. ^The
8876** first parameter, szPage, is the size in bytes of the pages that must
8877** be allocated by the cache. ^szPage will always a power of two. ^The
8878** second parameter szExtra is a number of bytes of extra storage
8879** associated with each page cache entry. ^The szExtra parameter will
8880** a number less than 250. SQLite will use the
8881** extra szExtra bytes on each page to store metadata about the underlying
8882** database page on disk. The value passed into szExtra depends
8883** on the SQLite version, the target platform, and how SQLite was compiled.
8884** ^The third argument to xCreate(), bPurgeable, is true if the cache being
8885** created will be used to cache database pages of a file stored on disk, or
8886** false if it is used for an in-memory database. The cache implementation
8887** does not have to do anything special based with the value of bPurgeable;
8888** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
8889** never invoke xUnpin() except to deliberately delete a page.
8890** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
8891** false will always have the "discard" flag set to true.
8892** ^Hence, a cache created with bPurgeable false will
8893** never contain any unpinned pages.
8894**
8895** [[the xCachesize() page cache method]]
8896** ^(The xCachesize() method may be called at any time by SQLite to set the
8897** suggested maximum cache-size (number of pages stored by) the cache
8898** instance passed as the first argument. This is the value configured using
8899** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
8900** parameter, the implementation is not required to do anything with this
8901** value; it is advisory only.
8902**
8903** [[the xPagecount() page cache methods]]
8904** The xPagecount() method must return the number of pages currently
8905** stored in the cache, both pinned and unpinned.
8906**
8907** [[the xFetch() page cache methods]]
8908** The xFetch() method locates a page in the cache and returns a pointer to
8909** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
8910** The pBuf element of the returned sqlite3_pcache_page object will be a
8911** pointer to a buffer of szPage bytes used to store the content of a
8912** single database page. The pExtra element of sqlite3_pcache_page will be
8913** a pointer to the szExtra bytes of extra storage that SQLite has requested
8914** for each entry in the page cache.
8915**
8916** The page to be fetched is determined by the key. ^The minimum key value
8917** is 1. After it has been retrieved using xFetch, the page is considered
8918** to be "pinned".
8919**
8920** If the requested page is already in the page cache, then the page cache
8921** implementation must return a pointer to the page buffer with its content
8922** intact. If the requested page is not already in the cache, then the
8923** cache implementation should use the value of the createFlag
8924** parameter to help it determined what action to take:
8925**
8926** <table border=1 width=85% align=center>
8927** <tr><th> createFlag <th> Behavior when page is not already in cache
8928** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
8929** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
8930** Otherwise return NULL.
8931** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
8932** NULL if allocating a new page is effectively impossible.
8933** </table>
8934**
8935** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
8936** will only use a createFlag of 2 after a prior call with a createFlag of 1
8937** failed.)^ In between the xFetch() calls, SQLite may
8938** attempt to unpin one or more cache pages by spilling the content of
8939** pinned pages to disk and synching the operating system disk cache.
8940**
8941** [[the xUnpin() page cache method]]
8942** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
8943** as its second argument. If the third parameter, discard, is non-zero,
8944** then the page must be evicted from the cache.
8945** ^If the discard parameter is
8946** zero, then the page may be discarded or retained at the discretion of
8947** page cache implementation. ^The page cache implementation
8948** may choose to evict unpinned pages at any time.
8949**
8950** The cache must not perform any reference counting. A single
8951** call to xUnpin() unpins the page regardless of the number of prior calls
8952** to xFetch().
8953**
8954** [[the xRekey() page cache methods]]
8955** The xRekey() method is used to change the key value associated with the
8956** page passed as the second argument. If the cache
8957** previously contains an entry associated with newKey, it must be
8958** discarded. ^Any prior cache entry associated with newKey is guaranteed not
8959** to be pinned.
8960**
8961** When SQLite calls the xTruncate() method, the cache must discard all
8962** existing cache entries with page numbers (keys) greater than or equal
8963** to the value of the iLimit parameter passed to xTruncate(). If any
8964** of these pages are pinned, they are implicitly unpinned, meaning that
8965** they can be safely discarded.
8966**
8967** [[the xDestroy() page cache method]]
8968** ^The xDestroy() method is used to delete a cache allocated by xCreate().
8969** All resources associated with the specified cache should be freed. ^After
8970** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
8971** handle invalid, and will not use it with any other sqlite3_pcache_methods2
8972** functions.
8973**
8974** [[the xShrink() page cache method]]
8975** ^SQLite invokes the xShrink() method when it wants the page cache to
8976** free up as much of heap memory as possible. The page cache implementation
8977** is not obligated to free any memory, but well-behaved implementations should
8978** do their best.
8979*/
8980typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
8981struct sqlite3_pcache_methods2 {
8982 int iVersion;
8983 void *pArg;
8984 int (*xInit)(void*);
8985 void (*xShutdown)(void*);
8986 sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
8987 void (*xCachesize)(sqlite3_pcache*, int nCachesize);
8988 int (*xPagecount)(sqlite3_pcache*);
8989 sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
8990 void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
8991 void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
8992 unsigned oldKey, unsigned newKey);
8993 void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
8994 void (*xDestroy)(sqlite3_pcache*);
8995 void (*xShrink)(sqlite3_pcache*);
8996};
8997
8998/*
8999** This is the obsolete pcache_methods object that has now been replaced
9000** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
9001** retained in the header file for backwards compatibility only.
9002*/
9003typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
9004struct sqlite3_pcache_methods {
9005 void *pArg;
9006 int (*xInit)(void*);
9007 void (*xShutdown)(void*);
9008 sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
9009 void (*xCachesize)(sqlite3_pcache*, int nCachesize);
9010 int (*xPagecount)(sqlite3_pcache*);
9011 void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
9012 void (*xUnpin)(sqlite3_pcache*, void*, int discard);
9013 void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
9014 void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
9015 void (*xDestroy)(sqlite3_pcache*);
9016};
9017
9018
9019/*
9020** CAPI3REF: Online Backup Object
9021**
9022** The sqlite3_backup object records state information about an ongoing
9023** online backup operation. ^The sqlite3_backup object is created by
9024** a call to [sqlite3_backup_init()] and is destroyed by a call to
9025** [sqlite3_backup_finish()].
9026**
9027** See Also: [Using the SQLite Online Backup API]
9028*/
9029typedef struct sqlite3_backup sqlite3_backup;
9030
9031/*
9032** CAPI3REF: Online Backup API.
9033**
9034** The backup API copies the content of one database into another.
9035** It is useful either for creating backups of databases or
9036** for copying in-memory databases to or from persistent files.
9037**
9038** See Also: [Using the SQLite Online Backup API]
9039**
9040** ^SQLite holds a write transaction open on the destination database file
9041** for the duration of the backup operation.
9042** ^The source database is read-locked only while it is being read;
9043** it is not locked continuously for the entire backup operation.
9044** ^Thus, the backup may be performed on a live source database without
9045** preventing other database connections from
9046** reading or writing to the source database while the backup is underway.
9047**
9048** ^(To perform a backup operation:
9049** <ol>
9050** <li><b>sqlite3_backup_init()</b> is called once to initialize the
9051** backup,
9052** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
9053** the data between the two databases, and finally
9054** <li><b>sqlite3_backup_finish()</b> is called to release all resources
9055** associated with the backup operation.
9056** </ol>)^
9057** There should be exactly one call to sqlite3_backup_finish() for each
9058** successful call to sqlite3_backup_init().
9059**
9060** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
9061**
9062** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
9063** [database connection] associated with the destination database
9064** and the database name, respectively.
9065** ^The database name is "main" for the main database, "temp" for the
9066** temporary database, or the name specified after the AS keyword in
9067** an [ATTACH] statement for an attached database.
9068** ^The S and M arguments passed to
9069** sqlite3_backup_init(D,N,S,M) identify the [database connection]
9070** and database name of the source database, respectively.
9071** ^The source and destination [database connections] (parameters S and D)
9072** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
9073** an error.
9074**
9075** ^A call to sqlite3_backup_init() will fail, returning NULL, if
9076** there is already a read or read-write transaction open on the
9077** destination database.
9078**
9079** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
9080** returned and an error code and error message are stored in the
9081** destination [database connection] D.
9082** ^The error code and message for the failed call to sqlite3_backup_init()
9083** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
9084** [sqlite3_errmsg16()] functions.
9085** ^A successful call to sqlite3_backup_init() returns a pointer to an
9086** [sqlite3_backup] object.
9087** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
9088** sqlite3_backup_finish() functions to perform the specified backup
9089** operation.
9090**
9091** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
9092**
9093** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
9094** the source and destination databases specified by [sqlite3_backup] object B.
9095** ^If N is negative, all remaining source pages are copied.
9096** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
9097** are still more pages to be copied, then the function returns [SQLITE_OK].
9098** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
9099** from source to destination, then it returns [SQLITE_DONE].
9100** ^If an error occurs while running sqlite3_backup_step(B,N),
9101** then an [error code] is returned. ^As well as [SQLITE_OK] and
9102** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
9103** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
9104** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
9105**
9106** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
9107** <ol>
9108** <li> the destination database was opened read-only, or
9109** <li> the destination database is using write-ahead-log journaling
9110** and the destination and source page sizes differ, or
9111** <li> the destination database is an in-memory database and the
9112** destination and source page sizes differ.
9113** </ol>)^
9114**
9115** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
9116** the [sqlite3_busy_handler | busy-handler function]
9117** is invoked (if one is specified). ^If the
9118** busy-handler returns non-zero before the lock is available, then
9119** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
9120** sqlite3_backup_step() can be retried later. ^If the source
9121** [database connection]
9122** is being used to write to the source database when sqlite3_backup_step()
9123** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
9124** case the call to sqlite3_backup_step() can be retried later on. ^(If
9125** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
9126** [SQLITE_READONLY] is returned, then
9127** there is no point in retrying the call to sqlite3_backup_step(). These
9128** errors are considered fatal.)^ The application must accept
9129** that the backup operation has failed and pass the backup operation handle
9130** to the sqlite3_backup_finish() to release associated resources.
9131**
9132** ^The first call to sqlite3_backup_step() obtains an exclusive lock
9133** on the destination file. ^The exclusive lock is not released until either
9134** sqlite3_backup_finish() is called or the backup operation is complete
9135** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
9136** sqlite3_backup_step() obtains a [shared lock] on the source database that
9137** lasts for the duration of the sqlite3_backup_step() call.
9138** ^Because the source database is not locked between calls to
9139** sqlite3_backup_step(), the source database may be modified mid-way
9140** through the backup process. ^If the source database is modified by an
9141** external process or via a database connection other than the one being
9142** used by the backup operation, then the backup will be automatically
9143** restarted by the next call to sqlite3_backup_step(). ^If the source
9144** database is modified by the using the same database connection as is used
9145** by the backup operation, then the backup database is automatically
9146** updated at the same time.
9147**
9148** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
9149**
9150** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
9151** application wishes to abandon the backup operation, the application
9152** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
9153** ^The sqlite3_backup_finish() interfaces releases all
9154** resources associated with the [sqlite3_backup] object.
9155** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
9156** active write-transaction on the destination database is rolled back.
9157** The [sqlite3_backup] object is invalid
9158** and may not be used following a call to sqlite3_backup_finish().
9159**
9160** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
9161** sqlite3_backup_step() errors occurred, regardless or whether or not
9162** sqlite3_backup_step() completed.
9163** ^If an out-of-memory condition or IO error occurred during any prior
9164** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
9165** sqlite3_backup_finish() returns the corresponding [error code].
9166**
9167** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
9168** is not a permanent error and does not affect the return value of
9169** sqlite3_backup_finish().
9170**
9171** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
9172** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
9173**
9174** ^The sqlite3_backup_remaining() routine returns the number of pages still
9175** to be backed up at the conclusion of the most recent sqlite3_backup_step().
9176** ^The sqlite3_backup_pagecount() routine returns the total number of pages
9177** in the source database at the conclusion of the most recent
9178** sqlite3_backup_step().
9179** ^(The values returned by these functions are only updated by
9180** sqlite3_backup_step(). If the source database is modified in a way that
9181** changes the size of the source database or the number of pages remaining,
9182** those changes are not reflected in the output of sqlite3_backup_pagecount()
9183** and sqlite3_backup_remaining() until after the next
9184** sqlite3_backup_step().)^
9185**
9186** <b>Concurrent Usage of Database Handles</b>
9187**
9188** ^The source [database connection] may be used by the application for other
9189** purposes while a backup operation is underway or being initialized.
9190** ^If SQLite is compiled and configured to support threadsafe database
9191** connections, then the source database connection may be used concurrently
9192** from within other threads.
9193**
9194** However, the application must guarantee that the destination
9195** [database connection] is not passed to any other API (by any thread) after
9196** sqlite3_backup_init() is called and before the corresponding call to
9197** sqlite3_backup_finish(). SQLite does not currently check to see
9198** if the application incorrectly accesses the destination [database connection]
9199** and so no error code is reported, but the operations may malfunction
9200** nevertheless. Use of the destination database connection while a
9201** backup is in progress might also also cause a mutex deadlock.
9202**
9203** If running in [shared cache mode], the application must
9204** guarantee that the shared cache used by the destination database
9205** is not accessed while the backup is running. In practice this means
9206** that the application must guarantee that the disk file being
9207** backed up to is not accessed by any connection within the process,
9208** not just the specific connection that was passed to sqlite3_backup_init().
9209**
9210** The [sqlite3_backup] object itself is partially threadsafe. Multiple
9211** threads may safely make multiple concurrent calls to sqlite3_backup_step().
9212** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
9213** APIs are not strictly speaking threadsafe. If they are invoked at the
9214** same time as another thread is invoking sqlite3_backup_step() it is
9215** possible that they return invalid values.
9216*/
9217SQLITE_API sqlite3_backup *sqlite3_backup_init(
9218 sqlite3 *pDest, /* Destination database handle */
9219 const char *zDestName, /* Destination database name */
9220 sqlite3 *pSource, /* Source database handle */
9221 const char *zSourceName /* Source database name */
9222);
9223SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
9224SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
9225SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
9226SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
9227
9228/*
9229** CAPI3REF: Unlock Notification
9230** METHOD: sqlite3
9231**
9232** ^When running in shared-cache mode, a database operation may fail with
9233** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
9234** individual tables within the shared-cache cannot be obtained. See
9235** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
9236** ^This API may be used to register a callback that SQLite will invoke
9237** when the connection currently holding the required lock relinquishes it.
9238** ^This API is only available if the library was compiled with the
9239** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
9240**
9241** See Also: [Using the SQLite Unlock Notification Feature].
9242**
9243** ^Shared-cache locks are released when a database connection concludes
9244** its current transaction, either by committing it or rolling it back.
9245**
9246** ^When a connection (known as the blocked connection) fails to obtain a
9247** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
9248** identity of the database connection (the blocking connection) that
9249** has locked the required resource is stored internally. ^After an
9250** application receives an SQLITE_LOCKED error, it may call the
9251** sqlite3_unlock_notify() method with the blocked connection handle as
9252** the first argument to register for a callback that will be invoked
9253** when the blocking connections current transaction is concluded. ^The
9254** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
9255** call that concludes the blocking connection's transaction.
9256**
9257** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
9258** there is a chance that the blocking connection will have already
9259** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
9260** If this happens, then the specified callback is invoked immediately,
9261** from within the call to sqlite3_unlock_notify().)^
9262**
9263** ^If the blocked connection is attempting to obtain a write-lock on a
9264** shared-cache table, and more than one other connection currently holds
9265** a read-lock on the same table, then SQLite arbitrarily selects one of
9266** the other connections to use as the blocking connection.
9267**
9268** ^(There may be at most one unlock-notify callback registered by a
9269** blocked connection. If sqlite3_unlock_notify() is called when the
9270** blocked connection already has a registered unlock-notify callback,
9271** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
9272** called with a NULL pointer as its second argument, then any existing
9273** unlock-notify callback is canceled. ^The blocked connections
9274** unlock-notify callback may also be canceled by closing the blocked
9275** connection using [sqlite3_close()].
9276**
9277** The unlock-notify callback is not reentrant. If an application invokes
9278** any sqlite3_xxx API functions from within an unlock-notify callback, a
9279** crash or deadlock may be the result.
9280**
9281** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
9282** returns SQLITE_OK.
9283**
9284** <b>Callback Invocation Details</b>
9285**
9286** When an unlock-notify callback is registered, the application provides a
9287** single void* pointer that is passed to the callback when it is invoked.
9288** However, the signature of the callback function allows SQLite to pass
9289** it an array of void* context pointers. The first argument passed to
9290** an unlock-notify callback is a pointer to an array of void* pointers,
9291** and the second is the number of entries in the array.
9292**
9293** When a blocking connection's transaction is concluded, there may be
9294** more than one blocked connection that has registered for an unlock-notify
9295** callback. ^If two or more such blocked connections have specified the
9296** same callback function, then instead of invoking the callback function
9297** multiple times, it is invoked once with the set of void* context pointers
9298** specified by the blocked connections bundled together into an array.
9299** This gives the application an opportunity to prioritize any actions
9300** related to the set of unblocked database connections.
9301**
9302** <b>Deadlock Detection</b>
9303**
9304** Assuming that after registering for an unlock-notify callback a
9305** database waits for the callback to be issued before taking any further
9306** action (a reasonable assumption), then using this API may cause the
9307** application to deadlock. For example, if connection X is waiting for
9308** connection Y's transaction to be concluded, and similarly connection
9309** Y is waiting on connection X's transaction, then neither connection
9310** will proceed and the system may remain deadlocked indefinitely.
9311**
9312** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
9313** detection. ^If a given call to sqlite3_unlock_notify() would put the
9314** system in a deadlocked state, then SQLITE_LOCKED is returned and no
9315** unlock-notify callback is registered. The system is said to be in
9316** a deadlocked state if connection A has registered for an unlock-notify
9317** callback on the conclusion of connection B's transaction, and connection
9318** B has itself registered for an unlock-notify callback when connection
9319** A's transaction is concluded. ^Indirect deadlock is also detected, so
9320** the system is also considered to be deadlocked if connection B has
9321** registered for an unlock-notify callback on the conclusion of connection
9322** C's transaction, where connection C is waiting on connection A. ^Any
9323** number of levels of indirection are allowed.
9324**
9325** <b>The "DROP TABLE" Exception</b>
9326**
9327** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
9328** always appropriate to call sqlite3_unlock_notify(). There is however,
9329** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
9330** SQLite checks if there are any currently executing SELECT statements
9331** that belong to the same connection. If there are, SQLITE_LOCKED is
9332** returned. In this case there is no "blocking connection", so invoking
9333** sqlite3_unlock_notify() results in the unlock-notify callback being
9334** invoked immediately. If the application then re-attempts the "DROP TABLE"
9335** or "DROP INDEX" query, an infinite loop might be the result.
9336**
9337** One way around this problem is to check the extended error code returned
9338** by an sqlite3_step() call. ^(If there is a blocking connection, then the
9339** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
9340** the special "DROP TABLE/INDEX" case, the extended error code is just
9341** SQLITE_LOCKED.)^
9342*/
9343SQLITE_API int sqlite3_unlock_notify(
9344 sqlite3 *pBlocked, /* Waiting connection */
9345 void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
9346 void *pNotifyArg /* Argument to pass to xNotify */
9347);
9348
9349
9350/*
9351** CAPI3REF: String Comparison
9352**
9353** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
9354** and extensions to compare the contents of two buffers containing UTF-8
9355** strings in a case-independent fashion, using the same definition of "case
9356** independence" that SQLite uses internally when comparing identifiers.
9357*/
9358SQLITE_API int sqlite3_stricmp(const char *, const char *);
9359SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
9360
9361/*
9362** CAPI3REF: String Globbing
9363*
9364** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
9365** string X matches the [GLOB] pattern P.
9366** ^The definition of [GLOB] pattern matching used in
9367** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
9368** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
9369** is case sensitive.
9370**
9371** Note that this routine returns zero on a match and non-zero if the strings
9372** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
9373**
9374** See also: [sqlite3_strlike()].
9375*/
9376SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
9377
9378/*
9379** CAPI3REF: String LIKE Matching
9380*
9381** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
9382** string X matches the [LIKE] pattern P with escape character E.
9383** ^The definition of [LIKE] pattern matching used in
9384** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
9385** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
9386** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
9387** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
9388** insensitive - equivalent upper and lower case ASCII characters match
9389** one another.
9390**
9391** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
9392** only ASCII characters are case folded.
9393**
9394** Note that this routine returns zero on a match and non-zero if the strings
9395** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
9396**
9397** See also: [sqlite3_strglob()].
9398*/
9399SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
9400
9401/*
9402** CAPI3REF: Error Logging Interface
9403**
9404** ^The [sqlite3_log()] interface writes a message into the [error log]
9405** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
9406** ^If logging is enabled, the zFormat string and subsequent arguments are
9407** used with [sqlite3_snprintf()] to generate the final output string.
9408**
9409** The sqlite3_log() interface is intended for use by extensions such as
9410** virtual tables, collating functions, and SQL functions. While there is
9411** nothing to prevent an application from calling sqlite3_log(), doing so
9412** is considered bad form.
9413**
9414** The zFormat string must not be NULL.
9415**
9416** To avoid deadlocks and other threading problems, the sqlite3_log() routine
9417** will not use dynamically allocated memory. The log message is stored in
9418** a fixed-length buffer on the stack. If the log message is longer than
9419** a few hundred characters, it will be truncated to the length of the
9420** buffer.
9421*/
9422SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
9423
9424/*
9425** CAPI3REF: Write-Ahead Log Commit Hook
9426** METHOD: sqlite3
9427**
9428** ^The [sqlite3_wal_hook()] function is used to register a callback that
9429** is invoked each time data is committed to a database in wal mode.
9430**
9431** ^(The callback is invoked by SQLite after the commit has taken place and
9432** the associated write-lock on the database released)^, so the implementation
9433** may read, write or [checkpoint] the database as required.
9434**
9435** ^The first parameter passed to the callback function when it is invoked
9436** is a copy of the third parameter passed to sqlite3_wal_hook() when
9437** registering the callback. ^The second is a copy of the database handle.
9438** ^The third parameter is the name of the database that was written to -
9439** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
9440** is the number of pages currently in the write-ahead log file,
9441** including those that were just committed.
9442**
9443** The callback function should normally return [SQLITE_OK]. ^If an error
9444** code is returned, that error will propagate back up through the
9445** SQLite code base to cause the statement that provoked the callback
9446** to report an error, though the commit will have still occurred. If the
9447** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
9448** that does not correspond to any valid SQLite error code, the results
9449** are undefined.
9450**
9451** A single database handle may have at most a single write-ahead log callback
9452** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
9453** previously registered write-ahead log callback. ^The return value is
9454** a copy of the third parameter from the previous call, if any, or 0.
9455** ^Note that the [sqlite3_wal_autocheckpoint()] interface and the
9456** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
9457** overwrite any prior [sqlite3_wal_hook()] settings.
9458*/
9459SQLITE_API void *sqlite3_wal_hook(
9460 sqlite3*,
9461 int(*)(void *,sqlite3*,const char*,int),
9462 void*
9463);
9464
9465/*
9466** CAPI3REF: Configure an auto-checkpoint
9467** METHOD: sqlite3
9468**
9469** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
9470** [sqlite3_wal_hook()] that causes any database on [database connection] D
9471** to automatically [checkpoint]
9472** after committing a transaction if there are N or
9473** more frames in the [write-ahead log] file. ^Passing zero or
9474** a negative value as the nFrame parameter disables automatic
9475** checkpoints entirely.
9476**
9477** ^The callback registered by this function replaces any existing callback
9478** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
9479** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
9480** configured by this function.
9481**
9482** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
9483** from SQL.
9484**
9485** ^Checkpoints initiated by this mechanism are
9486** [sqlite3_wal_checkpoint_v2|PASSIVE].
9487**
9488** ^Every new [database connection] defaults to having the auto-checkpoint
9489** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
9490** pages. The use of this interface
9491** is only necessary if the default setting is found to be suboptimal
9492** for a particular application.
9493*/
9494SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
9495
9496/*
9497** CAPI3REF: Checkpoint a database
9498** METHOD: sqlite3
9499**
9500** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
9501** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
9502**
9503** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
9504** [write-ahead log] for database X on [database connection] D to be
9505** transferred into the database file and for the write-ahead log to
9506** be reset. See the [checkpointing] documentation for addition
9507** information.
9508**
9509** This interface used to be the only way to cause a checkpoint to
9510** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
9511** interface was added. This interface is retained for backwards
9512** compatibility and as a convenience for applications that need to manually
9513** start a callback but which do not need the full power (and corresponding
9514** complication) of [sqlite3_wal_checkpoint_v2()].
9515*/
9516SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
9517
9518/*
9519** CAPI3REF: Checkpoint a database
9520** METHOD: sqlite3
9521**
9522** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
9523** operation on database X of [database connection] D in mode M. Status
9524** information is written back into integers pointed to by L and C.)^
9525** ^(The M parameter must be a valid [checkpoint mode]:)^
9526**
9527** <dl>
9528** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
9529** ^Checkpoint as many frames as possible without waiting for any database
9530** readers or writers to finish, then sync the database file if all frames
9531** in the log were checkpointed. ^The [busy-handler callback]
9532** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
9533** ^On the other hand, passive mode might leave the checkpoint unfinished
9534** if there are concurrent readers or writers.
9535**
9536** <dt>SQLITE_CHECKPOINT_FULL<dd>
9537** ^This mode blocks (it invokes the
9538** [sqlite3_busy_handler|busy-handler callback]) until there is no
9539** database writer and all readers are reading from the most recent database
9540** snapshot. ^It then checkpoints all frames in the log file and syncs the
9541** database file. ^This mode blocks new database writers while it is pending,
9542** but new database readers are allowed to continue unimpeded.
9543**
9544** <dt>SQLITE_CHECKPOINT_RESTART<dd>
9545** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
9546** that after checkpointing the log file it blocks (calls the
9547** [busy-handler callback])
9548** until all readers are reading from the database file only. ^This ensures
9549** that the next writer will restart the log file from the beginning.
9550** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
9551** database writer attempts while it is pending, but does not impede readers.
9552**
9553** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
9554** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
9555** addition that it also truncates the log file to zero bytes just prior
9556** to a successful return.
9557** </dl>
9558**
9559** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
9560** the log file or to -1 if the checkpoint could not run because
9561** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
9562** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
9563** log file (including any that were already checkpointed before the function
9564** was called) or to -1 if the checkpoint could not run due to an error or
9565** because the database is not in WAL mode. ^Note that upon successful
9566** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
9567** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
9568**
9569** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
9570** any other process is running a checkpoint operation at the same time, the
9571** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
9572** busy-handler configured, it will not be invoked in this case.
9573**
9574** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
9575** exclusive "writer" lock on the database file. ^If the writer lock cannot be
9576** obtained immediately, and a busy-handler is configured, it is invoked and
9577** the writer lock retried until either the busy-handler returns 0 or the lock
9578** is successfully obtained. ^The busy-handler is also invoked while waiting for
9579** database readers as described above. ^If the busy-handler returns 0 before
9580** the writer lock is obtained or while waiting for database readers, the
9581** checkpoint operation proceeds from that point in the same way as
9582** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
9583** without blocking any further. ^SQLITE_BUSY is returned in this case.
9584**
9585** ^If parameter zDb is NULL or points to a zero length string, then the
9586** specified operation is attempted on all WAL databases [attached] to
9587** [database connection] db. In this case the
9588** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
9589** an SQLITE_BUSY error is encountered when processing one or more of the
9590** attached WAL databases, the operation is still attempted on any remaining
9591** attached databases and SQLITE_BUSY is returned at the end. ^If any other
9592** error occurs while processing an attached database, processing is abandoned
9593** and the error code is returned to the caller immediately. ^If no error
9594** (SQLITE_BUSY or otherwise) is encountered while processing the attached
9595** databases, SQLITE_OK is returned.
9596**
9597** ^If database zDb is the name of an attached database that is not in WAL
9598** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
9599** zDb is not NULL (or a zero length string) and is not the name of any
9600** attached database, SQLITE_ERROR is returned to the caller.
9601**
9602** ^Unless it returns SQLITE_MISUSE,
9603** the sqlite3_wal_checkpoint_v2() interface
9604** sets the error information that is queried by
9605** [sqlite3_errcode()] and [sqlite3_errmsg()].
9606**
9607** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
9608** from SQL.
9609*/
9610SQLITE_API int sqlite3_wal_checkpoint_v2(
9611 sqlite3 *db, /* Database handle */
9612 const char *zDb, /* Name of attached database (or NULL) */
9613 int eMode, /* SQLITE_CHECKPOINT_* value */
9614 int *pnLog, /* OUT: Size of WAL log in frames */
9615 int *pnCkpt /* OUT: Total number of frames checkpointed */
9616);
9617
9618/*
9619** CAPI3REF: Checkpoint Mode Values
9620** KEYWORDS: {checkpoint mode}
9621**
9622** These constants define all valid values for the "checkpoint mode" passed
9623** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
9624** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
9625** meaning of each of these checkpoint modes.
9626*/
9627#define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
9628#define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
9629#define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
9630#define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
9631
9632/*
9633** CAPI3REF: Virtual Table Interface Configuration
9634**
9635** This function may be called by either the [xConnect] or [xCreate] method
9636** of a [virtual table] implementation to configure
9637** various facets of the virtual table interface.
9638**
9639** If this interface is invoked outside the context of an xConnect or
9640** xCreate virtual table method then the behavior is undefined.
9641**
9642** In the call sqlite3_vtab_config(D,C,...) the D parameter is the
9643** [database connection] in which the virtual table is being created and
9644** which is passed in as the first argument to the [xConnect] or [xCreate]
9645** method that is invoking sqlite3_vtab_config(). The C parameter is one
9646** of the [virtual table configuration options]. The presence and meaning
9647** of parameters after C depend on which [virtual table configuration option]
9648** is used.
9649*/
9650SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
9651
9652/*
9653** CAPI3REF: Virtual Table Configuration Options
9654** KEYWORDS: {virtual table configuration options}
9655** KEYWORDS: {virtual table configuration option}
9656**
9657** These macros define the various options to the
9658** [sqlite3_vtab_config()] interface that [virtual table] implementations
9659** can use to customize and optimize their behavior.
9660**
9661** <dl>
9662** [[SQLITE_VTAB_CONSTRAINT_SUPPORT]]
9663** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT</dt>
9664** <dd>Calls of the form
9665** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
9666** where X is an integer. If X is zero, then the [virtual table] whose
9667** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
9668** support constraints. In this configuration (which is the default) if
9669** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
9670** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
9671** specified as part of the users SQL statement, regardless of the actual
9672** ON CONFLICT mode specified.
9673**
9674** If X is non-zero, then the virtual table implementation guarantees
9675** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
9676** any modifications to internal or persistent data structures have been made.
9677** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
9678** is able to roll back a statement or database transaction, and abandon
9679** or continue processing the current SQL statement as appropriate.
9680** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
9681** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
9682** had been ABORT.
9683**
9684** Virtual table implementations that are required to handle OR REPLACE
9685** must do so within the [xUpdate] method. If a call to the
9686** [sqlite3_vtab_on_conflict()] function indicates that the current ON
9687** CONFLICT policy is REPLACE, the virtual table implementation should
9688** silently replace the appropriate rows within the xUpdate callback and
9689** return SQLITE_OK. Or, if this is not possible, it may return
9690** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
9691** constraint handling.
9692** </dd>
9693**
9694** [[SQLITE_VTAB_DIRECTONLY]]<dt>SQLITE_VTAB_DIRECTONLY</dt>
9695** <dd>Calls of the form
9696** [sqlite3_vtab_config](db,SQLITE_VTAB_DIRECTONLY) from within the
9697** the [xConnect] or [xCreate] methods of a [virtual table] implmentation
9698** prohibits that virtual table from being used from within triggers and
9699** views.
9700** </dd>
9701**
9702** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt>
9703** <dd>Calls of the form
9704** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the
9705** the [xConnect] or [xCreate] methods of a [virtual table] implmentation
9706** identify that virtual table as being safe to use from within triggers
9707** and views. Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the
9708** virtual table can do no serious harm even if it is controlled by a
9709** malicious hacker. Developers should avoid setting the SQLITE_VTAB_INNOCUOUS
9710** flag unless absolutely necessary.
9711** </dd>
9712** </dl>
9713*/
9714#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
9715#define SQLITE_VTAB_INNOCUOUS 2
9716#define SQLITE_VTAB_DIRECTONLY 3
9717
9718/*
9719** CAPI3REF: Determine The Virtual Table Conflict Policy
9720**
9721** This function may only be called from within a call to the [xUpdate] method
9722** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
9723** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
9724** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
9725** of the SQL statement that triggered the call to the [xUpdate] method of the
9726** [virtual table].
9727*/
9728SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
9729
9730/*
9731** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE
9732**
9733** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]
9734** method of a [virtual table], then it might return true if the
9735** column is being fetched as part of an UPDATE operation during which the
9736** column value will not change. The virtual table implementation can use
9737** this hint as permission to substitute a return value that is less
9738** expensive to compute and that the corresponding
9739** [xUpdate] method understands as a "no-change" value.
9740**
9741** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that
9742** the column is not changed by the UPDATE statement, then the xColumn
9743** method can optionally return without setting a result, without calling
9744** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].
9745** In that case, [sqlite3_value_nochange(X)] will return true for the
9746** same column in the [xUpdate] method.
9747**
9748** The sqlite3_vtab_nochange() routine is an optimization. Virtual table
9749** implementations should continue to give a correct answer even if the
9750** sqlite3_vtab_nochange() interface were to always return false. In the
9751** current implementation, the sqlite3_vtab_nochange() interface does always
9752** returns false for the enhanced [UPDATE FROM] statement.
9753*/
9754SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
9755
9756/*
9757** CAPI3REF: Determine The Collation For a Virtual Table Constraint
9758**
9759** This function may only be called from within a call to the [xBestIndex]
9760** method of a [virtual table].
9761**
9762** The first argument must be the sqlite3_index_info object that is the
9763** first parameter to the xBestIndex() method. The second argument must be
9764** an index into the aConstraint[] array belonging to the sqlite3_index_info
9765** structure passed to xBestIndex. This function returns a pointer to a buffer
9766** containing the name of the collation sequence for the corresponding
9767** constraint.
9768*/
9769SQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_info*,int);
9770
9771/*
9772** CAPI3REF: Conflict resolution modes
9773** KEYWORDS: {conflict resolution mode}
9774**
9775** These constants are returned by [sqlite3_vtab_on_conflict()] to
9776** inform a [virtual table] implementation what the [ON CONFLICT] mode
9777** is for the SQL statement being evaluated.
9778**
9779** Note that the [SQLITE_IGNORE] constant is also used as a potential
9780** return value from the [sqlite3_set_authorizer()] callback and that
9781** [SQLITE_ABORT] is also a [result code].
9782*/
9783#define SQLITE_ROLLBACK 1
9784/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
9785#define SQLITE_FAIL 3
9786/* #define SQLITE_ABORT 4 // Also an error code */
9787#define SQLITE_REPLACE 5
9788
9789/*
9790** CAPI3REF: Prepared Statement Scan Status Opcodes
9791** KEYWORDS: {scanstatus options}
9792**
9793** The following constants can be used for the T parameter to the
9794** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
9795** different metric for sqlite3_stmt_scanstatus() to return.
9796**
9797** When the value returned to V is a string, space to hold that string is
9798** managed by the prepared statement S and will be automatically freed when
9799** S is finalized.
9800**
9801** <dl>
9802** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
9803** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be
9804** set to the total number of times that the X-th loop has run.</dd>
9805**
9806** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
9807** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be set
9808** to the total number of rows examined by all iterations of the X-th loop.</dd>
9809**
9810** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
9811** <dd>^The "double" variable pointed to by the V parameter will be set to the
9812** query planner's estimate for the average number of rows output from each
9813** iteration of the X-th loop. If the query planner's estimates was accurate,
9814** then this value will approximate the quotient NVISIT/NLOOP and the
9815** product of this value for all prior loops with the same SELECTID will
9816** be the NLOOP value for the current loop.
9817**
9818** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
9819** <dd>^The "const char *" variable pointed to by the V parameter will be set
9820** to a zero-terminated UTF-8 string containing the name of the index or table
9821** used for the X-th loop.
9822**
9823** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
9824** <dd>^The "const char *" variable pointed to by the V parameter will be set
9825** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
9826** description for the X-th loop.
9827**
9828** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
9829** <dd>^The "int" variable pointed to by the V parameter will be set to the
9830** "select-id" for the X-th loop. The select-id identifies which query or
9831** subquery the loop is part of. The main query has a select-id of zero.
9832** The select-id is the same value as is output in the first column
9833** of an [EXPLAIN QUERY PLAN] query.
9834** </dl>
9835*/
9836#define SQLITE_SCANSTAT_NLOOP 0
9837#define SQLITE_SCANSTAT_NVISIT 1
9838#define SQLITE_SCANSTAT_EST 2
9839#define SQLITE_SCANSTAT_NAME 3
9840#define SQLITE_SCANSTAT_EXPLAIN 4
9841#define SQLITE_SCANSTAT_SELECTID 5
9842
9843/*
9844** CAPI3REF: Prepared Statement Scan Status
9845** METHOD: sqlite3_stmt
9846**
9847** This interface returns information about the predicted and measured
9848** performance for pStmt. Advanced applications can use this
9849** interface to compare the predicted and the measured performance and
9850** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
9851**
9852** Since this interface is expected to be rarely used, it is only
9853** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
9854** compile-time option.
9855**
9856** The "iScanStatusOp" parameter determines which status information to return.
9857** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
9858** of this interface is undefined.
9859** ^The requested measurement is written into a variable pointed to by
9860** the "pOut" parameter.
9861** Parameter "idx" identifies the specific loop to retrieve statistics for.
9862** Loops are numbered starting from zero. ^If idx is out of range - less than
9863** zero or greater than or equal to the total number of loops used to implement
9864** the statement - a non-zero value is returned and the variable that pOut
9865** points to is unchanged.
9866**
9867** ^Statistics might not be available for all loops in all statements. ^In cases
9868** where there exist loops with no available statistics, this function behaves
9869** as if the loop did not exist - it returns non-zero and leave the variable
9870** that pOut points to unchanged.
9871**
9872** See also: [sqlite3_stmt_scanstatus_reset()]
9873*/
9874SQLITE_API int sqlite3_stmt_scanstatus(
9875 sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
9876 int idx, /* Index of loop to report on */
9877 int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
9878 void *pOut /* Result written here */
9879);
9880
9881/*
9882** CAPI3REF: Zero Scan-Status Counters
9883** METHOD: sqlite3_stmt
9884**
9885** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
9886**
9887** This API is only available if the library is built with pre-processor
9888** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
9889*/
9890SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
9891
9892/*
9893** CAPI3REF: Flush caches to disk mid-transaction
9894** METHOD: sqlite3
9895**
9896** ^If a write-transaction is open on [database connection] D when the
9897** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
9898** pages in the pager-cache that are not currently in use are written out
9899** to disk. A dirty page may be in use if a database cursor created by an
9900** active SQL statement is reading from it, or if it is page 1 of a database
9901** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
9902** interface flushes caches for all schemas - "main", "temp", and
9903** any [attached] databases.
9904**
9905** ^If this function needs to obtain extra database locks before dirty pages
9906** can be flushed to disk, it does so. ^If those locks cannot be obtained
9907** immediately and there is a busy-handler callback configured, it is invoked
9908** in the usual manner. ^If the required lock still cannot be obtained, then
9909** the database is skipped and an attempt made to flush any dirty pages
9910** belonging to the next (if any) database. ^If any databases are skipped
9911** because locks cannot be obtained, but no other error occurs, this
9912** function returns SQLITE_BUSY.
9913**
9914** ^If any other error occurs while flushing dirty pages to disk (for
9915** example an IO error or out-of-memory condition), then processing is
9916** abandoned and an SQLite [error code] is returned to the caller immediately.
9917**
9918** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
9919**
9920** ^This function does not set the database handle error code or message
9921** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
9922*/
9923SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
9924
9925/*
9926** CAPI3REF: The pre-update hook.
9927** METHOD: sqlite3
9928**
9929** ^These interfaces are only available if SQLite is compiled using the
9930** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
9931**
9932** ^The [sqlite3_preupdate_hook()] interface registers a callback function
9933** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
9934** on a database table.
9935** ^At most one preupdate hook may be registered at a time on a single
9936** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
9937** the previous setting.
9938** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
9939** with a NULL pointer as the second parameter.
9940** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
9941** the first parameter to callbacks.
9942**
9943** ^The preupdate hook only fires for changes to real database tables; the
9944** preupdate hook is not invoked for changes to [virtual tables] or to
9945** system tables like sqlite_sequence or sqlite_stat1.
9946**
9947** ^The second parameter to the preupdate callback is a pointer to
9948** the [database connection] that registered the preupdate hook.
9949** ^The third parameter to the preupdate callback is one of the constants
9950** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
9951** kind of update operation that is about to occur.
9952** ^(The fourth parameter to the preupdate callback is the name of the
9953** database within the database connection that is being modified. This
9954** will be "main" for the main database or "temp" for TEMP tables or
9955** the name given after the AS keyword in the [ATTACH] statement for attached
9956** databases.)^
9957** ^The fifth parameter to the preupdate callback is the name of the
9958** table that is being modified.
9959**
9960** For an UPDATE or DELETE operation on a [rowid table], the sixth
9961** parameter passed to the preupdate callback is the initial [rowid] of the
9962** row being modified or deleted. For an INSERT operation on a rowid table,
9963** or any operation on a WITHOUT ROWID table, the value of the sixth
9964** parameter is undefined. For an INSERT or UPDATE on a rowid table the
9965** seventh parameter is the final rowid value of the row being inserted
9966** or updated. The value of the seventh parameter passed to the callback
9967** function is not defined for operations on WITHOUT ROWID tables, or for
9968** DELETE operations on rowid tables.
9969**
9970** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
9971** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
9972** provide additional information about a preupdate event. These routines
9973** may only be called from within a preupdate callback. Invoking any of
9974** these routines from outside of a preupdate callback or with a
9975** [database connection] pointer that is different from the one supplied
9976** to the preupdate callback results in undefined and probably undesirable
9977** behavior.
9978**
9979** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
9980** in the row that is being inserted, updated, or deleted.
9981**
9982** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
9983** a [protected sqlite3_value] that contains the value of the Nth column of
9984** the table row before it is updated. The N parameter must be between 0
9985** and one less than the number of columns or the behavior will be
9986** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
9987** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
9988** behavior is undefined. The [sqlite3_value] that P points to
9989** will be destroyed when the preupdate callback returns.
9990**
9991** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
9992** a [protected sqlite3_value] that contains the value of the Nth column of
9993** the table row after it is updated. The N parameter must be between 0
9994** and one less than the number of columns or the behavior will be
9995** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
9996** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
9997** behavior is undefined. The [sqlite3_value] that P points to
9998** will be destroyed when the preupdate callback returns.
9999**
10000** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
10001** callback was invoked as a result of a direct insert, update, or delete
10002** operation; or 1 for inserts, updates, or deletes invoked by top-level
10003** triggers; or 2 for changes resulting from triggers called by top-level
10004** triggers; and so forth.
10005**
10006** When the [sqlite3_blob_write()] API is used to update a blob column,
10007** the pre-update hook is invoked with SQLITE_DELETE. This is because the
10008** in this case the new values are not available. In this case, when a
10009** callback made with op==SQLITE_DELETE is actuall a write using the
10010** sqlite3_blob_write() API, the [sqlite3_preupdate_blobwrite()] returns
10011** the index of the column being written. In other cases, where the
10012** pre-update hook is being invoked for some other reason, including a
10013** regular DELETE, sqlite3_preupdate_blobwrite() returns -1.
10014**
10015** See also: [sqlite3_update_hook()]
10016*/
10017#if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
10018SQLITE_API void *sqlite3_preupdate_hook(
10019 sqlite3 *db,
10020 void(*xPreUpdate)(
10021 void *pCtx, /* Copy of third arg to preupdate_hook() */
10022 sqlite3 *db, /* Database handle */
10023 int op, /* SQLITE_UPDATE, DELETE or INSERT */
10024 char const *zDb, /* Database name */
10025 char const *zName, /* Table name */
10026 sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
10027 sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
10028 ),
10029 void*
10030);
10031SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
10032SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
10033SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
10034SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
10035SQLITE_API int sqlite3_preupdate_blobwrite(sqlite3 *);
10036#endif
10037
10038/*
10039** CAPI3REF: Low-level system error code
10040** METHOD: sqlite3
10041**
10042** ^Attempt to return the underlying operating system error code or error
10043** number that caused the most recent I/O error or failure to open a file.
10044** The return value is OS-dependent. For example, on unix systems, after
10045** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
10046** called to get back the underlying "errno" that caused the problem, such
10047** as ENOSPC, EAUTH, EISDIR, and so forth.
10048*/
10049SQLITE_API int sqlite3_system_errno(sqlite3*);
10050
10051/*
10052** CAPI3REF: Database Snapshot
10053** KEYWORDS: {snapshot} {sqlite3_snapshot}
10054**
10055** An instance of the snapshot object records the state of a [WAL mode]
10056** database for some specific point in history.
10057**
10058** In [WAL mode], multiple [database connections] that are open on the
10059** same database file can each be reading a different historical version
10060** of the database file. When a [database connection] begins a read
10061** transaction, that connection sees an unchanging copy of the database
10062** as it existed for the point in time when the transaction first started.
10063** Subsequent changes to the database from other connections are not seen
10064** by the reader until a new read transaction is started.
10065**
10066** The sqlite3_snapshot object records state information about an historical
10067** version of the database file so that it is possible to later open a new read
10068** transaction that sees that historical version of the database rather than
10069** the most recent version.
10070*/
10071typedef struct sqlite3_snapshot {
10072 unsigned char hidden[48];
10073} sqlite3_snapshot;
10074
10075/*
10076** CAPI3REF: Record A Database Snapshot
10077** CONSTRUCTOR: sqlite3_snapshot
10078**
10079** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
10080** new [sqlite3_snapshot] object that records the current state of
10081** schema S in database connection D. ^On success, the
10082** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
10083** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
10084** If there is not already a read-transaction open on schema S when
10085** this function is called, one is opened automatically.
10086**
10087** The following must be true for this function to succeed. If any of
10088** the following statements are false when sqlite3_snapshot_get() is
10089** called, SQLITE_ERROR is returned. The final value of *P is undefined
10090** in this case.
10091**
10092** <ul>
10093** <li> The database handle must not be in [autocommit mode].
10094**
10095** <li> Schema S of [database connection] D must be a [WAL mode] database.
10096**
10097** <li> There must not be a write transaction open on schema S of database
10098** connection D.
10099**
10100** <li> One or more transactions must have been written to the current wal
10101** file since it was created on disk (by any connection). This means
10102** that a snapshot cannot be taken on a wal mode database with no wal
10103** file immediately after it is first opened. At least one transaction
10104** must be written to it first.
10105** </ul>
10106**
10107** This function may also return SQLITE_NOMEM. If it is called with the
10108** database handle in autocommit mode but fails for some other reason,
10109** whether or not a read transaction is opened on schema S is undefined.
10110**
10111** The [sqlite3_snapshot] object returned from a successful call to
10112** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
10113** to avoid a memory leak.
10114**
10115** The [sqlite3_snapshot_get()] interface is only available when the
10116** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
10117*/
10118SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
10119 sqlite3 *db,
10120 const char *zSchema,
10121 sqlite3_snapshot **ppSnapshot
10122);
10123
10124/*
10125** CAPI3REF: Start a read transaction on an historical snapshot
10126** METHOD: sqlite3_snapshot
10127**
10128** ^The [sqlite3_snapshot_open(D,S,P)] interface either starts a new read
10129** transaction or upgrades an existing one for schema S of
10130** [database connection] D such that the read transaction refers to
10131** historical [snapshot] P, rather than the most recent change to the
10132** database. ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK
10133** on success or an appropriate [error code] if it fails.
10134**
10135** ^In order to succeed, the database connection must not be in
10136** [autocommit mode] when [sqlite3_snapshot_open(D,S,P)] is called. If there
10137** is already a read transaction open on schema S, then the database handle
10138** must have no active statements (SELECT statements that have been passed
10139** to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()).
10140** SQLITE_ERROR is returned if either of these conditions is violated, or
10141** if schema S does not exist, or if the snapshot object is invalid.
10142**
10143** ^A call to sqlite3_snapshot_open() will fail to open if the specified
10144** snapshot has been overwritten by a [checkpoint]. In this case
10145** SQLITE_ERROR_SNAPSHOT is returned.
10146**
10147** If there is already a read transaction open when this function is
10148** invoked, then the same read transaction remains open (on the same
10149** database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT
10150** is returned. If another error code - for example SQLITE_PROTOCOL or an
10151** SQLITE_IOERR error code - is returned, then the final state of the
10152** read transaction is undefined. If SQLITE_OK is returned, then the
10153** read transaction is now open on database snapshot P.
10154**
10155** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
10156** database connection D does not know that the database file for
10157** schema S is in [WAL mode]. A database connection might not know
10158** that the database file is in [WAL mode] if there has been no prior
10159** I/O on that database connection, or if the database entered [WAL mode]
10160** after the most recent I/O on the database connection.)^
10161** (Hint: Run "[PRAGMA application_id]" against a newly opened
10162** database connection in order to make it ready to use snapshots.)
10163**
10164** The [sqlite3_snapshot_open()] interface is only available when the
10165** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
10166*/
10167SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
10168 sqlite3 *db,
10169 const char *zSchema,
10170 sqlite3_snapshot *pSnapshot
10171);
10172
10173/*
10174** CAPI3REF: Destroy a snapshot
10175** DESTRUCTOR: sqlite3_snapshot
10176**
10177** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
10178** The application must eventually free every [sqlite3_snapshot] object
10179** using this routine to avoid a memory leak.
10180**
10181** The [sqlite3_snapshot_free()] interface is only available when the
10182** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
10183*/
10184SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
10185
10186/*
10187** CAPI3REF: Compare the ages of two snapshot handles.
10188** METHOD: sqlite3_snapshot
10189**
10190** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
10191** of two valid snapshot handles.
10192**
10193** If the two snapshot handles are not associated with the same database
10194** file, the result of the comparison is undefined.
10195**
10196** Additionally, the result of the comparison is only valid if both of the
10197** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
10198** last time the wal file was deleted. The wal file is deleted when the
10199** database is changed back to rollback mode or when the number of database
10200** clients drops to zero. If either snapshot handle was obtained before the
10201** wal file was last deleted, the value returned by this function
10202** is undefined.
10203**
10204** Otherwise, this API returns a negative value if P1 refers to an older
10205** snapshot than P2, zero if the two handles refer to the same database
10206** snapshot, and a positive value if P1 is a newer snapshot than P2.
10207**
10208** This interface is only available if SQLite is compiled with the
10209** [SQLITE_ENABLE_SNAPSHOT] option.
10210*/
10211SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
10212 sqlite3_snapshot *p1,
10213 sqlite3_snapshot *p2
10214);
10215
10216/*
10217** CAPI3REF: Recover snapshots from a wal file
10218** METHOD: sqlite3_snapshot
10219**
10220** If a [WAL file] remains on disk after all database connections close
10221** (either through the use of the [SQLITE_FCNTL_PERSIST_WAL] [file control]
10222** or because the last process to have the database opened exited without
10223** calling [sqlite3_close()]) and a new connection is subsequently opened
10224** on that database and [WAL file], the [sqlite3_snapshot_open()] interface
10225** will only be able to open the last transaction added to the WAL file
10226** even though the WAL file contains other valid transactions.
10227**
10228** This function attempts to scan the WAL file associated with database zDb
10229** of database handle db and make all valid snapshots available to
10230** sqlite3_snapshot_open(). It is an error if there is already a read
10231** transaction open on the database, or if the database is not a WAL mode
10232** database.
10233**
10234** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
10235**
10236** This interface is only available if SQLite is compiled with the
10237** [SQLITE_ENABLE_SNAPSHOT] option.
10238*/
10239SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
10240
10241/*
10242** CAPI3REF: Serialize a database
10243**
10244** The sqlite3_serialize(D,S,P,F) interface returns a pointer to memory
10245** that is a serialization of the S database on [database connection] D.
10246** If P is not a NULL pointer, then the size of the database in bytes
10247** is written into *P.
10248**
10249** For an ordinary on-disk database file, the serialization is just a
10250** copy of the disk file. For an in-memory database or a "TEMP" database,
10251** the serialization is the same sequence of bytes which would be written
10252** to disk if that database where backed up to disk.
10253**
10254** The usual case is that sqlite3_serialize() copies the serialization of
10255** the database into memory obtained from [sqlite3_malloc64()] and returns
10256** a pointer to that memory. The caller is responsible for freeing the
10257** returned value to avoid a memory leak. However, if the F argument
10258** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations
10259** are made, and the sqlite3_serialize() function will return a pointer
10260** to the contiguous memory representation of the database that SQLite
10261** is currently using for that database, or NULL if the no such contiguous
10262** memory representation of the database exists. A contiguous memory
10263** representation of the database will usually only exist if there has
10264** been a prior call to [sqlite3_deserialize(D,S,...)] with the same
10265** values of D and S.
10266** The size of the database is written into *P even if the
10267** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy
10268** of the database exists.
10269**
10270** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the
10271** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
10272** allocation error occurs.
10273**
10274** This interface is omitted if SQLite is compiled with the
10275** [SQLITE_OMIT_DESERIALIZE] option.
10276*/
10277SQLITE_API unsigned char *sqlite3_serialize(
10278 sqlite3 *db, /* The database connection */
10279 const char *zSchema, /* Which DB to serialize. ex: "main", "temp", ... */
10280 sqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */
10281 unsigned int mFlags /* Zero or more SQLITE_SERIALIZE_* flags */
10282);
10283
10284/*
10285** CAPI3REF: Flags for sqlite3_serialize
10286**
10287** Zero or more of the following constants can be OR-ed together for
10288** the F argument to [sqlite3_serialize(D,S,P,F)].
10289**
10290** SQLITE_SERIALIZE_NOCOPY means that [sqlite3_serialize()] will return
10291** a pointer to contiguous in-memory database that it is currently using,
10292** without making a copy of the database. If SQLite is not currently using
10293** a contiguous in-memory database, then this option causes
10294** [sqlite3_serialize()] to return a NULL pointer. SQLite will only be
10295** using a contiguous in-memory database if it has been initialized by a
10296** prior call to [sqlite3_deserialize()].
10297*/
10298#define SQLITE_SERIALIZE_NOCOPY 0x001 /* Do no memory allocations */
10299
10300/*
10301** CAPI3REF: Deserialize a database
10302**
10303** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the
10304** [database connection] D to disconnect from database S and then
10305** reopen S as an in-memory database based on the serialization contained
10306** in P. The serialized database P is N bytes in size. M is the size of
10307** the buffer P, which might be larger than N. If M is larger than N, and
10308** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is
10309** permitted to add content to the in-memory database as long as the total
10310** size does not exceed M bytes.
10311**
10312** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will
10313** invoke sqlite3_free() on the serialization buffer when the database
10314** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
10315** SQLite will try to increase the buffer size using sqlite3_realloc64()
10316** if writes on the database cause it to grow larger than M bytes.
10317**
10318** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the
10319** database is currently in a read transaction or is involved in a backup
10320** operation.
10321**
10322** It is not possible to deserialized into the TEMP database. If the
10323** S argument to sqlite3_deserialize(D,S,P,N,M,F) is "temp" then the
10324** function returns SQLITE_ERROR.
10325**
10326** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the
10327** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then
10328** [sqlite3_free()] is invoked on argument P prior to returning.
10329**
10330** This interface is omitted if SQLite is compiled with the
10331** [SQLITE_OMIT_DESERIALIZE] option.
10332*/
10333SQLITE_API int sqlite3_deserialize(
10334 sqlite3 *db, /* The database connection */
10335 const char *zSchema, /* Which DB to reopen with the deserialization */
10336 unsigned char *pData, /* The serialized database content */
10337 sqlite3_int64 szDb, /* Number bytes in the deserialization */
10338 sqlite3_int64 szBuf, /* Total size of buffer pData[] */
10339 unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */
10340);
10341
10342/*
10343** CAPI3REF: Flags for sqlite3_deserialize()
10344**
10345** The following are allowed values for 6th argument (the F argument) to
10346** the [sqlite3_deserialize(D,S,P,N,M,F)] interface.
10347**
10348** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization
10349** in the P argument is held in memory obtained from [sqlite3_malloc64()]
10350** and that SQLite should take ownership of this memory and automatically
10351** free it when it has finished using it. Without this flag, the caller
10352** is responsible for freeing any dynamically allocated memory.
10353**
10354** The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to
10355** grow the size of the database using calls to [sqlite3_realloc64()]. This
10356** flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used.
10357** Without this flag, the deserialized database cannot increase in size beyond
10358** the number of bytes specified by the M parameter.
10359**
10360** The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database
10361** should be treated as read-only.
10362*/
10363#define SQLITE_DESERIALIZE_FREEONCLOSE 1 /* Call sqlite3_free() on close */
10364#define SQLITE_DESERIALIZE_RESIZEABLE 2 /* Resize using sqlite3_realloc64() */
10365#define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */
10366
10367/*
10368** Undo the hack that converts floating point types to integer for
10369** builds on processors without floating point support.
10370*/
10371#ifdef SQLITE_OMIT_FLOATING_POINT
10372# undef double
10373#endif
10374
10375#if 0
10376} /* End of the 'extern "C"' block */
10377#endif
10378#endif /* SQLITE3_H */
10379
10380/******** Begin file sqlite3rtree.h *********/
10381/*
10382** 2010 August 30
10383**
10384** The author disclaims copyright to this source code. In place of
10385** a legal notice, here is a blessing:
10386**
10387** May you do good and not evil.
10388** May you find forgiveness for yourself and forgive others.
10389** May you share freely, never taking more than you give.
10390**
10391*************************************************************************
10392*/
10393
10394#ifndef _SQLITE3RTREE_H_
10395#define _SQLITE3RTREE_H_
10396
10397
10398#if 0
10399extern "C" {
10400#endif
10401
10402typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
10403typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
10404
10405/* The double-precision datatype used by RTree depends on the
10406** SQLITE_RTREE_INT_ONLY compile-time option.
10407*/
10408#ifdef SQLITE_RTREE_INT_ONLY
10409 typedef sqlite3_int64 sqlite3_rtree_dbl;
10410#else
10411 typedef double sqlite3_rtree_dbl;
10412#endif
10413
10414/*
10415** Register a geometry callback named zGeom that can be used as part of an
10416** R-Tree geometry query as follows:
10417**
10418** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
10419*/
10420SQLITE_API int sqlite3_rtree_geometry_callback(
10421 sqlite3 *db,
10422 const char *zGeom,
10423 int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
10424 void *pContext
10425);
10426
10427
10428/*
10429** A pointer to a structure of the following type is passed as the first
10430** argument to callbacks registered using rtree_geometry_callback().
10431*/
10432struct sqlite3_rtree_geometry {
10433 void *pContext; /* Copy of pContext passed to s_r_g_c() */
10434 int nParam; /* Size of array aParam[] */
10435 sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
10436 void *pUser; /* Callback implementation user data */
10437 void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
10438};
10439
10440/*
10441** Register a 2nd-generation geometry callback named zScore that can be
10442** used as part of an R-Tree geometry query as follows:
10443**
10444** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
10445*/
10446SQLITE_API int sqlite3_rtree_query_callback(
10447 sqlite3 *db,
10448 const char *zQueryFunc,
10449 int (*xQueryFunc)(sqlite3_rtree_query_info*),
10450 void *pContext,
10451 void (*xDestructor)(void*)
10452);
10453
10454
10455/*
10456** A pointer to a structure of the following type is passed as the
10457** argument to scored geometry callback registered using
10458** sqlite3_rtree_query_callback().
10459**
10460** Note that the first 5 fields of this structure are identical to
10461** sqlite3_rtree_geometry. This structure is a subclass of
10462** sqlite3_rtree_geometry.
10463*/
10464struct sqlite3_rtree_query_info {
10465 void *pContext; /* pContext from when function registered */
10466 int nParam; /* Number of function parameters */
10467 sqlite3_rtree_dbl *aParam; /* value of function parameters */
10468 void *pUser; /* callback can use this, if desired */
10469 void (*xDelUser)(void*); /* function to free pUser */
10470 sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
10471 unsigned int *anQueue; /* Number of pending entries in the queue */
10472 int nCoord; /* Number of coordinates */
10473 int iLevel; /* Level of current node or entry */
10474 int mxLevel; /* The largest iLevel value in the tree */
10475 sqlite3_int64 iRowid; /* Rowid for current entry */
10476 sqlite3_rtree_dbl rParentScore; /* Score of parent node */
10477 int eParentWithin; /* Visibility of parent node */
10478 int eWithin; /* OUT: Visibility */
10479 sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
10480 /* The following fields are only available in 3.8.11 and later */
10481 sqlite3_value **apSqlParam; /* Original SQL values of parameters */
10482};
10483
10484/*
10485** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
10486*/
10487#define NOT_WITHIN 0 /* Object completely outside of query region */
10488#define PARTLY_WITHIN 1 /* Object partially overlaps query region */
10489#define FULLY_WITHIN 2 /* Object fully contained within query region */
10490
10491
10492#if 0
10493} /* end of the 'extern "C"' block */
10494#endif
10495
10496#endif /* ifndef _SQLITE3RTREE_H_ */
10497
10498/******** End of sqlite3rtree.h *********/
10499/******** Begin file sqlite3session.h *********/
10500
10501#if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
10502#define __SQLITESESSION_H_ 1
10503
10504/*
10505** Make sure we can call this stuff from C++.
10506*/
10507#if 0
10508extern "C" {
10509#endif
10510
10511
10512/*
10513** CAPI3REF: Session Object Handle
10514**
10515** An instance of this object is a [session] that can be used to
10516** record changes to a database.
10517*/
10518typedef struct sqlite3_session sqlite3_session;
10519
10520/*
10521** CAPI3REF: Changeset Iterator Handle
10522**
10523** An instance of this object acts as a cursor for iterating
10524** over the elements of a [changeset] or [patchset].
10525*/
10526typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
10527
10528/*
10529** CAPI3REF: Create A New Session Object
10530** CONSTRUCTOR: sqlite3_session
10531**
10532** Create a new session object attached to database handle db. If successful,
10533** a pointer to the new object is written to *ppSession and SQLITE_OK is
10534** returned. If an error occurs, *ppSession is set to NULL and an SQLite
10535** error code (e.g. SQLITE_NOMEM) is returned.
10536**
10537** It is possible to create multiple session objects attached to a single
10538** database handle.
10539**
10540** Session objects created using this function should be deleted using the
10541** [sqlite3session_delete()] function before the database handle that they
10542** are attached to is itself closed. If the database handle is closed before
10543** the session object is deleted, then the results of calling any session
10544** module function, including [sqlite3session_delete()] on the session object
10545** are undefined.
10546**
10547** Because the session module uses the [sqlite3_preupdate_hook()] API, it
10548** is not possible for an application to register a pre-update hook on a
10549** database handle that has one or more session objects attached. Nor is
10550** it possible to create a session object attached to a database handle for
10551** which a pre-update hook is already defined. The results of attempting
10552** either of these things are undefined.
10553**
10554** The session object will be used to create changesets for tables in
10555** database zDb, where zDb is either "main", or "temp", or the name of an
10556** attached database. It is not an error if database zDb is not attached
10557** to the database when the session object is created.
10558*/
10559SQLITE_API int sqlite3session_create(
10560 sqlite3 *db, /* Database handle */
10561 const char *zDb, /* Name of db (e.g. "main") */
10562 sqlite3_session **ppSession /* OUT: New session object */
10563);
10564
10565/*
10566** CAPI3REF: Delete A Session Object
10567** DESTRUCTOR: sqlite3_session
10568**
10569** Delete a session object previously allocated using
10570** [sqlite3session_create()]. Once a session object has been deleted, the
10571** results of attempting to use pSession with any other session module
10572** function are undefined.
10573**
10574** Session objects must be deleted before the database handle to which they
10575** are attached is closed. Refer to the documentation for
10576** [sqlite3session_create()] for details.
10577*/
10578SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
10579
10580/*
10581** CAPIREF: Conigure a Session Object
10582** METHOD: sqlite3_session
10583**
10584** This method is used to configure a session object after it has been
10585** created. At present the only valid value for the second parameter is
10586** [SQLITE_SESSION_OBJCONFIG_SIZE].
10587**
10588** Arguments for sqlite3session_object_config()
10589**
10590** The following values may passed as the the 4th parameter to
10591** sqlite3session_object_config().
10592**
10593** <dt>SQLITE_SESSION_OBJCONFIG_SIZE <dd>
10594** This option is used to set, clear or query the flag that enables
10595** the [sqlite3session_changeset_size()] API. Because it imposes some
10596** computational overhead, this API is disabled by default. Argument
10597** pArg must point to a value of type (int). If the value is initially
10598** 0, then the sqlite3session_changeset_size() API is disabled. If it
10599** is greater than 0, then the same API is enabled. Or, if the initial
10600** value is less than zero, no change is made. In all cases the (int)
10601** variable is set to 1 if the sqlite3session_changeset_size() API is
10602** enabled following the current call, or 0 otherwise.
10603**
10604** It is an error (SQLITE_MISUSE) to attempt to modify this setting after
10605** the first table has been attached to the session object.
10606*/
10607SQLITE_API int sqlite3session_object_config(sqlite3_session*, int op, void *pArg);
10608
10609/*
10610*/
10611#define SQLITE_SESSION_OBJCONFIG_SIZE 1
10612
10613/*
10614** CAPI3REF: Enable Or Disable A Session Object
10615** METHOD: sqlite3_session
10616**
10617** Enable or disable the recording of changes by a session object. When
10618** enabled, a session object records changes made to the database. When
10619** disabled - it does not. A newly created session object is enabled.
10620** Refer to the documentation for [sqlite3session_changeset()] for further
10621** details regarding how enabling and disabling a session object affects
10622** the eventual changesets.
10623**
10624** Passing zero to this function disables the session. Passing a value
10625** greater than zero enables it. Passing a value less than zero is a
10626** no-op, and may be used to query the current state of the session.
10627**
10628** The return value indicates the final state of the session object: 0 if
10629** the session is disabled, or 1 if it is enabled.
10630*/
10631SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
10632
10633/*
10634** CAPI3REF: Set Or Clear the Indirect Change Flag
10635** METHOD: sqlite3_session
10636**
10637** Each change recorded by a session object is marked as either direct or
10638** indirect. A change is marked as indirect if either:
10639**
10640** <ul>
10641** <li> The session object "indirect" flag is set when the change is
10642** made, or
10643** <li> The change is made by an SQL trigger or foreign key action
10644** instead of directly as a result of a users SQL statement.
10645** </ul>
10646**
10647** If a single row is affected by more than one operation within a session,
10648** then the change is considered indirect if all operations meet the criteria
10649** for an indirect change above, or direct otherwise.
10650**
10651** This function is used to set, clear or query the session object indirect
10652** flag. If the second argument passed to this function is zero, then the
10653** indirect flag is cleared. If it is greater than zero, the indirect flag
10654** is set. Passing a value less than zero does not modify the current value
10655** of the indirect flag, and may be used to query the current state of the
10656** indirect flag for the specified session object.
10657**
10658** The return value indicates the final state of the indirect flag: 0 if
10659** it is clear, or 1 if it is set.
10660*/
10661SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
10662
10663/*
10664** CAPI3REF: Attach A Table To A Session Object
10665** METHOD: sqlite3_session
10666**
10667** If argument zTab is not NULL, then it is the name of a table to attach
10668** to the session object passed as the first argument. All subsequent changes
10669** made to the table while the session object is enabled will be recorded. See
10670** documentation for [sqlite3session_changeset()] for further details.
10671**
10672** Or, if argument zTab is NULL, then changes are recorded for all tables
10673** in the database. If additional tables are added to the database (by
10674** executing "CREATE TABLE" statements) after this call is made, changes for
10675** the new tables are also recorded.
10676**
10677** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
10678** defined as part of their CREATE TABLE statement. It does not matter if the
10679** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
10680** KEY may consist of a single column, or may be a composite key.
10681**
10682** It is not an error if the named table does not exist in the database. Nor
10683** is it an error if the named table does not have a PRIMARY KEY. However,
10684** no changes will be recorded in either of these scenarios.
10685**
10686** Changes are not recorded for individual rows that have NULL values stored
10687** in one or more of their PRIMARY KEY columns.
10688**
10689** SQLITE_OK is returned if the call completes without error. Or, if an error
10690** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
10691**
10692** <h3>Special sqlite_stat1 Handling</h3>
10693**
10694** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to
10695** some of the rules above. In SQLite, the schema of sqlite_stat1 is:
10696** <pre>
10697** &nbsp; CREATE TABLE sqlite_stat1(tbl,idx,stat)
10698** </pre>
10699**
10700** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are
10701** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes
10702** are recorded for rows for which (idx IS NULL) is true. However, for such
10703** rows a zero-length blob (SQL value X'') is stored in the changeset or
10704** patchset instead of a NULL value. This allows such changesets to be
10705** manipulated by legacy implementations of sqlite3changeset_invert(),
10706** concat() and similar.
10707**
10708** The sqlite3changeset_apply() function automatically converts the
10709** zero-length blob back to a NULL value when updating the sqlite_stat1
10710** table. However, if the application calls sqlite3changeset_new(),
10711** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset
10712** iterator directly (including on a changeset iterator passed to a
10713** conflict-handler callback) then the X'' value is returned. The application
10714** must translate X'' to NULL itself if required.
10715**
10716** Legacy (older than 3.22.0) versions of the sessions module cannot capture
10717** changes made to the sqlite_stat1 table. Legacy versions of the
10718** sqlite3changeset_apply() function silently ignore any modifications to the
10719** sqlite_stat1 table that are part of a changeset or patchset.
10720*/
10721SQLITE_API int sqlite3session_attach(
10722 sqlite3_session *pSession, /* Session object */
10723 const char *zTab /* Table name */
10724);
10725
10726/*
10727** CAPI3REF: Set a table filter on a Session Object.
10728** METHOD: sqlite3_session
10729**
10730** The second argument (xFilter) is the "filter callback". For changes to rows
10731** in tables that are not attached to the Session object, the filter is called
10732** to determine whether changes to the table's rows should be tracked or not.
10733** If xFilter returns 0, changes are not tracked. Note that once a table is
10734** attached, xFilter will not be called again.
10735*/
10736SQLITE_API void sqlite3session_table_filter(
10737 sqlite3_session *pSession, /* Session object */
10738 int(*xFilter)(
10739 void *pCtx, /* Copy of third arg to _filter_table() */
10740 const char *zTab /* Table name */
10741 ),
10742 void *pCtx /* First argument passed to xFilter */
10743);
10744
10745/*
10746** CAPI3REF: Generate A Changeset From A Session Object
10747** METHOD: sqlite3_session
10748**
10749** Obtain a changeset containing changes to the tables attached to the
10750** session object passed as the first argument. If successful,
10751** set *ppChangeset to point to a buffer containing the changeset
10752** and *pnChangeset to the size of the changeset in bytes before returning
10753** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
10754** zero and return an SQLite error code.
10755**
10756** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
10757** each representing a change to a single row of an attached table. An INSERT
10758** change contains the values of each field of a new database row. A DELETE
10759** contains the original values of each field of a deleted database row. An
10760** UPDATE change contains the original values of each field of an updated
10761** database row along with the updated values for each updated non-primary-key
10762** column. It is not possible for an UPDATE change to represent a change that
10763** modifies the values of primary key columns. If such a change is made, it
10764** is represented in a changeset as a DELETE followed by an INSERT.
10765**
10766** Changes are not recorded for rows that have NULL values stored in one or
10767** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
10768** no corresponding change is present in the changesets returned by this
10769** function. If an existing row with one or more NULL values stored in
10770** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
10771** only an INSERT is appears in the changeset. Similarly, if an existing row
10772** with non-NULL PRIMARY KEY values is updated so that one or more of its
10773** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
10774** DELETE change only.
10775**
10776** The contents of a changeset may be traversed using an iterator created
10777** using the [sqlite3changeset_start()] API. A changeset may be applied to
10778** a database with a compatible schema using the [sqlite3changeset_apply()]
10779** API.
10780**
10781** Within a changeset generated by this function, all changes related to a
10782** single table are grouped together. In other words, when iterating through
10783** a changeset or when applying a changeset to a database, all changes related
10784** to a single table are processed before moving on to the next table. Tables
10785** are sorted in the same order in which they were attached (or auto-attached)
10786** to the sqlite3_session object. The order in which the changes related to
10787** a single table are stored is undefined.
10788**
10789** Following a successful call to this function, it is the responsibility of
10790** the caller to eventually free the buffer that *ppChangeset points to using
10791** [sqlite3_free()].
10792**
10793** <h3>Changeset Generation</h3>
10794**
10795** Once a table has been attached to a session object, the session object
10796** records the primary key values of all new rows inserted into the table.
10797** It also records the original primary key and other column values of any
10798** deleted or updated rows. For each unique primary key value, data is only
10799** recorded once - the first time a row with said primary key is inserted,
10800** updated or deleted in the lifetime of the session.
10801**
10802** There is one exception to the previous paragraph: when a row is inserted,
10803** updated or deleted, if one or more of its primary key columns contain a
10804** NULL value, no record of the change is made.
10805**
10806** The session object therefore accumulates two types of records - those
10807** that consist of primary key values only (created when the user inserts
10808** a new record) and those that consist of the primary key values and the
10809** original values of other table columns (created when the users deletes
10810** or updates a record).
10811**
10812** When this function is called, the requested changeset is created using
10813** both the accumulated records and the current contents of the database
10814** file. Specifically:
10815**
10816** <ul>
10817** <li> For each record generated by an insert, the database is queried
10818** for a row with a matching primary key. If one is found, an INSERT
10819** change is added to the changeset. If no such row is found, no change
10820** is added to the changeset.
10821**
10822** <li> For each record generated by an update or delete, the database is
10823** queried for a row with a matching primary key. If such a row is
10824** found and one or more of the non-primary key fields have been
10825** modified from their original values, an UPDATE change is added to
10826** the changeset. Or, if no such row is found in the table, a DELETE
10827** change is added to the changeset. If there is a row with a matching
10828** primary key in the database, but all fields contain their original
10829** values, no change is added to the changeset.
10830** </ul>
10831**
10832** This means, amongst other things, that if a row is inserted and then later
10833** deleted while a session object is active, neither the insert nor the delete
10834** will be present in the changeset. Or if a row is deleted and then later a
10835** row with the same primary key values inserted while a session object is
10836** active, the resulting changeset will contain an UPDATE change instead of
10837** a DELETE and an INSERT.
10838**
10839** When a session object is disabled (see the [sqlite3session_enable()] API),
10840** it does not accumulate records when rows are inserted, updated or deleted.
10841** This may appear to have some counter-intuitive effects if a single row
10842** is written to more than once during a session. For example, if a row
10843** is inserted while a session object is enabled, then later deleted while
10844** the same session object is disabled, no INSERT record will appear in the
10845** changeset, even though the delete took place while the session was disabled.
10846** Or, if one field of a row is updated while a session is disabled, and
10847** another field of the same row is updated while the session is enabled, the
10848** resulting changeset will contain an UPDATE change that updates both fields.
10849*/
10850SQLITE_API int sqlite3session_changeset(
10851 sqlite3_session *pSession, /* Session object */
10852 int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
10853 void **ppChangeset /* OUT: Buffer containing changeset */
10854);
10855
10856/*
10857** CAPI3REF: Return An Upper-limit For The Size Of The Changeset
10858** METHOD: sqlite3_session
10859**
10860** By default, this function always returns 0. For it to return
10861** a useful result, the sqlite3_session object must have been configured
10862** to enable this API using sqlite3session_object_config() with the
10863** SQLITE_SESSION_OBJCONFIG_SIZE verb.
10864**
10865** When enabled, this function returns an upper limit, in bytes, for the size
10866** of the changeset that might be produced if sqlite3session_changeset() were
10867** called. The final changeset size might be equal to or smaller than the
10868** size in bytes returned by this function.
10869*/
10870SQLITE_API sqlite3_int64 sqlite3session_changeset_size(sqlite3_session *pSession);
10871
10872/*
10873** CAPI3REF: Load The Difference Between Tables Into A Session
10874** METHOD: sqlite3_session
10875**
10876** If it is not already attached to the session object passed as the first
10877** argument, this function attaches table zTbl in the same manner as the
10878** [sqlite3session_attach()] function. If zTbl does not exist, or if it
10879** does not have a primary key, this function is a no-op (but does not return
10880** an error).
10881**
10882** Argument zFromDb must be the name of a database ("main", "temp" etc.)
10883** attached to the same database handle as the session object that contains
10884** a table compatible with the table attached to the session by this function.
10885** A table is considered compatible if it:
10886**
10887** <ul>
10888** <li> Has the same name,
10889** <li> Has the same set of columns declared in the same order, and
10890** <li> Has the same PRIMARY KEY definition.
10891** </ul>
10892**
10893** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
10894** are compatible but do not have any PRIMARY KEY columns, it is not an error
10895** but no changes are added to the session object. As with other session
10896** APIs, tables without PRIMARY KEYs are simply ignored.
10897**
10898** This function adds a set of changes to the session object that could be
10899** used to update the table in database zFrom (call this the "from-table")
10900** so that its content is the same as the table attached to the session
10901** object (call this the "to-table"). Specifically:
10902**
10903** <ul>
10904** <li> For each row (primary key) that exists in the to-table but not in
10905** the from-table, an INSERT record is added to the session object.
10906**
10907** <li> For each row (primary key) that exists in the to-table but not in
10908** the from-table, a DELETE record is added to the session object.
10909**
10910** <li> For each row (primary key) that exists in both tables, but features
10911** different non-PK values in each, an UPDATE record is added to the
10912** session.
10913** </ul>
10914**
10915** To clarify, if this function is called and then a changeset constructed
10916** using [sqlite3session_changeset()], then after applying that changeset to
10917** database zFrom the contents of the two compatible tables would be
10918** identical.
10919**
10920** It an error if database zFrom does not exist or does not contain the
10921** required compatible table.
10922**
10923** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite
10924** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
10925** may be set to point to a buffer containing an English language error
10926** message. It is the responsibility of the caller to free this buffer using
10927** sqlite3_free().
10928*/
10929SQLITE_API int sqlite3session_diff(
10930 sqlite3_session *pSession,
10931 const char *zFromDb,
10932 const char *zTbl,
10933 char **pzErrMsg
10934);
10935
10936
10937/*
10938** CAPI3REF: Generate A Patchset From A Session Object
10939** METHOD: sqlite3_session
10940**
10941** The differences between a patchset and a changeset are that:
10942**
10943** <ul>
10944** <li> DELETE records consist of the primary key fields only. The
10945** original values of other fields are omitted.
10946** <li> The original values of any modified fields are omitted from
10947** UPDATE records.
10948** </ul>
10949**
10950** A patchset blob may be used with up to date versions of all
10951** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
10952** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
10953** attempting to use a patchset blob with old versions of the
10954** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
10955**
10956** Because the non-primary key "old.*" fields are omitted, no
10957** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
10958** is passed to the sqlite3changeset_apply() API. Other conflict types work
10959** in the same way as for changesets.
10960**
10961** Changes within a patchset are ordered in the same way as for changesets
10962** generated by the sqlite3session_changeset() function (i.e. all changes for
10963** a single table are grouped together, tables appear in the order in which
10964** they were attached to the session object).
10965*/
10966SQLITE_API int sqlite3session_patchset(
10967 sqlite3_session *pSession, /* Session object */
10968 int *pnPatchset, /* OUT: Size of buffer at *ppPatchset */
10969 void **ppPatchset /* OUT: Buffer containing patchset */
10970);
10971
10972/*
10973** CAPI3REF: Test if a changeset has recorded any changes.
10974**
10975** Return non-zero if no changes to attached tables have been recorded by
10976** the session object passed as the first argument. Otherwise, if one or
10977** more changes have been recorded, return zero.
10978**
10979** Even if this function returns zero, it is possible that calling
10980** [sqlite3session_changeset()] on the session handle may still return a
10981** changeset that contains no changes. This can happen when a row in
10982** an attached table is modified and then later on the original values
10983** are restored. However, if this function returns non-zero, then it is
10984** guaranteed that a call to sqlite3session_changeset() will return a
10985** changeset containing zero changes.
10986*/
10987SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
10988
10989/*
10990** CAPI3REF: Query for the amount of heap memory used by a session object.
10991**
10992** This API returns the total amount of heap memory in bytes currently
10993** used by the session object passed as the only argument.
10994*/
10995SQLITE_API sqlite3_int64 sqlite3session_memory_used(sqlite3_session *pSession);
10996
10997/*
10998** CAPI3REF: Create An Iterator To Traverse A Changeset
10999** CONSTRUCTOR: sqlite3_changeset_iter
11000**
11001** Create an iterator used to iterate through the contents of a changeset.
11002** If successful, *pp is set to point to the iterator handle and SQLITE_OK
11003** is returned. Otherwise, if an error occurs, *pp is set to zero and an
11004** SQLite error code is returned.
11005**
11006** The following functions can be used to advance and query a changeset
11007** iterator created by this function:
11008**
11009** <ul>
11010** <li> [sqlite3changeset_next()]
11011** <li> [sqlite3changeset_op()]
11012** <li> [sqlite3changeset_new()]
11013** <li> [sqlite3changeset_old()]
11014** </ul>
11015**
11016** It is the responsibility of the caller to eventually destroy the iterator
11017** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
11018** changeset (pChangeset) must remain valid until after the iterator is
11019** destroyed.
11020**
11021** Assuming the changeset blob was created by one of the
11022** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
11023** [sqlite3changeset_invert()] functions, all changes within the changeset
11024** that apply to a single table are grouped together. This means that when
11025** an application iterates through a changeset using an iterator created by
11026** this function, all changes that relate to a single table are visited
11027** consecutively. There is no chance that the iterator will visit a change
11028** the applies to table X, then one for table Y, and then later on visit
11029** another change for table X.
11030**
11031** The behavior of sqlite3changeset_start_v2() and its streaming equivalent
11032** may be modified by passing a combination of
11033** [SQLITE_CHANGESETSTART_INVERT | supported flags] as the 4th parameter.
11034**
11035** Note that the sqlite3changeset_start_v2() API is still <b>experimental</b>
11036** and therefore subject to change.
11037*/
11038SQLITE_API int sqlite3changeset_start(
11039 sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
11040 int nChangeset, /* Size of changeset blob in bytes */
11041 void *pChangeset /* Pointer to blob containing changeset */
11042);
11043SQLITE_API int sqlite3changeset_start_v2(
11044 sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
11045 int nChangeset, /* Size of changeset blob in bytes */
11046 void *pChangeset, /* Pointer to blob containing changeset */
11047 int flags /* SESSION_CHANGESETSTART_* flags */
11048);
11049
11050/*
11051** CAPI3REF: Flags for sqlite3changeset_start_v2
11052**
11053** The following flags may passed via the 4th parameter to
11054** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]:
11055**
11056** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
11057** Invert the changeset while iterating through it. This is equivalent to
11058** inverting a changeset using sqlite3changeset_invert() before applying it.
11059** It is an error to specify this flag with a patchset.
11060*/
11061#define SQLITE_CHANGESETSTART_INVERT 0x0002
11062
11063
11064/*
11065** CAPI3REF: Advance A Changeset Iterator
11066** METHOD: sqlite3_changeset_iter
11067**
11068** This function may only be used with iterators created by the function
11069** [sqlite3changeset_start()]. If it is called on an iterator passed to
11070** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
11071** is returned and the call has no effect.
11072**
11073** Immediately after an iterator is created by sqlite3changeset_start(), it
11074** does not point to any change in the changeset. Assuming the changeset
11075** is not empty, the first call to this function advances the iterator to
11076** point to the first change in the changeset. Each subsequent call advances
11077** the iterator to point to the next change in the changeset (if any). If
11078** no error occurs and the iterator points to a valid change after a call
11079** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
11080** Otherwise, if all changes in the changeset have already been visited,
11081** SQLITE_DONE is returned.
11082**
11083** If an error occurs, an SQLite error code is returned. Possible error
11084** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
11085** SQLITE_NOMEM.
11086*/
11087SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
11088
11089/*
11090** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
11091** METHOD: sqlite3_changeset_iter
11092**
11093** The pIter argument passed to this function may either be an iterator
11094** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
11095** created by [sqlite3changeset_start()]. In the latter case, the most recent
11096** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
11097** is not the case, this function returns [SQLITE_MISUSE].
11098**
11099** Arguments pOp, pnCol and pzTab may not be NULL. Upon return, three
11100** outputs are set through these pointers:
11101**
11102** *pOp is set to one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
11103** depending on the type of change that the iterator currently points to;
11104**
11105** *pnCol is set to the number of columns in the table affected by the change; and
11106**
11107** *pzTab is set to point to a nul-terminated utf-8 encoded string containing
11108** the name of the table affected by the current change. The buffer remains
11109** valid until either sqlite3changeset_next() is called on the iterator
11110** or until the conflict-handler function returns.
11111**
11112** If pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change
11113** is an indirect change, or false (0) otherwise. See the documentation for
11114** [sqlite3session_indirect()] for a description of direct and indirect
11115** changes.
11116**
11117** If no error occurs, SQLITE_OK is returned. If an error does occur, an
11118** SQLite error code is returned. The values of the output variables may not
11119** be trusted in this case.
11120*/
11121SQLITE_API int sqlite3changeset_op(
11122 sqlite3_changeset_iter *pIter, /* Iterator object */
11123 const char **pzTab, /* OUT: Pointer to table name */
11124 int *pnCol, /* OUT: Number of columns in table */
11125 int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
11126 int *pbIndirect /* OUT: True for an 'indirect' change */
11127);
11128
11129/*
11130** CAPI3REF: Obtain The Primary Key Definition Of A Table
11131** METHOD: sqlite3_changeset_iter
11132**
11133** For each modified table, a changeset includes the following:
11134**
11135** <ul>
11136** <li> The number of columns in the table, and
11137** <li> Which of those columns make up the tables PRIMARY KEY.
11138** </ul>
11139**
11140** This function is used to find which columns comprise the PRIMARY KEY of
11141** the table modified by the change that iterator pIter currently points to.
11142** If successful, *pabPK is set to point to an array of nCol entries, where
11143** nCol is the number of columns in the table. Elements of *pabPK are set to
11144** 0x01 if the corresponding column is part of the tables primary key, or
11145** 0x00 if it is not.
11146**
11147** If argument pnCol is not NULL, then *pnCol is set to the number of columns
11148** in the table.
11149**
11150** If this function is called when the iterator does not point to a valid
11151** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
11152** SQLITE_OK is returned and the output variables populated as described
11153** above.
11154*/
11155SQLITE_API int sqlite3changeset_pk(
11156 sqlite3_changeset_iter *pIter, /* Iterator object */
11157 unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
11158 int *pnCol /* OUT: Number of entries in output array */
11159);
11160
11161/*
11162** CAPI3REF: Obtain old.* Values From A Changeset Iterator
11163** METHOD: sqlite3_changeset_iter
11164**
11165** The pIter argument passed to this function may either be an iterator
11166** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
11167** created by [sqlite3changeset_start()]. In the latter case, the most recent
11168** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
11169** Furthermore, it may only be called if the type of change that the iterator
11170** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
11171** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
11172**
11173** Argument iVal must be greater than or equal to 0, and less than the number
11174** of columns in the table affected by the current change. Otherwise,
11175** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
11176**
11177** If successful, this function sets *ppValue to point to a protected
11178** sqlite3_value object containing the iVal'th value from the vector of
11179** original row values stored as part of the UPDATE or DELETE change and
11180** returns SQLITE_OK. The name of the function comes from the fact that this
11181** is similar to the "old.*" columns available to update or delete triggers.
11182**
11183** If some other error occurs (e.g. an OOM condition), an SQLite error code
11184** is returned and *ppValue is set to NULL.
11185*/
11186SQLITE_API int sqlite3changeset_old(
11187 sqlite3_changeset_iter *pIter, /* Changeset iterator */
11188 int iVal, /* Column number */
11189 sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
11190);
11191
11192/*
11193** CAPI3REF: Obtain new.* Values From A Changeset Iterator
11194** METHOD: sqlite3_changeset_iter
11195**
11196** The pIter argument passed to this function may either be an iterator
11197** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
11198** created by [sqlite3changeset_start()]. In the latter case, the most recent
11199** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
11200** Furthermore, it may only be called if the type of change that the iterator
11201** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
11202** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
11203**
11204** Argument iVal must be greater than or equal to 0, and less than the number
11205** of columns in the table affected by the current change. Otherwise,
11206** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
11207**
11208** If successful, this function sets *ppValue to point to a protected
11209** sqlite3_value object containing the iVal'th value from the vector of
11210** new row values stored as part of the UPDATE or INSERT change and
11211** returns SQLITE_OK. If the change is an UPDATE and does not include
11212** a new value for the requested column, *ppValue is set to NULL and
11213** SQLITE_OK returned. The name of the function comes from the fact that
11214** this is similar to the "new.*" columns available to update or delete
11215** triggers.
11216**
11217** If some other error occurs (e.g. an OOM condition), an SQLite error code
11218** is returned and *ppValue is set to NULL.
11219*/
11220SQLITE_API int sqlite3changeset_new(
11221 sqlite3_changeset_iter *pIter, /* Changeset iterator */
11222 int iVal, /* Column number */
11223 sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
11224);
11225
11226/*
11227** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
11228** METHOD: sqlite3_changeset_iter
11229**
11230** This function should only be used with iterator objects passed to a
11231** conflict-handler callback by [sqlite3changeset_apply()] with either
11232** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
11233** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
11234** is set to NULL.
11235**
11236** Argument iVal must be greater than or equal to 0, and less than the number
11237** of columns in the table affected by the current change. Otherwise,
11238** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
11239**
11240** If successful, this function sets *ppValue to point to a protected
11241** sqlite3_value object containing the iVal'th value from the
11242** "conflicting row" associated with the current conflict-handler callback
11243** and returns SQLITE_OK.
11244**
11245** If some other error occurs (e.g. an OOM condition), an SQLite error code
11246** is returned and *ppValue is set to NULL.
11247*/
11248SQLITE_API int sqlite3changeset_conflict(
11249 sqlite3_changeset_iter *pIter, /* Changeset iterator */
11250 int iVal, /* Column number */
11251 sqlite3_value **ppValue /* OUT: Value from conflicting row */
11252);
11253
11254/*
11255** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
11256** METHOD: sqlite3_changeset_iter
11257**
11258** This function may only be called with an iterator passed to an
11259** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
11260** it sets the output variable to the total number of known foreign key
11261** violations in the destination database and returns SQLITE_OK.
11262**
11263** In all other cases this function returns SQLITE_MISUSE.
11264*/
11265SQLITE_API int sqlite3changeset_fk_conflicts(
11266 sqlite3_changeset_iter *pIter, /* Changeset iterator */
11267 int *pnOut /* OUT: Number of FK violations */
11268);
11269
11270
11271/*
11272** CAPI3REF: Finalize A Changeset Iterator
11273** METHOD: sqlite3_changeset_iter
11274**
11275** This function is used to finalize an iterator allocated with
11276** [sqlite3changeset_start()].
11277**
11278** This function should only be called on iterators created using the
11279** [sqlite3changeset_start()] function. If an application calls this
11280** function with an iterator passed to a conflict-handler by
11281** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
11282** call has no effect.
11283**
11284** If an error was encountered within a call to an sqlite3changeset_xxx()
11285** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
11286** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
11287** to that error is returned by this function. Otherwise, SQLITE_OK is
11288** returned. This is to allow the following pattern (pseudo-code):
11289**
11290** <pre>
11291** sqlite3changeset_start();
11292** while( SQLITE_ROW==sqlite3changeset_next() ){
11293** // Do something with change.
11294** }
11295** rc = sqlite3changeset_finalize();
11296** if( rc!=SQLITE_OK ){
11297** // An error has occurred
11298** }
11299** </pre>
11300*/
11301SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
11302
11303/*
11304** CAPI3REF: Invert A Changeset
11305**
11306** This function is used to "invert" a changeset object. Applying an inverted
11307** changeset to a database reverses the effects of applying the uninverted
11308** changeset. Specifically:
11309**
11310** <ul>
11311** <li> Each DELETE change is changed to an INSERT, and
11312** <li> Each INSERT change is changed to a DELETE, and
11313** <li> For each UPDATE change, the old.* and new.* values are exchanged.
11314** </ul>
11315**
11316** This function does not change the order in which changes appear within
11317** the changeset. It merely reverses the sense of each individual change.
11318**
11319** If successful, a pointer to a buffer containing the inverted changeset
11320** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
11321** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
11322** zeroed and an SQLite error code returned.
11323**
11324** It is the responsibility of the caller to eventually call sqlite3_free()
11325** on the *ppOut pointer to free the buffer allocation following a successful
11326** call to this function.
11327**
11328** WARNING/TODO: This function currently assumes that the input is a valid
11329** changeset. If it is not, the results are undefined.
11330*/
11331SQLITE_API int sqlite3changeset_invert(
11332 int nIn, const void *pIn, /* Input changeset */
11333 int *pnOut, void **ppOut /* OUT: Inverse of input */
11334);
11335
11336/*
11337** CAPI3REF: Concatenate Two Changeset Objects
11338**
11339** This function is used to concatenate two changesets, A and B, into a
11340** single changeset. The result is a changeset equivalent to applying
11341** changeset A followed by changeset B.
11342**
11343** This function combines the two input changesets using an
11344** sqlite3_changegroup object. Calling it produces similar results as the
11345** following code fragment:
11346**
11347** <pre>
11348** sqlite3_changegroup *pGrp;
11349** rc = sqlite3_changegroup_new(&pGrp);
11350** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
11351** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
11352** if( rc==SQLITE_OK ){
11353** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
11354** }else{
11355** *ppOut = 0;
11356** *pnOut = 0;
11357** }
11358** </pre>
11359**
11360** Refer to the sqlite3_changegroup documentation below for details.
11361*/
11362SQLITE_API int sqlite3changeset_concat(
11363 int nA, /* Number of bytes in buffer pA */
11364 void *pA, /* Pointer to buffer containing changeset A */
11365 int nB, /* Number of bytes in buffer pB */
11366 void *pB, /* Pointer to buffer containing changeset B */
11367 int *pnOut, /* OUT: Number of bytes in output changeset */
11368 void **ppOut /* OUT: Buffer containing output changeset */
11369);
11370
11371
11372/*
11373** CAPI3REF: Changegroup Handle
11374**
11375** A changegroup is an object used to combine two or more
11376** [changesets] or [patchsets]
11377*/
11378typedef struct sqlite3_changegroup sqlite3_changegroup;
11379
11380/*
11381** CAPI3REF: Create A New Changegroup Object
11382** CONSTRUCTOR: sqlite3_changegroup
11383**
11384** An sqlite3_changegroup object is used to combine two or more changesets
11385** (or patchsets) into a single changeset (or patchset). A single changegroup
11386** object may combine changesets or patchsets, but not both. The output is
11387** always in the same format as the input.
11388**
11389** If successful, this function returns SQLITE_OK and populates (*pp) with
11390** a pointer to a new sqlite3_changegroup object before returning. The caller
11391** should eventually free the returned object using a call to
11392** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
11393** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
11394**
11395** The usual usage pattern for an sqlite3_changegroup object is as follows:
11396**
11397** <ul>
11398** <li> It is created using a call to sqlite3changegroup_new().
11399**
11400** <li> Zero or more changesets (or patchsets) are added to the object
11401** by calling sqlite3changegroup_add().
11402**
11403** <li> The result of combining all input changesets together is obtained
11404** by the application via a call to sqlite3changegroup_output().
11405**
11406** <li> The object is deleted using a call to sqlite3changegroup_delete().
11407** </ul>
11408**
11409** Any number of calls to add() and output() may be made between the calls to
11410** new() and delete(), and in any order.
11411**
11412** As well as the regular sqlite3changegroup_add() and
11413** sqlite3changegroup_output() functions, also available are the streaming
11414** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
11415*/
11416SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
11417
11418/*
11419** CAPI3REF: Add A Changeset To A Changegroup
11420** METHOD: sqlite3_changegroup
11421**
11422** Add all changes within the changeset (or patchset) in buffer pData (size
11423** nData bytes) to the changegroup.
11424**
11425** If the buffer contains a patchset, then all prior calls to this function
11426** on the same changegroup object must also have specified patchsets. Or, if
11427** the buffer contains a changeset, so must have the earlier calls to this
11428** function. Otherwise, SQLITE_ERROR is returned and no changes are added
11429** to the changegroup.
11430**
11431** Rows within the changeset and changegroup are identified by the values in
11432** their PRIMARY KEY columns. A change in the changeset is considered to
11433** apply to the same row as a change already present in the changegroup if
11434** the two rows have the same primary key.
11435**
11436** Changes to rows that do not already appear in the changegroup are
11437** simply copied into it. Or, if both the new changeset and the changegroup
11438** contain changes that apply to a single row, the final contents of the
11439** changegroup depends on the type of each change, as follows:
11440**
11441** <table border=1 style="margin-left:8ex;margin-right:8ex">
11442** <tr><th style="white-space:pre">Existing Change </th>
11443** <th style="white-space:pre">New Change </th>
11444** <th>Output Change
11445** <tr><td>INSERT <td>INSERT <td>
11446** The new change is ignored. This case does not occur if the new
11447** changeset was recorded immediately after the changesets already
11448** added to the changegroup.
11449** <tr><td>INSERT <td>UPDATE <td>
11450** The INSERT change remains in the changegroup. The values in the
11451** INSERT change are modified as if the row was inserted by the
11452** existing change and then updated according to the new change.
11453** <tr><td>INSERT <td>DELETE <td>
11454** The existing INSERT is removed from the changegroup. The DELETE is
11455** not added.
11456** <tr><td>UPDATE <td>INSERT <td>
11457** The new change is ignored. This case does not occur if the new
11458** changeset was recorded immediately after the changesets already
11459** added to the changegroup.
11460** <tr><td>UPDATE <td>UPDATE <td>
11461** The existing UPDATE remains within the changegroup. It is amended
11462** so that the accompanying values are as if the row was updated once
11463** by the existing change and then again by the new change.
11464** <tr><td>UPDATE <td>DELETE <td>
11465** The existing UPDATE is replaced by the new DELETE within the
11466** changegroup.
11467** <tr><td>DELETE <td>INSERT <td>
11468** If one or more of the column values in the row inserted by the
11469** new change differ from those in the row deleted by the existing
11470** change, the existing DELETE is replaced by an UPDATE within the
11471** changegroup. Otherwise, if the inserted row is exactly the same
11472** as the deleted row, the existing DELETE is simply discarded.
11473** <tr><td>DELETE <td>UPDATE <td>
11474** The new change is ignored. This case does not occur if the new
11475** changeset was recorded immediately after the changesets already
11476** added to the changegroup.
11477** <tr><td>DELETE <td>DELETE <td>
11478** The new change is ignored. This case does not occur if the new
11479** changeset was recorded immediately after the changesets already
11480** added to the changegroup.
11481** </table>
11482**
11483** If the new changeset contains changes to a table that is already present
11484** in the changegroup, then the number of columns and the position of the
11485** primary key columns for the table must be consistent. If this is not the
11486** case, this function fails with SQLITE_SCHEMA. If the input changeset
11487** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
11488** returned. Or, if an out-of-memory condition occurs during processing, this
11489** function returns SQLITE_NOMEM. In all cases, if an error occurs the state
11490** of the final contents of the changegroup is undefined.
11491**
11492** If no error occurs, SQLITE_OK is returned.
11493*/
11494SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
11495
11496/*
11497** CAPI3REF: Obtain A Composite Changeset From A Changegroup
11498** METHOD: sqlite3_changegroup
11499**
11500** Obtain a buffer containing a changeset (or patchset) representing the
11501** current contents of the changegroup. If the inputs to the changegroup
11502** were themselves changesets, the output is a changeset. Or, if the
11503** inputs were patchsets, the output is also a patchset.
11504**
11505** As with the output of the sqlite3session_changeset() and
11506** sqlite3session_patchset() functions, all changes related to a single
11507** table are grouped together in the output of this function. Tables appear
11508** in the same order as for the very first changeset added to the changegroup.
11509** If the second or subsequent changesets added to the changegroup contain
11510** changes for tables that do not appear in the first changeset, they are
11511** appended onto the end of the output changeset, again in the order in
11512** which they are first encountered.
11513**
11514** If an error occurs, an SQLite error code is returned and the output
11515** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
11516** is returned and the output variables are set to the size of and a
11517** pointer to the output buffer, respectively. In this case it is the
11518** responsibility of the caller to eventually free the buffer using a
11519** call to sqlite3_free().
11520*/
11521SQLITE_API int sqlite3changegroup_output(
11522 sqlite3_changegroup*,
11523 int *pnData, /* OUT: Size of output buffer in bytes */
11524 void **ppData /* OUT: Pointer to output buffer */
11525);
11526
11527/*
11528** CAPI3REF: Delete A Changegroup Object
11529** DESTRUCTOR: sqlite3_changegroup
11530*/
11531SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
11532
11533/*
11534** CAPI3REF: Apply A Changeset To A Database
11535**
11536** Apply a changeset or patchset to a database. These functions attempt to
11537** update the "main" database attached to handle db with the changes found in
11538** the changeset passed via the second and third arguments.
11539**
11540** The fourth argument (xFilter) passed to these functions is the "filter
11541** callback". If it is not NULL, then for each table affected by at least one
11542** change in the changeset, the filter callback is invoked with
11543** the table name as the second argument, and a copy of the context pointer
11544** passed as the sixth argument as the first. If the "filter callback"
11545** returns zero, then no attempt is made to apply any changes to the table.
11546** Otherwise, if the return value is non-zero or the xFilter argument to
11547** is NULL, all changes related to the table are attempted.
11548**
11549** For each table that is not excluded by the filter callback, this function
11550** tests that the target database contains a compatible table. A table is
11551** considered compatible if all of the following are true:
11552**
11553** <ul>
11554** <li> The table has the same name as the name recorded in the
11555** changeset, and
11556** <li> The table has at least as many columns as recorded in the
11557** changeset, and
11558** <li> The table has primary key columns in the same position as
11559** recorded in the changeset.
11560** </ul>
11561**
11562** If there is no compatible table, it is not an error, but none of the
11563** changes associated with the table are applied. A warning message is issued
11564** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
11565** one such warning is issued for each table in the changeset.
11566**
11567** For each change for which there is a compatible table, an attempt is made
11568** to modify the table contents according to the UPDATE, INSERT or DELETE
11569** change. If a change cannot be applied cleanly, the conflict handler
11570** function passed as the fifth argument to sqlite3changeset_apply() may be
11571** invoked. A description of exactly when the conflict handler is invoked for
11572** each type of change is below.
11573**
11574** Unlike the xFilter argument, xConflict may not be passed NULL. The results
11575** of passing anything other than a valid function pointer as the xConflict
11576** argument are undefined.
11577**
11578** Each time the conflict handler function is invoked, it must return one
11579** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
11580** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
11581** if the second argument passed to the conflict handler is either
11582** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
11583** returns an illegal value, any changes already made are rolled back and
11584** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
11585** actions are taken by sqlite3changeset_apply() depending on the value
11586** returned by each invocation of the conflict-handler function. Refer to
11587** the documentation for the three
11588** [SQLITE_CHANGESET_OMIT|available return values] for details.
11589**
11590** <dl>
11591** <dt>DELETE Changes<dd>
11592** For each DELETE change, the function checks if the target database
11593** contains a row with the same primary key value (or values) as the
11594** original row values stored in the changeset. If it does, and the values
11595** stored in all non-primary key columns also match the values stored in
11596** the changeset the row is deleted from the target database.
11597**
11598** If a row with matching primary key values is found, but one or more of
11599** the non-primary key fields contains a value different from the original
11600** row value stored in the changeset, the conflict-handler function is
11601** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
11602** database table has more columns than are recorded in the changeset,
11603** only the values of those non-primary key fields are compared against
11604** the current database contents - any trailing database table columns
11605** are ignored.
11606**
11607** If no row with matching primary key values is found in the database,
11608** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
11609** passed as the second argument.
11610**
11611** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
11612** (which can only happen if a foreign key constraint is violated), the
11613** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
11614** passed as the second argument. This includes the case where the DELETE
11615** operation is attempted because an earlier call to the conflict handler
11616** function returned [SQLITE_CHANGESET_REPLACE].
11617**
11618** <dt>INSERT Changes<dd>
11619** For each INSERT change, an attempt is made to insert the new row into
11620** the database. If the changeset row contains fewer fields than the
11621** database table, the trailing fields are populated with their default
11622** values.
11623**
11624** If the attempt to insert the row fails because the database already
11625** contains a row with the same primary key values, the conflict handler
11626** function is invoked with the second argument set to
11627** [SQLITE_CHANGESET_CONFLICT].
11628**
11629** If the attempt to insert the row fails because of some other constraint
11630** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
11631** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
11632** This includes the case where the INSERT operation is re-attempted because
11633** an earlier call to the conflict handler function returned
11634** [SQLITE_CHANGESET_REPLACE].
11635**
11636** <dt>UPDATE Changes<dd>
11637** For each UPDATE change, the function checks if the target database
11638** contains a row with the same primary key value (or values) as the
11639** original row values stored in the changeset. If it does, and the values
11640** stored in all modified non-primary key columns also match the values
11641** stored in the changeset the row is updated within the target database.
11642**
11643** If a row with matching primary key values is found, but one or more of
11644** the modified non-primary key fields contains a value different from an
11645** original row value stored in the changeset, the conflict-handler function
11646** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
11647** UPDATE changes only contain values for non-primary key fields that are
11648** to be modified, only those fields need to match the original values to
11649** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
11650**
11651** If no row with matching primary key values is found in the database,
11652** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
11653** passed as the second argument.
11654**
11655** If the UPDATE operation is attempted, but SQLite returns
11656** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
11657** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
11658** This includes the case where the UPDATE operation is attempted after
11659** an earlier call to the conflict handler function returned
11660** [SQLITE_CHANGESET_REPLACE].
11661** </dl>
11662**
11663** It is safe to execute SQL statements, including those that write to the
11664** table that the callback related to, from within the xConflict callback.
11665** This can be used to further customize the application's conflict
11666** resolution strategy.
11667**
11668** All changes made by these functions are enclosed in a savepoint transaction.
11669** If any other error (aside from a constraint failure when attempting to
11670** write to the target database) occurs, then the savepoint transaction is
11671** rolled back, restoring the target database to its original state, and an
11672** SQLite error code returned.
11673**
11674** If the output parameters (ppRebase) and (pnRebase) are non-NULL and
11675** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2()
11676** may set (*ppRebase) to point to a "rebase" that may be used with the
11677** sqlite3_rebaser APIs buffer before returning. In this case (*pnRebase)
11678** is set to the size of the buffer in bytes. It is the responsibility of the
11679** caller to eventually free any such buffer using sqlite3_free(). The buffer
11680** is only allocated and populated if one or more conflicts were encountered
11681** while applying the patchset. See comments surrounding the sqlite3_rebaser
11682** APIs for further details.
11683**
11684** The behavior of sqlite3changeset_apply_v2() and its streaming equivalent
11685** may be modified by passing a combination of
11686** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter.
11687**
11688** Note that the sqlite3changeset_apply_v2() API is still <b>experimental</b>
11689** and therefore subject to change.
11690*/
11691SQLITE_API int sqlite3changeset_apply(
11692 sqlite3 *db, /* Apply change to "main" db of this handle */
11693 int nChangeset, /* Size of changeset in bytes */
11694 void *pChangeset, /* Changeset blob */
11695 int(*xFilter)(
11696 void *pCtx, /* Copy of sixth arg to _apply() */
11697 const char *zTab /* Table name */
11698 ),
11699 int(*xConflict)(
11700 void *pCtx, /* Copy of sixth arg to _apply() */
11701 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
11702 sqlite3_changeset_iter *p /* Handle describing change and conflict */
11703 ),
11704 void *pCtx /* First argument passed to xConflict */
11705);
11706SQLITE_API int sqlite3changeset_apply_v2(
11707 sqlite3 *db, /* Apply change to "main" db of this handle */
11708 int nChangeset, /* Size of changeset in bytes */
11709 void *pChangeset, /* Changeset blob */
11710 int(*xFilter)(
11711 void *pCtx, /* Copy of sixth arg to _apply() */
11712 const char *zTab /* Table name */
11713 ),
11714 int(*xConflict)(
11715 void *pCtx, /* Copy of sixth arg to _apply() */
11716 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
11717 sqlite3_changeset_iter *p /* Handle describing change and conflict */
11718 ),
11719 void *pCtx, /* First argument passed to xConflict */
11720 void **ppRebase, int *pnRebase, /* OUT: Rebase data */
11721 int flags /* SESSION_CHANGESETAPPLY_* flags */
11722);
11723
11724/*
11725** CAPI3REF: Flags for sqlite3changeset_apply_v2
11726**
11727** The following flags may passed via the 9th parameter to
11728** [sqlite3changeset_apply_v2] and [sqlite3changeset_apply_v2_strm]:
11729**
11730** <dl>
11731** <dt>SQLITE_CHANGESETAPPLY_NOSAVEPOINT <dd>
11732** Usually, the sessions module encloses all operations performed by
11733** a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The
11734** SAVEPOINT is committed if the changeset or patchset is successfully
11735** applied, or rolled back if an error occurs. Specifying this flag
11736** causes the sessions module to omit this savepoint. In this case, if the
11737** caller has an open transaction or savepoint when apply_v2() is called,
11738** it may revert the partially applied changeset by rolling it back.
11739**
11740** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
11741** Invert the changeset before applying it. This is equivalent to inverting
11742** a changeset using sqlite3changeset_invert() before applying it. It is
11743** an error to specify this flag with a patchset.
11744*/
11745#define SQLITE_CHANGESETAPPLY_NOSAVEPOINT 0x0001
11746#define SQLITE_CHANGESETAPPLY_INVERT 0x0002
11747
11748/*
11749** CAPI3REF: Constants Passed To The Conflict Handler
11750**
11751** Values that may be passed as the second argument to a conflict-handler.
11752**
11753** <dl>
11754** <dt>SQLITE_CHANGESET_DATA<dd>
11755** The conflict handler is invoked with CHANGESET_DATA as the second argument
11756** when processing a DELETE or UPDATE change if a row with the required
11757** PRIMARY KEY fields is present in the database, but one or more other
11758** (non primary-key) fields modified by the update do not contain the
11759** expected "before" values.
11760**
11761** The conflicting row, in this case, is the database row with the matching
11762** primary key.
11763**
11764** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
11765** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
11766** argument when processing a DELETE or UPDATE change if a row with the
11767** required PRIMARY KEY fields is not present in the database.
11768**
11769** There is no conflicting row in this case. The results of invoking the
11770** sqlite3changeset_conflict() API are undefined.
11771**
11772** <dt>SQLITE_CHANGESET_CONFLICT<dd>
11773** CHANGESET_CONFLICT is passed as the second argument to the conflict
11774** handler while processing an INSERT change if the operation would result
11775** in duplicate primary key values.
11776**
11777** The conflicting row in this case is the database row with the matching
11778** primary key.
11779**
11780** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
11781** If foreign key handling is enabled, and applying a changeset leaves the
11782** database in a state containing foreign key violations, the conflict
11783** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
11784** exactly once before the changeset is committed. If the conflict handler
11785** returns CHANGESET_OMIT, the changes, including those that caused the
11786** foreign key constraint violation, are committed. Or, if it returns
11787** CHANGESET_ABORT, the changeset is rolled back.
11788**
11789** No current or conflicting row information is provided. The only function
11790** it is possible to call on the supplied sqlite3_changeset_iter handle
11791** is sqlite3changeset_fk_conflicts().
11792**
11793** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
11794** If any other constraint violation occurs while applying a change (i.e.
11795** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
11796** invoked with CHANGESET_CONSTRAINT as the second argument.
11797**
11798** There is no conflicting row in this case. The results of invoking the
11799** sqlite3changeset_conflict() API are undefined.
11800**
11801** </dl>
11802*/
11803#define SQLITE_CHANGESET_DATA 1
11804#define SQLITE_CHANGESET_NOTFOUND 2
11805#define SQLITE_CHANGESET_CONFLICT 3
11806#define SQLITE_CHANGESET_CONSTRAINT 4
11807#define SQLITE_CHANGESET_FOREIGN_KEY 5
11808
11809/*
11810** CAPI3REF: Constants Returned By The Conflict Handler
11811**
11812** A conflict handler callback must return one of the following three values.
11813**
11814** <dl>
11815** <dt>SQLITE_CHANGESET_OMIT<dd>
11816** If a conflict handler returns this value no special action is taken. The
11817** change that caused the conflict is not applied. The session module
11818** continues to the next change in the changeset.
11819**
11820** <dt>SQLITE_CHANGESET_REPLACE<dd>
11821** This value may only be returned if the second argument to the conflict
11822** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
11823** is not the case, any changes applied so far are rolled back and the
11824** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
11825**
11826** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
11827** handler, then the conflicting row is either updated or deleted, depending
11828** on the type of change.
11829**
11830** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
11831** handler, then the conflicting row is removed from the database and a
11832** second attempt to apply the change is made. If this second attempt fails,
11833** the original row is restored to the database before continuing.
11834**
11835** <dt>SQLITE_CHANGESET_ABORT<dd>
11836** If this value is returned, any changes applied so far are rolled back
11837** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
11838** </dl>
11839*/
11840#define SQLITE_CHANGESET_OMIT 0
11841#define SQLITE_CHANGESET_REPLACE 1
11842#define SQLITE_CHANGESET_ABORT 2
11843
11844/*
11845** CAPI3REF: Rebasing changesets
11846** EXPERIMENTAL
11847**
11848** Suppose there is a site hosting a database in state S0. And that
11849** modifications are made that move that database to state S1 and a
11850** changeset recorded (the "local" changeset). Then, a changeset based
11851** on S0 is received from another site (the "remote" changeset) and
11852** applied to the database. The database is then in state
11853** (S1+"remote"), where the exact state depends on any conflict
11854** resolution decisions (OMIT or REPLACE) made while applying "remote".
11855** Rebasing a changeset is to update it to take those conflict
11856** resolution decisions into account, so that the same conflicts
11857** do not have to be resolved elsewhere in the network.
11858**
11859** For example, if both the local and remote changesets contain an
11860** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)":
11861**
11862** local: INSERT INTO t1 VALUES(1, 'v1');
11863** remote: INSERT INTO t1 VALUES(1, 'v2');
11864**
11865** and the conflict resolution is REPLACE, then the INSERT change is
11866** removed from the local changeset (it was overridden). Or, if the
11867** conflict resolution was "OMIT", then the local changeset is modified
11868** to instead contain:
11869**
11870** UPDATE t1 SET b = 'v2' WHERE a=1;
11871**
11872** Changes within the local changeset are rebased as follows:
11873**
11874** <dl>
11875** <dt>Local INSERT<dd>
11876** This may only conflict with a remote INSERT. If the conflict
11877** resolution was OMIT, then add an UPDATE change to the rebased
11878** changeset. Or, if the conflict resolution was REPLACE, add
11879** nothing to the rebased changeset.
11880**
11881** <dt>Local DELETE<dd>
11882** This may conflict with a remote UPDATE or DELETE. In both cases the
11883** only possible resolution is OMIT. If the remote operation was a
11884** DELETE, then add no change to the rebased changeset. If the remote
11885** operation was an UPDATE, then the old.* fields of change are updated
11886** to reflect the new.* values in the UPDATE.
11887**
11888** <dt>Local UPDATE<dd>
11889** This may conflict with a remote UPDATE or DELETE. If it conflicts
11890** with a DELETE, and the conflict resolution was OMIT, then the update
11891** is changed into an INSERT. Any undefined values in the new.* record
11892** from the update change are filled in using the old.* values from
11893** the conflicting DELETE. Or, if the conflict resolution was REPLACE,
11894** the UPDATE change is simply omitted from the rebased changeset.
11895**
11896** If conflict is with a remote UPDATE and the resolution is OMIT, then
11897** the old.* values are rebased using the new.* values in the remote
11898** change. Or, if the resolution is REPLACE, then the change is copied
11899** into the rebased changeset with updates to columns also updated by
11900** the conflicting remote UPDATE removed. If this means no columns would
11901** be updated, the change is omitted.
11902** </dl>
11903**
11904** A local change may be rebased against multiple remote changes
11905** simultaneously. If a single key is modified by multiple remote
11906** changesets, they are combined as follows before the local changeset
11907** is rebased:
11908**
11909** <ul>
11910** <li> If there has been one or more REPLACE resolutions on a
11911** key, it is rebased according to a REPLACE.
11912**
11913** <li> If there have been no REPLACE resolutions on a key, then
11914** the local changeset is rebased according to the most recent
11915** of the OMIT resolutions.
11916** </ul>
11917**
11918** Note that conflict resolutions from multiple remote changesets are
11919** combined on a per-field basis, not per-row. This means that in the
11920** case of multiple remote UPDATE operations, some fields of a single
11921** local change may be rebased for REPLACE while others are rebased for
11922** OMIT.
11923**
11924** In order to rebase a local changeset, the remote changeset must first
11925** be applied to the local database using sqlite3changeset_apply_v2() and
11926** the buffer of rebase information captured. Then:
11927**
11928** <ol>
11929** <li> An sqlite3_rebaser object is created by calling
11930** sqlite3rebaser_create().
11931** <li> The new object is configured with the rebase buffer obtained from
11932** sqlite3changeset_apply_v2() by calling sqlite3rebaser_configure().
11933** If the local changeset is to be rebased against multiple remote
11934** changesets, then sqlite3rebaser_configure() should be called
11935** multiple times, in the same order that the multiple
11936** sqlite3changeset_apply_v2() calls were made.
11937** <li> Each local changeset is rebased by calling sqlite3rebaser_rebase().
11938** <li> The sqlite3_rebaser object is deleted by calling
11939** sqlite3rebaser_delete().
11940** </ol>
11941*/
11942typedef struct sqlite3_rebaser sqlite3_rebaser;
11943
11944/*
11945** CAPI3REF: Create a changeset rebaser object.
11946** EXPERIMENTAL
11947**
11948** Allocate a new changeset rebaser object. If successful, set (*ppNew) to
11949** point to the new object and return SQLITE_OK. Otherwise, if an error
11950** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew)
11951** to NULL.
11952*/
11953SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew);
11954
11955/*
11956** CAPI3REF: Configure a changeset rebaser object.
11957** EXPERIMENTAL
11958**
11959** Configure the changeset rebaser object to rebase changesets according
11960** to the conflict resolutions described by buffer pRebase (size nRebase
11961** bytes), which must have been obtained from a previous call to
11962** sqlite3changeset_apply_v2().
11963*/
11964SQLITE_API int sqlite3rebaser_configure(
11965 sqlite3_rebaser*,
11966 int nRebase, const void *pRebase
11967);
11968
11969/*
11970** CAPI3REF: Rebase a changeset
11971** EXPERIMENTAL
11972**
11973** Argument pIn must point to a buffer containing a changeset nIn bytes
11974** in size. This function allocates and populates a buffer with a copy
11975** of the changeset rebased according to the configuration of the
11976** rebaser object passed as the first argument. If successful, (*ppOut)
11977** is set to point to the new buffer containing the rebased changeset and
11978** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the
11979** responsibility of the caller to eventually free the new buffer using
11980** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut)
11981** are set to zero and an SQLite error code returned.
11982*/
11983SQLITE_API int sqlite3rebaser_rebase(
11984 sqlite3_rebaser*,
11985 int nIn, const void *pIn,
11986 int *pnOut, void **ppOut
11987);
11988
11989/*
11990** CAPI3REF: Delete a changeset rebaser object.
11991** EXPERIMENTAL
11992**
11993** Delete the changeset rebaser object and all associated resources. There
11994** should be one call to this function for each successful invocation
11995** of sqlite3rebaser_create().
11996*/
11997SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);
11998
11999/*
12000** CAPI3REF: Streaming Versions of API functions.
12001**
12002** The six streaming API xxx_strm() functions serve similar purposes to the
12003** corresponding non-streaming API functions:
12004**
12005** <table border=1 style="margin-left:8ex;margin-right:8ex">
12006** <tr><th>Streaming function<th>Non-streaming equivalent</th>
12007** <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply]
12008** <tr><td>sqlite3changeset_apply_strm_v2<td>[sqlite3changeset_apply_v2]
12009** <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat]
12010** <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert]
12011** <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start]
12012** <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset]
12013** <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset]
12014** </table>
12015**
12016** Non-streaming functions that accept changesets (or patchsets) as input
12017** require that the entire changeset be stored in a single buffer in memory.
12018** Similarly, those that return a changeset or patchset do so by returning
12019** a pointer to a single large buffer allocated using sqlite3_malloc().
12020** Normally this is convenient. However, if an application running in a
12021** low-memory environment is required to handle very large changesets, the
12022** large contiguous memory allocations required can become onerous.
12023**
12024** In order to avoid this problem, instead of a single large buffer, input
12025** is passed to a streaming API functions by way of a callback function that
12026** the sessions module invokes to incrementally request input data as it is
12027** required. In all cases, a pair of API function parameters such as
12028**
12029** <pre>
12030** &nbsp; int nChangeset,
12031** &nbsp; void *pChangeset,
12032** </pre>
12033**
12034** Is replaced by:
12035**
12036** <pre>
12037** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
12038** &nbsp; void *pIn,
12039** </pre>
12040**
12041** Each time the xInput callback is invoked by the sessions module, the first
12042** argument passed is a copy of the supplied pIn context pointer. The second
12043** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
12044** error occurs the xInput method should copy up to (*pnData) bytes of data
12045** into the buffer and set (*pnData) to the actual number of bytes copied
12046** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
12047** should be set to zero to indicate this. Or, if an error occurs, an SQLite
12048** error code should be returned. In all cases, if an xInput callback returns
12049** an error, all processing is abandoned and the streaming API function
12050** returns a copy of the error code to the caller.
12051**
12052** In the case of sqlite3changeset_start_strm(), the xInput callback may be
12053** invoked by the sessions module at any point during the lifetime of the
12054** iterator. If such an xInput callback returns an error, the iterator enters
12055** an error state, whereby all subsequent calls to iterator functions
12056** immediately fail with the same error code as returned by xInput.
12057**
12058** Similarly, streaming API functions that return changesets (or patchsets)
12059** return them in chunks by way of a callback function instead of via a
12060** pointer to a single large buffer. In this case, a pair of parameters such
12061** as:
12062**
12063** <pre>
12064** &nbsp; int *pnChangeset,
12065** &nbsp; void **ppChangeset,
12066** </pre>
12067**
12068** Is replaced by:
12069**
12070** <pre>
12071** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
12072** &nbsp; void *pOut
12073** </pre>
12074**
12075** The xOutput callback is invoked zero or more times to return data to
12076** the application. The first parameter passed to each call is a copy of the
12077** pOut pointer supplied by the application. The second parameter, pData,
12078** points to a buffer nData bytes in size containing the chunk of output
12079** data being returned. If the xOutput callback successfully processes the
12080** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
12081** it should return some other SQLite error code. In this case processing
12082** is immediately abandoned and the streaming API function returns a copy
12083** of the xOutput error code to the application.
12084**
12085** The sessions module never invokes an xOutput callback with the third
12086** parameter set to a value less than or equal to zero. Other than this,
12087** no guarantees are made as to the size of the chunks of data returned.
12088*/
12089SQLITE_API int sqlite3changeset_apply_strm(
12090 sqlite3 *db, /* Apply change to "main" db of this handle */
12091 int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
12092 void *pIn, /* First arg for xInput */
12093 int(*xFilter)(
12094 void *pCtx, /* Copy of sixth arg to _apply() */
12095 const char *zTab /* Table name */
12096 ),
12097 int(*xConflict)(
12098 void *pCtx, /* Copy of sixth arg to _apply() */
12099 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
12100 sqlite3_changeset_iter *p /* Handle describing change and conflict */
12101 ),
12102 void *pCtx /* First argument passed to xConflict */
12103);
12104SQLITE_API int sqlite3changeset_apply_v2_strm(
12105 sqlite3 *db, /* Apply change to "main" db of this handle */
12106 int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
12107 void *pIn, /* First arg for xInput */
12108 int(*xFilter)(
12109 void *pCtx, /* Copy of sixth arg to _apply() */
12110 const char *zTab /* Table name */
12111 ),
12112 int(*xConflict)(
12113 void *pCtx, /* Copy of sixth arg to _apply() */
12114 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
12115 sqlite3_changeset_iter *p /* Handle describing change and conflict */
12116 ),
12117 void *pCtx, /* First argument passed to xConflict */
12118 void **ppRebase, int *pnRebase,
12119 int flags
12120);
12121SQLITE_API int sqlite3changeset_concat_strm(
12122 int (*xInputA)(void *pIn, void *pData, int *pnData),
12123 void *pInA,
12124 int (*xInputB)(void *pIn, void *pData, int *pnData),
12125 void *pInB,
12126 int (*xOutput)(void *pOut, const void *pData, int nData),
12127 void *pOut
12128);
12129SQLITE_API int sqlite3changeset_invert_strm(
12130 int (*xInput)(void *pIn, void *pData, int *pnData),
12131 void *pIn,
12132 int (*xOutput)(void *pOut, const void *pData, int nData),
12133 void *pOut
12134);
12135SQLITE_API int sqlite3changeset_start_strm(
12136 sqlite3_changeset_iter **pp,
12137 int (*xInput)(void *pIn, void *pData, int *pnData),
12138 void *pIn
12139);
12140SQLITE_API int sqlite3changeset_start_v2_strm(
12141 sqlite3_changeset_iter **pp,
12142 int (*xInput)(void *pIn, void *pData, int *pnData),
12143 void *pIn,
12144 int flags
12145);
12146SQLITE_API int sqlite3session_changeset_strm(
12147 sqlite3_session *pSession,
12148 int (*xOutput)(void *pOut, const void *pData, int nData),
12149 void *pOut
12150);
12151SQLITE_API int sqlite3session_patchset_strm(
12152 sqlite3_session *pSession,
12153 int (*xOutput)(void *pOut, const void *pData, int nData),
12154 void *pOut
12155);
12156SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,
12157 int (*xInput)(void *pIn, void *pData, int *pnData),
12158 void *pIn
12159);
12160SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
12161 int (*xOutput)(void *pOut, const void *pData, int nData),
12162 void *pOut
12163);
12164SQLITE_API int sqlite3rebaser_rebase_strm(
12165 sqlite3_rebaser *pRebaser,
12166 int (*xInput)(void *pIn, void *pData, int *pnData),
12167 void *pIn,
12168 int (*xOutput)(void *pOut, const void *pData, int nData),
12169 void *pOut
12170);
12171
12172/*
12173** CAPI3REF: Configure global parameters
12174**
12175** The sqlite3session_config() interface is used to make global configuration
12176** changes to the sessions module in order to tune it to the specific needs
12177** of the application.
12178**
12179** The sqlite3session_config() interface is not threadsafe. If it is invoked
12180** while any other thread is inside any other sessions method then the
12181** results are undefined. Furthermore, if it is invoked after any sessions
12182** related objects have been created, the results are also undefined.
12183**
12184** The first argument to the sqlite3session_config() function must be one
12185** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The
12186** interpretation of the (void*) value passed as the second parameter and
12187** the effect of calling this function depends on the value of the first
12188** parameter.
12189**
12190** <dl>
12191** <dt>SQLITE_SESSION_CONFIG_STRMSIZE<dd>
12192** By default, the sessions module streaming interfaces attempt to input
12193** and output data in approximately 1 KiB chunks. This operand may be used
12194** to set and query the value of this configuration setting. The pointer
12195** passed as the second argument must point to a value of type (int).
12196** If this value is greater than 0, it is used as the new streaming data
12197** chunk size for both input and output. Before returning, the (int) value
12198** pointed to by pArg is set to the final value of the streaming interface
12199** chunk size.
12200** </dl>
12201**
12202** This function returns SQLITE_OK if successful, or an SQLite error code
12203** otherwise.
12204*/
12205SQLITE_API int sqlite3session_config(int op, void *pArg);
12206
12207/*
12208** CAPI3REF: Values for sqlite3session_config().
12209*/
12210#define SQLITE_SESSION_CONFIG_STRMSIZE 1
12211
12212/*
12213** Make sure we can call this stuff from C++.
12214*/
12215#if 0
12216}
12217#endif
12218
12219#endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
12220
12221/******** End of sqlite3session.h *********/
12222/******** Begin file fts5.h *********/
12223/*
12224** 2014 May 31
12225**
12226** The author disclaims copyright to this source code. In place of
12227** a legal notice, here is a blessing:
12228**
12229** May you do good and not evil.
12230** May you find forgiveness for yourself and forgive others.
12231** May you share freely, never taking more than you give.
12232**
12233******************************************************************************
12234**
12235** Interfaces to extend FTS5. Using the interfaces defined in this file,
12236** FTS5 may be extended with:
12237**
12238** * custom tokenizers, and
12239** * custom auxiliary functions.
12240*/
12241
12242
12243#ifndef _FTS5_H
12244#define _FTS5_H
12245
12246
12247#if 0
12248extern "C" {
12249#endif
12250
12251/*************************************************************************
12252** CUSTOM AUXILIARY FUNCTIONS
12253**
12254** Virtual table implementations may overload SQL functions by implementing
12255** the sqlite3_module.xFindFunction() method.
12256*/
12257
12258typedef struct Fts5ExtensionApi Fts5ExtensionApi;
12259typedef struct Fts5Context Fts5Context;
12260typedef struct Fts5PhraseIter Fts5PhraseIter;
12261
12262typedef void (*fts5_extension_function)(
12263 const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
12264 Fts5Context *pFts, /* First arg to pass to pApi functions */
12265 sqlite3_context *pCtx, /* Context for returning result/error */
12266 int nVal, /* Number of values in apVal[] array */
12267 sqlite3_value **apVal /* Array of trailing arguments */
12268);
12269
12270struct Fts5PhraseIter {
12271 const unsigned char *a;
12272 const unsigned char *b;
12273};
12274
12275/*
12276** EXTENSION API FUNCTIONS
12277**
12278** xUserData(pFts):
12279** Return a copy of the context pointer the extension function was
12280** registered with.
12281**
12282** xColumnTotalSize(pFts, iCol, pnToken):
12283** If parameter iCol is less than zero, set output variable *pnToken
12284** to the total number of tokens in the FTS5 table. Or, if iCol is
12285** non-negative but less than the number of columns in the table, return
12286** the total number of tokens in column iCol, considering all rows in
12287** the FTS5 table.
12288**
12289** If parameter iCol is greater than or equal to the number of columns
12290** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
12291** an OOM condition or IO error), an appropriate SQLite error code is
12292** returned.
12293**
12294** xColumnCount(pFts):
12295** Return the number of columns in the table.
12296**
12297** xColumnSize(pFts, iCol, pnToken):
12298** If parameter iCol is less than zero, set output variable *pnToken
12299** to the total number of tokens in the current row. Or, if iCol is
12300** non-negative but less than the number of columns in the table, set
12301** *pnToken to the number of tokens in column iCol of the current row.
12302**
12303** If parameter iCol is greater than or equal to the number of columns
12304** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
12305** an OOM condition or IO error), an appropriate SQLite error code is
12306** returned.
12307**
12308** This function may be quite inefficient if used with an FTS5 table
12309** created with the "columnsize=0" option.
12310**
12311** xColumnText:
12312** This function attempts to retrieve the text of column iCol of the
12313** current document. If successful, (*pz) is set to point to a buffer
12314** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
12315** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
12316** if an error occurs, an SQLite error code is returned and the final values
12317** of (*pz) and (*pn) are undefined.
12318**
12319** xPhraseCount:
12320** Returns the number of phrases in the current query expression.
12321**
12322** xPhraseSize:
12323** Returns the number of tokens in phrase iPhrase of the query. Phrases
12324** are numbered starting from zero.
12325**
12326** xInstCount:
12327** Set *pnInst to the total number of occurrences of all phrases within
12328** the query within the current row. Return SQLITE_OK if successful, or
12329** an error code (i.e. SQLITE_NOMEM) if an error occurs.
12330**
12331** This API can be quite slow if used with an FTS5 table created with the
12332** "detail=none" or "detail=column" option. If the FTS5 table is created
12333** with either "detail=none" or "detail=column" and "content=" option
12334** (i.e. if it is a contentless table), then this API always returns 0.
12335**
12336** xInst:
12337** Query for the details of phrase match iIdx within the current row.
12338** Phrase matches are numbered starting from zero, so the iIdx argument
12339** should be greater than or equal to zero and smaller than the value
12340** output by xInstCount().
12341**
12342** Usually, output parameter *piPhrase is set to the phrase number, *piCol
12343** to the column in which it occurs and *piOff the token offset of the
12344** first token of the phrase. Returns SQLITE_OK if successful, or an error
12345** code (i.e. SQLITE_NOMEM) if an error occurs.
12346**
12347** This API can be quite slow if used with an FTS5 table created with the
12348** "detail=none" or "detail=column" option.
12349**
12350** xRowid:
12351** Returns the rowid of the current row.
12352**
12353** xTokenize:
12354** Tokenize text using the tokenizer belonging to the FTS5 table.
12355**
12356** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
12357** This API function is used to query the FTS table for phrase iPhrase
12358** of the current query. Specifically, a query equivalent to:
12359**
12360** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
12361**
12362** with $p set to a phrase equivalent to the phrase iPhrase of the
12363** current query is executed. Any column filter that applies to
12364** phrase iPhrase of the current query is included in $p. For each
12365** row visited, the callback function passed as the fourth argument
12366** is invoked. The context and API objects passed to the callback
12367** function may be used to access the properties of each matched row.
12368** Invoking Api.xUserData() returns a copy of the pointer passed as
12369** the third argument to pUserData.
12370**
12371** If the callback function returns any value other than SQLITE_OK, the
12372** query is abandoned and the xQueryPhrase function returns immediately.
12373** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
12374** Otherwise, the error code is propagated upwards.
12375**
12376** If the query runs to completion without incident, SQLITE_OK is returned.
12377** Or, if some error occurs before the query completes or is aborted by
12378** the callback, an SQLite error code is returned.
12379**
12380**
12381** xSetAuxdata(pFts5, pAux, xDelete)
12382**
12383** Save the pointer passed as the second argument as the extension function's
12384** "auxiliary data". The pointer may then be retrieved by the current or any
12385** future invocation of the same fts5 extension function made as part of
12386** the same MATCH query using the xGetAuxdata() API.
12387**
12388** Each extension function is allocated a single auxiliary data slot for
12389** each FTS query (MATCH expression). If the extension function is invoked
12390** more than once for a single FTS query, then all invocations share a
12391** single auxiliary data context.
12392**
12393** If there is already an auxiliary data pointer when this function is
12394** invoked, then it is replaced by the new pointer. If an xDelete callback
12395** was specified along with the original pointer, it is invoked at this
12396** point.
12397**
12398** The xDelete callback, if one is specified, is also invoked on the
12399** auxiliary data pointer after the FTS5 query has finished.
12400**
12401** If an error (e.g. an OOM condition) occurs within this function,
12402** the auxiliary data is set to NULL and an error code returned. If the
12403** xDelete parameter was not NULL, it is invoked on the auxiliary data
12404** pointer before returning.
12405**
12406**
12407** xGetAuxdata(pFts5, bClear)
12408**
12409** Returns the current auxiliary data pointer for the fts5 extension
12410** function. See the xSetAuxdata() method for details.
12411**
12412** If the bClear argument is non-zero, then the auxiliary data is cleared
12413** (set to NULL) before this function returns. In this case the xDelete,
12414** if any, is not invoked.
12415**
12416**
12417** xRowCount(pFts5, pnRow)
12418**
12419** This function is used to retrieve the total number of rows in the table.
12420** In other words, the same value that would be returned by:
12421**
12422** SELECT count(*) FROM ftstable;
12423**
12424** xPhraseFirst()
12425** This function is used, along with type Fts5PhraseIter and the xPhraseNext
12426** method, to iterate through all instances of a single query phrase within
12427** the current row. This is the same information as is accessible via the
12428** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
12429** to use, this API may be faster under some circumstances. To iterate
12430** through instances of phrase iPhrase, use the following code:
12431**
12432** Fts5PhraseIter iter;
12433** int iCol, iOff;
12434** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
12435** iCol>=0;
12436** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
12437** ){
12438** // An instance of phrase iPhrase at offset iOff of column iCol
12439** }
12440**
12441** The Fts5PhraseIter structure is defined above. Applications should not
12442** modify this structure directly - it should only be used as shown above
12443** with the xPhraseFirst() and xPhraseNext() API methods (and by
12444** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
12445**
12446** This API can be quite slow if used with an FTS5 table created with the
12447** "detail=none" or "detail=column" option. If the FTS5 table is created
12448** with either "detail=none" or "detail=column" and "content=" option
12449** (i.e. if it is a contentless table), then this API always iterates
12450** through an empty set (all calls to xPhraseFirst() set iCol to -1).
12451**
12452** xPhraseNext()
12453** See xPhraseFirst above.
12454**
12455** xPhraseFirstColumn()
12456** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
12457** and xPhraseNext() APIs described above. The difference is that instead
12458** of iterating through all instances of a phrase in the current row, these
12459** APIs are used to iterate through the set of columns in the current row
12460** that contain one or more instances of a specified phrase. For example:
12461**
12462** Fts5PhraseIter iter;
12463** int iCol;
12464** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
12465** iCol>=0;
12466** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
12467** ){
12468** // Column iCol contains at least one instance of phrase iPhrase
12469** }
12470**
12471** This API can be quite slow if used with an FTS5 table created with the
12472** "detail=none" option. If the FTS5 table is created with either
12473** "detail=none" "content=" option (i.e. if it is a contentless table),
12474** then this API always iterates through an empty set (all calls to
12475** xPhraseFirstColumn() set iCol to -1).
12476**
12477** The information accessed using this API and its companion
12478** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
12479** (or xInst/xInstCount). The chief advantage of this API is that it is
12480** significantly more efficient than those alternatives when used with
12481** "detail=column" tables.
12482**
12483** xPhraseNextColumn()
12484** See xPhraseFirstColumn above.
12485*/
12486struct Fts5ExtensionApi {
12487 int iVersion; /* Currently always set to 3 */
12488
12489 void *(*xUserData)(Fts5Context*);
12490
12491 int (*xColumnCount)(Fts5Context*);
12492 int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
12493 int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
12494
12495 int (*xTokenize)(Fts5Context*,
12496 const char *pText, int nText, /* Text to tokenize */
12497 void *pCtx, /* Context passed to xToken() */
12498 int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
12499 );
12500
12501 int (*xPhraseCount)(Fts5Context*);
12502 int (*xPhraseSize)(Fts5Context*, int iPhrase);
12503
12504 int (*xInstCount)(Fts5Context*, int *pnInst);
12505 int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
12506
12507 sqlite3_int64 (*xRowid)(Fts5Context*);
12508 int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
12509 int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
12510
12511 int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
12512 int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
12513 );
12514 int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
12515 void *(*xGetAuxdata)(Fts5Context*, int bClear);
12516
12517 int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
12518 void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
12519
12520 int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
12521 void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
12522};
12523
12524/*
12525** CUSTOM AUXILIARY FUNCTIONS
12526*************************************************************************/
12527
12528/*************************************************************************
12529** CUSTOM TOKENIZERS
12530**
12531** Applications may also register custom tokenizer types. A tokenizer
12532** is registered by providing fts5 with a populated instance of the
12533** following structure. All structure methods must be defined, setting
12534** any member of the fts5_tokenizer struct to NULL leads to undefined
12535** behaviour. The structure methods are expected to function as follows:
12536**
12537** xCreate:
12538** This function is used to allocate and initialize a tokenizer instance.
12539** A tokenizer instance is required to actually tokenize text.
12540**
12541** The first argument passed to this function is a copy of the (void*)
12542** pointer provided by the application when the fts5_tokenizer object
12543** was registered with FTS5 (the third argument to xCreateTokenizer()).
12544** The second and third arguments are an array of nul-terminated strings
12545** containing the tokenizer arguments, if any, specified following the
12546** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
12547** to create the FTS5 table.
12548**
12549** The final argument is an output variable. If successful, (*ppOut)
12550** should be set to point to the new tokenizer handle and SQLITE_OK
12551** returned. If an error occurs, some value other than SQLITE_OK should
12552** be returned. In this case, fts5 assumes that the final value of *ppOut
12553** is undefined.
12554**
12555** xDelete:
12556** This function is invoked to delete a tokenizer handle previously
12557** allocated using xCreate(). Fts5 guarantees that this function will
12558** be invoked exactly once for each successful call to xCreate().
12559**
12560** xTokenize:
12561** This function is expected to tokenize the nText byte string indicated
12562** by argument pText. pText may or may not be nul-terminated. The first
12563** argument passed to this function is a pointer to an Fts5Tokenizer object
12564** returned by an earlier call to xCreate().
12565**
12566** The second argument indicates the reason that FTS5 is requesting
12567** tokenization of the supplied text. This is always one of the following
12568** four values:
12569**
12570** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
12571** or removed from the FTS table. The tokenizer is being invoked to
12572** determine the set of tokens to add to (or delete from) the
12573** FTS index.
12574**
12575** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
12576** against the FTS index. The tokenizer is being called to tokenize
12577** a bareword or quoted string specified as part of the query.
12578**
12579** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
12580** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
12581** followed by a "*" character, indicating that the last token
12582** returned by the tokenizer will be treated as a token prefix.
12583**
12584** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
12585** satisfy an fts5_api.xTokenize() request made by an auxiliary
12586** function. Or an fts5_api.xColumnSize() request made by the same
12587** on a columnsize=0 database.
12588** </ul>
12589**
12590** For each token in the input string, the supplied callback xToken() must
12591** be invoked. The first argument to it should be a copy of the pointer
12592** passed as the second argument to xTokenize(). The third and fourth
12593** arguments are a pointer to a buffer containing the token text, and the
12594** size of the token in bytes. The 4th and 5th arguments are the byte offsets
12595** of the first byte of and first byte immediately following the text from
12596** which the token is derived within the input.
12597**
12598** The second argument passed to the xToken() callback ("tflags") should
12599** normally be set to 0. The exception is if the tokenizer supports
12600** synonyms. In this case see the discussion below for details.
12601**
12602** FTS5 assumes the xToken() callback is invoked for each token in the
12603** order that they occur within the input text.
12604**
12605** If an xToken() callback returns any value other than SQLITE_OK, then
12606** the tokenization should be abandoned and the xTokenize() method should
12607** immediately return a copy of the xToken() return value. Or, if the
12608** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
12609** if an error occurs with the xTokenize() implementation itself, it
12610** may abandon the tokenization and return any error code other than
12611** SQLITE_OK or SQLITE_DONE.
12612**
12613** SYNONYM SUPPORT
12614**
12615** Custom tokenizers may also support synonyms. Consider a case in which a
12616** user wishes to query for a phrase such as "first place". Using the
12617** built-in tokenizers, the FTS5 query 'first + place' will match instances
12618** of "first place" within the document set, but not alternative forms
12619** such as "1st place". In some applications, it would be better to match
12620** all instances of "first place" or "1st place" regardless of which form
12621** the user specified in the MATCH query text.
12622**
12623** There are several ways to approach this in FTS5:
12624**
12625** <ol><li> By mapping all synonyms to a single token. In this case, using
12626** the above example, this means that the tokenizer returns the
12627** same token for inputs "first" and "1st". Say that token is in
12628** fact "first", so that when the user inserts the document "I won
12629** 1st place" entries are added to the index for tokens "i", "won",
12630** "first" and "place". If the user then queries for '1st + place',
12631** the tokenizer substitutes "first" for "1st" and the query works
12632** as expected.
12633**
12634** <li> By querying the index for all synonyms of each query term
12635** separately. In this case, when tokenizing query text, the
12636** tokenizer may provide multiple synonyms for a single term
12637** within the document. FTS5 then queries the index for each
12638** synonym individually. For example, faced with the query:
12639**
12640** <codeblock>
12641** ... MATCH 'first place'</codeblock>
12642**
12643** the tokenizer offers both "1st" and "first" as synonyms for the
12644** first token in the MATCH query and FTS5 effectively runs a query
12645** similar to:
12646**
12647** <codeblock>
12648** ... MATCH '(first OR 1st) place'</codeblock>
12649**
12650** except that, for the purposes of auxiliary functions, the query
12651** still appears to contain just two phrases - "(first OR 1st)"
12652** being treated as a single phrase.
12653**
12654** <li> By adding multiple synonyms for a single term to the FTS index.
12655** Using this method, when tokenizing document text, the tokenizer
12656** provides multiple synonyms for each token. So that when a
12657** document such as "I won first place" is tokenized, entries are
12658** added to the FTS index for "i", "won", "first", "1st" and
12659** "place".
12660**
12661** This way, even if the tokenizer does not provide synonyms
12662** when tokenizing query text (it should not - to do so would be
12663** inefficient), it doesn't matter if the user queries for
12664** 'first + place' or '1st + place', as there are entries in the
12665** FTS index corresponding to both forms of the first token.
12666** </ol>
12667**
12668** Whether it is parsing document or query text, any call to xToken that
12669** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
12670** is considered to supply a synonym for the previous token. For example,
12671** when parsing the document "I won first place", a tokenizer that supports
12672** synonyms would call xToken() 5 times, as follows:
12673**
12674** <codeblock>
12675** xToken(pCtx, 0, "i", 1, 0, 1);
12676** xToken(pCtx, 0, "won", 3, 2, 5);
12677** xToken(pCtx, 0, "first", 5, 6, 11);
12678** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
12679** xToken(pCtx, 0, "place", 5, 12, 17);
12680**</codeblock>
12681**
12682** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
12683** xToken() is called. Multiple synonyms may be specified for a single token
12684** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
12685** There is no limit to the number of synonyms that may be provided for a
12686** single token.
12687**
12688** In many cases, method (1) above is the best approach. It does not add
12689** extra data to the FTS index or require FTS5 to query for multiple terms,
12690** so it is efficient in terms of disk space and query speed. However, it
12691** does not support prefix queries very well. If, as suggested above, the
12692** token "first" is substituted for "1st" by the tokenizer, then the query:
12693**
12694** <codeblock>
12695** ... MATCH '1s*'</codeblock>
12696**
12697** will not match documents that contain the token "1st" (as the tokenizer
12698** will probably not map "1s" to any prefix of "first").
12699**
12700** For full prefix support, method (3) may be preferred. In this case,
12701** because the index contains entries for both "first" and "1st", prefix
12702** queries such as 'fi*' or '1s*' will match correctly. However, because
12703** extra entries are added to the FTS index, this method uses more space
12704** within the database.
12705**
12706** Method (2) offers a midpoint between (1) and (3). Using this method,
12707** a query such as '1s*' will match documents that contain the literal
12708** token "1st", but not "first" (assuming the tokenizer is not able to
12709** provide synonyms for prefixes). However, a non-prefix query like '1st'
12710** will match against "1st" and "first". This method does not require
12711** extra disk space, as no extra entries are added to the FTS index.
12712** On the other hand, it may require more CPU cycles to run MATCH queries,
12713** as separate queries of the FTS index are required for each synonym.
12714**
12715** When using methods (2) or (3), it is important that the tokenizer only
12716** provide synonyms when tokenizing document text (method (2)) or query
12717** text (method (3)), not both. Doing so will not cause any errors, but is
12718** inefficient.
12719*/
12720typedef struct Fts5Tokenizer Fts5Tokenizer;
12721typedef struct fts5_tokenizer fts5_tokenizer;
12722struct fts5_tokenizer {
12723 int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
12724 void (*xDelete)(Fts5Tokenizer*);
12725 int (*xTokenize)(Fts5Tokenizer*,
12726 void *pCtx,
12727 int flags, /* Mask of FTS5_TOKENIZE_* flags */
12728 const char *pText, int nText,
12729 int (*xToken)(
12730 void *pCtx, /* Copy of 2nd argument to xTokenize() */
12731 int tflags, /* Mask of FTS5_TOKEN_* flags */
12732 const char *pToken, /* Pointer to buffer containing token */
12733 int nToken, /* Size of token in bytes */
12734 int iStart, /* Byte offset of token within input text */
12735 int iEnd /* Byte offset of end of token within input text */
12736 )
12737 );
12738};
12739
12740/* Flags that may be passed as the third argument to xTokenize() */
12741#define FTS5_TOKENIZE_QUERY 0x0001
12742#define FTS5_TOKENIZE_PREFIX 0x0002
12743#define FTS5_TOKENIZE_DOCUMENT 0x0004
12744#define FTS5_TOKENIZE_AUX 0x0008
12745
12746/* Flags that may be passed by the tokenizer implementation back to FTS5
12747** as the third argument to the supplied xToken callback. */
12748#define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
12749
12750/*
12751** END OF CUSTOM TOKENIZERS
12752*************************************************************************/
12753
12754/*************************************************************************
12755** FTS5 EXTENSION REGISTRATION API
12756*/
12757typedef struct fts5_api fts5_api;
12758struct fts5_api {
12759 int iVersion; /* Currently always set to 2 */
12760
12761 /* Create a new tokenizer */
12762 int (*xCreateTokenizer)(
12763 fts5_api *pApi,
12764 const char *zName,
12765 void *pContext,
12766 fts5_tokenizer *pTokenizer,
12767 void (*xDestroy)(void*)
12768 );
12769
12770 /* Find an existing tokenizer */
12771 int (*xFindTokenizer)(
12772 fts5_api *pApi,
12773 const char *zName,
12774 void **ppContext,
12775 fts5_tokenizer *pTokenizer
12776 );
12777
12778 /* Create a new auxiliary function */
12779 int (*xCreateFunction)(
12780 fts5_api *pApi,
12781 const char *zName,
12782 void *pContext,
12783 fts5_extension_function xFunction,
12784 void (*xDestroy)(void*)
12785 );
12786};
12787
12788/*
12789** END OF REGISTRATION API
12790*************************************************************************/
12791
12792#if 0
12793} /* end of the 'extern "C"' block */
12794#endif
12795
12796#endif /* _FTS5_H */
12797
12798/******** End of fts5.h *********/
12799
12800/************** End of sqlite3.h *********************************************/
12801/************** Continuing where we left off in sqliteInt.h ******************/
12802
12803/*
12804** Include the configuration header output by 'configure' if we're using the
12805** autoconf-based build
12806*/
12807#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
12808#include "config.h"
12809#define SQLITECONFIG_H 1
12810#endif
12811
12812/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
12813/************** Begin file sqliteLimit.h *************************************/
12814/*
12815** 2007 May 7
12816**
12817** The author disclaims copyright to this source code. In place of
12818** a legal notice, here is a blessing:
12819**
12820** May you do good and not evil.
12821** May you find forgiveness for yourself and forgive others.
12822** May you share freely, never taking more than you give.
12823**
12824*************************************************************************
12825**
12826** This file defines various limits of what SQLite can process.
12827*/
12828
12829/*
12830** The maximum length of a TEXT or BLOB in bytes. This also
12831** limits the size of a row in a table or index.
12832**
12833** The hard limit is the ability of a 32-bit signed integer
12834** to count the size: 2^31-1 or 2147483647.
12835*/
12836#ifndef SQLITE_MAX_LENGTH
12837# define SQLITE_MAX_LENGTH 1000000000
12838#endif
12839
12840/*
12841** This is the maximum number of
12842**
12843** * Columns in a table
12844** * Columns in an index
12845** * Columns in a view
12846** * Terms in the SET clause of an UPDATE statement
12847** * Terms in the result set of a SELECT statement
12848** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
12849** * Terms in the VALUES clause of an INSERT statement
12850**
12851** The hard upper limit here is 32676. Most database people will
12852** tell you that in a well-normalized database, you usually should
12853** not have more than a dozen or so columns in any table. And if
12854** that is the case, there is no point in having more than a few
12855** dozen values in any of the other situations described above.
12856*/
12857#ifndef SQLITE_MAX_COLUMN
12858# define SQLITE_MAX_COLUMN 2000
12859#endif
12860
12861/*
12862** The maximum length of a single SQL statement in bytes.
12863**
12864** It used to be the case that setting this value to zero would
12865** turn the limit off. That is no longer true. It is not possible
12866** to turn this limit off.
12867*/
12868#ifndef SQLITE_MAX_SQL_LENGTH
12869# define SQLITE_MAX_SQL_LENGTH 1000000000
12870#endif
12871
12872/*
12873** The maximum depth of an expression tree. This is limited to
12874** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
12875** want to place more severe limits on the complexity of an
12876** expression. A value of 0 means that there is no limit.
12877*/
12878#ifndef SQLITE_MAX_EXPR_DEPTH
12879# define SQLITE_MAX_EXPR_DEPTH 1000
12880#endif
12881
12882/*
12883** The maximum number of terms in a compound SELECT statement.
12884** The code generator for compound SELECT statements does one
12885** level of recursion for each term. A stack overflow can result
12886** if the number of terms is too large. In practice, most SQL
12887** never has more than 3 or 4 terms. Use a value of 0 to disable
12888** any limit on the number of terms in a compount SELECT.
12889*/
12890#ifndef SQLITE_MAX_COMPOUND_SELECT
12891# define SQLITE_MAX_COMPOUND_SELECT 500
12892#endif
12893
12894/*
12895** The maximum number of opcodes in a VDBE program.
12896** Not currently enforced.
12897*/
12898#ifndef SQLITE_MAX_VDBE_OP
12899# define SQLITE_MAX_VDBE_OP 250000000
12900#endif
12901
12902/*
12903** The maximum number of arguments to an SQL function.
12904*/
12905#ifndef SQLITE_MAX_FUNCTION_ARG
12906# define SQLITE_MAX_FUNCTION_ARG 127
12907#endif
12908
12909/*
12910** The suggested maximum number of in-memory pages to use for
12911** the main database table and for temporary tables.
12912**
12913** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
12914** which means the cache size is limited to 2048000 bytes of memory.
12915** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
12916** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
12917*/
12918#ifndef SQLITE_DEFAULT_CACHE_SIZE
12919# define SQLITE_DEFAULT_CACHE_SIZE -2000
12920#endif
12921
12922/*
12923** The default number of frames to accumulate in the log file before
12924** checkpointing the database in WAL mode.
12925*/
12926#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
12927# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
12928#endif
12929
12930/*
12931** The maximum number of attached databases. This must be between 0
12932** and 125. The upper bound of 125 is because the attached databases are
12933** counted using a signed 8-bit integer which has a maximum value of 127
12934** and we have to allow 2 extra counts for the "main" and "temp" databases.
12935*/
12936#ifndef SQLITE_MAX_ATTACHED
12937# define SQLITE_MAX_ATTACHED 10
12938#endif
12939
12940
12941/*
12942** The maximum value of a ?nnn wildcard that the parser will accept.
12943** If the value exceeds 32767 then extra space is required for the Expr
12944** structure. But otherwise, we believe that the number can be as large
12945** as a signed 32-bit integer can hold.
12946*/
12947#ifndef SQLITE_MAX_VARIABLE_NUMBER
12948# define SQLITE_MAX_VARIABLE_NUMBER 32766
12949#endif
12950
12951/* Maximum page size. The upper bound on this value is 65536. This a limit
12952** imposed by the use of 16-bit offsets within each page.
12953**
12954** Earlier versions of SQLite allowed the user to change this value at
12955** compile time. This is no longer permitted, on the grounds that it creates
12956** a library that is technically incompatible with an SQLite library
12957** compiled with a different limit. If a process operating on a database
12958** with a page-size of 65536 bytes crashes, then an instance of SQLite
12959** compiled with the default page-size limit will not be able to rollback
12960** the aborted transaction. This could lead to database corruption.
12961*/
12962#ifdef SQLITE_MAX_PAGE_SIZE
12963# undef SQLITE_MAX_PAGE_SIZE
12964#endif
12965#define SQLITE_MAX_PAGE_SIZE 65536
12966
12967
12968/*
12969** The default size of a database page.
12970*/
12971#ifndef SQLITE_DEFAULT_PAGE_SIZE
12972# define SQLITE_DEFAULT_PAGE_SIZE 4096
12973#endif
12974#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
12975# undef SQLITE_DEFAULT_PAGE_SIZE
12976# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
12977#endif
12978
12979/*
12980** Ordinarily, if no value is explicitly provided, SQLite creates databases
12981** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
12982** device characteristics (sector-size and atomic write() support),
12983** SQLite may choose a larger value. This constant is the maximum value
12984** SQLite will choose on its own.
12985*/
12986#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
12987# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
12988#endif
12989#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
12990# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
12991# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
12992#endif
12993
12994
12995/*
12996** Maximum number of pages in one database file.
12997**
12998** This is really just the default value for the max_page_count pragma.
12999** This value can be lowered (or raised) at run-time using that the
13000** max_page_count macro.
13001*/
13002#ifndef SQLITE_MAX_PAGE_COUNT
13003# define SQLITE_MAX_PAGE_COUNT 1073741823
13004#endif
13005
13006/*
13007** Maximum length (in bytes) of the pattern in a LIKE or GLOB
13008** operator.
13009*/
13010#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
13011# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
13012#endif
13013
13014/*
13015** Maximum depth of recursion for triggers.
13016**
13017** A value of 1 means that a trigger program will not be able to itself
13018** fire any triggers. A value of 0 means that no trigger programs at all
13019** may be executed.
13020*/
13021#ifndef SQLITE_MAX_TRIGGER_DEPTH
13022# define SQLITE_MAX_TRIGGER_DEPTH 1000
13023#endif
13024
13025/************** End of sqliteLimit.h *****************************************/
13026/************** Continuing where we left off in sqliteInt.h ******************/
13027
13028/* Disable nuisance warnings on Borland compilers */
13029#if defined(__BORLANDC__)
13030#pragma warn -rch /* unreachable code */
13031#pragma warn -ccc /* Condition is always true or false */
13032#pragma warn -aus /* Assigned value is never used */
13033#pragma warn -csu /* Comparing signed and unsigned */
13034#pragma warn -spa /* Suspicious pointer arithmetic */
13035#endif
13036
13037/*
13038** WAL mode depends on atomic aligned 32-bit loads and stores in a few
13039** places. The following macros try to make this explicit.
13040*/
13041#ifndef __has_extension
13042# define __has_extension(x) 0 /* compatibility with non-clang compilers */
13043#endif
13044#if GCC_VERSION>=4007000 || __has_extension(c_atomic)
13045# define SQLITE_ATOMIC_INTRINSICS 1
13046# define AtomicLoad(PTR) __atomic_load_n((PTR),__ATOMIC_RELAXED)
13047# define AtomicStore(PTR,VAL) __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED)
13048#else
13049# define SQLITE_ATOMIC_INTRINSICS 0
13050# define AtomicLoad(PTR) (*(PTR))
13051# define AtomicStore(PTR,VAL) (*(PTR) = (VAL))
13052#endif
13053
13054/*
13055** Include standard header files as necessary
13056*/
13057#ifdef HAVE_STDINT_H
13058#include <stdint.h>
13059#endif
13060#ifdef HAVE_INTTYPES_H
13061#include <inttypes.h>
13062#endif
13063
13064/*
13065** The following macros are used to cast pointers to integers and
13066** integers to pointers. The way you do this varies from one compiler
13067** to the next, so we have developed the following set of #if statements
13068** to generate appropriate macros for a wide range of compilers.
13069**
13070** The correct "ANSI" way to do this is to use the intptr_t type.
13071** Unfortunately, that typedef is not available on all compilers, or
13072** if it is available, it requires an #include of specific headers
13073** that vary from one machine to the next.
13074**
13075** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
13076** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
13077** So we have to define the macros in different ways depending on the
13078** compiler.
13079*/
13080#if defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
13081# define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
13082# define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
13083#elif defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
13084# define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
13085# define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
13086#elif !defined(__GNUC__) /* Works for compilers other than LLVM */
13087# define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
13088# define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
13089#else /* Generates a warning - but it always works */
13090# define SQLITE_INT_TO_PTR(X) ((void*)(X))
13091# define SQLITE_PTR_TO_INT(X) ((int)(X))
13092#endif
13093
13094/*
13095** A macro to hint to the compiler that a function should not be
13096** inlined.
13097*/
13098#if defined(__GNUC__)
13099# define SQLITE_NOINLINE __attribute__((noinline))
13100#elif defined(_MSC_VER) && _MSC_VER>=1310
13101# define SQLITE_NOINLINE __declspec(noinline)
13102#else
13103# define SQLITE_NOINLINE
13104#endif
13105
13106/*
13107** Make sure that the compiler intrinsics we desire are enabled when
13108** compiling with an appropriate version of MSVC unless prevented by
13109** the SQLITE_DISABLE_INTRINSIC define.
13110*/
13111#if !defined(SQLITE_DISABLE_INTRINSIC)
13112# if defined(_MSC_VER) && _MSC_VER>=1400
13113# if !defined(_WIN32_WCE)
13114# include <intrin.h>
13115# pragma intrinsic(_byteswap_ushort)
13116# pragma intrinsic(_byteswap_ulong)
13117# pragma intrinsic(_byteswap_uint64)
13118# pragma intrinsic(_ReadWriteBarrier)
13119# else
13120# include <cmnintrin.h>
13121# endif
13122# endif
13123#endif
13124
13125/*
13126** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
13127** 0 means mutexes are permanently disable and the library is never
13128** threadsafe. 1 means the library is serialized which is the highest
13129** level of threadsafety. 2 means the library is multithreaded - multiple
13130** threads can use SQLite as long as no two threads try to use the same
13131** database connection at the same time.
13132**
13133** Older versions of SQLite used an optional THREADSAFE macro.
13134** We support that for legacy.
13135**
13136** To ensure that the correct value of "THREADSAFE" is reported when querying
13137** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
13138** logic is partially replicated in ctime.c. If it is updated here, it should
13139** also be updated there.
13140*/
13141#if !defined(SQLITE_THREADSAFE)
13142# if defined(THREADSAFE)
13143# define SQLITE_THREADSAFE THREADSAFE
13144# else
13145# define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
13146# endif
13147#endif
13148
13149/*
13150** Powersafe overwrite is on by default. But can be turned off using
13151** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
13152*/
13153#ifndef SQLITE_POWERSAFE_OVERWRITE
13154# define SQLITE_POWERSAFE_OVERWRITE 1
13155#endif
13156
13157/*
13158** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
13159** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
13160** which case memory allocation statistics are disabled by default.
13161*/
13162#if !defined(SQLITE_DEFAULT_MEMSTATUS)
13163# define SQLITE_DEFAULT_MEMSTATUS 1
13164#endif
13165
13166/*
13167** Exactly one of the following macros must be defined in order to
13168** specify which memory allocation subsystem to use.
13169**
13170** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
13171** SQLITE_WIN32_MALLOC // Use Win32 native heap API
13172** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
13173** SQLITE_MEMDEBUG // Debugging version of system malloc()
13174**
13175** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
13176** assert() macro is enabled, each call into the Win32 native heap subsystem
13177** will cause HeapValidate to be called. If heap validation should fail, an
13178** assertion will be triggered.
13179**
13180** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
13181** the default.
13182*/
13183#if defined(SQLITE_SYSTEM_MALLOC) \
13184 + defined(SQLITE_WIN32_MALLOC) \
13185 + defined(SQLITE_ZERO_MALLOC) \
13186 + defined(SQLITE_MEMDEBUG)>1
13187# error "Two or more of the following compile-time configuration options\
13188 are defined but at most one is allowed:\
13189 SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
13190 SQLITE_ZERO_MALLOC"
13191#endif
13192#if defined(SQLITE_SYSTEM_MALLOC) \
13193 + defined(SQLITE_WIN32_MALLOC) \
13194 + defined(SQLITE_ZERO_MALLOC) \
13195 + defined(SQLITE_MEMDEBUG)==0
13196# define SQLITE_SYSTEM_MALLOC 1
13197#endif
13198
13199/*
13200** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
13201** sizes of memory allocations below this value where possible.
13202*/
13203#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
13204# define SQLITE_MALLOC_SOFT_LIMIT 1024
13205#endif
13206
13207/*
13208** We need to define _XOPEN_SOURCE as follows in order to enable
13209** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
13210** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
13211** it.
13212*/
13213#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
13214# define _XOPEN_SOURCE 600
13215#endif
13216
13217/*
13218** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
13219** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
13220** make it true by defining or undefining NDEBUG.
13221**
13222** Setting NDEBUG makes the code smaller and faster by disabling the
13223** assert() statements in the code. So we want the default action
13224** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
13225** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
13226** feature.
13227*/
13228#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
13229# define NDEBUG 1
13230#endif
13231#if defined(NDEBUG) && defined(SQLITE_DEBUG)
13232# undef NDEBUG
13233#endif
13234
13235/*
13236** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
13237*/
13238#if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
13239# define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
13240#endif
13241
13242/*
13243** The testcase() macro is used to aid in coverage testing. When
13244** doing coverage testing, the condition inside the argument to
13245** testcase() must be evaluated both true and false in order to
13246** get full branch coverage. The testcase() macro is inserted
13247** to help ensure adequate test coverage in places where simple
13248** condition/decision coverage is inadequate. For example, testcase()
13249** can be used to make sure boundary values are tested. For
13250** bitmask tests, testcase() can be used to make sure each bit
13251** is significant and used at least once. On switch statements
13252** where multiple cases go to the same block of code, testcase()
13253** can insure that all cases are evaluated.
13254*/
13255#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
13256# ifndef SQLITE_AMALGAMATION
13257 extern unsigned int sqlite3CoverageCounter;
13258# endif
13259# define testcase(X) if( X ){ sqlite3CoverageCounter += (unsigned)__LINE__; }
13260#else
13261# define testcase(X)
13262#endif
13263
13264/*
13265** The TESTONLY macro is used to enclose variable declarations or
13266** other bits of code that are needed to support the arguments
13267** within testcase() and assert() macros.
13268*/
13269#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
13270# define TESTONLY(X) X
13271#else
13272# define TESTONLY(X)
13273#endif
13274
13275/*
13276** Sometimes we need a small amount of code such as a variable initialization
13277** to setup for a later assert() statement. We do not want this code to
13278** appear when assert() is disabled. The following macro is therefore
13279** used to contain that setup code. The "VVA" acronym stands for
13280** "Verification, Validation, and Accreditation". In other words, the
13281** code within VVA_ONLY() will only run during verification processes.
13282*/
13283#ifndef NDEBUG
13284# define VVA_ONLY(X) X
13285#else
13286# define VVA_ONLY(X)
13287#endif
13288
13289/*
13290** Disable ALWAYS() and NEVER() (make them pass-throughs) for coverage
13291** and mutation testing
13292*/
13293#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
13294# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
13295#endif
13296
13297/*
13298** The ALWAYS and NEVER macros surround boolean expressions which
13299** are intended to always be true or false, respectively. Such
13300** expressions could be omitted from the code completely. But they
13301** are included in a few cases in order to enhance the resilience
13302** of SQLite to unexpected behavior - to make the code "self-healing"
13303** or "ductile" rather than being "brittle" and crashing at the first
13304** hint of unplanned behavior.
13305**
13306** In other words, ALWAYS and NEVER are added for defensive code.
13307**
13308** When doing coverage testing ALWAYS and NEVER are hard-coded to
13309** be true and false so that the unreachable code they specify will
13310** not be counted as untested code.
13311*/
13312#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
13313# define ALWAYS(X) (1)
13314# define NEVER(X) (0)
13315#elif !defined(NDEBUG)
13316# define ALWAYS(X) ((X)?1:(assert(0),0))
13317# define NEVER(X) ((X)?(assert(0),1):0)
13318#else
13319# define ALWAYS(X) (X)
13320# define NEVER(X) (X)
13321#endif
13322
13323/*
13324** Some conditionals are optimizations only. In other words, if the
13325** conditionals are replaced with a constant 1 (true) or 0 (false) then
13326** the correct answer is still obtained, though perhaps not as quickly.
13327**
13328** The following macros mark these optimizations conditionals.
13329*/
13330#if defined(SQLITE_MUTATION_TEST)
13331# define OK_IF_ALWAYS_TRUE(X) (1)
13332# define OK_IF_ALWAYS_FALSE(X) (0)
13333#else
13334# define OK_IF_ALWAYS_TRUE(X) (X)
13335# define OK_IF_ALWAYS_FALSE(X) (X)
13336#endif
13337
13338/*
13339** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
13340** defined. We need to defend against those failures when testing with
13341** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
13342** during a normal build. The following macro can be used to disable tests
13343** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
13344*/
13345#if defined(SQLITE_TEST_REALLOC_STRESS)
13346# define ONLY_IF_REALLOC_STRESS(X) (X)
13347#elif !defined(NDEBUG)
13348# define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0)
13349#else
13350# define ONLY_IF_REALLOC_STRESS(X) (0)
13351#endif
13352
13353/*
13354** Declarations used for tracing the operating system interfaces.
13355*/
13356#if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
13357 (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
13358 extern int sqlite3OSTrace;
13359# define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
13360# define SQLITE_HAVE_OS_TRACE
13361#else
13362# define OSTRACE(X)
13363# undef SQLITE_HAVE_OS_TRACE
13364#endif
13365
13366/*
13367** Is the sqlite3ErrName() function needed in the build? Currently,
13368** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
13369** OSTRACE is enabled), and by several "test*.c" files (which are
13370** compiled using SQLITE_TEST).
13371*/
13372#if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
13373 (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
13374# define SQLITE_NEED_ERR_NAME
13375#else
13376# undef SQLITE_NEED_ERR_NAME
13377#endif
13378
13379/*
13380** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
13381*/
13382#ifdef SQLITE_OMIT_EXPLAIN
13383# undef SQLITE_ENABLE_EXPLAIN_COMMENTS
13384#endif
13385
13386/*
13387** SQLITE_OMIT_VIRTUALTABLE implies SQLITE_OMIT_ALTERTABLE
13388*/
13389#if defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_ALTERTABLE)
13390# define SQLITE_OMIT_ALTERTABLE
13391#endif
13392
13393/*
13394** Return true (non-zero) if the input is an integer that is too large
13395** to fit in 32-bits. This macro is used inside of various testcase()
13396** macros to verify that we have tested SQLite for large-file support.
13397*/
13398#define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
13399
13400/*
13401** The macro unlikely() is a hint that surrounds a boolean
13402** expression that is usually false. Macro likely() surrounds
13403** a boolean expression that is usually true. These hints could,
13404** in theory, be used by the compiler to generate better code, but
13405** currently they are just comments for human readers.
13406*/
13407#define likely(X) (X)
13408#define unlikely(X) (X)
13409
13410/************** Include hash.h in the middle of sqliteInt.h ******************/
13411/************** Begin file hash.h ********************************************/
13412/*
13413** 2001 September 22
13414**
13415** The author disclaims copyright to this source code. In place of
13416** a legal notice, here is a blessing:
13417**
13418** May you do good and not evil.
13419** May you find forgiveness for yourself and forgive others.
13420** May you share freely, never taking more than you give.
13421**
13422*************************************************************************
13423** This is the header file for the generic hash-table implementation
13424** used in SQLite.
13425*/
13426#ifndef SQLITE_HASH_H
13427#define SQLITE_HASH_H
13428
13429/* Forward declarations of structures. */
13430typedef struct Hash Hash;
13431typedef struct HashElem HashElem;
13432
13433/* A complete hash table is an instance of the following structure.
13434** The internals of this structure are intended to be opaque -- client
13435** code should not attempt to access or modify the fields of this structure
13436** directly. Change this structure only by using the routines below.
13437** However, some of the "procedures" and "functions" for modifying and
13438** accessing this structure are really macros, so we can't really make
13439** this structure opaque.
13440**
13441** All elements of the hash table are on a single doubly-linked list.
13442** Hash.first points to the head of this list.
13443**
13444** There are Hash.htsize buckets. Each bucket points to a spot in
13445** the global doubly-linked list. The contents of the bucket are the
13446** element pointed to plus the next _ht.count-1 elements in the list.
13447**
13448** Hash.htsize and Hash.ht may be zero. In that case lookup is done
13449** by a linear search of the global list. For small tables, the
13450** Hash.ht table is never allocated because if there are few elements
13451** in the table, it is faster to do a linear search than to manage
13452** the hash table.
13453*/
13454struct Hash {
13455 unsigned int htsize; /* Number of buckets in the hash table */
13456 unsigned int count; /* Number of entries in this table */
13457 HashElem *first; /* The first element of the array */
13458 struct _ht { /* the hash table */
13459 unsigned int count; /* Number of entries with this hash */
13460 HashElem *chain; /* Pointer to first entry with this hash */
13461 } *ht;
13462};
13463
13464/* Each element in the hash table is an instance of the following
13465** structure. All elements are stored on a single doubly-linked list.
13466**
13467** Again, this structure is intended to be opaque, but it can't really
13468** be opaque because it is used by macros.
13469*/
13470struct HashElem {
13471 HashElem *next, *prev; /* Next and previous elements in the table */
13472 void *data; /* Data associated with this element */
13473 const char *pKey; /* Key associated with this element */
13474};
13475
13476/*
13477** Access routines. To delete, insert a NULL pointer.
13478*/
13479SQLITE_PRIVATE void sqlite3HashInit(Hash*);
13480SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
13481SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
13482SQLITE_PRIVATE void sqlite3HashClear(Hash*);
13483
13484/*
13485** Macros for looping over all elements of a hash table. The idiom is
13486** like this:
13487**
13488** Hash h;
13489** HashElem *p;
13490** ...
13491** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
13492** SomeStructure *pData = sqliteHashData(p);
13493** // do something with pData
13494** }
13495*/
13496#define sqliteHashFirst(H) ((H)->first)
13497#define sqliteHashNext(E) ((E)->next)
13498#define sqliteHashData(E) ((E)->data)
13499/* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
13500/* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
13501
13502/*
13503** Number of entries in a hash table
13504*/
13505#define sqliteHashCount(H) ((H)->count)
13506
13507#endif /* SQLITE_HASH_H */
13508
13509/************** End of hash.h ************************************************/
13510/************** Continuing where we left off in sqliteInt.h ******************/
13511/************** Include parse.h in the middle of sqliteInt.h *****************/
13512/************** Begin file parse.h *******************************************/
13513#define TK_SEMI 1
13514#define TK_EXPLAIN 2
13515#define TK_QUERY 3
13516#define TK_PLAN 4
13517#define TK_BEGIN 5
13518#define TK_TRANSACTION 6
13519#define TK_DEFERRED 7
13520#define TK_IMMEDIATE 8
13521#define TK_EXCLUSIVE 9
13522#define TK_COMMIT 10
13523#define TK_END 11
13524#define TK_ROLLBACK 12
13525#define TK_SAVEPOINT 13
13526#define TK_RELEASE 14
13527#define TK_TO 15
13528#define TK_TABLE 16
13529#define TK_CREATE 17
13530#define TK_IF 18
13531#define TK_NOT 19
13532#define TK_EXISTS 20
13533#define TK_TEMP 21
13534#define TK_LP 22
13535#define TK_RP 23
13536#define TK_AS 24
13537#define TK_COMMA 25
13538#define TK_WITHOUT 26
13539#define TK_ABORT 27
13540#define TK_ACTION 28
13541#define TK_AFTER 29
13542#define TK_ANALYZE 30
13543#define TK_ASC 31
13544#define TK_ATTACH 32
13545#define TK_BEFORE 33
13546#define TK_BY 34
13547#define TK_CASCADE 35
13548#define TK_CAST 36
13549#define TK_CONFLICT 37
13550#define TK_DATABASE 38
13551#define TK_DESC 39
13552#define TK_DETACH 40
13553#define TK_EACH 41
13554#define TK_FAIL 42
13555#define TK_OR 43
13556#define TK_AND 44
13557#define TK_IS 45
13558#define TK_MATCH 46
13559#define TK_LIKE_KW 47
13560#define TK_BETWEEN 48
13561#define TK_IN 49
13562#define TK_ISNULL 50
13563#define TK_NOTNULL 51
13564#define TK_NE 52
13565#define TK_EQ 53
13566#define TK_GT 54
13567#define TK_LE 55
13568#define TK_LT 56
13569#define TK_GE 57
13570#define TK_ESCAPE 58
13571#define TK_ID 59
13572#define TK_COLUMNKW 60
13573#define TK_DO 61
13574#define TK_FOR 62
13575#define TK_IGNORE 63
13576#define TK_INITIALLY 64
13577#define TK_INSTEAD 65
13578#define TK_NO 66
13579#define TK_KEY 67
13580#define TK_OF 68
13581#define TK_OFFSET 69
13582#define TK_PRAGMA 70
13583#define TK_RAISE 71
13584#define TK_RECURSIVE 72
13585#define TK_REPLACE 73
13586#define TK_RESTRICT 74
13587#define TK_ROW 75
13588#define TK_ROWS 76
13589#define TK_TRIGGER 77
13590#define TK_VACUUM 78
13591#define TK_VIEW 79
13592#define TK_VIRTUAL 80
13593#define TK_WITH 81
13594#define TK_NULLS 82
13595#define TK_FIRST 83
13596#define TK_LAST 84
13597#define TK_CURRENT 85
13598#define TK_FOLLOWING 86
13599#define TK_PARTITION 87
13600#define TK_PRECEDING 88
13601#define TK_RANGE 89
13602#define TK_UNBOUNDED 90
13603#define TK_EXCLUDE 91
13604#define TK_GROUPS 92
13605#define TK_OTHERS 93
13606#define TK_TIES 94
13607#define TK_GENERATED 95
13608#define TK_ALWAYS 96
13609#define TK_MATERIALIZED 97
13610#define TK_REINDEX 98
13611#define TK_RENAME 99
13612#define TK_CTIME_KW 100
13613#define TK_ANY 101
13614#define TK_BITAND 102
13615#define TK_BITOR 103
13616#define TK_LSHIFT 104
13617#define TK_RSHIFT 105
13618#define TK_PLUS 106
13619#define TK_MINUS 107
13620#define TK_STAR 108
13621#define TK_SLASH 109
13622#define TK_REM 110
13623#define TK_CONCAT 111
13624#define TK_COLLATE 112
13625#define TK_BITNOT 113
13626#define TK_ON 114
13627#define TK_INDEXED 115
13628#define TK_STRING 116
13629#define TK_JOIN_KW 117
13630#define TK_CONSTRAINT 118
13631#define TK_DEFAULT 119
13632#define TK_NULL 120
13633#define TK_PRIMARY 121
13634#define TK_UNIQUE 122
13635#define TK_CHECK 123
13636#define TK_REFERENCES 124
13637#define TK_AUTOINCR 125
13638#define TK_INSERT 126
13639#define TK_DELETE 127
13640#define TK_UPDATE 128
13641#define TK_SET 129
13642#define TK_DEFERRABLE 130
13643#define TK_FOREIGN 131
13644#define TK_DROP 132
13645#define TK_UNION 133
13646#define TK_ALL 134
13647#define TK_EXCEPT 135
13648#define TK_INTERSECT 136
13649#define TK_SELECT 137
13650#define TK_VALUES 138
13651#define TK_DISTINCT 139
13652#define TK_DOT 140
13653#define TK_FROM 141
13654#define TK_JOIN 142
13655#define TK_USING 143
13656#define TK_ORDER 144
13657#define TK_GROUP 145
13658#define TK_HAVING 146
13659#define TK_LIMIT 147
13660#define TK_WHERE 148
13661#define TK_RETURNING 149
13662#define TK_INTO 150
13663#define TK_NOTHING 151
13664#define TK_FLOAT 152
13665#define TK_BLOB 153
13666#define TK_INTEGER 154
13667#define TK_VARIABLE 155
13668#define TK_CASE 156
13669#define TK_WHEN 157
13670#define TK_THEN 158
13671#define TK_ELSE 159
13672#define TK_INDEX 160
13673#define TK_ALTER 161
13674#define TK_ADD 162
13675#define TK_WINDOW 163
13676#define TK_OVER 164
13677#define TK_FILTER 165
13678#define TK_COLUMN 166
13679#define TK_AGG_FUNCTION 167
13680#define TK_AGG_COLUMN 168
13681#define TK_TRUEFALSE 169
13682#define TK_ISNOT 170
13683#define TK_FUNCTION 171
13684#define TK_UMINUS 172
13685#define TK_UPLUS 173
13686#define TK_TRUTH 174
13687#define TK_REGISTER 175
13688#define TK_VECTOR 176
13689#define TK_SELECT_COLUMN 177
13690#define TK_IF_NULL_ROW 178
13691#define TK_ASTERISK 179
13692#define TK_SPAN 180
13693#define TK_ERROR 181
13694#define TK_SPACE 182
13695#define TK_ILLEGAL 183
13696
13697/************** End of parse.h ***********************************************/
13698/************** Continuing where we left off in sqliteInt.h ******************/
13699#include <stdio.h>
13700#include <stdlib.h>
13701#include <string.h>
13702#include <assert.h>
13703#include <stddef.h>
13704
13705/*
13706** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
13707** This allows better measurements of where memcpy() is used when running
13708** cachegrind. But this macro version of memcpy() is very slow so it
13709** should not be used in production. This is a performance measurement
13710** hack only.
13711*/
13712#ifdef SQLITE_INLINE_MEMCPY
13713# define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
13714 int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
13715#endif
13716
13717/*
13718** If compiling for a processor that lacks floating point support,
13719** substitute integer for floating-point
13720*/
13721#ifdef SQLITE_OMIT_FLOATING_POINT
13722# define double sqlite_int64
13723# define float sqlite_int64
13724# define LONGDOUBLE_TYPE sqlite_int64
13725# ifndef SQLITE_BIG_DBL
13726# define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
13727# endif
13728# define SQLITE_OMIT_DATETIME_FUNCS 1
13729# define SQLITE_OMIT_TRACE 1
13730# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
13731# undef SQLITE_HAVE_ISNAN
13732#endif
13733#ifndef SQLITE_BIG_DBL
13734# define SQLITE_BIG_DBL (1e99)
13735#endif
13736
13737/*
13738** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
13739** afterward. Having this macro allows us to cause the C compiler
13740** to omit code used by TEMP tables without messy #ifndef statements.
13741*/
13742#ifdef SQLITE_OMIT_TEMPDB
13743#define OMIT_TEMPDB 1
13744#else
13745#define OMIT_TEMPDB 0
13746#endif
13747
13748/*
13749** The "file format" number is an integer that is incremented whenever
13750** the VDBE-level file format changes. The following macros define the
13751** the default file format for new databases and the maximum file format
13752** that the library can read.
13753*/
13754#define SQLITE_MAX_FILE_FORMAT 4
13755#ifndef SQLITE_DEFAULT_FILE_FORMAT
13756# define SQLITE_DEFAULT_FILE_FORMAT 4
13757#endif
13758
13759/*
13760** Determine whether triggers are recursive by default. This can be
13761** changed at run-time using a pragma.
13762*/
13763#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
13764# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
13765#endif
13766
13767/*
13768** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
13769** on the command-line
13770*/
13771#ifndef SQLITE_TEMP_STORE
13772# define SQLITE_TEMP_STORE 1
13773#endif
13774
13775/*
13776** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
13777** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
13778** to zero.
13779*/
13780#if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
13781# undef SQLITE_MAX_WORKER_THREADS
13782# define SQLITE_MAX_WORKER_THREADS 0
13783#endif
13784#ifndef SQLITE_MAX_WORKER_THREADS
13785# define SQLITE_MAX_WORKER_THREADS 8
13786#endif
13787#ifndef SQLITE_DEFAULT_WORKER_THREADS
13788# define SQLITE_DEFAULT_WORKER_THREADS 0
13789#endif
13790#if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
13791# undef SQLITE_MAX_WORKER_THREADS
13792# define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
13793#endif
13794
13795/*
13796** The default initial allocation for the pagecache when using separate
13797** pagecaches for each database connection. A positive number is the
13798** number of pages. A negative number N translations means that a buffer
13799** of -1024*N bytes is allocated and used for as many pages as it will hold.
13800**
13801** The default value of "20" was chosen to minimize the run-time of the
13802** speedtest1 test program with options: --shrink-memory --reprepare
13803*/
13804#ifndef SQLITE_DEFAULT_PCACHE_INITSZ
13805# define SQLITE_DEFAULT_PCACHE_INITSZ 20
13806#endif
13807
13808/*
13809** Default value for the SQLITE_CONFIG_SORTERREF_SIZE option.
13810*/
13811#ifndef SQLITE_DEFAULT_SORTERREF_SIZE
13812# define SQLITE_DEFAULT_SORTERREF_SIZE 0x7fffffff
13813#endif
13814
13815/*
13816** The compile-time options SQLITE_MMAP_READWRITE and
13817** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.
13818** You must choose one or the other (or neither) but not both.
13819*/
13820#if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
13821#error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE
13822#endif
13823
13824/*
13825** GCC does not define the offsetof() macro so we'll have to do it
13826** ourselves.
13827*/
13828#ifndef offsetof
13829#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
13830#endif
13831
13832/*
13833** Macros to compute minimum and maximum of two numbers.
13834*/
13835#ifndef MIN
13836# define MIN(A,B) ((A)<(B)?(A):(B))
13837#endif
13838#ifndef MAX
13839# define MAX(A,B) ((A)>(B)?(A):(B))
13840#endif
13841
13842/*
13843** Swap two objects of type TYPE.
13844*/
13845#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
13846
13847/*
13848** Check to see if this machine uses EBCDIC. (Yes, believe it or
13849** not, there are still machines out there that use EBCDIC.)
13850*/
13851#if 'A' == '\301'
13852# define SQLITE_EBCDIC 1
13853#else
13854# define SQLITE_ASCII 1
13855#endif
13856
13857/*
13858** Integers of known sizes. These typedefs might change for architectures
13859** where the sizes very. Preprocessor macros are available so that the
13860** types can be conveniently redefined at compile-type. Like this:
13861**
13862** cc '-DUINTPTR_TYPE=long long int' ...
13863*/
13864#ifndef UINT32_TYPE
13865# ifdef HAVE_UINT32_T
13866# define UINT32_TYPE uint32_t
13867# else
13868# define UINT32_TYPE unsigned int
13869# endif
13870#endif
13871#ifndef UINT16_TYPE
13872# ifdef HAVE_UINT16_T
13873# define UINT16_TYPE uint16_t
13874# else
13875# define UINT16_TYPE unsigned short int
13876# endif
13877#endif
13878#ifndef INT16_TYPE
13879# ifdef HAVE_INT16_T
13880# define INT16_TYPE int16_t
13881# else
13882# define INT16_TYPE short int
13883# endif
13884#endif
13885#ifndef UINT8_TYPE
13886# ifdef HAVE_UINT8_T
13887# define UINT8_TYPE uint8_t
13888# else
13889# define UINT8_TYPE unsigned char
13890# endif
13891#endif
13892#ifndef INT8_TYPE
13893# ifdef HAVE_INT8_T
13894# define INT8_TYPE int8_t
13895# else
13896# define INT8_TYPE signed char
13897# endif
13898#endif
13899#ifndef LONGDOUBLE_TYPE
13900# define LONGDOUBLE_TYPE long double
13901#endif
13902typedef sqlite_int64 i64; /* 8-byte signed integer */
13903typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
13904typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
13905typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
13906typedef INT16_TYPE i16; /* 2-byte signed integer */
13907typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
13908typedef INT8_TYPE i8; /* 1-byte signed integer */
13909
13910/*
13911** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
13912** that can be stored in a u32 without loss of data. The value
13913** is 0x00000000ffffffff. But because of quirks of some compilers, we
13914** have to specify the value in the less intuitive manner shown:
13915*/
13916#define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
13917
13918/*
13919** The datatype used to store estimates of the number of rows in a
13920** table or index. This is an unsigned integer type. For 99.9% of
13921** the world, a 32-bit integer is sufficient. But a 64-bit integer
13922** can be used at compile-time if desired.
13923*/
13924#ifdef SQLITE_64BIT_STATS
13925 typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
13926#else
13927 typedef u32 tRowcnt; /* 32-bit is the default */
13928#endif
13929
13930/*
13931** Estimated quantities used for query planning are stored as 16-bit
13932** logarithms. For quantity X, the value stored is 10*log2(X). This
13933** gives a possible range of values of approximately 1.0e986 to 1e-986.
13934** But the allowed values are "grainy". Not every value is representable.
13935** For example, quantities 16 and 17 are both represented by a LogEst
13936** of 40. However, since LogEst quantities are suppose to be estimates,
13937** not exact values, this imprecision is not a problem.
13938**
13939** "LogEst" is short for "Logarithmic Estimate".
13940**
13941** Examples:
13942** 1 -> 0 20 -> 43 10000 -> 132
13943** 2 -> 10 25 -> 46 25000 -> 146
13944** 3 -> 16 100 -> 66 1000000 -> 199
13945** 4 -> 20 1000 -> 99 1048576 -> 200
13946** 10 -> 33 1024 -> 100 4294967296 -> 320
13947**
13948** The LogEst can be negative to indicate fractional values.
13949** Examples:
13950**
13951** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
13952*/
13953typedef INT16_TYPE LogEst;
13954
13955/*
13956** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
13957*/
13958#ifndef SQLITE_PTRSIZE
13959# if defined(__SIZEOF_POINTER__)
13960# define SQLITE_PTRSIZE __SIZEOF_POINTER__
13961# elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
13962 defined(_M_ARM) || defined(__arm__) || defined(__x86) || \
13963 (defined(__APPLE__) && defined(__POWERPC__)) || \
13964 (defined(__TOS_AIX__) && !defined(__64BIT__))
13965# define SQLITE_PTRSIZE 4
13966# else
13967# define SQLITE_PTRSIZE 8
13968# endif
13969#endif
13970
13971/* The uptr type is an unsigned integer large enough to hold a pointer
13972*/
13973#if defined(HAVE_STDINT_H)
13974 typedef uintptr_t uptr;
13975#elif SQLITE_PTRSIZE==4
13976 typedef u32 uptr;
13977#else
13978 typedef u64 uptr;
13979#endif
13980
13981/*
13982** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
13983** something between S (inclusive) and E (exclusive).
13984**
13985** In other words, S is a buffer and E is a pointer to the first byte after
13986** the end of buffer S. This macro returns true if P points to something
13987** contained within the buffer S.
13988*/
13989#define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
13990
13991
13992/*
13993** Macros to determine whether the machine is big or little endian,
13994** and whether or not that determination is run-time or compile-time.
13995**
13996** For best performance, an attempt is made to guess at the byte-order
13997** using C-preprocessor macros. If that is unsuccessful, or if
13998** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
13999** at run-time.
14000*/
14001#ifndef SQLITE_BYTEORDER
14002# if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
14003 defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
14004 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
14005 defined(__ARMEL__) || defined(__AARCH64EL__) || defined(_M_ARM64)
14006# define SQLITE_BYTEORDER 1234
14007# elif defined(sparc) || defined(__ppc__) || \
14008 defined(__ARMEB__) || defined(__AARCH64EB__)
14009# define SQLITE_BYTEORDER 4321
14010# else
14011# define SQLITE_BYTEORDER 0
14012# endif
14013#endif
14014#if SQLITE_BYTEORDER==4321
14015# define SQLITE_BIGENDIAN 1
14016# define SQLITE_LITTLEENDIAN 0
14017# define SQLITE_UTF16NATIVE SQLITE_UTF16BE
14018#elif SQLITE_BYTEORDER==1234
14019# define SQLITE_BIGENDIAN 0
14020# define SQLITE_LITTLEENDIAN 1
14021# define SQLITE_UTF16NATIVE SQLITE_UTF16LE
14022#else
14023# ifdef SQLITE_AMALGAMATION
14024 const int sqlite3one = 1;
14025# else
14026 extern const int sqlite3one;
14027# endif
14028# define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
14029# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
14030# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
14031#endif
14032
14033/*
14034** Constants for the largest and smallest possible 64-bit signed integers.
14035** These macros are designed to work correctly on both 32-bit and 64-bit
14036** compilers.
14037*/
14038#define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
14039#define LARGEST_UINT64 (0xffffffff|(((u64)0xffffffff)<<32))
14040#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
14041
14042/*
14043** Round up a number to the next larger multiple of 8. This is used
14044** to force 8-byte alignment on 64-bit architectures.
14045*/
14046#define ROUND8(x) (((x)+7)&~7)
14047
14048/*
14049** Round down to the nearest multiple of 8
14050*/
14051#define ROUNDDOWN8(x) ((x)&~7)
14052
14053/*
14054** Assert that the pointer X is aligned to an 8-byte boundary. This
14055** macro is used only within assert() to verify that the code gets
14056** all alignment restrictions correct.
14057**
14058** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
14059** underlying malloc() implementation might return us 4-byte aligned
14060** pointers. In that case, only verify 4-byte alignment.
14061*/
14062#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
14063# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
14064#else
14065# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
14066#endif
14067
14068/*
14069** Disable MMAP on platforms where it is known to not work
14070*/
14071#if defined(__OpenBSD__) || defined(__QNXNTO__)
14072# undef SQLITE_MAX_MMAP_SIZE
14073# define SQLITE_MAX_MMAP_SIZE 0
14074#endif
14075
14076/*
14077** Default maximum size of memory used by memory-mapped I/O in the VFS
14078*/
14079#ifdef __APPLE__
14080# include <TargetConditionals.h>
14081#endif
14082#ifndef SQLITE_MAX_MMAP_SIZE
14083# if defined(__linux__) \
14084 || defined(_WIN32) \
14085 || (defined(__APPLE__) && defined(__MACH__)) \
14086 || defined(__sun) \
14087 || defined(__FreeBSD__) \
14088 || defined(__DragonFly__)
14089# define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
14090# else
14091# define SQLITE_MAX_MMAP_SIZE 0
14092# endif
14093#endif
14094
14095/*
14096** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
14097** default MMAP_SIZE is specified at compile-time, make sure that it does
14098** not exceed the maximum mmap size.
14099*/
14100#ifndef SQLITE_DEFAULT_MMAP_SIZE
14101# define SQLITE_DEFAULT_MMAP_SIZE 0
14102#endif
14103#if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
14104# undef SQLITE_DEFAULT_MMAP_SIZE
14105# define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
14106#endif
14107
14108/*
14109** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
14110** the Select query generator tracing logic is turned on.
14111*/
14112#if !defined(SQLITE_AMALGAMATION)
14113SQLITE_PRIVATE u32 sqlite3SelectTrace;
14114#endif
14115#if defined(SQLITE_DEBUG) \
14116 && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_SELECTTRACE))
14117# define SELECTTRACE_ENABLED 1
14118# define SELECTTRACE(K,P,S,X) \
14119 if(sqlite3SelectTrace&(K)) \
14120 sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\
14121 sqlite3DebugPrintf X
14122#else
14123# define SELECTTRACE(K,P,S,X)
14124# define SELECTTRACE_ENABLED 0
14125#endif
14126
14127/*
14128** Macros for "wheretrace"
14129*/
14130SQLITE_PRIVATE u32 sqlite3WhereTrace;
14131#if defined(SQLITE_DEBUG) \
14132 && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
14133# define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
14134# define WHERETRACE_ENABLED 1
14135#else
14136# define WHERETRACE(K,X)
14137#endif
14138
14139
14140/*
14141** An instance of the following structure is used to store the busy-handler
14142** callback for a given sqlite handle.
14143**
14144** The sqlite.busyHandler member of the sqlite struct contains the busy
14145** callback for the database handle. Each pager opened via the sqlite
14146** handle is passed a pointer to sqlite.busyHandler. The busy-handler
14147** callback is currently invoked only from within pager.c.
14148*/
14149typedef struct BusyHandler BusyHandler;
14150struct BusyHandler {
14151 int (*xBusyHandler)(void *,int); /* The busy callback */
14152 void *pBusyArg; /* First arg to busy callback */
14153 int nBusy; /* Incremented with each busy call */
14154};
14155
14156/*
14157** Name of table that holds the database schema.
14158**
14159** The PREFERRED names are used whereever possible. But LEGACY is also
14160** used for backwards compatibility.
14161**
14162** 1. Queries can use either the PREFERRED or the LEGACY names
14163** 2. The sqlite3_set_authorizer() callback uses the LEGACY name
14164** 3. The PRAGMA table_list statement uses the PREFERRED name
14165**
14166** The LEGACY names are stored in the internal symbol hash table
14167** in support of (2). Names are translated using sqlite3PreferredTableName()
14168** for (3). The sqlite3FindTable() function takes care of translating
14169** names for (1).
14170**
14171** Note that "sqlite_temp_schema" can also be called "temp.sqlite_schema".
14172*/
14173#define LEGACY_SCHEMA_TABLE "sqlite_master"
14174#define LEGACY_TEMP_SCHEMA_TABLE "sqlite_temp_master"
14175#define PREFERRED_SCHEMA_TABLE "sqlite_schema"
14176#define PREFERRED_TEMP_SCHEMA_TABLE "sqlite_temp_schema"
14177
14178
14179/*
14180** The root-page of the schema table.
14181*/
14182#define SCHEMA_ROOT 1
14183
14184/*
14185** The name of the schema table. The name is different for TEMP.
14186*/
14187#define SCHEMA_TABLE(x) \
14188 ((!OMIT_TEMPDB)&&(x==1)?LEGACY_TEMP_SCHEMA_TABLE:LEGACY_SCHEMA_TABLE)
14189
14190/*
14191** A convenience macro that returns the number of elements in
14192** an array.
14193*/
14194#define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
14195
14196/*
14197** Determine if the argument is a power of two
14198*/
14199#define IsPowerOfTwo(X) (((X)&((X)-1))==0)
14200
14201/*
14202** The following value as a destructor means to use sqlite3DbFree().
14203** The sqlite3DbFree() routine requires two parameters instead of the
14204** one parameter that destructors normally want. So we have to introduce
14205** this magic value that the code knows to handle differently. Any
14206** pointer will work here as long as it is distinct from SQLITE_STATIC
14207** and SQLITE_TRANSIENT.
14208*/
14209#define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3OomFault)
14210
14211/*
14212** When SQLITE_OMIT_WSD is defined, it means that the target platform does
14213** not support Writable Static Data (WSD) such as global and static variables.
14214** All variables must either be on the stack or dynamically allocated from
14215** the heap. When WSD is unsupported, the variable declarations scattered
14216** throughout the SQLite code must become constants instead. The SQLITE_WSD
14217** macro is used for this purpose. And instead of referencing the variable
14218** directly, we use its constant as a key to lookup the run-time allocated
14219** buffer that holds real variable. The constant is also the initializer
14220** for the run-time allocated buffer.
14221**
14222** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
14223** macros become no-ops and have zero performance impact.
14224*/
14225#ifdef SQLITE_OMIT_WSD
14226 #define SQLITE_WSD const
14227 #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
14228 #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
14229SQLITE_API int sqlite3_wsd_init(int N, int J);
14230SQLITE_API void *sqlite3_wsd_find(void *K, int L);
14231#else
14232 #define SQLITE_WSD
14233 #define GLOBAL(t,v) v
14234 #define sqlite3GlobalConfig sqlite3Config
14235#endif
14236
14237/*
14238** The following macros are used to suppress compiler warnings and to
14239** make it clear to human readers when a function parameter is deliberately
14240** left unused within the body of a function. This usually happens when
14241** a function is called via a function pointer. For example the
14242** implementation of an SQL aggregate step callback may not use the
14243** parameter indicating the number of arguments passed to the aggregate,
14244** if it knows that this is enforced elsewhere.
14245**
14246** When a function parameter is not used at all within the body of a function,
14247** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
14248** However, these macros may also be used to suppress warnings related to
14249** parameters that may or may not be used depending on compilation options.
14250** For example those parameters only used in assert() statements. In these
14251** cases the parameters are named as per the usual conventions.
14252*/
14253#define UNUSED_PARAMETER(x) (void)(x)
14254#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
14255
14256/*
14257** Forward references to structures
14258*/
14259typedef struct AggInfo AggInfo;
14260typedef struct AuthContext AuthContext;
14261typedef struct AutoincInfo AutoincInfo;
14262typedef struct Bitvec Bitvec;
14263typedef struct CollSeq CollSeq;
14264typedef struct Column Column;
14265typedef struct Cte Cte;
14266typedef struct CteUse CteUse;
14267typedef struct Db Db;
14268typedef struct DbFixer DbFixer;
14269typedef struct Schema Schema;
14270typedef struct Expr Expr;
14271typedef struct ExprList ExprList;
14272typedef struct FKey FKey;
14273typedef struct FuncDestructor FuncDestructor;
14274typedef struct FuncDef FuncDef;
14275typedef struct FuncDefHash FuncDefHash;
14276typedef struct IdList IdList;
14277typedef struct Index Index;
14278typedef struct IndexSample IndexSample;
14279typedef struct KeyClass KeyClass;
14280typedef struct KeyInfo KeyInfo;
14281typedef struct Lookaside Lookaside;
14282typedef struct LookasideSlot LookasideSlot;
14283typedef struct Module Module;
14284typedef struct NameContext NameContext;
14285typedef struct Parse Parse;
14286typedef struct ParseCleanup ParseCleanup;
14287typedef struct PreUpdate PreUpdate;
14288typedef struct PrintfArguments PrintfArguments;
14289typedef struct RenameToken RenameToken;
14290typedef struct Returning Returning;
14291typedef struct RowSet RowSet;
14292typedef struct Savepoint Savepoint;
14293typedef struct Select Select;
14294typedef struct SQLiteThread SQLiteThread;
14295typedef struct SelectDest SelectDest;
14296typedef struct SrcItem SrcItem;
14297typedef struct SrcList SrcList;
14298typedef struct sqlite3_str StrAccum; /* Internal alias for sqlite3_str */
14299typedef struct Table Table;
14300typedef struct TableLock TableLock;
14301typedef struct Token Token;
14302typedef struct TreeView TreeView;
14303typedef struct Trigger Trigger;
14304typedef struct TriggerPrg TriggerPrg;
14305typedef struct TriggerStep TriggerStep;
14306typedef struct UnpackedRecord UnpackedRecord;
14307typedef struct Upsert Upsert;
14308typedef struct VTable VTable;
14309typedef struct VtabCtx VtabCtx;
14310typedef struct Walker Walker;
14311typedef struct WhereInfo WhereInfo;
14312typedef struct Window Window;
14313typedef struct With With;
14314
14315
14316/*
14317** The bitmask datatype defined below is used for various optimizations.
14318**
14319** Changing this from a 64-bit to a 32-bit type limits the number of
14320** tables in a join to 32 instead of 64. But it also reduces the size
14321** of the library by 738 bytes on ix86.
14322*/
14323#ifdef SQLITE_BITMASK_TYPE
14324 typedef SQLITE_BITMASK_TYPE Bitmask;
14325#else
14326 typedef u64 Bitmask;
14327#endif
14328
14329/*
14330** The number of bits in a Bitmask. "BMS" means "BitMask Size".
14331*/
14332#define BMS ((int)(sizeof(Bitmask)*8))
14333
14334/*
14335** A bit in a Bitmask
14336*/
14337#define MASKBIT(n) (((Bitmask)1)<<(n))
14338#define MASKBIT64(n) (((u64)1)<<(n))
14339#define MASKBIT32(n) (((unsigned int)1)<<(n))
14340#define ALLBITS ((Bitmask)-1)
14341
14342/* A VList object records a mapping between parameters/variables/wildcards
14343** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
14344** variable number associated with that parameter. See the format description
14345** on the sqlite3VListAdd() routine for more information. A VList is really
14346** just an array of integers.
14347*/
14348typedef int VList;
14349
14350/*
14351** Defer sourcing vdbe.h and btree.h until after the "u8" and
14352** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
14353** pointer types (i.e. FuncDef) defined above.
14354*/
14355/************** Include pager.h in the middle of sqliteInt.h *****************/
14356/************** Begin file pager.h *******************************************/
14357/*
14358** 2001 September 15
14359**
14360** The author disclaims copyright to this source code. In place of
14361** a legal notice, here is a blessing:
14362**
14363** May you do good and not evil.
14364** May you find forgiveness for yourself and forgive others.
14365** May you share freely, never taking more than you give.
14366**
14367*************************************************************************
14368** This header file defines the interface that the sqlite page cache
14369** subsystem. The page cache subsystem reads and writes a file a page
14370** at a time and provides a journal for rollback.
14371*/
14372
14373#ifndef SQLITE_PAGER_H
14374#define SQLITE_PAGER_H
14375
14376/*
14377** Default maximum size for persistent journal files. A negative
14378** value means no limit. This value may be overridden using the
14379** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
14380*/
14381#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
14382 #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
14383#endif
14384
14385/*
14386** The type used to represent a page number. The first page in a file
14387** is called page 1. 0 is used to represent "not a page".
14388*/
14389typedef u32 Pgno;
14390
14391/*
14392** Each open file is managed by a separate instance of the "Pager" structure.
14393*/
14394typedef struct Pager Pager;
14395
14396/*
14397** Handle type for pages.
14398*/
14399typedef struct PgHdr DbPage;
14400
14401/*
14402** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
14403** reserved for working around a windows/posix incompatibility). It is
14404** used in the journal to signify that the remainder of the journal file
14405** is devoted to storing a super-journal name - there are no more pages to
14406** roll back. See comments for function writeSuperJournal() in pager.c
14407** for details.
14408*/
14409#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
14410
14411/*
14412** Allowed values for the flags parameter to sqlite3PagerOpen().
14413**
14414** NOTE: These values must match the corresponding BTREE_ values in btree.h.
14415*/
14416#define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
14417#define PAGER_MEMORY 0x0002 /* In-memory database */
14418
14419/*
14420** Valid values for the second argument to sqlite3PagerLockingMode().
14421*/
14422#define PAGER_LOCKINGMODE_QUERY -1
14423#define PAGER_LOCKINGMODE_NORMAL 0
14424#define PAGER_LOCKINGMODE_EXCLUSIVE 1
14425
14426/*
14427** Numeric constants that encode the journalmode.
14428**
14429** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
14430** are exposed in the API via the "PRAGMA journal_mode" command and
14431** therefore cannot be changed without a compatibility break.
14432*/
14433#define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
14434#define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
14435#define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
14436#define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
14437#define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
14438#define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
14439#define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
14440
14441/*
14442** Flags that make up the mask passed to sqlite3PagerGet().
14443*/
14444#define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
14445#define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
14446
14447/*
14448** Flags for sqlite3PagerSetFlags()
14449**
14450** Value constraints (enforced via assert()):
14451** PAGER_FULLFSYNC == SQLITE_FullFSync
14452** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
14453** PAGER_CACHE_SPILL == SQLITE_CacheSpill
14454*/
14455#define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
14456#define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
14457#define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
14458#define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
14459#define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */
14460#define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */
14461#define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */
14462#define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */
14463#define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */
14464
14465/*
14466** The remainder of this file contains the declarations of the functions
14467** that make up the Pager sub-system API. See source code comments for
14468** a detailed description of each routine.
14469*/
14470
14471/* Open and close a Pager connection. */
14472SQLITE_PRIVATE int sqlite3PagerOpen(
14473 sqlite3_vfs*,
14474 Pager **ppPager,
14475 const char*,
14476 int,
14477 int,
14478 int,
14479 void(*)(DbPage*)
14480);
14481SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
14482SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
14483
14484/* Functions used to configure a Pager object. */
14485SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(Pager*, int(*)(void *), void *);
14486SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
14487SQLITE_PRIVATE Pgno sqlite3PagerMaxPageCount(Pager*, Pgno);
14488SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
14489SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
14490SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
14491SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
14492SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
14493SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
14494SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
14495SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
14496SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
14497SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
14498SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
14499SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
14500
14501/* Functions used to obtain and release page references. */
14502SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
14503SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
14504SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
14505SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
14506SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
14507SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage*);
14508
14509/* Operations on page references. */
14510SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
14511SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
14512SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
14513SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
14514SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
14515SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
14516
14517/* Functions used to manage pager transactions and savepoints. */
14518SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
14519SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
14520SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zSuper, int);
14521SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
14522SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zSuper);
14523SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
14524SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
14525SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
14526SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
14527SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
14528
14529#ifndef SQLITE_OMIT_WAL
14530SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
14531SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
14532SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
14533SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
14534SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
14535# ifdef SQLITE_ENABLE_SNAPSHOT
14536SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager*, sqlite3_snapshot **ppSnapshot);
14537SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager*, sqlite3_snapshot *pSnapshot);
14538SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager);
14539SQLITE_PRIVATE int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot);
14540SQLITE_PRIVATE void sqlite3PagerSnapshotUnlock(Pager *pPager);
14541# endif
14542#endif
14543
14544#if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_ENABLE_SETLK_TIMEOUT)
14545SQLITE_PRIVATE int sqlite3PagerWalWriteLock(Pager*, int);
14546SQLITE_PRIVATE void sqlite3PagerWalDb(Pager*, sqlite3*);
14547#else
14548# define sqlite3PagerWalWriteLock(y,z) SQLITE_OK
14549# define sqlite3PagerWalDb(x,y)
14550#endif
14551
14552#ifdef SQLITE_DIRECT_OVERFLOW_READ
14553SQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno);
14554#endif
14555
14556#ifdef SQLITE_ENABLE_ZIPVFS
14557SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
14558#endif
14559
14560/* Functions used to query pager state and configuration. */
14561SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
14562SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
14563#ifdef SQLITE_DEBUG
14564SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
14565#endif
14566SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
14567SQLITE_PRIVATE const char *sqlite3PagerFilename(const Pager*, int);
14568SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
14569SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
14570SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
14571SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
14572SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
14573SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
14574SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
14575SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
14576SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
14577
14578/* Functions used to truncate the database file. */
14579SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
14580
14581SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
14582
14583/* Functions to support testing and debugging. */
14584#if !defined(NDEBUG) || defined(SQLITE_TEST)
14585SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
14586SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
14587#endif
14588#ifdef SQLITE_TEST
14589SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
14590SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
14591 void disable_simulated_io_errors(void);
14592 void enable_simulated_io_errors(void);
14593#else
14594# define disable_simulated_io_errors()
14595# define enable_simulated_io_errors()
14596#endif
14597
14598#endif /* SQLITE_PAGER_H */
14599
14600/************** End of pager.h ***********************************************/
14601/************** Continuing where we left off in sqliteInt.h ******************/
14602/************** Include btree.h in the middle of sqliteInt.h *****************/
14603/************** Begin file btree.h *******************************************/
14604/*
14605** 2001 September 15
14606**
14607** The author disclaims copyright to this source code. In place of
14608** a legal notice, here is a blessing:
14609**
14610** May you do good and not evil.
14611** May you find forgiveness for yourself and forgive others.
14612** May you share freely, never taking more than you give.
14613**
14614*************************************************************************
14615** This header file defines the interface that the sqlite B-Tree file
14616** subsystem. See comments in the source code for a detailed description
14617** of what each interface routine does.
14618*/
14619#ifndef SQLITE_BTREE_H
14620#define SQLITE_BTREE_H
14621
14622/* TODO: This definition is just included so other modules compile. It
14623** needs to be revisited.
14624*/
14625#define SQLITE_N_BTREE_META 16
14626
14627/*
14628** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
14629** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
14630*/
14631#ifndef SQLITE_DEFAULT_AUTOVACUUM
14632 #define SQLITE_DEFAULT_AUTOVACUUM 0
14633#endif
14634
14635#define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
14636#define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
14637#define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
14638
14639/*
14640** Forward declarations of structure
14641*/
14642typedef struct Btree Btree;
14643typedef struct BtCursor BtCursor;
14644typedef struct BtShared BtShared;
14645typedef struct BtreePayload BtreePayload;
14646
14647
14648SQLITE_PRIVATE int sqlite3BtreeOpen(
14649 sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
14650 const char *zFilename, /* Name of database file to open */
14651 sqlite3 *db, /* Associated database connection */
14652 Btree **ppBtree, /* Return open Btree* here */
14653 int flags, /* Flags */
14654 int vfsFlags /* Flags passed through to VFS open */
14655);
14656
14657/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
14658** following values.
14659**
14660** NOTE: These values must match the corresponding PAGER_ values in
14661** pager.h.
14662*/
14663#define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
14664#define BTREE_MEMORY 2 /* This is an in-memory DB */
14665#define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
14666#define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
14667
14668SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
14669SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
14670SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
14671#if SQLITE_MAX_MMAP_SIZE>0
14672SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
14673#endif
14674SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
14675SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
14676SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
14677SQLITE_PRIVATE Pgno sqlite3BtreeMaxPageCount(Btree*,Pgno);
14678SQLITE_PRIVATE Pgno sqlite3BtreeLastPage(Btree*);
14679SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
14680SQLITE_PRIVATE int sqlite3BtreeGetRequestedReserve(Btree*);
14681SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
14682SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
14683SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
14684SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int,int*);
14685SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char*);
14686SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
14687SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
14688SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
14689SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
14690SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, Pgno*, int flags);
14691SQLITE_PRIVATE int sqlite3BtreeTxnState(Btree*);
14692SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
14693
14694SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
14695SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
14696#ifndef SQLITE_OMIT_SHARED_CACHE
14697SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
14698#endif
14699
14700/* Savepoints are named, nestable SQL transactions mostly implemented */
14701/* in vdbe.c and pager.c See https://sqlite.org/lang_savepoint.html */
14702SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
14703
14704/* "Checkpoint" only refers to WAL. See https://sqlite.org/wal.html#ckpt */
14705#ifndef SQLITE_OMIT_WAL
14706SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
14707#endif
14708
14709SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
14710SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
14711SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
14712
14713SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
14714
14715/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
14716** of the flags shown below.
14717**
14718** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
14719** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
14720** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
14721** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
14722** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
14723** indices.)
14724*/
14725#define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
14726#define BTREE_BLOBKEY 2 /* Table has keys only - no data */
14727
14728SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
14729SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, i64*);
14730SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
14731SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
14732
14733SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
14734SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
14735
14736SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
14737
14738/*
14739** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
14740** should be one of the following values. The integer values are assigned
14741** to constants so that the offset of the corresponding field in an
14742** SQLite database header may be found using the following formula:
14743**
14744** offset = 36 + (idx * 4)
14745**
14746** For example, the free-page-count field is located at byte offset 36 of
14747** the database file header. The incr-vacuum-flag field is located at
14748** byte offset 64 (== 36+4*7).
14749**
14750** The BTREE_DATA_VERSION value is not really a value stored in the header.
14751** It is a read-only number computed by the pager. But we merge it with
14752** the header value access routines since its access pattern is the same.
14753** Call it a "virtual meta value".
14754*/
14755#define BTREE_FREE_PAGE_COUNT 0
14756#define BTREE_SCHEMA_VERSION 1
14757#define BTREE_FILE_FORMAT 2
14758#define BTREE_DEFAULT_CACHE_SIZE 3
14759#define BTREE_LARGEST_ROOT_PAGE 4
14760#define BTREE_TEXT_ENCODING 5
14761#define BTREE_USER_VERSION 6
14762#define BTREE_INCR_VACUUM 7
14763#define BTREE_APPLICATION_ID 8
14764#define BTREE_DATA_VERSION 15 /* A virtual meta-value */
14765
14766/*
14767** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
14768** interface.
14769**
14770** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
14771**
14772** The first argument is an Expr* (which is guaranteed to be constant for
14773** the lifetime of the cursor) that defines constraints on which rows
14774** might be fetched with this cursor. The Expr* tree may contain
14775** TK_REGISTER nodes that refer to values stored in the array of registers
14776** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
14777** then the value of the node is the value in Mem[pExpr.iTable]. Any
14778** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
14779** column of the b-tree of the cursor. The Expr tree will not contain
14780** any function calls nor subqueries nor references to b-trees other than
14781** the cursor being hinted.
14782**
14783** The design of the _RANGE hint is aid b-tree implementations that try
14784** to prefetch content from remote machines - to provide those
14785** implementations with limits on what needs to be prefetched and thereby
14786** reduce network bandwidth.
14787**
14788** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
14789** standard SQLite. The other hints are provided for extentions that use
14790** the SQLite parser and code generator but substitute their own storage
14791** engine.
14792*/
14793#define BTREE_HINT_RANGE 0 /* Range constraints on queries */
14794
14795/*
14796** Values that may be OR'd together to form the argument to the
14797** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
14798**
14799** The BTREE_BULKLOAD flag is set on index cursors when the index is going
14800** to be filled with content that is already in sorted order.
14801**
14802** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
14803** OP_SeekLE opcodes for a range search, but where the range of entries
14804** selected will all have the same key. In other words, the cursor will
14805** be used only for equality key searches.
14806**
14807*/
14808#define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
14809#define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
14810
14811/*
14812** Flags passed as the third argument to sqlite3BtreeCursor().
14813**
14814** For read-only cursors the wrFlag argument is always zero. For read-write
14815** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
14816** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
14817** only be used by SQLite for the following:
14818**
14819** * to seek to and then delete specific entries, and/or
14820**
14821** * to read values that will be used to create keys that other
14822** BTREE_FORDELETE cursors will seek to and delete.
14823**
14824** The BTREE_FORDELETE flag is an optimization hint. It is not used by
14825** by this, the native b-tree engine of SQLite, but it is available to
14826** alternative storage engines that might be substituted in place of this
14827** b-tree system. For alternative storage engines in which a delete of
14828** the main table row automatically deletes corresponding index rows,
14829** the FORDELETE flag hint allows those alternative storage engines to
14830** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK
14831** and DELETE operations as no-ops, and any READ operation against a
14832** FORDELETE cursor may return a null row: 0x01 0x00.
14833*/
14834#define BTREE_WRCSR 0x00000004 /* read-write cursor */
14835#define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */
14836
14837SQLITE_PRIVATE int sqlite3BtreeCursor(
14838 Btree*, /* BTree containing table to open */
14839 Pgno iTable, /* Index of root page */
14840 int wrFlag, /* 1 for writing. 0 for read-only */
14841 struct KeyInfo*, /* First argument to compare function */
14842 BtCursor *pCursor /* Space to write cursor structure */
14843);
14844SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void);
14845SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
14846SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
14847SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
14848#ifdef SQLITE_ENABLE_CURSOR_HINTS
14849SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
14850#endif
14851
14852SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
14853SQLITE_PRIVATE int sqlite3BtreeTableMoveto(
14854 BtCursor*,
14855 i64 intKey,
14856 int bias,
14857 int *pRes
14858);
14859SQLITE_PRIVATE int sqlite3BtreeIndexMoveto(
14860 BtCursor*,
14861 UnpackedRecord *pUnKey,
14862 int *pRes
14863);
14864SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
14865SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
14866SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
14867
14868/* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */
14869#define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */
14870#define BTREE_AUXDELETE 0x04 /* not the primary delete operation */
14871#define BTREE_APPEND 0x08 /* Insert is likely an append */
14872#define BTREE_PREFORMAT 0x80 /* Inserted data is a preformated cell */
14873
14874/* An instance of the BtreePayload object describes the content of a single
14875** entry in either an index or table btree.
14876**
14877** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
14878** an arbitrary key and no data. These btrees have pKey,nKey set to the
14879** key and the pData,nData,nZero fields are uninitialized. The aMem,nMem
14880** fields give an array of Mem objects that are a decomposition of the key.
14881** The nMem field might be zero, indicating that no decomposition is available.
14882**
14883** Table btrees (used for rowid tables) contain an integer rowid used as
14884** the key and passed in the nKey field. The pKey field is zero.
14885** pData,nData hold the content of the new entry. nZero extra zero bytes
14886** are appended to the end of the content when constructing the entry.
14887** The aMem,nMem fields are uninitialized for table btrees.
14888**
14889** Field usage summary:
14890**
14891** Table BTrees Index Btrees
14892**
14893** pKey always NULL encoded key
14894** nKey the ROWID length of pKey
14895** pData data not used
14896** aMem not used decomposed key value
14897** nMem not used entries in aMem
14898** nData length of pData not used
14899** nZero extra zeros after pData not used
14900**
14901** This object is used to pass information into sqlite3BtreeInsert(). The
14902** same information used to be passed as five separate parameters. But placing
14903** the information into this object helps to keep the interface more
14904** organized and understandable, and it also helps the resulting code to
14905** run a little faster by using fewer registers for parameter passing.
14906*/
14907struct BtreePayload {
14908 const void *pKey; /* Key content for indexes. NULL for tables */
14909 sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */
14910 const void *pData; /* Data for tables. */
14911 sqlite3_value *aMem; /* First of nMem value in the unpacked pKey */
14912 u16 nMem; /* Number of aMem[] value. Might be zero */
14913 int nData; /* Size of pData. 0 if none. */
14914 int nZero; /* Extra zero data appended after pData,nData */
14915};
14916
14917SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
14918 int flags, int seekResult);
14919SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
14920SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
14921SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags);
14922SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
14923SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int flags);
14924SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
14925SQLITE_PRIVATE void sqlite3BtreeCursorPin(BtCursor*);
14926SQLITE_PRIVATE void sqlite3BtreeCursorUnpin(BtCursor*);
14927#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
14928SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor*);
14929#endif
14930SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);
14931SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
14932SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
14933SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor*);
14934
14935SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(sqlite3*,Btree*,Pgno*aRoot,int nRoot,int,int*);
14936SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
14937SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);
14938
14939#ifndef SQLITE_OMIT_INCRBLOB
14940SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);
14941SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
14942SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
14943#endif
14944SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
14945SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
14946SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
14947SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
14948SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
14949
14950#ifdef SQLITE_DEBUG
14951SQLITE_PRIVATE sqlite3_uint64 sqlite3BtreeSeekCount(Btree*);
14952#else
14953# define sqlite3BtreeSeekCount(X) 0
14954#endif
14955
14956#ifndef NDEBUG
14957SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
14958#endif
14959SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);
14960
14961SQLITE_PRIVATE int sqlite3BtreeCount(sqlite3*, BtCursor*, i64*);
14962
14963#ifdef SQLITE_TEST
14964SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
14965SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
14966#endif
14967
14968#ifndef SQLITE_OMIT_WAL
14969SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
14970#endif
14971
14972SQLITE_PRIVATE int sqlite3BtreeTransferRow(BtCursor*, BtCursor*, i64);
14973
14974/*
14975** If we are not using shared cache, then there is no need to
14976** use mutexes to access the BtShared structures. So make the
14977** Enter and Leave procedures no-ops.
14978*/
14979#ifndef SQLITE_OMIT_SHARED_CACHE
14980SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
14981SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
14982SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
14983SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
14984SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree*);
14985#else
14986# define sqlite3BtreeEnter(X)
14987# define sqlite3BtreeEnterAll(X)
14988# define sqlite3BtreeSharable(X) 0
14989# define sqlite3BtreeEnterCursor(X)
14990# define sqlite3BtreeConnectionCount(X) 1
14991#endif
14992
14993#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
14994SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
14995SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
14996SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
14997#ifndef NDEBUG
14998 /* These routines are used inside assert() statements only. */
14999SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
15000SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
15001SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
15002#endif
15003#else
15004
15005# define sqlite3BtreeLeave(X)
15006# define sqlite3BtreeLeaveCursor(X)
15007# define sqlite3BtreeLeaveAll(X)
15008
15009# define sqlite3BtreeHoldsMutex(X) 1
15010# define sqlite3BtreeHoldsAllMutexes(X) 1
15011# define sqlite3SchemaMutexHeld(X,Y,Z) 1
15012#endif
15013
15014
15015#endif /* SQLITE_BTREE_H */
15016
15017/************** End of btree.h ***********************************************/
15018/************** Continuing where we left off in sqliteInt.h ******************/
15019/************** Include vdbe.h in the middle of sqliteInt.h ******************/
15020/************** Begin file vdbe.h ********************************************/
15021/*
15022** 2001 September 15
15023**
15024** The author disclaims copyright to this source code. In place of
15025** a legal notice, here is a blessing:
15026**
15027** May you do good and not evil.
15028** May you find forgiveness for yourself and forgive others.
15029** May you share freely, never taking more than you give.
15030**
15031*************************************************************************
15032** Header file for the Virtual DataBase Engine (VDBE)
15033**
15034** This header defines the interface to the virtual database engine
15035** or VDBE. The VDBE implements an abstract machine that runs a
15036** simple program to access and modify the underlying database.
15037*/
15038#ifndef SQLITE_VDBE_H
15039#define SQLITE_VDBE_H
15040/* #include <stdio.h> */
15041
15042/*
15043** A single VDBE is an opaque structure named "Vdbe". Only routines
15044** in the source file sqliteVdbe.c are allowed to see the insides
15045** of this structure.
15046*/
15047typedef struct Vdbe Vdbe;
15048
15049/*
15050** The names of the following types declared in vdbeInt.h are required
15051** for the VdbeOp definition.
15052*/
15053typedef struct sqlite3_value Mem;
15054typedef struct SubProgram SubProgram;
15055
15056/*
15057** A single instruction of the virtual machine has an opcode
15058** and as many as three operands. The instruction is recorded
15059** as an instance of the following structure:
15060*/
15061struct VdbeOp {
15062 u8 opcode; /* What operation to perform */
15063 signed char p4type; /* One of the P4_xxx constants for p4 */
15064 u16 p5; /* Fifth parameter is an unsigned 16-bit integer */
15065 int p1; /* First operand */
15066 int p2; /* Second parameter (often the jump destination) */
15067 int p3; /* The third parameter */
15068 union p4union { /* fourth parameter */
15069 int i; /* Integer value if p4type==P4_INT32 */
15070 void *p; /* Generic pointer */
15071 char *z; /* Pointer to data for string (char array) types */
15072 i64 *pI64; /* Used when p4type is P4_INT64 */
15073 double *pReal; /* Used when p4type is P4_REAL */
15074 FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
15075 sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
15076 CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
15077 Mem *pMem; /* Used when p4type is P4_MEM */
15078 VTable *pVtab; /* Used when p4type is P4_VTAB */
15079 KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
15080 u32 *ai; /* Used when p4type is P4_INTARRAY */
15081 SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
15082 Table *pTab; /* Used when p4type is P4_TABLE */
15083#ifdef SQLITE_ENABLE_CURSOR_HINTS
15084 Expr *pExpr; /* Used when p4type is P4_EXPR */
15085#endif
15086 int (*xAdvance)(BtCursor *, int);
15087 } p4;
15088#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
15089 char *zComment; /* Comment to improve readability */
15090#endif
15091#ifdef VDBE_PROFILE
15092 u32 cnt; /* Number of times this instruction was executed */
15093 u64 cycles; /* Total time spent executing this instruction */
15094#endif
15095#ifdef SQLITE_VDBE_COVERAGE
15096 u32 iSrcLine; /* Source-code line that generated this opcode
15097 ** with flags in the upper 8 bits */
15098#endif
15099};
15100typedef struct VdbeOp VdbeOp;
15101
15102
15103/*
15104** A sub-routine used to implement a trigger program.
15105*/
15106struct SubProgram {
15107 VdbeOp *aOp; /* Array of opcodes for sub-program */
15108 int nOp; /* Elements in aOp[] */
15109 int nMem; /* Number of memory cells required */
15110 int nCsr; /* Number of cursors required */
15111 u8 *aOnce; /* Array of OP_Once flags */
15112 void *token; /* id that may be used to recursive triggers */
15113 SubProgram *pNext; /* Next sub-program already visited */
15114};
15115
15116/*
15117** A smaller version of VdbeOp used for the VdbeAddOpList() function because
15118** it takes up less space.
15119*/
15120struct VdbeOpList {
15121 u8 opcode; /* What operation to perform */
15122 signed char p1; /* First operand */
15123 signed char p2; /* Second parameter (often the jump destination) */
15124 signed char p3; /* Third parameter */
15125};
15126typedef struct VdbeOpList VdbeOpList;
15127
15128/*
15129** Allowed values of VdbeOp.p4type
15130*/
15131#define P4_NOTUSED 0 /* The P4 parameter is not used */
15132#define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
15133#define P4_STATIC (-1) /* Pointer to a static string */
15134#define P4_COLLSEQ (-2) /* P4 is a pointer to a CollSeq structure */
15135#define P4_INT32 (-3) /* P4 is a 32-bit signed integer */
15136#define P4_SUBPROGRAM (-4) /* P4 is a pointer to a SubProgram structure */
15137#define P4_ADVANCE (-5) /* P4 is a pointer to BtreeNext() or BtreePrev() */
15138#define P4_TABLE (-6) /* P4 is a pointer to a Table structure */
15139/* Above do not own any resources. Must free those below */
15140#define P4_FREE_IF_LE (-7)
15141#define P4_DYNAMIC (-7) /* Pointer to memory from sqliteMalloc() */
15142#define P4_FUNCDEF (-8) /* P4 is a pointer to a FuncDef structure */
15143#define P4_KEYINFO (-9) /* P4 is a pointer to a KeyInfo structure */
15144#define P4_EXPR (-10) /* P4 is a pointer to an Expr tree */
15145#define P4_MEM (-11) /* P4 is a pointer to a Mem* structure */
15146#define P4_VTAB (-12) /* P4 is a pointer to an sqlite3_vtab structure */
15147#define P4_REAL (-13) /* P4 is a 64-bit floating point value */
15148#define P4_INT64 (-14) /* P4 is a 64-bit signed integer */
15149#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
15150#define P4_FUNCCTX (-16) /* P4 is a pointer to an sqlite3_context object */
15151#define P4_DYNBLOB (-17) /* Pointer to memory from sqliteMalloc() */
15152
15153/* Error message codes for OP_Halt */
15154#define P5_ConstraintNotNull 1
15155#define P5_ConstraintUnique 2
15156#define P5_ConstraintCheck 3
15157#define P5_ConstraintFK 4
15158
15159/*
15160** The Vdbe.aColName array contains 5n Mem structures, where n is the
15161** number of columns of data returned by the statement.
15162*/
15163#define COLNAME_NAME 0
15164#define COLNAME_DECLTYPE 1
15165#define COLNAME_DATABASE 2
15166#define COLNAME_TABLE 3
15167#define COLNAME_COLUMN 4
15168#ifdef SQLITE_ENABLE_COLUMN_METADATA
15169# define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
15170#else
15171# ifdef SQLITE_OMIT_DECLTYPE
15172# define COLNAME_N 1 /* Store only the name */
15173# else
15174# define COLNAME_N 2 /* Store the name and decltype */
15175# endif
15176#endif
15177
15178/*
15179** The following macro converts a label returned by sqlite3VdbeMakeLabel()
15180** into an index into the Parse.aLabel[] array that contains the resolved
15181** address of that label.
15182*/
15183#define ADDR(X) (~(X))
15184
15185/*
15186** The makefile scans the vdbe.c source file and creates the "opcodes.h"
15187** header file that defines a number for each opcode used by the VDBE.
15188*/
15189/************** Include opcodes.h in the middle of vdbe.h ********************/
15190/************** Begin file opcodes.h *****************************************/
15191/* Automatically generated. Do not edit */
15192/* See the tool/mkopcodeh.tcl script for details */
15193#define OP_Savepoint 0
15194#define OP_AutoCommit 1
15195#define OP_Transaction 2
15196#define OP_SorterNext 3 /* jump */
15197#define OP_Prev 4 /* jump */
15198#define OP_Next 5 /* jump */
15199#define OP_Checkpoint 6
15200#define OP_JournalMode 7
15201#define OP_Vacuum 8
15202#define OP_VFilter 9 /* jump, synopsis: iplan=r[P3] zplan='P4' */
15203#define OP_VUpdate 10 /* synopsis: data=r[P3@P2] */
15204#define OP_Goto 11 /* jump */
15205#define OP_Gosub 12 /* jump */
15206#define OP_InitCoroutine 13 /* jump */
15207#define OP_Yield 14 /* jump */
15208#define OP_MustBeInt 15 /* jump */
15209#define OP_Jump 16 /* jump */
15210#define OP_Once 17 /* jump */
15211#define OP_If 18 /* jump */
15212#define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
15213#define OP_IfNot 20 /* jump */
15214#define OP_IsNullOrType 21 /* jump, synopsis: if typeof(r[P1]) IN (P3,5) goto P2 */
15215#define OP_IfNullRow 22 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
15216#define OP_SeekLT 23 /* jump, synopsis: key=r[P3@P4] */
15217#define OP_SeekLE 24 /* jump, synopsis: key=r[P3@P4] */
15218#define OP_SeekGE 25 /* jump, synopsis: key=r[P3@P4] */
15219#define OP_SeekGT 26 /* jump, synopsis: key=r[P3@P4] */
15220#define OP_IfNotOpen 27 /* jump, synopsis: if( !csr[P1] ) goto P2 */
15221#define OP_IfNoHope 28 /* jump, synopsis: key=r[P3@P4] */
15222#define OP_NoConflict 29 /* jump, synopsis: key=r[P3@P4] */
15223#define OP_NotFound 30 /* jump, synopsis: key=r[P3@P4] */
15224#define OP_Found 31 /* jump, synopsis: key=r[P3@P4] */
15225#define OP_SeekRowid 32 /* jump, synopsis: intkey=r[P3] */
15226#define OP_NotExists 33 /* jump, synopsis: intkey=r[P3] */
15227#define OP_Last 34 /* jump */
15228#define OP_IfSmaller 35 /* jump */
15229#define OP_SorterSort 36 /* jump */
15230#define OP_Sort 37 /* jump */
15231#define OP_Rewind 38 /* jump */
15232#define OP_IdxLE 39 /* jump, synopsis: key=r[P3@P4] */
15233#define OP_IdxGT 40 /* jump, synopsis: key=r[P3@P4] */
15234#define OP_IdxLT 41 /* jump, synopsis: key=r[P3@P4] */
15235#define OP_IdxGE 42 /* jump, synopsis: key=r[P3@P4] */
15236#define OP_Or 43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
15237#define OP_And 44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
15238#define OP_RowSetRead 45 /* jump, synopsis: r[P3]=rowset(P1) */
15239#define OP_RowSetTest 46 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
15240#define OP_Program 47 /* jump */
15241#define OP_FkIfZero 48 /* jump, synopsis: if fkctr[P1]==0 goto P2 */
15242#define OP_IfPos 49 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
15243#define OP_IsNull 50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
15244#define OP_NotNull 51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
15245#define OP_Ne 52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */
15246#define OP_Eq 53 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */
15247#define OP_Gt 54 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */
15248#define OP_Le 55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */
15249#define OP_Lt 56 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */
15250#define OP_Ge 57 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */
15251#define OP_ElseEq 58 /* jump, same as TK_ESCAPE */
15252#define OP_IfNotZero 59 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
15253#define OP_DecrJumpZero 60 /* jump, synopsis: if (--r[P1])==0 goto P2 */
15254#define OP_IncrVacuum 61 /* jump */
15255#define OP_VNext 62 /* jump */
15256#define OP_Init 63 /* jump, synopsis: Start at P2 */
15257#define OP_PureFunc 64 /* synopsis: r[P3]=func(r[P2@NP]) */
15258#define OP_Function 65 /* synopsis: r[P3]=func(r[P2@NP]) */
15259#define OP_Return 66
15260#define OP_EndCoroutine 67
15261#define OP_HaltIfNull 68 /* synopsis: if r[P3]=null halt */
15262#define OP_Halt 69
15263#define OP_Integer 70 /* synopsis: r[P2]=P1 */
15264#define OP_Int64 71 /* synopsis: r[P2]=P4 */
15265#define OP_String 72 /* synopsis: r[P2]='P4' (len=P1) */
15266#define OP_Null 73 /* synopsis: r[P2..P3]=NULL */
15267#define OP_SoftNull 74 /* synopsis: r[P1]=NULL */
15268#define OP_Blob 75 /* synopsis: r[P2]=P4 (len=P1) */
15269#define OP_Variable 76 /* synopsis: r[P2]=parameter(P1,P4) */
15270#define OP_Move 77 /* synopsis: r[P2@P3]=r[P1@P3] */
15271#define OP_Copy 78 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
15272#define OP_SCopy 79 /* synopsis: r[P2]=r[P1] */
15273#define OP_IntCopy 80 /* synopsis: r[P2]=r[P1] */
15274#define OP_ChngCntRow 81 /* synopsis: output=r[P1] */
15275#define OP_ResultRow 82 /* synopsis: output=r[P1@P2] */
15276#define OP_CollSeq 83
15277#define OP_AddImm 84 /* synopsis: r[P1]=r[P1]+P2 */
15278#define OP_RealAffinity 85
15279#define OP_Cast 86 /* synopsis: affinity(r[P1]) */
15280#define OP_Permutation 87
15281#define OP_Compare 88 /* synopsis: r[P1@P3] <-> r[P2@P3] */
15282#define OP_IsTrue 89 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */
15283#define OP_ZeroOrNull 90 /* synopsis: r[P2] = 0 OR NULL */
15284#define OP_Offset 91 /* synopsis: r[P3] = sqlite_offset(P1) */
15285#define OP_Column 92 /* synopsis: r[P3]=PX */
15286#define OP_TypeCheck 93 /* synopsis: typecheck(r[P1@P2]) */
15287#define OP_Affinity 94 /* synopsis: affinity(r[P1@P2]) */
15288#define OP_MakeRecord 95 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
15289#define OP_Count 96 /* synopsis: r[P2]=count() */
15290#define OP_ReadCookie 97
15291#define OP_SetCookie 98
15292#define OP_ReopenIdx 99 /* synopsis: root=P2 iDb=P3 */
15293#define OP_OpenRead 100 /* synopsis: root=P2 iDb=P3 */
15294#define OP_OpenWrite 101 /* synopsis: root=P2 iDb=P3 */
15295#define OP_BitAnd 102 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
15296#define OP_BitOr 103 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
15297#define OP_ShiftLeft 104 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
15298#define OP_ShiftRight 105 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
15299#define OP_Add 106 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
15300#define OP_Subtract 107 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
15301#define OP_Multiply 108 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
15302#define OP_Divide 109 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
15303#define OP_Remainder 110 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
15304#define OP_Concat 111 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
15305#define OP_OpenDup 112
15306#define OP_BitNot 113 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */
15307#define OP_OpenAutoindex 114 /* synopsis: nColumn=P2 */
15308#define OP_OpenEphemeral 115 /* synopsis: nColumn=P2 */
15309#define OP_String8 116 /* same as TK_STRING, synopsis: r[P2]='P4' */
15310#define OP_SorterOpen 117
15311#define OP_SequenceTest 118 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
15312#define OP_OpenPseudo 119 /* synopsis: P3 columns in r[P2] */
15313#define OP_Close 120
15314#define OP_ColumnsUsed 121
15315#define OP_SeekScan 122 /* synopsis: Scan-ahead up to P1 rows */
15316#define OP_SeekHit 123 /* synopsis: set P2<=seekHit<=P3 */
15317#define OP_Sequence 124 /* synopsis: r[P2]=cursor[P1].ctr++ */
15318#define OP_NewRowid 125 /* synopsis: r[P2]=rowid */
15319#define OP_Insert 126 /* synopsis: intkey=r[P3] data=r[P2] */
15320#define OP_RowCell 127
15321#define OP_Delete 128
15322#define OP_ResetCount 129
15323#define OP_SorterCompare 130 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
15324#define OP_SorterData 131 /* synopsis: r[P2]=data */
15325#define OP_RowData 132 /* synopsis: r[P2]=data */
15326#define OP_Rowid 133 /* synopsis: r[P2]=rowid */
15327#define OP_NullRow 134
15328#define OP_SeekEnd 135
15329#define OP_IdxInsert 136 /* synopsis: key=r[P2] */
15330#define OP_SorterInsert 137 /* synopsis: key=r[P2] */
15331#define OP_IdxDelete 138 /* synopsis: key=r[P2@P3] */
15332#define OP_DeferredSeek 139 /* synopsis: Move P3 to P1.rowid if needed */
15333#define OP_IdxRowid 140 /* synopsis: r[P2]=rowid */
15334#define OP_FinishSeek 141
15335#define OP_Destroy 142
15336#define OP_Clear 143
15337#define OP_ResetSorter 144
15338#define OP_CreateBtree 145 /* synopsis: r[P2]=root iDb=P1 flags=P3 */
15339#define OP_SqlExec 146
15340#define OP_ParseSchema 147
15341#define OP_LoadAnalysis 148
15342#define OP_DropTable 149
15343#define OP_DropIndex 150
15344#define OP_DropTrigger 151
15345#define OP_Real 152 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
15346#define OP_IntegrityCk 153
15347#define OP_RowSetAdd 154 /* synopsis: rowset(P1)=r[P2] */
15348#define OP_Param 155
15349#define OP_FkCounter 156 /* synopsis: fkctr[P1]+=P2 */
15350#define OP_MemMax 157 /* synopsis: r[P1]=max(r[P1],r[P2]) */
15351#define OP_OffsetLimit 158 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
15352#define OP_AggInverse 159 /* synopsis: accum=r[P3] inverse(r[P2@P5]) */
15353#define OP_AggStep 160 /* synopsis: accum=r[P3] step(r[P2@P5]) */
15354#define OP_AggStep1 161 /* synopsis: accum=r[P3] step(r[P2@P5]) */
15355#define OP_AggValue 162 /* synopsis: r[P3]=value N=P2 */
15356#define OP_AggFinal 163 /* synopsis: accum=r[P1] N=P2 */
15357#define OP_Expire 164
15358#define OP_CursorLock 165
15359#define OP_CursorUnlock 166
15360#define OP_TableLock 167 /* synopsis: iDb=P1 root=P2 write=P3 */
15361#define OP_VBegin 168
15362#define OP_VCreate 169
15363#define OP_VDestroy 170
15364#define OP_VOpen 171
15365#define OP_VColumn 172 /* synopsis: r[P3]=vcolumn(P2) */
15366#define OP_VRename 173
15367#define OP_Pagecount 174
15368#define OP_MaxPgcnt 175
15369#define OP_Trace 176
15370#define OP_CursorHint 177
15371#define OP_ReleaseReg 178 /* synopsis: release r[P1@P2] mask P3 */
15372#define OP_Noop 179
15373#define OP_Explain 180
15374#define OP_Abortable 181
15375
15376/* Properties such as "out2" or "jump" that are specified in
15377** comments following the "case" for each opcode in the vdbe.c
15378** are encoded into bitvectors as follows:
15379*/
15380#define OPFLG_JUMP 0x01 /* jump: P2 holds jmp target */
15381#define OPFLG_IN1 0x02 /* in1: P1 is an input */
15382#define OPFLG_IN2 0x04 /* in2: P2 is an input */
15383#define OPFLG_IN3 0x08 /* in3: P3 is an input */
15384#define OPFLG_OUT2 0x10 /* out2: P2 is an output */
15385#define OPFLG_OUT3 0x20 /* out3: P3 is an output */
15386#define OPFLG_INITIALIZER {\
15387/* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x10,\
15388/* 8 */ 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x03, 0x03,\
15389/* 16 */ 0x01, 0x01, 0x03, 0x12, 0x03, 0x03, 0x01, 0x09,\
15390/* 24 */ 0x09, 0x09, 0x09, 0x01, 0x09, 0x09, 0x09, 0x09,\
15391/* 32 */ 0x09, 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
15392/* 40 */ 0x01, 0x01, 0x01, 0x26, 0x26, 0x23, 0x0b, 0x01,\
15393/* 48 */ 0x01, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
15394/* 56 */ 0x0b, 0x0b, 0x01, 0x03, 0x03, 0x01, 0x01, 0x01,\
15395/* 64 */ 0x00, 0x00, 0x02, 0x02, 0x08, 0x00, 0x10, 0x10,\
15396/* 72 */ 0x10, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10,\
15397/* 80 */ 0x10, 0x00, 0x00, 0x00, 0x02, 0x02, 0x02, 0x00,\
15398/* 88 */ 0x00, 0x12, 0x1e, 0x20, 0x00, 0x00, 0x00, 0x00,\
15399/* 96 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x26, 0x26,\
15400/* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26,\
15401/* 112 */ 0x00, 0x12, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,\
15402/* 120 */ 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
15403/* 128 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00,\
15404/* 136 */ 0x04, 0x04, 0x00, 0x00, 0x10, 0x00, 0x10, 0x00,\
15405/* 144 */ 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
15406/* 152 */ 0x10, 0x00, 0x06, 0x10, 0x00, 0x04, 0x1a, 0x00,\
15407/* 160 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
15408/* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10,\
15409/* 176 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,}
15410
15411/* The resolve3P2Values() routine is able to run faster if it knows
15412** the value of the largest JUMP opcode. The smaller the maximum
15413** JUMP opcode the better, so the mkopcodeh.tcl script that
15414** generated this include file strives to group all JUMP opcodes
15415** together near the beginning of the list.
15416*/
15417#define SQLITE_MX_JUMP_OPCODE 63 /* Maximum JUMP opcode */
15418
15419/************** End of opcodes.h *********************************************/
15420/************** Continuing where we left off in vdbe.h ***********************/
15421
15422/*
15423** Additional non-public SQLITE_PREPARE_* flags
15424*/
15425#define SQLITE_PREPARE_SAVESQL 0x80 /* Preserve SQL text */
15426#define SQLITE_PREPARE_MASK 0x0f /* Mask of public flags */
15427
15428/*
15429** Prototypes for the VDBE interface. See comments on the implementation
15430** for a description of what each of these routines does.
15431*/
15432SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
15433SQLITE_PRIVATE Parse *sqlite3VdbeParser(Vdbe*);
15434SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
15435SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
15436SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
15437SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
15438SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
15439SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
15440SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
15441SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
15442SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
15443SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
15444SQLITE_PRIVATE int sqlite3VdbeAddFunctionCall(Parse*,int,int,int,int,const FuncDef*,int);
15445SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
15446#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
15447SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
15448SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
15449#else
15450# define sqlite3VdbeVerifyNoMallocRequired(A,B)
15451# define sqlite3VdbeVerifyNoResultRow(A)
15452#endif
15453#if defined(SQLITE_DEBUG)
15454SQLITE_PRIVATE void sqlite3VdbeVerifyAbortable(Vdbe *p, int);
15455#else
15456# define sqlite3VdbeVerifyAbortable(A,B)
15457#endif
15458SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp,int iLineno);
15459#ifndef SQLITE_OMIT_EXPLAIN
15460SQLITE_PRIVATE void sqlite3VdbeExplain(Parse*,u8,const char*,...);
15461SQLITE_PRIVATE void sqlite3VdbeExplainPop(Parse*);
15462SQLITE_PRIVATE int sqlite3VdbeExplainParent(Parse*);
15463# define ExplainQueryPlan(P) sqlite3VdbeExplain P
15464# define ExplainQueryPlanPop(P) sqlite3VdbeExplainPop(P)
15465# define ExplainQueryPlanParent(P) sqlite3VdbeExplainParent(P)
15466#else
15467# define ExplainQueryPlan(P)
15468# define ExplainQueryPlanPop(P)
15469# define ExplainQueryPlanParent(P) 0
15470# define sqlite3ExplainBreakpoint(A,B) /*no-op*/
15471#endif
15472#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_EXPLAIN)
15473SQLITE_PRIVATE void sqlite3ExplainBreakpoint(const char*,const char*);
15474#else
15475# define sqlite3ExplainBreakpoint(A,B) /*no-op*/
15476#endif
15477SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*, int, char*, u16);
15478SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, int addr, u8);
15479SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
15480SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
15481SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
15482SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
15483SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
15484SQLITE_PRIVATE void sqlite3VdbeJumpHereOrPopInst(Vdbe*, int addr);
15485SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
15486SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
15487#ifdef SQLITE_DEBUG
15488SQLITE_PRIVATE void sqlite3VdbeReleaseRegisters(Parse*,int addr, int n, u32 mask, int);
15489#else
15490# define sqlite3VdbeReleaseRegisters(P,A,N,M,F)
15491#endif
15492SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
15493SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
15494SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
15495SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
15496SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
15497SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Parse*);
15498SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
15499SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
15500SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
15501SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
15502SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
15503SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
15504SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
15505SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
15506#ifdef SQLITE_DEBUG
15507SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
15508#endif
15509SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
15510SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
15511SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
15512SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
15513SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
15514SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
15515SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
15516SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe*);
15517SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8);
15518#ifdef SQLITE_ENABLE_NORMALIZE
15519SQLITE_PRIVATE void sqlite3VdbeAddDblquoteStr(sqlite3*,Vdbe*,const char*);
15520SQLITE_PRIVATE int sqlite3VdbeUsesDoubleQuotedString(Vdbe*,const char*);
15521#endif
15522SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
15523SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
15524SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
15525SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
15526#ifndef SQLITE_OMIT_TRACE
15527SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
15528#endif
15529SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
15530SQLITE_PRIVATE int sqlite3BlobCompare(const Mem*, const Mem*);
15531
15532SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
15533SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
15534SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
15535SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
15536
15537typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
15538SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
15539
15540SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
15541SQLITE_PRIVATE int sqlite3VdbeHasSubProgram(Vdbe*);
15542
15543SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*);
15544#ifdef SQLITE_ENABLE_BYTECODE_VTAB
15545SQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3*);
15546#endif
15547
15548/* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
15549** each VDBE opcode.
15550**
15551** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
15552** comments in VDBE programs that show key decision points in the code
15553** generator.
15554*/
15555#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
15556SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
15557# define VdbeComment(X) sqlite3VdbeComment X
15558SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
15559# define VdbeNoopComment(X) sqlite3VdbeNoopComment X
15560# ifdef SQLITE_ENABLE_MODULE_COMMENTS
15561# define VdbeModuleComment(X) sqlite3VdbeNoopComment X
15562# else
15563# define VdbeModuleComment(X)
15564# endif
15565#else
15566# define VdbeComment(X)
15567# define VdbeNoopComment(X)
15568# define VdbeModuleComment(X)
15569#endif
15570
15571/*
15572** The VdbeCoverage macros are used to set a coverage testing point
15573** for VDBE branch instructions. The coverage testing points are line
15574** numbers in the sqlite3.c source file. VDBE branch coverage testing
15575** only works with an amalagmation build. That's ok since a VDBE branch
15576** coverage build designed for testing the test suite only. No application
15577** should ever ship with VDBE branch coverage measuring turned on.
15578**
15579** VdbeCoverage(v) // Mark the previously coded instruction
15580** // as a branch
15581**
15582** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
15583**
15584** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
15585**
15586** VdbeCoverageNeverTaken(v) // Previous branch is never taken
15587**
15588** VdbeCoverageNeverNull(v) // Previous three-way branch is only
15589** // taken on the first two ways. The
15590** // NULL option is not possible
15591**
15592** VdbeCoverageEqNe(v) // Previous OP_Jump is only interested
15593** // in distingishing equal and not-equal.
15594**
15595** Every VDBE branch operation must be tagged with one of the macros above.
15596** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
15597** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
15598** routine in vdbe.c, alerting the developer to the missed tag.
15599**
15600** During testing, the test application will invoke
15601** sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE,...) to set a callback
15602** routine that is invoked as each bytecode branch is taken. The callback
15603** contains the sqlite3.c source line number ov the VdbeCoverage macro and
15604** flags to indicate whether or not the branch was taken. The test application
15605** is responsible for keeping track of this and reporting byte-code branches
15606** that are never taken.
15607**
15608** See the VdbeBranchTaken() macro and vdbeTakeBranch() function in the
15609** vdbe.c source file for additional information.
15610*/
15611#ifdef SQLITE_VDBE_COVERAGE
15612SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
15613# define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
15614# define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
15615# define VdbeCoverageAlwaysTaken(v) \
15616 sqlite3VdbeSetLineNumber(v,__LINE__|0x5000000);
15617# define VdbeCoverageNeverTaken(v) \
15618 sqlite3VdbeSetLineNumber(v,__LINE__|0x6000000);
15619# define VdbeCoverageNeverNull(v) \
15620 sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);
15621# define VdbeCoverageNeverNullIf(v,x) \
15622 if(x)sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);
15623# define VdbeCoverageEqNe(v) \
15624 sqlite3VdbeSetLineNumber(v,__LINE__|0x8000000);
15625# define VDBE_OFFSET_LINENO(x) (__LINE__+x)
15626#else
15627# define VdbeCoverage(v)
15628# define VdbeCoverageIf(v,x)
15629# define VdbeCoverageAlwaysTaken(v)
15630# define VdbeCoverageNeverTaken(v)
15631# define VdbeCoverageNeverNull(v)
15632# define VdbeCoverageNeverNullIf(v,x)
15633# define VdbeCoverageEqNe(v)
15634# define VDBE_OFFSET_LINENO(x) 0
15635#endif
15636
15637#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
15638SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
15639#else
15640# define sqlite3VdbeScanStatus(a,b,c,d,e)
15641#endif
15642
15643#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
15644SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, VdbeOp*);
15645#endif
15646
15647#endif /* SQLITE_VDBE_H */
15648
15649/************** End of vdbe.h ************************************************/
15650/************** Continuing where we left off in sqliteInt.h ******************/
15651/************** Include pcache.h in the middle of sqliteInt.h ****************/
15652/************** Begin file pcache.h ******************************************/
15653/*
15654** 2008 August 05
15655**
15656** The author disclaims copyright to this source code. In place of
15657** a legal notice, here is a blessing:
15658**
15659** May you do good and not evil.
15660** May you find forgiveness for yourself and forgive others.
15661** May you share freely, never taking more than you give.
15662**
15663*************************************************************************
15664** This header file defines the interface that the sqlite page cache
15665** subsystem.
15666*/
15667
15668#ifndef _PCACHE_H_
15669
15670typedef struct PgHdr PgHdr;
15671typedef struct PCache PCache;
15672
15673/*
15674** Every page in the cache is controlled by an instance of the following
15675** structure.
15676*/
15677struct PgHdr {
15678 sqlite3_pcache_page *pPage; /* Pcache object page handle */
15679 void *pData; /* Page data */
15680 void *pExtra; /* Extra content */
15681 PCache *pCache; /* PRIVATE: Cache that owns this page */
15682 PgHdr *pDirty; /* Transient list of dirty sorted by pgno */
15683 Pager *pPager; /* The pager this page is part of */
15684 Pgno pgno; /* Page number for this page */
15685#ifdef SQLITE_CHECK_PAGES
15686 u32 pageHash; /* Hash of page content */
15687#endif
15688 u16 flags; /* PGHDR flags defined below */
15689
15690 /**********************************************************************
15691 ** Elements above, except pCache, are public. All that follow are
15692 ** private to pcache.c and should not be accessed by other modules.
15693 ** pCache is grouped with the public elements for efficiency.
15694 */
15695 i16 nRef; /* Number of users of this page */
15696 PgHdr *pDirtyNext; /* Next element in list of dirty pages */
15697 PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
15698 /* NB: pDirtyNext and pDirtyPrev are undefined if the
15699 ** PgHdr object is not dirty */
15700};
15701
15702/* Bit values for PgHdr.flags */
15703#define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
15704#define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
15705#define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
15706#define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
15707 ** writing this page to the database */
15708#define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */
15709#define PGHDR_MMAP 0x020 /* This is an mmap page object */
15710
15711#define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */
15712
15713/* Initialize and shutdown the page cache subsystem */
15714SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
15715SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
15716
15717/* Page cache buffer management:
15718** These routines implement SQLITE_CONFIG_PAGECACHE.
15719*/
15720SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
15721
15722/* Create a new pager cache.
15723** Under memory stress, invoke xStress to try to make pages clean.
15724** Only clean and unpinned pages can be reclaimed.
15725*/
15726SQLITE_PRIVATE int sqlite3PcacheOpen(
15727 int szPage, /* Size of every page */
15728 int szExtra, /* Extra space associated with each page */
15729 int bPurgeable, /* True if pages are on backing store */
15730 int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
15731 void *pStress, /* Argument to xStress */
15732 PCache *pToInit /* Preallocated space for the PCache */
15733);
15734
15735/* Modify the page-size after the cache has been created. */
15736SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
15737
15738/* Return the size in bytes of a PCache object. Used to preallocate
15739** storage space.
15740*/
15741SQLITE_PRIVATE int sqlite3PcacheSize(void);
15742
15743/* One release per successful fetch. Page is pinned until released.
15744** Reference counted.
15745*/
15746SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
15747SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
15748SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
15749SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
15750
15751SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
15752SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
15753SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
15754SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
15755SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
15756
15757/* Change a page number. Used by incr-vacuum. */
15758SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
15759
15760/* Remove all pages with pgno>x. Reset the cache if x==0 */
15761SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
15762
15763/* Get a list of all dirty pages in the cache, sorted by page number */
15764SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
15765
15766/* Reset and close the cache object */
15767SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
15768
15769/* Clear flags from pages of the page cache */
15770SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
15771
15772/* Discard the contents of the cache */
15773SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
15774
15775/* Return the total number of outstanding page references */
15776SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
15777
15778/* Increment the reference count of an existing page */
15779SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
15780
15781SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
15782
15783/* Return the total number of pages stored in the cache */
15784SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
15785
15786#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
15787/* Iterate through all dirty pages currently stored in the cache. This
15788** interface is only available if SQLITE_CHECK_PAGES is defined when the
15789** library is built.
15790*/
15791SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
15792#endif
15793
15794#if defined(SQLITE_DEBUG)
15795/* Check invariants on a PgHdr object */
15796SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
15797#endif
15798
15799/* Set and get the suggested cache-size for the specified pager-cache.
15800**
15801** If no global maximum is configured, then the system attempts to limit
15802** the total number of pages cached by purgeable pager-caches to the sum
15803** of the suggested cache-sizes.
15804*/
15805SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
15806#ifdef SQLITE_TEST
15807SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
15808#endif
15809
15810/* Set or get the suggested spill-size for the specified pager-cache.
15811**
15812** The spill-size is the minimum number of pages in cache before the cache
15813** will attempt to spill dirty pages by calling xStress.
15814*/
15815SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
15816
15817/* Free up as much memory as possible from the page cache */
15818SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
15819
15820#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
15821/* Try to return memory used by the pcache module to the main memory heap */
15822SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
15823#endif
15824
15825#ifdef SQLITE_TEST
15826SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
15827#endif
15828
15829SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
15830
15831/* Return the header size */
15832SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
15833SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
15834
15835/* Number of dirty pages as a percentage of the configured cache size */
15836SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
15837
15838#ifdef SQLITE_DIRECT_OVERFLOW_READ
15839SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache);
15840#endif
15841
15842#endif /* _PCACHE_H_ */
15843
15844/************** End of pcache.h **********************************************/
15845/************** Continuing where we left off in sqliteInt.h ******************/
15846/************** Include os.h in the middle of sqliteInt.h ********************/
15847/************** Begin file os.h **********************************************/
15848/*
15849** 2001 September 16
15850**
15851** The author disclaims copyright to this source code. In place of
15852** a legal notice, here is a blessing:
15853**
15854** May you do good and not evil.
15855** May you find forgiveness for yourself and forgive others.
15856** May you share freely, never taking more than you give.
15857**
15858******************************************************************************
15859**
15860** This header file (together with is companion C source-code file
15861** "os.c") attempt to abstract the underlying operating system so that
15862** the SQLite library will work on both POSIX and windows systems.
15863**
15864** This header file is #include-ed by sqliteInt.h and thus ends up
15865** being included by every source file.
15866*/
15867#ifndef _SQLITE_OS_H_
15868#define _SQLITE_OS_H_
15869
15870/*
15871** Attempt to automatically detect the operating system and setup the
15872** necessary pre-processor macros for it.
15873*/
15874/************** Include os_setup.h in the middle of os.h *********************/
15875/************** Begin file os_setup.h ****************************************/
15876/*
15877** 2013 November 25
15878**
15879** The author disclaims copyright to this source code. In place of
15880** a legal notice, here is a blessing:
15881**
15882** May you do good and not evil.
15883** May you find forgiveness for yourself and forgive others.
15884** May you share freely, never taking more than you give.
15885**
15886******************************************************************************
15887**
15888** This file contains pre-processor directives related to operating system
15889** detection and/or setup.
15890*/
15891#ifndef SQLITE_OS_SETUP_H
15892#define SQLITE_OS_SETUP_H
15893
15894/*
15895** Figure out if we are dealing with Unix, Windows, or some other operating
15896** system.
15897**
15898** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
15899** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
15900** the three will be 1. The other two will be 0.
15901*/
15902#if defined(SQLITE_OS_OTHER)
15903# if SQLITE_OS_OTHER==1
15904# undef SQLITE_OS_UNIX
15905# define SQLITE_OS_UNIX 0
15906# undef SQLITE_OS_WIN
15907# define SQLITE_OS_WIN 0
15908# else
15909# undef SQLITE_OS_OTHER
15910# endif
15911#endif
15912#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
15913# define SQLITE_OS_OTHER 0
15914# ifndef SQLITE_OS_WIN
15915# if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
15916 defined(__MINGW32__) || defined(__BORLANDC__)
15917# define SQLITE_OS_WIN 1
15918# define SQLITE_OS_UNIX 0
15919# else
15920# define SQLITE_OS_WIN 0
15921# define SQLITE_OS_UNIX 1
15922# endif
15923# else
15924# define SQLITE_OS_UNIX 0
15925# endif
15926#else
15927# ifndef SQLITE_OS_WIN
15928# define SQLITE_OS_WIN 0
15929# endif
15930#endif
15931
15932#endif /* SQLITE_OS_SETUP_H */
15933
15934/************** End of os_setup.h ********************************************/
15935/************** Continuing where we left off in os.h *************************/
15936
15937/* If the SET_FULLSYNC macro is not defined above, then make it
15938** a no-op
15939*/
15940#ifndef SET_FULLSYNC
15941# define SET_FULLSYNC(x,y)
15942#endif
15943
15944/* Maximum pathname length. Note: FILENAME_MAX defined by stdio.h
15945*/
15946#ifndef SQLITE_MAX_PATHLEN
15947# define SQLITE_MAX_PATHLEN FILENAME_MAX
15948#endif
15949
15950/*
15951** The default size of a disk sector
15952*/
15953#ifndef SQLITE_DEFAULT_SECTOR_SIZE
15954# define SQLITE_DEFAULT_SECTOR_SIZE 4096
15955#endif
15956
15957/*
15958** Temporary files are named starting with this prefix followed by 16 random
15959** alphanumeric characters, and no file extension. They are stored in the
15960** OS's standard temporary file directory, and are deleted prior to exit.
15961** If sqlite is being embedded in another program, you may wish to change the
15962** prefix to reflect your program's name, so that if your program exits
15963** prematurely, old temporary files can be easily identified. This can be done
15964** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
15965**
15966** 2006-10-31: The default prefix used to be "sqlite_". But then
15967** Mcafee started using SQLite in their anti-virus product and it
15968** started putting files with the "sqlite" name in the c:/temp folder.
15969** This annoyed many windows users. Those users would then do a
15970** Google search for "sqlite", find the telephone numbers of the
15971** developers and call to wake them up at night and complain.
15972** For this reason, the default name prefix is changed to be "sqlite"
15973** spelled backwards. So the temp files are still identified, but
15974** anybody smart enough to figure out the code is also likely smart
15975** enough to know that calling the developer will not help get rid
15976** of the file.
15977*/
15978#ifndef SQLITE_TEMP_FILE_PREFIX
15979# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
15980#endif
15981
15982/*
15983** The following values may be passed as the second argument to
15984** sqlite3OsLock(). The various locks exhibit the following semantics:
15985**
15986** SHARED: Any number of processes may hold a SHARED lock simultaneously.
15987** RESERVED: A single process may hold a RESERVED lock on a file at
15988** any time. Other processes may hold and obtain new SHARED locks.
15989** PENDING: A single process may hold a PENDING lock on a file at
15990** any one time. Existing SHARED locks may persist, but no new
15991** SHARED locks may be obtained by other processes.
15992** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
15993**
15994** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
15995** process that requests an EXCLUSIVE lock may actually obtain a PENDING
15996** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
15997** sqlite3OsLock().
15998*/
15999#define NO_LOCK 0
16000#define SHARED_LOCK 1
16001#define RESERVED_LOCK 2
16002#define PENDING_LOCK 3
16003#define EXCLUSIVE_LOCK 4
16004
16005/*
16006** File Locking Notes: (Mostly about windows but also some info for Unix)
16007**
16008** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
16009** those functions are not available. So we use only LockFile() and
16010** UnlockFile().
16011**
16012** LockFile() prevents not just writing but also reading by other processes.
16013** A SHARED_LOCK is obtained by locking a single randomly-chosen
16014** byte out of a specific range of bytes. The lock byte is obtained at
16015** random so two separate readers can probably access the file at the
16016** same time, unless they are unlucky and choose the same lock byte.
16017** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
16018** There can only be one writer. A RESERVED_LOCK is obtained by locking
16019** a single byte of the file that is designated as the reserved lock byte.
16020** A PENDING_LOCK is obtained by locking a designated byte different from
16021** the RESERVED_LOCK byte.
16022**
16023** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
16024** which means we can use reader/writer locks. When reader/writer locks
16025** are used, the lock is placed on the same range of bytes that is used
16026** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
16027** will support two or more Win95 readers or two or more WinNT readers.
16028** But a single Win95 reader will lock out all WinNT readers and a single
16029** WinNT reader will lock out all other Win95 readers.
16030**
16031** The following #defines specify the range of bytes used for locking.
16032** SHARED_SIZE is the number of bytes available in the pool from which
16033** a random byte is selected for a shared lock. The pool of bytes for
16034** shared locks begins at SHARED_FIRST.
16035**
16036** The same locking strategy and
16037** byte ranges are used for Unix. This leaves open the possibility of having
16038** clients on win95, winNT, and unix all talking to the same shared file
16039** and all locking correctly. To do so would require that samba (or whatever
16040** tool is being used for file sharing) implements locks correctly between
16041** windows and unix. I'm guessing that isn't likely to happen, but by
16042** using the same locking range we are at least open to the possibility.
16043**
16044** Locking in windows is manditory. For this reason, we cannot store
16045** actual data in the bytes used for locking. The pager never allocates
16046** the pages involved in locking therefore. SHARED_SIZE is selected so
16047** that all locks will fit on a single page even at the minimum page size.
16048** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
16049** is set high so that we don't have to allocate an unused page except
16050** for very large databases. But one should test the page skipping logic
16051** by setting PENDING_BYTE low and running the entire regression suite.
16052**
16053** Changing the value of PENDING_BYTE results in a subtly incompatible
16054** file format. Depending on how it is changed, you might not notice
16055** the incompatibility right away, even running a full regression test.
16056** The default location of PENDING_BYTE is the first byte past the
16057** 1GB boundary.
16058**
16059*/
16060#ifdef SQLITE_OMIT_WSD
16061# define PENDING_BYTE (0x40000000)
16062#else
16063# define PENDING_BYTE sqlite3PendingByte
16064#endif
16065#define RESERVED_BYTE (PENDING_BYTE+1)
16066#define SHARED_FIRST (PENDING_BYTE+2)
16067#define SHARED_SIZE 510
16068
16069/*
16070** Wrapper around OS specific sqlite3_os_init() function.
16071*/
16072SQLITE_PRIVATE int sqlite3OsInit(void);
16073
16074/*
16075** Functions for accessing sqlite3_file methods
16076*/
16077SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
16078SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
16079SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
16080SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
16081SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
16082SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
16083SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
16084SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
16085SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
16086SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
16087SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
16088#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
16089SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
16090SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
16091#ifndef SQLITE_OMIT_WAL
16092SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
16093SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
16094SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
16095SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
16096#endif /* SQLITE_OMIT_WAL */
16097SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
16098SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
16099
16100
16101/*
16102** Functions for accessing sqlite3_vfs methods
16103*/
16104SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
16105SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
16106SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
16107SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
16108#ifndef SQLITE_OMIT_LOAD_EXTENSION
16109SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
16110SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
16111SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
16112SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
16113#endif /* SQLITE_OMIT_LOAD_EXTENSION */
16114SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
16115SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
16116SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
16117SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
16118
16119/*
16120** Convenience functions for opening and closing files using
16121** sqlite3_malloc() to obtain space for the file-handle structure.
16122*/
16123SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
16124SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
16125
16126#endif /* _SQLITE_OS_H_ */
16127
16128/************** End of os.h **************************************************/
16129/************** Continuing where we left off in sqliteInt.h ******************/
16130/************** Include mutex.h in the middle of sqliteInt.h *****************/
16131/************** Begin file mutex.h *******************************************/
16132/*
16133** 2007 August 28
16134**
16135** The author disclaims copyright to this source code. In place of
16136** a legal notice, here is a blessing:
16137**
16138** May you do good and not evil.
16139** May you find forgiveness for yourself and forgive others.
16140** May you share freely, never taking more than you give.
16141**
16142*************************************************************************
16143**
16144** This file contains the common header for all mutex implementations.
16145** The sqliteInt.h header #includes this file so that it is available
16146** to all source files. We break it out in an effort to keep the code
16147** better organized.
16148**
16149** NOTE: source files should *not* #include this header file directly.
16150** Source files should #include the sqliteInt.h file and let that file
16151** include this one indirectly.
16152*/
16153
16154
16155/*
16156** Figure out what version of the code to use. The choices are
16157**
16158** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
16159** mutexes implementation cannot be overridden
16160** at start-time.
16161**
16162** SQLITE_MUTEX_NOOP For single-threaded applications. No
16163** mutual exclusion is provided. But this
16164** implementation can be overridden at
16165** start-time.
16166**
16167** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
16168**
16169** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
16170*/
16171#if !SQLITE_THREADSAFE
16172# define SQLITE_MUTEX_OMIT
16173#endif
16174#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
16175# if SQLITE_OS_UNIX
16176# define SQLITE_MUTEX_PTHREADS
16177# elif SQLITE_OS_WIN
16178# define SQLITE_MUTEX_W32
16179# else
16180# define SQLITE_MUTEX_NOOP
16181# endif
16182#endif
16183
16184#ifdef SQLITE_MUTEX_OMIT
16185/*
16186** If this is a no-op implementation, implement everything as macros.
16187*/
16188#define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
16189#define sqlite3_mutex_free(X)
16190#define sqlite3_mutex_enter(X)
16191#define sqlite3_mutex_try(X) SQLITE_OK
16192#define sqlite3_mutex_leave(X)
16193#define sqlite3_mutex_held(X) ((void)(X),1)
16194#define sqlite3_mutex_notheld(X) ((void)(X),1)
16195#define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
16196#define sqlite3MutexInit() SQLITE_OK
16197#define sqlite3MutexEnd()
16198#define MUTEX_LOGIC(X)
16199#else
16200#define MUTEX_LOGIC(X) X
16201SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
16202#endif /* defined(SQLITE_MUTEX_OMIT) */
16203
16204/************** End of mutex.h ***********************************************/
16205/************** Continuing where we left off in sqliteInt.h ******************/
16206
16207/* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
16208** synchronous setting to EXTRA. It is no longer supported.
16209*/
16210#ifdef SQLITE_EXTRA_DURABLE
16211# warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
16212# define SQLITE_DEFAULT_SYNCHRONOUS 3
16213#endif
16214
16215/*
16216** Default synchronous levels.
16217**
16218** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
16219** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
16220**
16221** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS
16222** OFF 1 0
16223** NORMAL 2 1
16224** FULL 3 2
16225** EXTRA 4 3
16226**
16227** The "PRAGMA synchronous" statement also uses the zero-based numbers.
16228** In other words, the zero-based numbers are used for all external interfaces
16229** and the one-based values are used internally.
16230*/
16231#ifndef SQLITE_DEFAULT_SYNCHRONOUS
16232# define SQLITE_DEFAULT_SYNCHRONOUS 2
16233#endif
16234#ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
16235# define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
16236#endif
16237
16238/*
16239** Each database file to be accessed by the system is an instance
16240** of the following structure. There are normally two of these structures
16241** in the sqlite.aDb[] array. aDb[0] is the main database file and
16242** aDb[1] is the database file used to hold temporary tables. Additional
16243** databases may be attached.
16244*/
16245struct Db {
16246 char *zDbSName; /* Name of this database. (schema name, not filename) */
16247 Btree *pBt; /* The B*Tree structure for this database file */
16248 u8 safety_level; /* How aggressive at syncing data to disk */
16249 u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */
16250 Schema *pSchema; /* Pointer to database schema (possibly shared) */
16251};
16252
16253/*
16254** An instance of the following structure stores a database schema.
16255**
16256** Most Schema objects are associated with a Btree. The exception is
16257** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
16258** In shared cache mode, a single Schema object can be shared by multiple
16259** Btrees that refer to the same underlying BtShared object.
16260**
16261** Schema objects are automatically deallocated when the last Btree that
16262** references them is destroyed. The TEMP Schema is manually freed by
16263** sqlite3_close().
16264*
16265** A thread must be holding a mutex on the corresponding Btree in order
16266** to access Schema content. This implies that the thread must also be
16267** holding a mutex on the sqlite3 connection pointer that owns the Btree.
16268** For a TEMP Schema, only the connection mutex is required.
16269*/
16270struct Schema {
16271 int schema_cookie; /* Database schema version number for this file */
16272 int iGeneration; /* Generation counter. Incremented with each change */
16273 Hash tblHash; /* All tables indexed by name */
16274 Hash idxHash; /* All (named) indices indexed by name */
16275 Hash trigHash; /* All triggers indexed by name */
16276 Hash fkeyHash; /* All foreign keys by referenced table name */
16277 Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
16278 u8 file_format; /* Schema format version for this file */
16279 u8 enc; /* Text encoding used by this database */
16280 u16 schemaFlags; /* Flags associated with this schema */
16281 int cache_size; /* Number of pages to use in the cache */
16282};
16283
16284/*
16285** These macros can be used to test, set, or clear bits in the
16286** Db.pSchema->flags field.
16287*/
16288#define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
16289#define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
16290#define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
16291#define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
16292
16293/*
16294** Allowed values for the DB.pSchema->flags field.
16295**
16296** The DB_SchemaLoaded flag is set after the database schema has been
16297** read into internal hash tables.
16298**
16299** DB_UnresetViews means that one or more views have column names that
16300** have been filled out. If the schema changes, these column names might
16301** changes and so the view will need to be reset.
16302*/
16303#define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
16304#define DB_UnresetViews 0x0002 /* Some views have defined column names */
16305#define DB_ResetWanted 0x0008 /* Reset the schema when nSchemaLock==0 */
16306
16307/*
16308** The number of different kinds of things that can be limited
16309** using the sqlite3_limit() interface.
16310*/
16311#define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
16312
16313/*
16314** Lookaside malloc is a set of fixed-size buffers that can be used
16315** to satisfy small transient memory allocation requests for objects
16316** associated with a particular database connection. The use of
16317** lookaside malloc provides a significant performance enhancement
16318** (approx 10%) by avoiding numerous malloc/free requests while parsing
16319** SQL statements.
16320**
16321** The Lookaside structure holds configuration information about the
16322** lookaside malloc subsystem. Each available memory allocation in
16323** the lookaside subsystem is stored on a linked list of LookasideSlot
16324** objects.
16325**
16326** Lookaside allocations are only allowed for objects that are associated
16327** with a particular database connection. Hence, schema information cannot
16328** be stored in lookaside because in shared cache mode the schema information
16329** is shared by multiple database connections. Therefore, while parsing
16330** schema information, the Lookaside.bEnabled flag is cleared so that
16331** lookaside allocations are not used to construct the schema objects.
16332**
16333** New lookaside allocations are only allowed if bDisable==0. When
16334** bDisable is greater than zero, sz is set to zero which effectively
16335** disables lookaside without adding a new test for the bDisable flag
16336** in a performance-critical path. sz should be set by to szTrue whenever
16337** bDisable changes back to zero.
16338**
16339** Lookaside buffers are initially held on the pInit list. As they are
16340** used and freed, they are added back to the pFree list. New allocations
16341** come off of pFree first, then pInit as a fallback. This dual-list
16342** allows use to compute a high-water mark - the maximum number of allocations
16343** outstanding at any point in the past - by subtracting the number of
16344** allocations on the pInit list from the total number of allocations.
16345**
16346** Enhancement on 2019-12-12: Two-size-lookaside
16347** The default lookaside configuration is 100 slots of 1200 bytes each.
16348** The larger slot sizes are important for performance, but they waste
16349** a lot of space, as most lookaside allocations are less than 128 bytes.
16350** The two-size-lookaside enhancement breaks up the lookaside allocation
16351** into two pools: One of 128-byte slots and the other of the default size
16352** (1200-byte) slots. Allocations are filled from the small-pool first,
16353** failing over to the full-size pool if that does not work. Thus more
16354** lookaside slots are available while also using less memory.
16355** This enhancement can be omitted by compiling with
16356** SQLITE_OMIT_TWOSIZE_LOOKASIDE.
16357*/
16358struct Lookaside {
16359 u32 bDisable; /* Only operate the lookaside when zero */
16360 u16 sz; /* Size of each buffer in bytes */
16361 u16 szTrue; /* True value of sz, even if disabled */
16362 u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
16363 u32 nSlot; /* Number of lookaside slots allocated */
16364 u32 anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
16365 LookasideSlot *pInit; /* List of buffers not previously used */
16366 LookasideSlot *pFree; /* List of available buffers */
16367#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
16368 LookasideSlot *pSmallInit; /* List of small buffers not prediously used */
16369 LookasideSlot *pSmallFree; /* List of available small buffers */
16370 void *pMiddle; /* First byte past end of full-size buffers and
16371 ** the first byte of LOOKASIDE_SMALL buffers */
16372#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
16373 void *pStart; /* First byte of available memory space */
16374 void *pEnd; /* First byte past end of available space */
16375};
16376struct LookasideSlot {
16377 LookasideSlot *pNext; /* Next buffer in the list of free buffers */
16378};
16379
16380#define DisableLookaside db->lookaside.bDisable++;db->lookaside.sz=0
16381#define EnableLookaside db->lookaside.bDisable--;\
16382 db->lookaside.sz=db->lookaside.bDisable?0:db->lookaside.szTrue
16383
16384/* Size of the smaller allocations in two-size lookside */
16385#ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE
16386# define LOOKASIDE_SMALL 0
16387#else
16388# define LOOKASIDE_SMALL 128
16389#endif
16390
16391/*
16392** A hash table for built-in function definitions. (Application-defined
16393** functions use a regular table table from hash.h.)
16394**
16395** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
16396** Collisions are on the FuncDef.u.pHash chain. Use the SQLITE_FUNC_HASH()
16397** macro to compute a hash on the function name.
16398*/
16399#define SQLITE_FUNC_HASH_SZ 23
16400struct FuncDefHash {
16401 FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */
16402};
16403#define SQLITE_FUNC_HASH(C,L) (((C)+(L))%SQLITE_FUNC_HASH_SZ)
16404
16405#ifdef SQLITE_USER_AUTHENTICATION
16406/*
16407** Information held in the "sqlite3" database connection object and used
16408** to manage user authentication.
16409*/
16410typedef struct sqlite3_userauth sqlite3_userauth;
16411struct sqlite3_userauth {
16412 u8 authLevel; /* Current authentication level */
16413 int nAuthPW; /* Size of the zAuthPW in bytes */
16414 char *zAuthPW; /* Password used to authenticate */
16415 char *zAuthUser; /* User name used to authenticate */
16416};
16417
16418/* Allowed values for sqlite3_userauth.authLevel */
16419#define UAUTH_Unknown 0 /* Authentication not yet checked */
16420#define UAUTH_Fail 1 /* User authentication failed */
16421#define UAUTH_User 2 /* Authenticated as a normal user */
16422#define UAUTH_Admin 3 /* Authenticated as an administrator */
16423
16424/* Functions used only by user authorization logic */
16425SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
16426SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
16427SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
16428SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
16429
16430#endif /* SQLITE_USER_AUTHENTICATION */
16431
16432/*
16433** typedef for the authorization callback function.
16434*/
16435#ifdef SQLITE_USER_AUTHENTICATION
16436 typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
16437 const char*, const char*);
16438#else
16439 typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
16440 const char*);
16441#endif
16442
16443#ifndef SQLITE_OMIT_DEPRECATED
16444/* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
16445** in the style of sqlite3_trace()
16446*/
16447#define SQLITE_TRACE_LEGACY 0x40 /* Use the legacy xTrace */
16448#define SQLITE_TRACE_XPROFILE 0x80 /* Use the legacy xProfile */
16449#else
16450#define SQLITE_TRACE_LEGACY 0
16451#define SQLITE_TRACE_XPROFILE 0
16452#endif /* SQLITE_OMIT_DEPRECATED */
16453#define SQLITE_TRACE_NONLEGACY_MASK 0x0f /* Normal flags */
16454
16455/*
16456** Maximum number of sqlite3.aDb[] entries. This is the number of attached
16457** databases plus 2 for "main" and "temp".
16458*/
16459#define SQLITE_MAX_DB (SQLITE_MAX_ATTACHED+2)
16460
16461/*
16462** Each database connection is an instance of the following structure.
16463*/
16464struct sqlite3 {
16465 sqlite3_vfs *pVfs; /* OS Interface */
16466 struct Vdbe *pVdbe; /* List of active virtual machines */
16467 CollSeq *pDfltColl; /* BINARY collseq for the database encoding */
16468 sqlite3_mutex *mutex; /* Connection mutex */
16469 Db *aDb; /* All backends */
16470 int nDb; /* Number of backends currently in use */
16471 u32 mDbFlags; /* flags recording internal state */
16472 u64 flags; /* flags settable by pragmas. See below */
16473 i64 lastRowid; /* ROWID of most recent insert (see above) */
16474 i64 szMmap; /* Default mmap_size setting */
16475 u32 nSchemaLock; /* Do not reset the schema when non-zero */
16476 unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
16477 int errCode; /* Most recent error code (SQLITE_*) */
16478 int errMask; /* & result codes with this before returning */
16479 int iSysErrno; /* Errno value from last system error */
16480 u32 dbOptFlags; /* Flags to enable/disable optimizations */
16481 u8 enc; /* Text encoding */
16482 u8 autoCommit; /* The auto-commit flag. */
16483 u8 temp_store; /* 1: file 2: memory 0: default */
16484 u8 mallocFailed; /* True if we have seen a malloc failure */
16485 u8 bBenignMalloc; /* Do not require OOMs if true */
16486 u8 dfltLockMode; /* Default locking-mode for attached dbs */
16487 signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
16488 u8 suppressErr; /* Do not issue error messages if true */
16489 u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
16490 u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
16491 u8 mTrace; /* zero or more SQLITE_TRACE flags */
16492 u8 noSharedCache; /* True if no shared-cache backends */
16493 u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */
16494 u8 eOpenState; /* Current condition of the connection */
16495 int nextPagesize; /* Pagesize after VACUUM if >0 */
16496 i64 nChange; /* Value returned by sqlite3_changes() */
16497 i64 nTotalChange; /* Value returned by sqlite3_total_changes() */
16498 int aLimit[SQLITE_N_LIMIT]; /* Limits */
16499 int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
16500 struct sqlite3InitInfo { /* Information used during initialization */
16501 Pgno newTnum; /* Rootpage of table being initialized */
16502 u8 iDb; /* Which db file is being initialized */
16503 u8 busy; /* TRUE if currently initializing */
16504 unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */
16505 unsigned imposterTable : 1; /* Building an imposter table */
16506 unsigned reopenMemdb : 1; /* ATTACH is really a reopen using MemDB */
16507 const char **azInit; /* "type", "name", and "tbl_name" columns */
16508 } init;
16509 int nVdbeActive; /* Number of VDBEs currently running */
16510 int nVdbeRead; /* Number of active VDBEs that read or write */
16511 int nVdbeWrite; /* Number of active VDBEs that read and write */
16512 int nVdbeExec; /* Number of nested calls to VdbeExec() */
16513 int nVDestroy; /* Number of active OP_VDestroy operations */
16514 int nExtension; /* Number of loaded extensions */
16515 void **aExtension; /* Array of shared library handles */
16516 union {
16517 void (*xLegacy)(void*,const char*); /* mTrace==SQLITE_TRACE_LEGACY */
16518 int (*xV2)(u32,void*,void*,void*); /* All other mTrace values */
16519 } trace;
16520 void *pTraceArg; /* Argument to the trace function */
16521#ifndef SQLITE_OMIT_DEPRECATED
16522 void (*xProfile)(void*,const char*,u64); /* Profiling function */
16523 void *pProfileArg; /* Argument to profile function */
16524#endif
16525 void *pCommitArg; /* Argument to xCommitCallback() */
16526 int (*xCommitCallback)(void*); /* Invoked at every commit. */
16527 void *pRollbackArg; /* Argument to xRollbackCallback() */
16528 void (*xRollbackCallback)(void*); /* Invoked at every commit. */
16529 void *pUpdateArg;
16530 void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
16531 void *pAutovacPagesArg; /* Client argument to autovac_pages */
16532 void (*xAutovacDestr)(void*); /* Destructor for pAutovacPAgesArg */
16533 unsigned int (*xAutovacPages)(void*,const char*,u32,u32,u32);
16534 Parse *pParse; /* Current parse */
16535#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
16536 void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
16537 void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
16538 void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
16539 );
16540 PreUpdate *pPreUpdate; /* Context for active pre-update callback */
16541#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
16542#ifndef SQLITE_OMIT_WAL
16543 int (*xWalCallback)(void *, sqlite3 *, const char *, int);
16544 void *pWalArg;
16545#endif
16546 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
16547 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
16548 void *pCollNeededArg;
16549 sqlite3_value *pErr; /* Most recent error message */
16550 union {
16551 volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
16552 double notUsed1; /* Spacer */
16553 } u1;
16554 Lookaside lookaside; /* Lookaside malloc configuration */
16555#ifndef SQLITE_OMIT_AUTHORIZATION
16556 sqlite3_xauth xAuth; /* Access authorization function */
16557 void *pAuthArg; /* 1st argument to the access auth function */
16558#endif
16559#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
16560 int (*xProgress)(void *); /* The progress callback */
16561 void *pProgressArg; /* Argument to the progress callback */
16562 unsigned nProgressOps; /* Number of opcodes for progress callback */
16563#endif
16564#ifndef SQLITE_OMIT_VIRTUALTABLE
16565 int nVTrans; /* Allocated size of aVTrans */
16566 Hash aModule; /* populated by sqlite3_create_module() */
16567 VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
16568 VTable **aVTrans; /* Virtual tables with open transactions */
16569 VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
16570#endif
16571 Hash aFunc; /* Hash table of connection functions */
16572 Hash aCollSeq; /* All collating sequences */
16573 BusyHandler busyHandler; /* Busy callback */
16574 Db aDbStatic[2]; /* Static space for the 2 default backends */
16575 Savepoint *pSavepoint; /* List of active savepoints */
16576 int nAnalysisLimit; /* Number of index rows to ANALYZE */
16577 int busyTimeout; /* Busy handler timeout, in msec */
16578 int nSavepoint; /* Number of non-transaction savepoints */
16579 int nStatement; /* Number of nested statement-transactions */
16580 i64 nDeferredCons; /* Net deferred constraints this transaction. */
16581 i64 nDeferredImmCons; /* Net deferred immediate constraints */
16582 int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
16583#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
16584 /* The following variables are all protected by the STATIC_MAIN
16585 ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
16586 **
16587 ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
16588 ** unlock so that it can proceed.
16589 **
16590 ** When X.pBlockingConnection==Y, that means that something that X tried
16591 ** tried to do recently failed with an SQLITE_LOCKED error due to locks
16592 ** held by Y.
16593 */
16594 sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
16595 sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
16596 void *pUnlockArg; /* Argument to xUnlockNotify */
16597 void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
16598 sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
16599#endif
16600#ifdef SQLITE_USER_AUTHENTICATION
16601 sqlite3_userauth auth; /* User authentication information */
16602#endif
16603};
16604
16605/*
16606** A macro to discover the encoding of a database.
16607*/
16608#define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
16609#define ENC(db) ((db)->enc)
16610
16611/*
16612** A u64 constant where the lower 32 bits are all zeros. Only the
16613** upper 32 bits are included in the argument. Necessary because some
16614** C-compilers still do not accept LL integer literals.
16615*/
16616#define HI(X) ((u64)(X)<<32)
16617
16618/*
16619** Possible values for the sqlite3.flags.
16620**
16621** Value constraints (enforced via assert()):
16622** SQLITE_FullFSync == PAGER_FULLFSYNC
16623** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
16624** SQLITE_CacheSpill == PAGER_CACHE_SPILL
16625*/
16626#define SQLITE_WriteSchema 0x00000001 /* OK to update SQLITE_SCHEMA */
16627#define SQLITE_LegacyFileFmt 0x00000002 /* Create new databases in format 1 */
16628#define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
16629#define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
16630#define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */
16631#define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */
16632#define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
16633#define SQLITE_TrustedSchema 0x00000080 /* Allow unsafe functions and
16634 ** vtabs in the schema definition */
16635#define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
16636 /* result set is empty */
16637#define SQLITE_IgnoreChecks 0x00000200 /* Do not enforce check constraints */
16638#define SQLITE_ReadUncommit 0x00000400 /* READ UNCOMMITTED in shared-cache */
16639#define SQLITE_NoCkptOnClose 0x00000800 /* No checkpoint on close()/DETACH */
16640#define SQLITE_ReverseOrder 0x00001000 /* Reverse unordered SELECTs */
16641#define SQLITE_RecTriggers 0x00002000 /* Enable recursive triggers */
16642#define SQLITE_ForeignKeys 0x00004000 /* Enforce foreign key constraints */
16643#define SQLITE_AutoIndex 0x00008000 /* Enable automatic indexes */
16644#define SQLITE_LoadExtension 0x00010000 /* Enable load_extension */
16645#define SQLITE_LoadExtFunc 0x00020000 /* Enable load_extension() SQL func */
16646#define SQLITE_EnableTrigger 0x00040000 /* True to enable triggers */
16647#define SQLITE_DeferFKs 0x00080000 /* Defer all FK constraints */
16648#define SQLITE_QueryOnly 0x00100000 /* Disable database changes */
16649#define SQLITE_CellSizeCk 0x00200000 /* Check btree cell sizes on load */
16650#define SQLITE_Fts3Tokenizer 0x00400000 /* Enable fts3_tokenizer(2) */
16651#define SQLITE_EnableQPSG 0x00800000 /* Query Planner Stability Guarantee*/
16652#define SQLITE_TriggerEQP 0x01000000 /* Show trigger EXPLAIN QUERY PLAN */
16653#define SQLITE_ResetDatabase 0x02000000 /* Reset the database */
16654#define SQLITE_LegacyAlter 0x04000000 /* Legacy ALTER TABLE behaviour */
16655#define SQLITE_NoSchemaError 0x08000000 /* Do not report schema parse errors*/
16656#define SQLITE_Defensive 0x10000000 /* Input SQL is likely hostile */
16657#define SQLITE_DqsDDL 0x20000000 /* dbl-quoted strings allowed in DDL*/
16658#define SQLITE_DqsDML 0x40000000 /* dbl-quoted strings allowed in DML*/
16659#define SQLITE_EnableView 0x80000000 /* Enable the use of views */
16660#define SQLITE_CountRows HI(0x00001) /* Count rows changed by INSERT, */
16661 /* DELETE, or UPDATE and return */
16662 /* the count using a callback. */
16663#define SQLITE_CorruptRdOnly HI(0x00002) /* Prohibit writes due to error */
16664
16665/* Flags used only if debugging */
16666#ifdef SQLITE_DEBUG
16667#define SQLITE_SqlTrace HI(0x0100000) /* Debug print SQL as it executes */
16668#define SQLITE_VdbeListing HI(0x0200000) /* Debug listings of VDBE progs */
16669#define SQLITE_VdbeTrace HI(0x0400000) /* True to trace VDBE execution */
16670#define SQLITE_VdbeAddopTrace HI(0x0800000) /* Trace sqlite3VdbeAddOp() calls */
16671#define SQLITE_VdbeEQP HI(0x1000000) /* Debug EXPLAIN QUERY PLAN */
16672#define SQLITE_ParserTrace HI(0x2000000) /* PRAGMA parser_trace=ON */
16673#endif
16674
16675/*
16676** Allowed values for sqlite3.mDbFlags
16677*/
16678#define DBFLAG_SchemaChange 0x0001 /* Uncommitted Hash table changes */
16679#define DBFLAG_PreferBuiltin 0x0002 /* Preference to built-in funcs */
16680#define DBFLAG_Vacuum 0x0004 /* Currently in a VACUUM */
16681#define DBFLAG_VacuumInto 0x0008 /* Currently running VACUUM INTO */
16682#define DBFLAG_SchemaKnownOk 0x0010 /* Schema is known to be valid */
16683#define DBFLAG_InternalFunc 0x0020 /* Allow use of internal functions */
16684#define DBFLAG_EncodingFixed 0x0040 /* No longer possible to change enc. */
16685
16686/*
16687** Bits of the sqlite3.dbOptFlags field that are used by the
16688** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
16689** selectively disable various optimizations.
16690*/
16691#define SQLITE_QueryFlattener 0x00000001 /* Query flattening */
16692#define SQLITE_WindowFunc 0x00000002 /* Use xInverse for window functions */
16693#define SQLITE_GroupByOrder 0x00000004 /* GROUPBY cover of ORDERBY */
16694#define SQLITE_FactorOutConst 0x00000008 /* Constant factoring */
16695#define SQLITE_DistinctOpt 0x00000010 /* DISTINCT using indexes */
16696#define SQLITE_CoverIdxScan 0x00000020 /* Covering index scans */
16697#define SQLITE_OrderByIdxJoin 0x00000040 /* ORDER BY of joins via index */
16698#define SQLITE_Transitive 0x00000080 /* Transitive constraints */
16699#define SQLITE_OmitNoopJoin 0x00000100 /* Omit unused tables in joins */
16700#define SQLITE_CountOfView 0x00000200 /* The count-of-view optimization */
16701#define SQLITE_CursorHints 0x00000400 /* Add OP_CursorHint opcodes */
16702#define SQLITE_Stat4 0x00000800 /* Use STAT4 data */
16703 /* TH3 expects this value ^^^^^^^^^^ to be 0x0000800. Don't change it */
16704#define SQLITE_PushDown 0x00001000 /* The push-down optimization */
16705#define SQLITE_SimplifyJoin 0x00002000 /* Convert LEFT JOIN to JOIN */
16706#define SQLITE_SkipScan 0x00004000 /* Skip-scans */
16707#define SQLITE_PropagateConst 0x00008000 /* The constant propagation opt */
16708#define SQLITE_MinMaxOpt 0x00010000 /* The min/max optimization */
16709#define SQLITE_SeekScan 0x00020000 /* The OP_SeekScan optimization */
16710#define SQLITE_OmitOrderBy 0x00040000 /* Omit pointless ORDER BY */
16711 /* TH3 expects this value ^^^^^^^^^^ to be 0x40000. Coordinate any change */
16712#define SQLITE_AllOpts 0xffffffff /* All optimizations */
16713
16714/*
16715** Macros for testing whether or not optimizations are enabled or disabled.
16716*/
16717#define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
16718#define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
16719
16720/*
16721** Return true if it OK to factor constant expressions into the initialization
16722** code. The argument is a Parse object for the code generator.
16723*/
16724#define ConstFactorOk(P) ((P)->okConstFactor)
16725
16726/* Possible values for the sqlite3.eOpenState field.
16727** The numbers are randomly selected such that a minimum of three bits must
16728** change to convert any number to another or to zero
16729*/
16730#define SQLITE_STATE_OPEN 0x76 /* Database is open */
16731#define SQLITE_STATE_CLOSED 0xce /* Database is closed */
16732#define SQLITE_STATE_SICK 0xba /* Error and awaiting close */
16733#define SQLITE_STATE_BUSY 0x6d /* Database currently in use */
16734#define SQLITE_STATE_ERROR 0xd5 /* An SQLITE_MISUSE error occurred */
16735#define SQLITE_STATE_ZOMBIE 0xa7 /* Close with last statement close */
16736
16737/*
16738** Each SQL function is defined by an instance of the following
16739** structure. For global built-in functions (ex: substr(), max(), count())
16740** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
16741** For per-connection application-defined functions, a pointer to this
16742** structure is held in the db->aHash hash table.
16743**
16744** The u.pHash field is used by the global built-ins. The u.pDestructor
16745** field is used by per-connection app-def functions.
16746*/
16747struct FuncDef {
16748 i8 nArg; /* Number of arguments. -1 means unlimited */
16749 u32 funcFlags; /* Some combination of SQLITE_FUNC_* */
16750 void *pUserData; /* User data parameter */
16751 FuncDef *pNext; /* Next function with same name */
16752 void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
16753 void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
16754 void (*xValue)(sqlite3_context*); /* Current agg value */
16755 void (*xInverse)(sqlite3_context*,int,sqlite3_value**); /* inverse agg-step */
16756 const char *zName; /* SQL name of the function. */
16757 union {
16758 FuncDef *pHash; /* Next with a different name but the same hash */
16759 FuncDestructor *pDestructor; /* Reference counted destructor function */
16760 } u; /* pHash if SQLITE_FUNC_BUILTIN, pDestructor otherwise */
16761};
16762
16763/*
16764** This structure encapsulates a user-function destructor callback (as
16765** configured using create_function_v2()) and a reference counter. When
16766** create_function_v2() is called to create a function with a destructor,
16767** a single object of this type is allocated. FuncDestructor.nRef is set to
16768** the number of FuncDef objects created (either 1 or 3, depending on whether
16769** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
16770** member of each of the new FuncDef objects is set to point to the allocated
16771** FuncDestructor.
16772**
16773** Thereafter, when one of the FuncDef objects is deleted, the reference
16774** count on this object is decremented. When it reaches 0, the destructor
16775** is invoked and the FuncDestructor structure freed.
16776*/
16777struct FuncDestructor {
16778 int nRef;
16779 void (*xDestroy)(void *);
16780 void *pUserData;
16781};
16782
16783/*
16784** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
16785** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
16786** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
16787** are assert() statements in the code to verify this.
16788**
16789** Value constraints (enforced via assert()):
16790** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
16791** SQLITE_FUNC_ANYORDER == NC_OrderAgg == SF_OrderByReqd
16792** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
16793** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
16794** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
16795** SQLITE_FUNC_DIRECT == SQLITE_DIRECTONLY from the API
16796** SQLITE_FUNC_UNSAFE == SQLITE_INNOCUOUS
16797** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
16798*/
16799#define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
16800#define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
16801#define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
16802#define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
16803#define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
16804#define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
16805#define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
16806#define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
16807/* 0x0200 -- available for reuse */
16808#define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
16809#define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
16810#define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
16811#define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
16812 ** single query - might change over time */
16813#define SQLITE_FUNC_TEST 0x4000 /* Built-in testing functions */
16814#define SQLITE_FUNC_OFFSET 0x8000 /* Built-in sqlite_offset() function */
16815#define SQLITE_FUNC_WINDOW 0x00010000 /* Built-in window-only function */
16816#define SQLITE_FUNC_INTERNAL 0x00040000 /* For use by NestedParse() only */
16817#define SQLITE_FUNC_DIRECT 0x00080000 /* Not for use in TRIGGERs or VIEWs */
16818#define SQLITE_FUNC_SUBTYPE 0x00100000 /* Result likely to have sub-type */
16819#define SQLITE_FUNC_UNSAFE 0x00200000 /* Function has side effects */
16820#define SQLITE_FUNC_INLINE 0x00400000 /* Functions implemented in-line */
16821#define SQLITE_FUNC_BUILTIN 0x00800000 /* This is a built-in function */
16822#define SQLITE_FUNC_ANYORDER 0x08000000 /* count/min/max aggregate */
16823
16824/* Identifier numbers for each in-line function */
16825#define INLINEFUNC_coalesce 0
16826#define INLINEFUNC_implies_nonnull_row 1
16827#define INLINEFUNC_expr_implies_expr 2
16828#define INLINEFUNC_expr_compare 3
16829#define INLINEFUNC_affinity 4
16830#define INLINEFUNC_iif 5
16831#define INLINEFUNC_unlikely 99 /* Default case */
16832
16833/*
16834** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
16835** used to create the initializers for the FuncDef structures.
16836**
16837** FUNCTION(zName, nArg, iArg, bNC, xFunc)
16838** Used to create a scalar function definition of a function zName
16839** implemented by C function xFunc that accepts nArg arguments. The
16840** value passed as iArg is cast to a (void*) and made available
16841** as the user-data (sqlite3_user_data()) for the function. If
16842** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
16843**
16844** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
16845** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
16846**
16847** SFUNCTION(zName, nArg, iArg, bNC, xFunc)
16848** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
16849** adds the SQLITE_DIRECTONLY flag.
16850**
16851** INLINE_FUNC(zName, nArg, iFuncId, mFlags)
16852** zName is the name of a function that is implemented by in-line
16853** byte code rather than by the usual callbacks. The iFuncId
16854** parameter determines the function id. The mFlags parameter is
16855** optional SQLITE_FUNC_ flags for this function.
16856**
16857** TEST_FUNC(zName, nArg, iFuncId, mFlags)
16858** zName is the name of a test-only function implemented by in-line
16859** byte code rather than by the usual callbacks. The iFuncId
16860** parameter determines the function id. The mFlags parameter is
16861** optional SQLITE_FUNC_ flags for this function.
16862**
16863** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
16864** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
16865** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
16866** and functions like sqlite_version() that can change, but not during
16867** a single query. The iArg is ignored. The user-data is always set
16868** to a NULL pointer. The bNC parameter is not used.
16869**
16870** MFUNCTION(zName, nArg, xPtr, xFunc)
16871** For math-library functions. xPtr is an arbitrary pointer.
16872**
16873** PURE_DATE(zName, nArg, iArg, bNC, xFunc)
16874** Used for "pure" date/time functions, this macro is like DFUNCTION
16875** except that it does set the SQLITE_FUNC_CONSTANT flags. iArg is
16876** ignored and the user-data for these functions is set to an
16877** arbitrary non-NULL pointer. The bNC parameter is not used.
16878**
16879** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
16880** Used to create an aggregate function definition implemented by
16881** the C functions xStep and xFinal. The first four parameters
16882** are interpreted in the same way as the first 4 parameters to
16883** FUNCTION().
16884**
16885** WFUNCTION(zName, nArg, iArg, xStep, xFinal, xValue, xInverse)
16886** Used to create an aggregate function definition implemented by
16887** the C functions xStep and xFinal. The first four parameters
16888** are interpreted in the same way as the first 4 parameters to
16889** FUNCTION().
16890**
16891** LIKEFUNC(zName, nArg, pArg, flags)
16892** Used to create a scalar function definition of a function zName
16893** that accepts nArg arguments and is implemented by a call to C
16894** function likeFunc. Argument pArg is cast to a (void *) and made
16895** available as the function user-data (sqlite3_user_data()). The
16896** FuncDef.flags variable is set to the value passed as the flags
16897** parameter.
16898*/
16899#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
16900 {nArg, SQLITE_FUNC_BUILTIN|\
16901 SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
16902 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
16903#define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
16904 {nArg, SQLITE_FUNC_BUILTIN|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
16905 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
16906#define SFUNCTION(zName, nArg, iArg, bNC, xFunc) \
16907 {nArg, SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_DIRECTONLY|SQLITE_FUNC_UNSAFE, \
16908 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
16909#define MFUNCTION(zName, nArg, xPtr, xFunc) \
16910 {nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_CONSTANT|SQLITE_UTF8, \
16911 xPtr, 0, xFunc, 0, 0, 0, #zName, {0} }
16912#define INLINE_FUNC(zName, nArg, iArg, mFlags) \
16913 {nArg, SQLITE_FUNC_BUILTIN|\
16914 SQLITE_UTF8|SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \
16915 SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }
16916#define TEST_FUNC(zName, nArg, iArg, mFlags) \
16917 {nArg, SQLITE_FUNC_BUILTIN|\
16918 SQLITE_UTF8|SQLITE_FUNC_INTERNAL|SQLITE_FUNC_TEST| \
16919 SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \
16920 SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }
16921#define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
16922 {nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
16923 0, 0, xFunc, 0, 0, 0, #zName, {0} }
16924#define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \
16925 {nArg, SQLITE_FUNC_BUILTIN|\
16926 SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
16927 (void*)&sqlite3Config, 0, xFunc, 0, 0, 0, #zName, {0} }
16928#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
16929 {nArg, SQLITE_FUNC_BUILTIN|\
16930 SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
16931 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
16932#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
16933 {nArg, SQLITE_FUNC_BUILTIN|\
16934 SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
16935 pArg, 0, xFunc, 0, 0, 0, #zName, }
16936#define LIKEFUNC(zName, nArg, arg, flags) \
16937 {nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
16938 (void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} }
16939#define WAGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue, xInverse, f) \
16940 {nArg, SQLITE_FUNC_BUILTIN|SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|f, \
16941 SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,xInverse,#zName, {0}}
16942#define INTERNAL_FUNCTION(zName, nArg, xFunc) \
16943 {nArg, SQLITE_FUNC_BUILTIN|\
16944 SQLITE_FUNC_INTERNAL|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
16945 0, 0, xFunc, 0, 0, 0, #zName, {0} }
16946
16947
16948/*
16949** All current savepoints are stored in a linked list starting at
16950** sqlite3.pSavepoint. The first element in the list is the most recently
16951** opened savepoint. Savepoints are added to the list by the vdbe
16952** OP_Savepoint instruction.
16953*/
16954struct Savepoint {
16955 char *zName; /* Savepoint name (nul-terminated) */
16956 i64 nDeferredCons; /* Number of deferred fk violations */
16957 i64 nDeferredImmCons; /* Number of deferred imm fk. */
16958 Savepoint *pNext; /* Parent savepoint (if any) */
16959};
16960
16961/*
16962** The following are used as the second parameter to sqlite3Savepoint(),
16963** and as the P1 argument to the OP_Savepoint instruction.
16964*/
16965#define SAVEPOINT_BEGIN 0
16966#define SAVEPOINT_RELEASE 1
16967#define SAVEPOINT_ROLLBACK 2
16968
16969
16970/*
16971** Each SQLite module (virtual table definition) is defined by an
16972** instance of the following structure, stored in the sqlite3.aModule
16973** hash table.
16974*/
16975struct Module {
16976 const sqlite3_module *pModule; /* Callback pointers */
16977 const char *zName; /* Name passed to create_module() */
16978 int nRefModule; /* Number of pointers to this object */
16979 void *pAux; /* pAux passed to create_module() */
16980 void (*xDestroy)(void *); /* Module destructor function */
16981 Table *pEpoTab; /* Eponymous table for this module */
16982};
16983
16984/*
16985** Information about each column of an SQL table is held in an instance
16986** of the Column structure, in the Table.aCol[] array.
16987**
16988** Definitions:
16989**
16990** "table column index" This is the index of the column in the
16991** Table.aCol[] array, and also the index of
16992** the column in the original CREATE TABLE stmt.
16993**
16994** "storage column index" This is the index of the column in the
16995** record BLOB generated by the OP_MakeRecord
16996** opcode. The storage column index is less than
16997** or equal to the table column index. It is
16998** equal if and only if there are no VIRTUAL
16999** columns to the left.
17000**
17001** Notes on zCnName:
17002** The zCnName field stores the name of the column, the datatype of the
17003** column, and the collating sequence for the column, in that order, all in
17004** a single allocation. Each string is 0x00 terminated. The datatype
17005** is only included if the COLFLAG_HASTYPE bit of colFlags is set and the
17006** collating sequence name is only included if the COLFLAG_HASCOLL bit is
17007** set.
17008*/
17009struct Column {
17010 char *zCnName; /* Name of this column */
17011 unsigned notNull :4; /* An OE_ code for handling a NOT NULL constraint */
17012 unsigned eCType :4; /* One of the standard types */
17013 char affinity; /* One of the SQLITE_AFF_... values */
17014 u8 szEst; /* Est size of value in this column. sizeof(INT)==1 */
17015 u8 hName; /* Column name hash for faster lookup */
17016 u16 iDflt; /* 1-based index of DEFAULT. 0 means "none" */
17017 u16 colFlags; /* Boolean properties. See COLFLAG_ defines below */
17018};
17019
17020/* Allowed values for Column.eCType.
17021**
17022** Values must match entries in the global constant arrays
17023** sqlite3StdTypeLen[] and sqlite3StdType[]. Each value is one more
17024** than the offset into these arrays for the corresponding name.
17025** Adjust the SQLITE_N_STDTYPE value if adding or removing entries.
17026*/
17027#define COLTYPE_CUSTOM 0 /* Type appended to zName */
17028#define COLTYPE_ANY 1
17029#define COLTYPE_BLOB 2
17030#define COLTYPE_INT 3
17031#define COLTYPE_INTEGER 4
17032#define COLTYPE_REAL 5
17033#define COLTYPE_TEXT 6
17034#define SQLITE_N_STDTYPE 6 /* Number of standard types */
17035
17036/* Allowed values for Column.colFlags.
17037**
17038** Constraints:
17039** TF_HasVirtual == COLFLAG_VIRTUAL
17040** TF_HasStored == COLFLAG_STORED
17041** TF_HasHidden == COLFLAG_HIDDEN
17042*/
17043#define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
17044#define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
17045#define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */
17046#define COLFLAG_UNIQUE 0x0008 /* Column def contains "UNIQUE" or "PK" */
17047#define COLFLAG_SORTERREF 0x0010 /* Use sorter-refs with this column */
17048#define COLFLAG_VIRTUAL 0x0020 /* GENERATED ALWAYS AS ... VIRTUAL */
17049#define COLFLAG_STORED 0x0040 /* GENERATED ALWAYS AS ... STORED */
17050#define COLFLAG_NOTAVAIL 0x0080 /* STORED column not yet calculated */
17051#define COLFLAG_BUSY 0x0100 /* Blocks recursion on GENERATED columns */
17052#define COLFLAG_HASCOLL 0x0200 /* Has collating sequence name in zCnName */
17053#define COLFLAG_GENERATED 0x0060 /* Combo: _STORED, _VIRTUAL */
17054#define COLFLAG_NOINSERT 0x0062 /* Combo: _HIDDEN, _STORED, _VIRTUAL */
17055
17056/*
17057** A "Collating Sequence" is defined by an instance of the following
17058** structure. Conceptually, a collating sequence consists of a name and
17059** a comparison routine that defines the order of that sequence.
17060**
17061** If CollSeq.xCmp is NULL, it means that the
17062** collating sequence is undefined. Indices built on an undefined
17063** collating sequence may not be read or written.
17064*/
17065struct CollSeq {
17066 char *zName; /* Name of the collating sequence, UTF-8 encoded */
17067 u8 enc; /* Text encoding handled by xCmp() */
17068 void *pUser; /* First argument to xCmp() */
17069 int (*xCmp)(void*,int, const void*, int, const void*);
17070 void (*xDel)(void*); /* Destructor for pUser */
17071};
17072
17073/*
17074** A sort order can be either ASC or DESC.
17075*/
17076#define SQLITE_SO_ASC 0 /* Sort in ascending order */
17077#define SQLITE_SO_DESC 1 /* Sort in ascending order */
17078#define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
17079
17080/*
17081** Column affinity types.
17082**
17083** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
17084** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
17085** the speed a little by numbering the values consecutively.
17086**
17087** But rather than start with 0 or 1, we begin with 'A'. That way,
17088** when multiple affinity types are concatenated into a string and
17089** used as the P4 operand, they will be more readable.
17090**
17091** Note also that the numeric types are grouped together so that testing
17092** for a numeric type is a single comparison. And the BLOB type is first.
17093*/
17094#define SQLITE_AFF_NONE 0x40 /* '@' */
17095#define SQLITE_AFF_BLOB 0x41 /* 'A' */
17096#define SQLITE_AFF_TEXT 0x42 /* 'B' */
17097#define SQLITE_AFF_NUMERIC 0x43 /* 'C' */
17098#define SQLITE_AFF_INTEGER 0x44 /* 'D' */
17099#define SQLITE_AFF_REAL 0x45 /* 'E' */
17100
17101#define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
17102
17103/*
17104** The SQLITE_AFF_MASK values masks off the significant bits of an
17105** affinity value.
17106*/
17107#define SQLITE_AFF_MASK 0x47
17108
17109/*
17110** Additional bit values that can be ORed with an affinity without
17111** changing the affinity.
17112**
17113** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
17114** It causes an assert() to fire if either operand to a comparison
17115** operator is NULL. It is added to certain comparison operators to
17116** prove that the operands are always NOT NULL.
17117*/
17118#define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
17119#define SQLITE_NULLEQ 0x80 /* NULL=NULL */
17120#define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
17121
17122/*
17123** An object of this type is created for each virtual table present in
17124** the database schema.
17125**
17126** If the database schema is shared, then there is one instance of this
17127** structure for each database connection (sqlite3*) that uses the shared
17128** schema. This is because each database connection requires its own unique
17129** instance of the sqlite3_vtab* handle used to access the virtual table
17130** implementation. sqlite3_vtab* handles can not be shared between
17131** database connections, even when the rest of the in-memory database
17132** schema is shared, as the implementation often stores the database
17133** connection handle passed to it via the xConnect() or xCreate() method
17134** during initialization internally. This database connection handle may
17135** then be used by the virtual table implementation to access real tables
17136** within the database. So that they appear as part of the callers
17137** transaction, these accesses need to be made via the same database
17138** connection as that used to execute SQL operations on the virtual table.
17139**
17140** All VTable objects that correspond to a single table in a shared
17141** database schema are initially stored in a linked-list pointed to by
17142** the Table.pVTable member variable of the corresponding Table object.
17143** When an sqlite3_prepare() operation is required to access the virtual
17144** table, it searches the list for the VTable that corresponds to the
17145** database connection doing the preparing so as to use the correct
17146** sqlite3_vtab* handle in the compiled query.
17147**
17148** When an in-memory Table object is deleted (for example when the
17149** schema is being reloaded for some reason), the VTable objects are not
17150** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
17151** immediately. Instead, they are moved from the Table.pVTable list to
17152** another linked list headed by the sqlite3.pDisconnect member of the
17153** corresponding sqlite3 structure. They are then deleted/xDisconnected
17154** next time a statement is prepared using said sqlite3*. This is done
17155** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
17156** Refer to comments above function sqlite3VtabUnlockList() for an
17157** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
17158** list without holding the corresponding sqlite3.mutex mutex.
17159**
17160** The memory for objects of this type is always allocated by
17161** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
17162** the first argument.
17163*/
17164struct VTable {
17165 sqlite3 *db; /* Database connection associated with this table */
17166 Module *pMod; /* Pointer to module implementation */
17167 sqlite3_vtab *pVtab; /* Pointer to vtab instance */
17168 int nRef; /* Number of pointers to this structure */
17169 u8 bConstraint; /* True if constraints are supported */
17170 u8 eVtabRisk; /* Riskiness of allowing hacker access */
17171 int iSavepoint; /* Depth of the SAVEPOINT stack */
17172 VTable *pNext; /* Next in linked list (see above) */
17173};
17174
17175/* Allowed values for VTable.eVtabRisk
17176*/
17177#define SQLITE_VTABRISK_Low 0
17178#define SQLITE_VTABRISK_Normal 1
17179#define SQLITE_VTABRISK_High 2
17180
17181/*
17182** The schema for each SQL table, virtual table, and view is represented
17183** in memory by an instance of the following structure.
17184*/
17185struct Table {
17186 char *zName; /* Name of the table or view */
17187 Column *aCol; /* Information about each column */
17188 Index *pIndex; /* List of SQL indexes on this table. */
17189 char *zColAff; /* String defining the affinity of each column */
17190 ExprList *pCheck; /* All CHECK constraints */
17191 /* ... also used as column name list in a VIEW */
17192 Pgno tnum; /* Root BTree page for this table */
17193 u32 nTabRef; /* Number of pointers to this Table */
17194 u32 tabFlags; /* Mask of TF_* values */
17195 i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
17196 i16 nCol; /* Number of columns in this table */
17197 i16 nNVCol; /* Number of columns that are not VIRTUAL */
17198 LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
17199 LogEst szTabRow; /* Estimated size of each table row in bytes */
17200#ifdef SQLITE_ENABLE_COSTMULT
17201 LogEst costMult; /* Cost multiplier for using this table */
17202#endif
17203 u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
17204 u8 eTabType; /* 0: normal, 1: virtual, 2: view */
17205 union {
17206 struct { /* Used by ordinary tables: */
17207 int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
17208 FKey *pFKey; /* Linked list of all foreign keys in this table */
17209 ExprList *pDfltList; /* DEFAULT clauses on various columns.
17210 ** Or the AS clause for generated columns. */
17211 } tab;
17212 struct { /* Used by views: */
17213 Select *pSelect; /* View definition */
17214 } view;
17215 struct { /* Used by virtual tables only: */
17216 int nArg; /* Number of arguments to the module */
17217 char **azArg; /* 0: module 1: schema 2: vtab name 3...: args */
17218 VTable *p; /* List of VTable objects. */
17219 } vtab;
17220 } u;
17221 Trigger *pTrigger; /* List of triggers on this object */
17222 Schema *pSchema; /* Schema that contains this table */
17223};
17224
17225/*
17226** Allowed values for Table.tabFlags.
17227**
17228** TF_OOOHidden applies to tables or view that have hidden columns that are
17229** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
17230** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
17231** the TF_OOOHidden attribute would apply in this case. Such tables require
17232** special handling during INSERT processing. The "OOO" means "Out Of Order".
17233**
17234** Constraints:
17235**
17236** TF_HasVirtual == COLFLAG_VIRTUAL
17237** TF_HasStored == COLFLAG_STORED
17238** TF_HasHidden == COLFLAG_HIDDEN
17239*/
17240#define TF_Readonly 0x00000001 /* Read-only system table */
17241#define TF_HasHidden 0x00000002 /* Has one or more hidden columns */
17242#define TF_HasPrimaryKey 0x00000004 /* Table has a primary key */
17243#define TF_Autoincrement 0x00000008 /* Integer primary key is autoincrement */
17244#define TF_HasStat1 0x00000010 /* nRowLogEst set from sqlite_stat1 */
17245#define TF_HasVirtual 0x00000020 /* Has one or more VIRTUAL columns */
17246#define TF_HasStored 0x00000040 /* Has one or more STORED columns */
17247#define TF_HasGenerated 0x00000060 /* Combo: HasVirtual + HasStored */
17248#define TF_WithoutRowid 0x00000080 /* No rowid. PRIMARY KEY is the key */
17249#define TF_StatsUsed 0x00000100 /* Query planner decisions affected by
17250 ** Index.aiRowLogEst[] values */
17251#define TF_NoVisibleRowid 0x00000200 /* No user-visible "rowid" column */
17252#define TF_OOOHidden 0x00000400 /* Out-of-Order hidden columns */
17253#define TF_HasNotNull 0x00000800 /* Contains NOT NULL constraints */
17254#define TF_Shadow 0x00001000 /* True for a shadow table */
17255#define TF_HasStat4 0x00002000 /* STAT4 info available for this table */
17256#define TF_Ephemeral 0x00004000 /* An ephemeral table */
17257#define TF_Eponymous 0x00008000 /* An eponymous virtual table */
17258#define TF_Strict 0x00010000 /* STRICT mode */
17259
17260/*
17261** Allowed values for Table.eTabType
17262*/
17263#define TABTYP_NORM 0 /* Ordinary table */
17264#define TABTYP_VTAB 1 /* Virtual table */
17265#define TABTYP_VIEW 2 /* A view */
17266
17267#define IsView(X) ((X)->eTabType==TABTYP_VIEW)
17268#define IsOrdinaryTable(X) ((X)->eTabType==TABTYP_NORM)
17269
17270/*
17271** Test to see whether or not a table is a virtual table. This is
17272** done as a macro so that it will be optimized out when virtual
17273** table support is omitted from the build.
17274*/
17275#ifndef SQLITE_OMIT_VIRTUALTABLE
17276# define IsVirtual(X) ((X)->eTabType==TABTYP_VTAB)
17277# define ExprIsVtab(X) \
17278 ((X)->op==TK_COLUMN && (X)->y.pTab!=0 && (X)->y.pTab->eTabType==TABTYP_VTAB)
17279#else
17280# define IsVirtual(X) 0
17281# define ExprIsVtab(X) 0
17282#endif
17283
17284/*
17285** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
17286** only works for non-virtual tables (ordinary tables and views) and is
17287** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
17288** IsHiddenColumn() macro is general purpose.
17289*/
17290#if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
17291# define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
17292# define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
17293#elif !defined(SQLITE_OMIT_VIRTUALTABLE)
17294# define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
17295# define IsOrdinaryHiddenColumn(X) 0
17296#else
17297# define IsHiddenColumn(X) 0
17298# define IsOrdinaryHiddenColumn(X) 0
17299#endif
17300
17301
17302/* Does the table have a rowid */
17303#define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
17304#define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
17305
17306/*
17307** Each foreign key constraint is an instance of the following structure.
17308**
17309** A foreign key is associated with two tables. The "from" table is
17310** the table that contains the REFERENCES clause that creates the foreign
17311** key. The "to" table is the table that is named in the REFERENCES clause.
17312** Consider this example:
17313**
17314** CREATE TABLE ex1(
17315** a INTEGER PRIMARY KEY,
17316** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
17317** );
17318**
17319** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
17320** Equivalent names:
17321**
17322** from-table == child-table
17323** to-table == parent-table
17324**
17325** Each REFERENCES clause generates an instance of the following structure
17326** which is attached to the from-table. The to-table need not exist when
17327** the from-table is created. The existence of the to-table is not checked.
17328**
17329** The list of all parents for child Table X is held at X.pFKey.
17330**
17331** A list of all children for a table named Z (which might not even exist)
17332** is held in Schema.fkeyHash with a hash key of Z.
17333*/
17334struct FKey {
17335 Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
17336 FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
17337 char *zTo; /* Name of table that the key points to (aka: Parent) */
17338 FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
17339 FKey *pPrevTo; /* Previous with the same zTo */
17340 int nCol; /* Number of columns in this key */
17341 /* EV: R-30323-21917 */
17342 u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
17343 u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
17344 Trigger *apTrigger[2];/* Triggers for aAction[] actions */
17345 struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
17346 int iFrom; /* Index of column in pFrom */
17347 char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
17348 } aCol[1]; /* One entry for each of nCol columns */
17349};
17350
17351/*
17352** SQLite supports many different ways to resolve a constraint
17353** error. ROLLBACK processing means that a constraint violation
17354** causes the operation in process to fail and for the current transaction
17355** to be rolled back. ABORT processing means the operation in process
17356** fails and any prior changes from that one operation are backed out,
17357** but the transaction is not rolled back. FAIL processing means that
17358** the operation in progress stops and returns an error code. But prior
17359** changes due to the same operation are not backed out and no rollback
17360** occurs. IGNORE means that the particular row that caused the constraint
17361** error is not inserted or updated. Processing continues and no error
17362** is returned. REPLACE means that preexisting database rows that caused
17363** a UNIQUE constraint violation are removed so that the new insert or
17364** update can proceed. Processing continues and no error is reported.
17365** UPDATE applies to insert operations only and means that the insert
17366** is omitted and the DO UPDATE clause of an upsert is run instead.
17367**
17368** RESTRICT, SETNULL, SETDFLT, and CASCADE actions apply only to foreign keys.
17369** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
17370** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
17371** key is set to NULL. SETDFLT means that the foreign key is set
17372** to its default value. CASCADE means that a DELETE or UPDATE of the
17373** referenced table row is propagated into the row that holds the
17374** foreign key.
17375**
17376** The OE_Default value is a place holder that means to use whatever
17377** conflict resolution algorthm is required from context.
17378**
17379** The following symbolic values are used to record which type
17380** of conflict resolution action to take.
17381*/
17382#define OE_None 0 /* There is no constraint to check */
17383#define OE_Rollback 1 /* Fail the operation and rollback the transaction */
17384#define OE_Abort 2 /* Back out changes but do no rollback transaction */
17385#define OE_Fail 3 /* Stop the operation but leave all prior changes */
17386#define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
17387#define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
17388#define OE_Update 6 /* Process as a DO UPDATE in an upsert */
17389#define OE_Restrict 7 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
17390#define OE_SetNull 8 /* Set the foreign key value to NULL */
17391#define OE_SetDflt 9 /* Set the foreign key value to its default */
17392#define OE_Cascade 10 /* Cascade the changes */
17393#define OE_Default 11 /* Do whatever the default action is */
17394
17395
17396/*
17397** An instance of the following structure is passed as the first
17398** argument to sqlite3VdbeKeyCompare and is used to control the
17399** comparison of the two index keys.
17400**
17401** Note that aSortOrder[] and aColl[] have nField+1 slots. There
17402** are nField slots for the columns of an index then one extra slot
17403** for the rowid at the end.
17404*/
17405struct KeyInfo {
17406 u32 nRef; /* Number of references to this KeyInfo object */
17407 u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
17408 u16 nKeyField; /* Number of key columns in the index */
17409 u16 nAllField; /* Total columns, including key plus others */
17410 sqlite3 *db; /* The database connection */
17411 u8 *aSortFlags; /* Sort order for each column. */
17412 CollSeq *aColl[1]; /* Collating sequence for each term of the key */
17413};
17414
17415/*
17416** Allowed bit values for entries in the KeyInfo.aSortFlags[] array.
17417*/
17418#define KEYINFO_ORDER_DESC 0x01 /* DESC sort order */
17419#define KEYINFO_ORDER_BIGNULL 0x02 /* NULL is larger than any other value */
17420
17421/*
17422** This object holds a record which has been parsed out into individual
17423** fields, for the purposes of doing a comparison.
17424**
17425** A record is an object that contains one or more fields of data.
17426** Records are used to store the content of a table row and to store
17427** the key of an index. A blob encoding of a record is created by
17428** the OP_MakeRecord opcode of the VDBE and is disassembled by the
17429** OP_Column opcode.
17430**
17431** An instance of this object serves as a "key" for doing a search on
17432** an index b+tree. The goal of the search is to find the entry that
17433** is closed to the key described by this object. This object might hold
17434** just a prefix of the key. The number of fields is given by
17435** pKeyInfo->nField.
17436**
17437** The r1 and r2 fields are the values to return if this key is less than
17438** or greater than a key in the btree, respectively. These are normally
17439** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
17440** is in DESC order.
17441**
17442** The key comparison functions actually return default_rc when they find
17443** an equals comparison. default_rc can be -1, 0, or +1. If there are
17444** multiple entries in the b-tree with the same key (when only looking
17445** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
17446** cause the search to find the last match, or +1 to cause the search to
17447** find the first match.
17448**
17449** The key comparison functions will set eqSeen to true if they ever
17450** get and equal results when comparing this structure to a b-tree record.
17451** When default_rc!=0, the search might end up on the record immediately
17452** before the first match or immediately after the last match. The
17453** eqSeen field will indicate whether or not an exact match exists in the
17454** b-tree.
17455*/
17456struct UnpackedRecord {
17457 KeyInfo *pKeyInfo; /* Collation and sort-order information */
17458 Mem *aMem; /* Values */
17459 u16 nField; /* Number of entries in apMem[] */
17460 i8 default_rc; /* Comparison result if keys are equal */
17461 u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
17462 i8 r1; /* Value to return if (lhs < rhs) */
17463 i8 r2; /* Value to return if (lhs > rhs) */
17464 u8 eqSeen; /* True if an equality comparison has been seen */
17465};
17466
17467
17468/*
17469** Each SQL index is represented in memory by an
17470** instance of the following structure.
17471**
17472** The columns of the table that are to be indexed are described
17473** by the aiColumn[] field of this structure. For example, suppose
17474** we have the following table and index:
17475**
17476** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
17477** CREATE INDEX Ex2 ON Ex1(c3,c1);
17478**
17479** In the Table structure describing Ex1, nCol==3 because there are
17480** three columns in the table. In the Index structure describing
17481** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
17482** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
17483** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
17484** The second column to be indexed (c1) has an index of 0 in
17485** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
17486**
17487** The Index.onError field determines whether or not the indexed columns
17488** must be unique and what to do if they are not. When Index.onError=OE_None,
17489** it means this is not a unique index. Otherwise it is a unique index
17490** and the value of Index.onError indicate the which conflict resolution
17491** algorithm to employ whenever an attempt is made to insert a non-unique
17492** element.
17493**
17494** While parsing a CREATE TABLE or CREATE INDEX statement in order to
17495** generate VDBE code (as opposed to parsing one read from an sqlite_schema
17496** table as part of parsing an existing database schema), transient instances
17497** of this structure may be created. In this case the Index.tnum variable is
17498** used to store the address of a VDBE instruction, not a database page
17499** number (it cannot - the database page is not allocated until the VDBE
17500** program is executed). See convertToWithoutRowidTable() for details.
17501*/
17502struct Index {
17503 char *zName; /* Name of this index */
17504 i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
17505 LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
17506 Table *pTable; /* The SQL table being indexed */
17507 char *zColAff; /* String defining the affinity of each column */
17508 Index *pNext; /* The next index associated with the same table */
17509 Schema *pSchema; /* Schema containing this index */
17510 u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
17511 const char **azColl; /* Array of collation sequence names for index */
17512 Expr *pPartIdxWhere; /* WHERE clause for partial indices */
17513 ExprList *aColExpr; /* Column expressions */
17514 Pgno tnum; /* DB Page containing root of this index */
17515 LogEst szIdxRow; /* Estimated average row size in bytes */
17516 u16 nKeyCol; /* Number of columns forming the key */
17517 u16 nColumn; /* Number of columns stored in the index */
17518 u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
17519 unsigned idxType:2; /* 0:Normal 1:UNIQUE, 2:PRIMARY KEY, 3:IPK */
17520 unsigned bUnordered:1; /* Use this index for == or IN queries only */
17521 unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
17522 unsigned isResized:1; /* True if resizeIndexObject() has been called */
17523 unsigned isCovering:1; /* True if this is a covering index */
17524 unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
17525 unsigned hasStat1:1; /* aiRowLogEst values come from sqlite_stat1 */
17526 unsigned bNoQuery:1; /* Do not use this index to optimize queries */
17527 unsigned bAscKeyBug:1; /* True if the bba7b69f9849b5bf bug applies */
17528 unsigned bHasVCol:1; /* Index references one or more VIRTUAL columns */
17529#ifdef SQLITE_ENABLE_STAT4
17530 int nSample; /* Number of elements in aSample[] */
17531 int nSampleCol; /* Size of IndexSample.anEq[] and so on */
17532 tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
17533 IndexSample *aSample; /* Samples of the left-most key */
17534 tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
17535 tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
17536#endif
17537 Bitmask colNotIdxed; /* 0 for unindexed columns in pTab */
17538};
17539
17540/*
17541** Allowed values for Index.idxType
17542*/
17543#define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
17544#define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
17545#define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
17546#define SQLITE_IDXTYPE_IPK 3 /* INTEGER PRIMARY KEY index */
17547
17548/* Return true if index X is a PRIMARY KEY index */
17549#define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
17550
17551/* Return true if index X is a UNIQUE index */
17552#define IsUniqueIndex(X) ((X)->onError!=OE_None)
17553
17554/* The Index.aiColumn[] values are normally positive integer. But
17555** there are some negative values that have special meaning:
17556*/
17557#define XN_ROWID (-1) /* Indexed column is the rowid */
17558#define XN_EXPR (-2) /* Indexed column is an expression */
17559
17560/*
17561** Each sample stored in the sqlite_stat4 table is represented in memory
17562** using a structure of this type. See documentation at the top of the
17563** analyze.c source file for additional information.
17564*/
17565struct IndexSample {
17566 void *p; /* Pointer to sampled record */
17567 int n; /* Size of record in bytes */
17568 tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
17569 tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
17570 tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
17571};
17572
17573/*
17574** Possible values to use within the flags argument to sqlite3GetToken().
17575*/
17576#define SQLITE_TOKEN_QUOTED 0x1 /* Token is a quoted identifier. */
17577#define SQLITE_TOKEN_KEYWORD 0x2 /* Token is a keyword. */
17578
17579/*
17580** Each token coming out of the lexer is an instance of
17581** this structure. Tokens are also used as part of an expression.
17582**
17583** The memory that "z" points to is owned by other objects. Take care
17584** that the owner of the "z" string does not deallocate the string before
17585** the Token goes out of scope! Very often, the "z" points to some place
17586** in the middle of the Parse.zSql text. But it might also point to a
17587** static string.
17588*/
17589struct Token {
17590 const char *z; /* Text of the token. Not NULL-terminated! */
17591 unsigned int n; /* Number of characters in this token */
17592};
17593
17594/*
17595** An instance of this structure contains information needed to generate
17596** code for a SELECT that contains aggregate functions.
17597**
17598** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
17599** pointer to this structure. The Expr.iAgg field is the index in
17600** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
17601** code for that node.
17602**
17603** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
17604** original Select structure that describes the SELECT statement. These
17605** fields do not need to be freed when deallocating the AggInfo structure.
17606*/
17607struct AggInfo {
17608 u8 directMode; /* Direct rendering mode means take data directly
17609 ** from source tables rather than from accumulators */
17610 u8 useSortingIdx; /* In direct mode, reference the sorting index rather
17611 ** than the source table */
17612 int sortingIdx; /* Cursor number of the sorting index */
17613 int sortingIdxPTab; /* Cursor number of pseudo-table */
17614 int nSortingColumn; /* Number of columns in the sorting index */
17615 int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
17616 ExprList *pGroupBy; /* The group by clause */
17617 struct AggInfo_col { /* For each column used in source tables */
17618 Table *pTab; /* Source table */
17619 Expr *pCExpr; /* The original expression */
17620 int iTable; /* Cursor number of the source table */
17621 int iMem; /* Memory location that acts as accumulator */
17622 i16 iColumn; /* Column number within the source table */
17623 i16 iSorterColumn; /* Column number in the sorting index */
17624 } *aCol;
17625 int nColumn; /* Number of used entries in aCol[] */
17626 int nAccumulator; /* Number of columns that show through to the output.
17627 ** Additional columns are used only as parameters to
17628 ** aggregate functions */
17629 struct AggInfo_func { /* For each aggregate function */
17630 Expr *pFExpr; /* Expression encoding the function */
17631 FuncDef *pFunc; /* The aggregate function implementation */
17632 int iMem; /* Memory location that acts as accumulator */
17633 int iDistinct; /* Ephemeral table used to enforce DISTINCT */
17634 int iDistAddr; /* Address of OP_OpenEphemeral */
17635 } *aFunc;
17636 int nFunc; /* Number of entries in aFunc[] */
17637 u32 selId; /* Select to which this AggInfo belongs */
17638};
17639
17640/*
17641** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
17642** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
17643** than 32767 we have to make it 32-bit. 16-bit is preferred because
17644** it uses less memory in the Expr object, which is a big memory user
17645** in systems with lots of prepared statements. And few applications
17646** need more than about 10 or 20 variables. But some extreme users want
17647** to have prepared statements with over 32766 variables, and for them
17648** the option is available (at compile-time).
17649*/
17650#if SQLITE_MAX_VARIABLE_NUMBER<32767
17651typedef i16 ynVar;
17652#else
17653typedef int ynVar;
17654#endif
17655
17656/*
17657** Each node of an expression in the parse tree is an instance
17658** of this structure.
17659**
17660** Expr.op is the opcode. The integer parser token codes are reused
17661** as opcodes here. For example, the parser defines TK_GE to be an integer
17662** code representing the ">=" operator. This same integer code is reused
17663** to represent the greater-than-or-equal-to operator in the expression
17664** tree.
17665**
17666** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
17667** or TK_STRING), then Expr.u.zToken contains the text of the SQL literal. If
17668** the expression is a variable (TK_VARIABLE), then Expr.u.zToken contains the
17669** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
17670** then Expr.u.zToken contains the name of the function.
17671**
17672** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
17673** binary operator. Either or both may be NULL.
17674**
17675** Expr.x.pList is a list of arguments if the expression is an SQL function,
17676** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
17677** Expr.x.pSelect is used if the expression is a sub-select or an expression of
17678** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
17679** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
17680** valid.
17681**
17682** An expression of the form ID or ID.ID refers to a column in a table.
17683** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
17684** the integer cursor number of a VDBE cursor pointing to that table and
17685** Expr.iColumn is the column number for the specific column. If the
17686** expression is used as a result in an aggregate SELECT, then the
17687** value is also stored in the Expr.iAgg column in the aggregate so that
17688** it can be accessed after all aggregates are computed.
17689**
17690** If the expression is an unbound variable marker (a question mark
17691** character '?' in the original SQL) then the Expr.iTable holds the index
17692** number for that variable.
17693**
17694** If the expression is a subquery then Expr.iColumn holds an integer
17695** register number containing the result of the subquery. If the
17696** subquery gives a constant result, then iTable is -1. If the subquery
17697** gives a different answer at different times during statement processing
17698** then iTable is the address of a subroutine that computes the subquery.
17699**
17700** If the Expr is of type OP_Column, and the table it is selecting from
17701** is a disk table or the "old.*" pseudo-table, then pTab points to the
17702** corresponding table definition.
17703**
17704** ALLOCATION NOTES:
17705**
17706** Expr objects can use a lot of memory space in database schema. To
17707** help reduce memory requirements, sometimes an Expr object will be
17708** truncated. And to reduce the number of memory allocations, sometimes
17709** two or more Expr objects will be stored in a single memory allocation,
17710** together with Expr.u.zToken strings.
17711**
17712** If the EP_Reduced and EP_TokenOnly flags are set when
17713** an Expr object is truncated. When EP_Reduced is set, then all
17714** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
17715** are contained within the same memory allocation. Note, however, that
17716** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
17717** allocated, regardless of whether or not EP_Reduced is set.
17718*/
17719struct Expr {
17720 u8 op; /* Operation performed by this node */
17721 char affExpr; /* affinity, or RAISE type */
17722 u8 op2; /* TK_REGISTER/TK_TRUTH: original value of Expr.op
17723 ** TK_COLUMN: the value of p5 for OP_Column
17724 ** TK_AGG_FUNCTION: nesting depth
17725 ** TK_FUNCTION: NC_SelfRef flag if needs OP_PureFunc */
17726#ifdef SQLITE_DEBUG
17727 u8 vvaFlags; /* Verification flags. */
17728#endif
17729 u32 flags; /* Various flags. EP_* See below */
17730 union {
17731 char *zToken; /* Token value. Zero terminated and dequoted */
17732 int iValue; /* Non-negative integer value if EP_IntValue */
17733 } u;
17734
17735 /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
17736 ** space is allocated for the fields below this point. An attempt to
17737 ** access them will result in a segfault or malfunction.
17738 *********************************************************************/
17739
17740 Expr *pLeft; /* Left subnode */
17741 Expr *pRight; /* Right subnode */
17742 union {
17743 ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
17744 Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
17745 } x;
17746
17747 /* If the EP_Reduced flag is set in the Expr.flags mask, then no
17748 ** space is allocated for the fields below this point. An attempt to
17749 ** access them will result in a segfault or malfunction.
17750 *********************************************************************/
17751
17752#if SQLITE_MAX_EXPR_DEPTH>0
17753 int nHeight; /* Height of the tree headed by this node */
17754#endif
17755 int iTable; /* TK_COLUMN: cursor number of table holding column
17756 ** TK_REGISTER: register number
17757 ** TK_TRIGGER: 1 -> new, 0 -> old
17758 ** EP_Unlikely: 134217728 times likelihood
17759 ** TK_IN: ephemerial table holding RHS
17760 ** TK_SELECT_COLUMN: Number of columns on the LHS
17761 ** TK_SELECT: 1st register of result vector */
17762 ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
17763 ** TK_VARIABLE: variable number (always >= 1).
17764 ** TK_SELECT_COLUMN: column of the result vector */
17765 i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
17766 int iRightJoinTable; /* If EP_FromJoin, the right table of the join */
17767 AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
17768 union {
17769 Table *pTab; /* TK_COLUMN: Table containing column. Can be NULL
17770 ** for a column of an index on an expression */
17771 Window *pWin; /* EP_WinFunc: Window/Filter defn for a function */
17772 struct { /* TK_IN, TK_SELECT, and TK_EXISTS */
17773 int iAddr; /* Subroutine entry address */
17774 int regReturn; /* Register used to hold return address */
17775 } sub;
17776 } y;
17777};
17778
17779/* The following are the meanings of bits in the Expr.flags field.
17780** Value restrictions:
17781**
17782** EP_Agg == NC_HasAgg == SF_HasAgg
17783** EP_Win == NC_HasWin
17784*/
17785#define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
17786#define EP_Distinct 0x000002 /* Aggregate function with DISTINCT keyword */
17787#define EP_HasFunc 0x000004 /* Contains one or more functions of any kind */
17788#define EP_FixedCol 0x000008 /* TK_Column with a known fixed value */
17789#define EP_Agg 0x000010 /* Contains one or more aggregate functions */
17790#define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
17791#define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
17792#define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
17793#define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
17794#define EP_Commuted 0x000200 /* Comparison operator has been commuted */
17795#define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
17796#define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
17797#define EP_Skip 0x001000 /* Operator does not contribute to affinity */
17798#define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
17799#define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
17800#define EP_Win 0x008000 /* Contains window functions */
17801#define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
17802#define EP_IfNullRow 0x020000 /* The TK_IF_NULL_ROW opcode */
17803#define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
17804#define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
17805#define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
17806#define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
17807 /* 0x400000 // Available */
17808#define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
17809#define EP_WinFunc 0x1000000 /* TK_FUNCTION with Expr.y.pWin set */
17810#define EP_Subrtn 0x2000000 /* Uses Expr.y.sub. TK_IN, _SELECT, or _EXISTS */
17811#define EP_Quoted 0x4000000 /* TK_ID was originally quoted */
17812#define EP_Static 0x8000000 /* Held in memory not obtained from malloc() */
17813#define EP_IsTrue 0x10000000 /* Always has boolean value of TRUE */
17814#define EP_IsFalse 0x20000000 /* Always has boolean value of FALSE */
17815#define EP_FromDDL 0x40000000 /* Originates from sqlite_schema */
17816 /* 0x80000000 // Available */
17817
17818/* The EP_Propagate mask is a set of properties that automatically propagate
17819** upwards into parent nodes.
17820*/
17821#define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc)
17822
17823/* Macros can be used to test, set, or clear bits in the
17824** Expr.flags field.
17825*/
17826#define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
17827#define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
17828#define ExprSetProperty(E,P) (E)->flags|=(P)
17829#define ExprClearProperty(E,P) (E)->flags&=~(P)
17830#define ExprAlwaysTrue(E) (((E)->flags&(EP_FromJoin|EP_IsTrue))==EP_IsTrue)
17831#define ExprAlwaysFalse(E) (((E)->flags&(EP_FromJoin|EP_IsFalse))==EP_IsFalse)
17832
17833/* Macros used to ensure that the correct members of unions are accessed
17834** in Expr.
17835*/
17836#define ExprUseUToken(E) (((E)->flags&EP_IntValue)==0)
17837#define ExprUseUValue(E) (((E)->flags&EP_IntValue)!=0)
17838#define ExprUseXList(E) (((E)->flags&EP_xIsSelect)==0)
17839#define ExprUseXSelect(E) (((E)->flags&EP_xIsSelect)!=0)
17840#define ExprUseYTab(E) (((E)->flags&(EP_WinFunc|EP_Subrtn))==0)
17841#define ExprUseYWin(E) (((E)->flags&EP_WinFunc)!=0)
17842#define ExprUseYSub(E) (((E)->flags&EP_Subrtn)!=0)
17843
17844/* Flags for use with Expr.vvaFlags
17845*/
17846#define EP_NoReduce 0x01 /* Cannot EXPRDUP_REDUCE this Expr */
17847#define EP_Immutable 0x02 /* Do not change this Expr node */
17848
17849/* The ExprSetVVAProperty() macro is used for Verification, Validation,
17850** and Accreditation only. It works like ExprSetProperty() during VVA
17851** processes but is a no-op for delivery.
17852*/
17853#ifdef SQLITE_DEBUG
17854# define ExprSetVVAProperty(E,P) (E)->vvaFlags|=(P)
17855# define ExprHasVVAProperty(E,P) (((E)->vvaFlags&(P))!=0)
17856# define ExprClearVVAProperties(E) (E)->vvaFlags = 0
17857#else
17858# define ExprSetVVAProperty(E,P)
17859# define ExprHasVVAProperty(E,P) 0
17860# define ExprClearVVAProperties(E)
17861#endif
17862
17863/*
17864** Macros to determine the number of bytes required by a normal Expr
17865** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
17866** and an Expr struct with the EP_TokenOnly flag set.
17867*/
17868#define EXPR_FULLSIZE sizeof(Expr) /* Full size */
17869#define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
17870#define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
17871
17872/*
17873** Flags passed to the sqlite3ExprDup() function. See the header comment
17874** above sqlite3ExprDup() for details.
17875*/
17876#define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
17877
17878/*
17879** True if the expression passed as an argument was a function with
17880** an OVER() clause (a window function).
17881*/
17882#ifdef SQLITE_OMIT_WINDOWFUNC
17883# define IsWindowFunc(p) 0
17884#else
17885# define IsWindowFunc(p) ( \
17886 ExprHasProperty((p), EP_WinFunc) && p->y.pWin->eFrmType!=TK_FILTER \
17887 )
17888#endif
17889
17890/*
17891** A list of expressions. Each expression may optionally have a
17892** name. An expr/name combination can be used in several ways, such
17893** as the list of "expr AS ID" fields following a "SELECT" or in the
17894** list of "ID = expr" items in an UPDATE. A list of expressions can
17895** also be used as the argument to a function, in which case the a.zName
17896** field is not used.
17897**
17898** In order to try to keep memory usage down, the Expr.a.zEName field
17899** is used for multiple purposes:
17900**
17901** eEName Usage
17902** ---------- -------------------------
17903** ENAME_NAME (1) the AS of result set column
17904** (2) COLUMN= of an UPDATE
17905**
17906** ENAME_TAB DB.TABLE.NAME used to resolve names
17907** of subqueries
17908**
17909** ENAME_SPAN Text of the original result set
17910** expression.
17911*/
17912struct ExprList {
17913 int nExpr; /* Number of expressions on the list */
17914 int nAlloc; /* Number of a[] slots allocated */
17915 struct ExprList_item { /* For each expression in the list */
17916 Expr *pExpr; /* The parse tree for this expression */
17917 char *zEName; /* Token associated with this expression */
17918 u8 sortFlags; /* Mask of KEYINFO_ORDER_* flags */
17919 unsigned eEName :2; /* Meaning of zEName */
17920 unsigned done :1; /* A flag to indicate when processing is finished */
17921 unsigned reusable :1; /* Constant expression is reusable */
17922 unsigned bSorterRef :1; /* Defer evaluation until after sorting */
17923 unsigned bNulls: 1; /* True if explicit "NULLS FIRST/LAST" */
17924 union {
17925 struct { /* Used by any ExprList other than Parse.pConsExpr */
17926 u16 iOrderByCol; /* For ORDER BY, column number in result set */
17927 u16 iAlias; /* Index into Parse.aAlias[] for zName */
17928 } x;
17929 int iConstExprReg; /* Register in which Expr value is cached. Used only
17930 ** by Parse.pConstExpr */
17931 } u;
17932 } a[1]; /* One slot for each expression in the list */
17933};
17934
17935/*
17936** Allowed values for Expr.a.eEName
17937*/
17938#define ENAME_NAME 0 /* The AS clause of a result set */
17939#define ENAME_SPAN 1 /* Complete text of the result set expression */
17940#define ENAME_TAB 2 /* "DB.TABLE.NAME" for the result set */
17941
17942/*
17943** An instance of this structure can hold a simple list of identifiers,
17944** such as the list "a,b,c" in the following statements:
17945**
17946** INSERT INTO t(a,b,c) VALUES ...;
17947** CREATE INDEX idx ON t(a,b,c);
17948** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
17949**
17950** The IdList.a.idx field is used when the IdList represents the list of
17951** column names after a table name in an INSERT statement. In the statement
17952**
17953** INSERT INTO t(a,b,c) ...
17954**
17955** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
17956*/
17957struct IdList {
17958 struct IdList_item {
17959 char *zName; /* Name of the identifier */
17960 int idx; /* Index in some Table.aCol[] of a column named zName */
17961 } *a;
17962 int nId; /* Number of identifiers on the list */
17963};
17964
17965/*
17966** The SrcItem object represents a single term in the FROM clause of a query.
17967** The SrcList object is mostly an array of SrcItems.
17968**
17969** Union member validity:
17970**
17971** u1.zIndexedBy fg.isIndexedBy && !fg.isTabFunc
17972** u1.pFuncArg fg.isTabFunc && !fg.isIndexedBy
17973** u2.pIBIndex fg.isIndexedBy && !fg.isCte
17974** u2.pCteUse fg.isCte && !fg.isIndexedBy
17975*/
17976struct SrcItem {
17977 Schema *pSchema; /* Schema to which this item is fixed */
17978 char *zDatabase; /* Name of database holding this table */
17979 char *zName; /* Name of the table */
17980 char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
17981 Table *pTab; /* An SQL table corresponding to zName */
17982 Select *pSelect; /* A SELECT statement used in place of a table name */
17983 int addrFillSub; /* Address of subroutine to manifest a subquery */
17984 int regReturn; /* Register holding return address of addrFillSub */
17985 int regResult; /* Registers holding results of a co-routine */
17986 struct {
17987 u8 jointype; /* Type of join between this table and the previous */
17988 unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
17989 unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
17990 unsigned isTabFunc :1; /* True if table-valued-function syntax */
17991 unsigned isCorrelated :1; /* True if sub-query is correlated */
17992 unsigned viaCoroutine :1; /* Implemented as a co-routine */
17993 unsigned isRecursive :1; /* True for recursive reference in WITH */
17994 unsigned fromDDL :1; /* Comes from sqlite_schema */
17995 unsigned isCte :1; /* This is a CTE */
17996 unsigned notCte :1; /* This item may not match a CTE */
17997 } fg;
17998 int iCursor; /* The VDBE cursor number used to access this table */
17999 Expr *pOn; /* The ON clause of a join */
18000 IdList *pUsing; /* The USING clause of a join */
18001 Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
18002 union {
18003 char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
18004 ExprList *pFuncArg; /* Arguments to table-valued-function */
18005 } u1;
18006 union {
18007 Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
18008 CteUse *pCteUse; /* CTE Usage info info fg.isCte is true */
18009 } u2;
18010};
18011
18012/*
18013** The following structure describes the FROM clause of a SELECT statement.
18014** Each table or subquery in the FROM clause is a separate element of
18015** the SrcList.a[] array.
18016**
18017** With the addition of multiple database support, the following structure
18018** can also be used to describe a particular table such as the table that
18019** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
18020** such a table must be a simple name: ID. But in SQLite, the table can
18021** now be identified by a database name, a dot, then the table name: ID.ID.
18022**
18023** The jointype starts out showing the join type between the current table
18024** and the next table on the list. The parser builds the list this way.
18025** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
18026** jointype expresses the join between the table and the previous table.
18027**
18028** In the colUsed field, the high-order bit (bit 63) is set if the table
18029** contains more than 63 columns and the 64-th or later column is used.
18030*/
18031struct SrcList {
18032 int nSrc; /* Number of tables or subqueries in the FROM clause */
18033 u32 nAlloc; /* Number of entries allocated in a[] below */
18034 SrcItem a[1]; /* One entry for each identifier on the list */
18035};
18036
18037/*
18038** Permitted values of the SrcList.a.jointype field
18039*/
18040#define JT_INNER 0x0001 /* Any kind of inner or cross join */
18041#define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
18042#define JT_NATURAL 0x0004 /* True for a "natural" join */
18043#define JT_LEFT 0x0008 /* Left outer join */
18044#define JT_RIGHT 0x0010 /* Right outer join */
18045#define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
18046#define JT_ERROR 0x0040 /* unknown or unsupported join type */
18047
18048
18049/*
18050** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
18051** and the WhereInfo.wctrlFlags member.
18052**
18053** Value constraints (enforced via assert()):
18054** WHERE_USE_LIMIT == SF_FixedLimit
18055*/
18056#define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
18057#define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
18058#define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
18059#define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
18060#define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
18061#define WHERE_DUPLICATES_OK 0x0010 /* Ok to return a row more than once */
18062#define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of
18063 ** the OR optimization */
18064#define WHERE_GROUPBY 0x0040 /* pOrderBy is really a GROUP BY */
18065#define WHERE_DISTINCTBY 0x0080 /* pOrderby is really a DISTINCT clause */
18066#define WHERE_WANT_DISTINCT 0x0100 /* All output needs to be distinct */
18067#define WHERE_SORTBYGROUP 0x0200 /* Support sqlite3WhereIsSorted() */
18068#define WHERE_AGG_DISTINCT 0x0400 /* Query is "SELECT agg(DISTINCT ...)" */
18069#define WHERE_ORDERBY_LIMIT 0x0800 /* ORDERBY+LIMIT on the inner loop */
18070 /* 0x1000 not currently used */
18071 /* 0x2000 not currently used */
18072#define WHERE_USE_LIMIT 0x4000 /* Use the LIMIT in cost estimates */
18073 /* 0x8000 not currently used */
18074
18075/* Allowed return values from sqlite3WhereIsDistinct()
18076*/
18077#define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
18078#define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
18079#define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
18080#define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
18081
18082/*
18083** A NameContext defines a context in which to resolve table and column
18084** names. The context consists of a list of tables (the pSrcList) field and
18085** a list of named expression (pEList). The named expression list may
18086** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
18087** to the table being operated on by INSERT, UPDATE, or DELETE. The
18088** pEList corresponds to the result set of a SELECT and is NULL for
18089** other statements.
18090**
18091** NameContexts can be nested. When resolving names, the inner-most
18092** context is searched first. If no match is found, the next outer
18093** context is checked. If there is still no match, the next context
18094** is checked. This process continues until either a match is found
18095** or all contexts are check. When a match is found, the nRef member of
18096** the context containing the match is incremented.
18097**
18098** Each subquery gets a new NameContext. The pNext field points to the
18099** NameContext in the parent query. Thus the process of scanning the
18100** NameContext list corresponds to searching through successively outer
18101** subqueries looking for a match.
18102*/
18103struct NameContext {
18104 Parse *pParse; /* The parser */
18105 SrcList *pSrcList; /* One or more tables used to resolve names */
18106 union {
18107 ExprList *pEList; /* Optional list of result-set columns */
18108 AggInfo *pAggInfo; /* Information about aggregates at this level */
18109 Upsert *pUpsert; /* ON CONFLICT clause information from an upsert */
18110 int iBaseReg; /* For TK_REGISTER when parsing RETURNING */
18111 } uNC;
18112 NameContext *pNext; /* Next outer name context. NULL for outermost */
18113 int nRef; /* Number of names resolved by this context */
18114 int nNcErr; /* Number of errors encountered while resolving names */
18115 int ncFlags; /* Zero or more NC_* flags defined below */
18116 Select *pWinSelect; /* SELECT statement for any window functions */
18117};
18118
18119/*
18120** Allowed values for the NameContext, ncFlags field.
18121**
18122** Value constraints (all checked via assert()):
18123** NC_HasAgg == SF_HasAgg == EP_Agg
18124** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
18125** NC_OrderAgg == SF_OrderByReqd == SQLITE_FUNC_ANYORDER
18126** NC_HasWin == EP_Win
18127**
18128*/
18129#define NC_AllowAgg 0x000001 /* Aggregate functions are allowed here */
18130#define NC_PartIdx 0x000002 /* True if resolving a partial index WHERE */
18131#define NC_IsCheck 0x000004 /* True if resolving a CHECK constraint */
18132#define NC_GenCol 0x000008 /* True for a GENERATED ALWAYS AS clause */
18133#define NC_HasAgg 0x000010 /* One or more aggregate functions seen */
18134#define NC_IdxExpr 0x000020 /* True if resolving columns of CREATE INDEX */
18135#define NC_SelfRef 0x00002e /* Combo: PartIdx, isCheck, GenCol, and IdxExpr */
18136#define NC_VarSelect 0x000040 /* A correlated subquery has been seen */
18137#define NC_UEList 0x000080 /* True if uNC.pEList is used */
18138#define NC_UAggInfo 0x000100 /* True if uNC.pAggInfo is used */
18139#define NC_UUpsert 0x000200 /* True if uNC.pUpsert is used */
18140#define NC_UBaseReg 0x000400 /* True if uNC.iBaseReg is used */
18141#define NC_MinMaxAgg 0x001000 /* min/max aggregates seen. See note above */
18142#define NC_Complex 0x002000 /* True if a function or subquery seen */
18143#define NC_AllowWin 0x004000 /* Window functions are allowed here */
18144#define NC_HasWin 0x008000 /* One or more window functions seen */
18145#define NC_IsDDL 0x010000 /* Resolving names in a CREATE statement */
18146#define NC_InAggFunc 0x020000 /* True if analyzing arguments to an agg func */
18147#define NC_FromDDL 0x040000 /* SQL text comes from sqlite_schema */
18148#define NC_NoSelect 0x080000 /* Do not descend into sub-selects */
18149#define NC_OrderAgg 0x8000000 /* Has an aggregate other than count/min/max */
18150
18151/*
18152** An instance of the following object describes a single ON CONFLICT
18153** clause in an upsert.
18154**
18155** The pUpsertTarget field is only set if the ON CONFLICT clause includes
18156** conflict-target clause. (In "ON CONFLICT(a,b)" the "(a,b)" is the
18157** conflict-target clause.) The pUpsertTargetWhere is the optional
18158** WHERE clause used to identify partial unique indexes.
18159**
18160** pUpsertSet is the list of column=expr terms of the UPDATE statement.
18161** The pUpsertSet field is NULL for a ON CONFLICT DO NOTHING. The
18162** pUpsertWhere is the WHERE clause for the UPDATE and is NULL if the
18163** WHERE clause is omitted.
18164*/
18165struct Upsert {
18166 ExprList *pUpsertTarget; /* Optional description of conflict target */
18167 Expr *pUpsertTargetWhere; /* WHERE clause for partial index targets */
18168 ExprList *pUpsertSet; /* The SET clause from an ON CONFLICT UPDATE */
18169 Expr *pUpsertWhere; /* WHERE clause for the ON CONFLICT UPDATE */
18170 Upsert *pNextUpsert; /* Next ON CONFLICT clause in the list */
18171 u8 isDoUpdate; /* True for DO UPDATE. False for DO NOTHING */
18172 /* Above this point is the parse tree for the ON CONFLICT clauses.
18173 ** The next group of fields stores intermediate data. */
18174 void *pToFree; /* Free memory when deleting the Upsert object */
18175 /* All fields above are owned by the Upsert object and must be freed
18176 ** when the Upsert is destroyed. The fields below are used to transfer
18177 ** information from the INSERT processing down into the UPDATE processing
18178 ** while generating code. The fields below are owned by the INSERT
18179 ** statement and will be freed by INSERT processing. */
18180 Index *pUpsertIdx; /* UNIQUE constraint specified by pUpsertTarget */
18181 SrcList *pUpsertSrc; /* Table to be updated */
18182 int regData; /* First register holding array of VALUES */
18183 int iDataCur; /* Index of the data cursor */
18184 int iIdxCur; /* Index of the first index cursor */
18185};
18186
18187/*
18188** An instance of the following structure contains all information
18189** needed to generate code for a single SELECT statement.
18190**
18191** See the header comment on the computeLimitRegisters() routine for a
18192** detailed description of the meaning of the iLimit and iOffset fields.
18193**
18194** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
18195** These addresses must be stored so that we can go back and fill in
18196** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
18197** the number of columns in P2 can be computed at the same time
18198** as the OP_OpenEphm instruction is coded because not
18199** enough information about the compound query is known at that point.
18200** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
18201** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
18202** sequences for the ORDER BY clause.
18203*/
18204struct Select {
18205 u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
18206 LogEst nSelectRow; /* Estimated number of result rows */
18207 u32 selFlags; /* Various SF_* values */
18208 int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
18209 u32 selId; /* Unique identifier number for this SELECT */
18210 int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
18211 ExprList *pEList; /* The fields of the result */
18212 SrcList *pSrc; /* The FROM clause */
18213 Expr *pWhere; /* The WHERE clause */
18214 ExprList *pGroupBy; /* The GROUP BY clause */
18215 Expr *pHaving; /* The HAVING clause */
18216 ExprList *pOrderBy; /* The ORDER BY clause */
18217 Select *pPrior; /* Prior select in a compound select statement */
18218 Select *pNext; /* Next select to the left in a compound */
18219 Expr *pLimit; /* LIMIT expression. NULL means not used. */
18220 With *pWith; /* WITH clause attached to this select. Or NULL. */
18221#ifndef SQLITE_OMIT_WINDOWFUNC
18222 Window *pWin; /* List of window functions */
18223 Window *pWinDefn; /* List of named window definitions */
18224#endif
18225};
18226
18227/*
18228** Allowed values for Select.selFlags. The "SF" prefix stands for
18229** "Select Flag".
18230**
18231** Value constraints (all checked via assert())
18232** SF_HasAgg == NC_HasAgg
18233** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
18234** SF_OrderByReqd == NC_OrderAgg == SQLITE_FUNC_ANYORDER
18235** SF_FixedLimit == WHERE_USE_LIMIT
18236*/
18237#define SF_Distinct 0x0000001 /* Output should be DISTINCT */
18238#define SF_All 0x0000002 /* Includes the ALL keyword */
18239#define SF_Resolved 0x0000004 /* Identifiers have been resolved */
18240#define SF_Aggregate 0x0000008 /* Contains agg functions or a GROUP BY */
18241#define SF_HasAgg 0x0000010 /* Contains aggregate functions */
18242#define SF_UsesEphemeral 0x0000020 /* Uses the OpenEphemeral opcode */
18243#define SF_Expanded 0x0000040 /* sqlite3SelectExpand() called on this */
18244#define SF_HasTypeInfo 0x0000080 /* FROM subqueries have Table metadata */
18245#define SF_Compound 0x0000100 /* Part of a compound query */
18246#define SF_Values 0x0000200 /* Synthesized from VALUES clause */
18247#define SF_MultiValue 0x0000400 /* Single VALUES term with multiple rows */
18248#define SF_NestedFrom 0x0000800 /* Part of a parenthesized FROM clause */
18249#define SF_MinMaxAgg 0x0001000 /* Aggregate containing min() or max() */
18250#define SF_Recursive 0x0002000 /* The recursive part of a recursive CTE */
18251#define SF_FixedLimit 0x0004000 /* nSelectRow set by a constant LIMIT */
18252#define SF_MaybeConvert 0x0008000 /* Need convertCompoundSelectToSubquery() */
18253#define SF_Converted 0x0010000 /* By convertCompoundSelectToSubquery() */
18254#define SF_IncludeHidden 0x0020000 /* Include hidden columns in output */
18255#define SF_ComplexResult 0x0040000 /* Result contains subquery or function */
18256#define SF_WhereBegin 0x0080000 /* Really a WhereBegin() call. Debug Only */
18257#define SF_WinRewrite 0x0100000 /* Window function rewrite accomplished */
18258#define SF_View 0x0200000 /* SELECT statement is a view */
18259#define SF_NoopOrderBy 0x0400000 /* ORDER BY is ignored for this query */
18260#define SF_UFSrcCheck 0x0800000 /* Check pSrc as required by UPDATE...FROM */
18261#define SF_PushDown 0x1000000 /* SELECT has be modified by push-down opt */
18262#define SF_MultiPart 0x2000000 /* Has multiple incompatible PARTITIONs */
18263#define SF_CopyCte 0x4000000 /* SELECT statement is a copy of a CTE */
18264#define SF_OrderByReqd 0x8000000 /* The ORDER BY clause may not be omitted */
18265
18266/*
18267** The results of a SELECT can be distributed in several ways, as defined
18268** by one of the following macros. The "SRT" prefix means "SELECT Result
18269** Type".
18270**
18271** SRT_Union Store results as a key in a temporary index
18272** identified by pDest->iSDParm.
18273**
18274** SRT_Except Remove results from the temporary index pDest->iSDParm.
18275**
18276** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
18277** set is not empty.
18278**
18279** SRT_Discard Throw the results away. This is used by SELECT
18280** statements within triggers whose only purpose is
18281** the side-effects of functions.
18282**
18283** SRT_Output Generate a row of output (using the OP_ResultRow
18284** opcode) for each row in the result set.
18285**
18286** SRT_Mem Only valid if the result is a single column.
18287** Store the first column of the first result row
18288** in register pDest->iSDParm then abandon the rest
18289** of the query. This destination implies "LIMIT 1".
18290**
18291** SRT_Set The result must be a single column. Store each
18292** row of result as the key in table pDest->iSDParm.
18293** Apply the affinity pDest->affSdst before storing
18294** results. Used to implement "IN (SELECT ...)".
18295**
18296** SRT_EphemTab Create an temporary table pDest->iSDParm and store
18297** the result there. The cursor is left open after
18298** returning. This is like SRT_Table except that
18299** this destination uses OP_OpenEphemeral to create
18300** the table first.
18301**
18302** SRT_Coroutine Generate a co-routine that returns a new row of
18303** results each time it is invoked. The entry point
18304** of the co-routine is stored in register pDest->iSDParm
18305** and the result row is stored in pDest->nDest registers
18306** starting with pDest->iSdst.
18307**
18308** SRT_Table Store results in temporary table pDest->iSDParm.
18309** SRT_Fifo This is like SRT_EphemTab except that the table
18310** is assumed to already be open. SRT_Fifo has
18311** the additional property of being able to ignore
18312** the ORDER BY clause.
18313**
18314** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
18315** But also use temporary table pDest->iSDParm+1 as
18316** a record of all prior results and ignore any duplicate
18317** rows. Name means: "Distinct Fifo".
18318**
18319** SRT_Queue Store results in priority queue pDest->iSDParm (really
18320** an index). Append a sequence number so that all entries
18321** are distinct.
18322**
18323** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
18324** the same record has never been stored before. The
18325** index at pDest->iSDParm+1 hold all prior stores.
18326**
18327** SRT_Upfrom Store results in the temporary table already opened by
18328** pDest->iSDParm. If (pDest->iSDParm<0), then the temp
18329** table is an intkey table - in this case the first
18330** column returned by the SELECT is used as the integer
18331** key. If (pDest->iSDParm>0), then the table is an index
18332** table. (pDest->iSDParm) is the number of key columns in
18333** each index record in this case.
18334*/
18335#define SRT_Union 1 /* Store result as keys in an index */
18336#define SRT_Except 2 /* Remove result from a UNION index */
18337#define SRT_Exists 3 /* Store 1 if the result is not empty */
18338#define SRT_Discard 4 /* Do not save the results anywhere */
18339#define SRT_DistFifo 5 /* Like SRT_Fifo, but unique results only */
18340#define SRT_DistQueue 6 /* Like SRT_Queue, but unique results only */
18341
18342/* The DISTINCT clause is ignored for all of the above. Not that
18343** IgnorableDistinct() implies IgnorableOrderby() */
18344#define IgnorableDistinct(X) ((X->eDest)<=SRT_DistQueue)
18345
18346#define SRT_Queue 7 /* Store result in an queue */
18347#define SRT_Fifo 8 /* Store result as data with an automatic rowid */
18348
18349/* The ORDER BY clause is ignored for all of the above */
18350#define IgnorableOrderby(X) ((X->eDest)<=SRT_Fifo)
18351
18352#define SRT_Output 9 /* Output each row of result */
18353#define SRT_Mem 10 /* Store result in a memory cell */
18354#define SRT_Set 11 /* Store results as keys in an index */
18355#define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
18356#define SRT_Coroutine 13 /* Generate a single row of result */
18357#define SRT_Table 14 /* Store result as data with an automatic rowid */
18358#define SRT_Upfrom 15 /* Store result as data with rowid */
18359
18360/*
18361** An instance of this object describes where to put of the results of
18362** a SELECT statement.
18363*/
18364struct SelectDest {
18365 u8 eDest; /* How to dispose of the results. One of SRT_* above. */
18366 int iSDParm; /* A parameter used by the eDest disposal method */
18367 int iSDParm2; /* A second parameter for the eDest disposal method */
18368 int iSdst; /* Base register where results are written */
18369 int nSdst; /* Number of registers allocated */
18370 char *zAffSdst; /* Affinity used when eDest==SRT_Set */
18371 ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
18372};
18373
18374/*
18375** During code generation of statements that do inserts into AUTOINCREMENT
18376** tables, the following information is attached to the Table.u.autoInc.p
18377** pointer of each autoincrement table to record some side information that
18378** the code generator needs. We have to keep per-table autoincrement
18379** information in case inserts are done within triggers. Triggers do not
18380** normally coordinate their activities, but we do need to coordinate the
18381** loading and saving of autoincrement information.
18382*/
18383struct AutoincInfo {
18384 AutoincInfo *pNext; /* Next info block in a list of them all */
18385 Table *pTab; /* Table this info block refers to */
18386 int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
18387 int regCtr; /* Memory register holding the rowid counter */
18388};
18389
18390/*
18391** At least one instance of the following structure is created for each
18392** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
18393** statement. All such objects are stored in the linked list headed at
18394** Parse.pTriggerPrg and deleted once statement compilation has been
18395** completed.
18396**
18397** A Vdbe sub-program that implements the body and WHEN clause of trigger
18398** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
18399** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
18400** The Parse.pTriggerPrg list never contains two entries with the same
18401** values for both pTrigger and orconf.
18402**
18403** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
18404** accessed (or set to 0 for triggers fired as a result of INSERT
18405** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
18406** a mask of new.* columns used by the program.
18407*/
18408struct TriggerPrg {
18409 Trigger *pTrigger; /* Trigger this program was coded from */
18410 TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
18411 SubProgram *pProgram; /* Program implementing pTrigger/orconf */
18412 int orconf; /* Default ON CONFLICT policy */
18413 u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
18414};
18415
18416/*
18417** The yDbMask datatype for the bitmask of all attached databases.
18418*/
18419#if SQLITE_MAX_ATTACHED>30
18420 typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
18421# define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
18422# define DbMaskZero(M) memset((M),0,sizeof(M))
18423# define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
18424# define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
18425# define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
18426#else
18427 typedef unsigned int yDbMask;
18428# define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
18429# define DbMaskZero(M) (M)=0
18430# define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
18431# define DbMaskAllZero(M) (M)==0
18432# define DbMaskNonZero(M) (M)!=0
18433#endif
18434
18435/*
18436** An instance of the ParseCleanup object specifies an operation that
18437** should be performed after parsing to deallocation resources obtained
18438** during the parse and which are no longer needed.
18439*/
18440struct ParseCleanup {
18441 ParseCleanup *pNext; /* Next cleanup task */
18442 void *pPtr; /* Pointer to object to deallocate */
18443 void (*xCleanup)(sqlite3*,void*); /* Deallocation routine */
18444};
18445
18446/*
18447** An SQL parser context. A copy of this structure is passed through
18448** the parser and down into all the parser action routine in order to
18449** carry around information that is global to the entire parse.
18450**
18451** The structure is divided into two parts. When the parser and code
18452** generate call themselves recursively, the first part of the structure
18453** is constant but the second part is reset at the beginning and end of
18454** each recursion.
18455**
18456** The nTableLock and aTableLock variables are only used if the shared-cache
18457** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
18458** used to store the set of table-locks required by the statement being
18459** compiled. Function sqlite3TableLock() is used to add entries to the
18460** list.
18461*/
18462struct Parse {
18463 sqlite3 *db; /* The main database structure */
18464 char *zErrMsg; /* An error message */
18465 Vdbe *pVdbe; /* An engine for executing database bytecode */
18466 int rc; /* Return code from execution */
18467 u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
18468 u8 checkSchema; /* Causes schema cookie check after an error */
18469 u8 nested; /* Number of nested calls to the parser/code generator */
18470 u8 nTempReg; /* Number of temporary registers in aTempReg[] */
18471 u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
18472 u8 mayAbort; /* True if statement may throw an ABORT exception */
18473 u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
18474 u8 okConstFactor; /* OK to factor out constants */
18475 u8 disableLookaside; /* Number of times lookaside has been disabled */
18476 u8 disableVtab; /* Disable all virtual tables for this parse */
18477#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
18478 u8 earlyCleanup; /* OOM inside sqlite3ParserAddCleanup() */
18479#endif
18480 int nRangeReg; /* Size of the temporary register block */
18481 int iRangeReg; /* First register in temporary register block */
18482 int nErr; /* Number of errors seen */
18483 int nTab; /* Number of previously allocated VDBE cursors */
18484 int nMem; /* Number of memory cells used so far */
18485 int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
18486 int iSelfTab; /* Table associated with an index on expr, or negative
18487 ** of the base register during check-constraint eval */
18488 int nLabel; /* The *negative* of the number of labels used */
18489 int nLabelAlloc; /* Number of slots in aLabel */
18490 int *aLabel; /* Space to hold the labels */
18491 ExprList *pConstExpr;/* Constant expressions */
18492 Token constraintName;/* Name of the constraint currently being parsed */
18493 yDbMask writeMask; /* Start a write transaction on these databases */
18494 yDbMask cookieMask; /* Bitmask of schema verified databases */
18495 int regRowid; /* Register holding rowid of CREATE TABLE entry */
18496 int regRoot; /* Register holding root page number for new objects */
18497 int nMaxArg; /* Max args passed to user function by sub-program */
18498 int nSelect; /* Number of SELECT stmts. Counter for Select.selId */
18499#ifndef SQLITE_OMIT_SHARED_CACHE
18500 int nTableLock; /* Number of locks in aTableLock */
18501 TableLock *aTableLock; /* Required table locks for shared-cache mode */
18502#endif
18503 AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
18504 Parse *pToplevel; /* Parse structure for main program (or NULL) */
18505 Table *pTriggerTab; /* Table triggers are being coded for */
18506 TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
18507 ParseCleanup *pCleanup; /* List of cleanup operations to run after parse */
18508 union {
18509 int addrCrTab; /* Address of OP_CreateBtree on CREATE TABLE */
18510 Returning *pReturning; /* The RETURNING clause */
18511 } u1;
18512 u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
18513 u32 oldmask; /* Mask of old.* columns referenced */
18514 u32 newmask; /* Mask of new.* columns referenced */
18515 u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
18516 u8 bReturning; /* Coding a RETURNING trigger */
18517 u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
18518 u8 disableTriggers; /* True to disable triggers */
18519
18520 /**************************************************************************
18521 ** Fields above must be initialized to zero. The fields that follow,
18522 ** down to the beginning of the recursive section, do not need to be
18523 ** initialized as they will be set before being used. The boundary is
18524 ** determined by offsetof(Parse,aTempReg).
18525 **************************************************************************/
18526
18527 int aTempReg[8]; /* Holding area for temporary registers */
18528 Token sNameToken; /* Token with unqualified schema object name */
18529
18530 /************************************************************************
18531 ** Above is constant between recursions. Below is reset before and after
18532 ** each recursion. The boundary between these two regions is determined
18533 ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
18534 ** first field in the recursive region.
18535 ************************************************************************/
18536
18537 Token sLastToken; /* The last token parsed */
18538 ynVar nVar; /* Number of '?' variables seen in the SQL so far */
18539 u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
18540 u8 explain; /* True if the EXPLAIN flag is found on the query */
18541 u8 eParseMode; /* PARSE_MODE_XXX constant */
18542#ifndef SQLITE_OMIT_VIRTUALTABLE
18543 int nVtabLock; /* Number of virtual tables to lock */
18544#endif
18545 int nHeight; /* Expression tree height of current sub-select */
18546#ifndef SQLITE_OMIT_EXPLAIN
18547 int addrExplain; /* Address of current OP_Explain opcode */
18548#endif
18549 VList *pVList; /* Mapping between variable names and numbers */
18550 Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
18551 const char *zTail; /* All SQL text past the last semicolon parsed */
18552 Table *pNewTable; /* A table being constructed by CREATE TABLE */
18553 Index *pNewIndex; /* An index being constructed by CREATE INDEX.
18554 ** Also used to hold redundant UNIQUE constraints
18555 ** during a RENAME COLUMN */
18556 Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
18557 const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
18558#ifndef SQLITE_OMIT_VIRTUALTABLE
18559 Token sArg; /* Complete text of a module argument */
18560 Table **apVtabLock; /* Pointer to virtual tables needing locking */
18561#endif
18562 With *pWith; /* Current WITH clause, or NULL */
18563#ifndef SQLITE_OMIT_ALTERTABLE
18564 RenameToken *pRename; /* Tokens subject to renaming by ALTER TABLE */
18565#endif
18566};
18567
18568/* Allowed values for Parse.eParseMode
18569*/
18570#define PARSE_MODE_NORMAL 0
18571#define PARSE_MODE_DECLARE_VTAB 1
18572#define PARSE_MODE_RENAME 2
18573#define PARSE_MODE_UNMAP 3
18574
18575/*
18576** Sizes and pointers of various parts of the Parse object.
18577*/
18578#define PARSE_HDR_SZ offsetof(Parse,aTempReg) /* Recursive part w/o aColCache*/
18579#define PARSE_RECURSE_SZ offsetof(Parse,sLastToken) /* Recursive part */
18580#define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
18581#define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ) /* Pointer to tail */
18582
18583/*
18584** Return true if currently inside an sqlite3_declare_vtab() call.
18585*/
18586#ifdef SQLITE_OMIT_VIRTUALTABLE
18587 #define IN_DECLARE_VTAB 0
18588#else
18589 #define IN_DECLARE_VTAB (pParse->eParseMode==PARSE_MODE_DECLARE_VTAB)
18590#endif
18591
18592#if defined(SQLITE_OMIT_ALTERTABLE)
18593 #define IN_RENAME_OBJECT 0
18594#else
18595 #define IN_RENAME_OBJECT (pParse->eParseMode>=PARSE_MODE_RENAME)
18596#endif
18597
18598#if defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE)
18599 #define IN_SPECIAL_PARSE 0
18600#else
18601 #define IN_SPECIAL_PARSE (pParse->eParseMode!=PARSE_MODE_NORMAL)
18602#endif
18603
18604/*
18605** An instance of the following structure can be declared on a stack and used
18606** to save the Parse.zAuthContext value so that it can be restored later.
18607*/
18608struct AuthContext {
18609 const char *zAuthContext; /* Put saved Parse.zAuthContext here */
18610 Parse *pParse; /* The Parse structure */
18611};
18612
18613/*
18614** Bitfield flags for P5 value in various opcodes.
18615**
18616** Value constraints (enforced via assert()):
18617** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
18618** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
18619** OPFLAG_BULKCSR == BTREE_BULKLOAD
18620** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
18621** OPFLAG_FORDELETE == BTREE_FORDELETE
18622** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
18623** OPFLAG_AUXDELETE == BTREE_AUXDELETE
18624*/
18625#define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
18626 /* Also used in P2 (not P5) of OP_Delete */
18627#define OPFLAG_NOCHNG 0x01 /* OP_VColumn nochange for UPDATE */
18628#define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
18629#define OPFLAG_LASTROWID 0x20 /* Set to update db->lastRowid */
18630#define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
18631#define OPFLAG_APPEND 0x08 /* This is likely to be an append */
18632#define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
18633#define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
18634#define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
18635#define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
18636#define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
18637#define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
18638#define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
18639#define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
18640#define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
18641#define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete/Insert: save cursor pos */
18642#define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */
18643#define OPFLAG_NOCHNG_MAGIC 0x6d /* OP_MakeRecord: serialtype 10 is ok */
18644#define OPFLAG_PREFORMAT 0x80 /* OP_Insert uses preformatted cell */
18645
18646/*
18647 * Each trigger present in the database schema is stored as an instance of
18648 * struct Trigger.
18649 *
18650 * Pointers to instances of struct Trigger are stored in two ways.
18651 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
18652 * database). This allows Trigger structures to be retrieved by name.
18653 * 2. All triggers associated with a single table form a linked list, using the
18654 * pNext member of struct Trigger. A pointer to the first element of the
18655 * linked list is stored as the "pTrigger" member of the associated
18656 * struct Table.
18657 *
18658 * The "step_list" member points to the first element of a linked list
18659 * containing the SQL statements specified as the trigger program.
18660 */
18661struct Trigger {
18662 char *zName; /* The name of the trigger */
18663 char *table; /* The table or view to which the trigger applies */
18664 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
18665 u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
18666 u8 bReturning; /* This trigger implements a RETURNING clause */
18667 Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
18668 IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
18669 the <column-list> is stored here */
18670 Schema *pSchema; /* Schema containing the trigger */
18671 Schema *pTabSchema; /* Schema containing the table */
18672 TriggerStep *step_list; /* Link list of trigger program steps */
18673 Trigger *pNext; /* Next trigger associated with the table */
18674};
18675
18676/*
18677** A trigger is either a BEFORE or an AFTER trigger. The following constants
18678** determine which.
18679**
18680** If there are multiple triggers, you might of some BEFORE and some AFTER.
18681** In that cases, the constants below can be ORed together.
18682*/
18683#define TRIGGER_BEFORE 1
18684#define TRIGGER_AFTER 2
18685
18686/*
18687 * An instance of struct TriggerStep is used to store a single SQL statement
18688 * that is a part of a trigger-program.
18689 *
18690 * Instances of struct TriggerStep are stored in a singly linked list (linked
18691 * using the "pNext" member) referenced by the "step_list" member of the
18692 * associated struct Trigger instance. The first element of the linked list is
18693 * the first step of the trigger-program.
18694 *
18695 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
18696 * "SELECT" statement. The meanings of the other members is determined by the
18697 * value of "op" as follows:
18698 *
18699 * (op == TK_INSERT)
18700 * orconf -> stores the ON CONFLICT algorithm
18701 * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
18702 * this stores a pointer to the SELECT statement. Otherwise NULL.
18703 * zTarget -> Dequoted name of the table to insert into.
18704 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
18705 * this stores values to be inserted. Otherwise NULL.
18706 * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
18707 * statement, then this stores the column-names to be
18708 * inserted into.
18709 *
18710 * (op == TK_DELETE)
18711 * zTarget -> Dequoted name of the table to delete from.
18712 * pWhere -> The WHERE clause of the DELETE statement if one is specified.
18713 * Otherwise NULL.
18714 *
18715 * (op == TK_UPDATE)
18716 * zTarget -> Dequoted name of the table to update.
18717 * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
18718 * Otherwise NULL.
18719 * pExprList -> A list of the columns to update and the expressions to update
18720 * them to. See sqlite3Update() documentation of "pChanges"
18721 * argument.
18722 *
18723 */
18724struct TriggerStep {
18725 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT,
18726 ** or TK_RETURNING */
18727 u8 orconf; /* OE_Rollback etc. */
18728 Trigger *pTrig; /* The trigger that this step is a part of */
18729 Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
18730 char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
18731 SrcList *pFrom; /* FROM clause for UPDATE statement (if any) */
18732 Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
18733 ExprList *pExprList; /* SET clause for UPDATE, or RETURNING clause */
18734 IdList *pIdList; /* Column names for INSERT */
18735 Upsert *pUpsert; /* Upsert clauses on an INSERT */
18736 char *zSpan; /* Original SQL text of this command */
18737 TriggerStep *pNext; /* Next in the link-list */
18738 TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
18739};
18740
18741/*
18742** Information about a RETURNING clause
18743*/
18744struct Returning {
18745 Parse *pParse; /* The parse that includes the RETURNING clause */
18746 ExprList *pReturnEL; /* List of expressions to return */
18747 Trigger retTrig; /* The transient trigger that implements RETURNING */
18748 TriggerStep retTStep; /* The trigger step */
18749 int iRetCur; /* Transient table holding RETURNING results */
18750 int nRetCol; /* Number of in pReturnEL after expansion */
18751 int iRetReg; /* Register array for holding a row of RETURNING */
18752};
18753
18754/*
18755** An objected used to accumulate the text of a string where we
18756** do not necessarily know how big the string will be in the end.
18757*/
18758struct sqlite3_str {
18759 sqlite3 *db; /* Optional database for lookaside. Can be NULL */
18760 char *zText; /* The string collected so far */
18761 u32 nAlloc; /* Amount of space allocated in zText */
18762 u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
18763 u32 nChar; /* Length of the string so far */
18764 u8 accError; /* SQLITE_NOMEM or SQLITE_TOOBIG */
18765 u8 printfFlags; /* SQLITE_PRINTF flags below */
18766};
18767#define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
18768#define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */
18769#define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */
18770
18771#define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
18772
18773
18774/*
18775** A pointer to this structure is used to communicate information
18776** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
18777*/
18778typedef struct {
18779 sqlite3 *db; /* The database being initialized */
18780 char **pzErrMsg; /* Error message stored here */
18781 int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
18782 int rc; /* Result code stored here */
18783 u32 mInitFlags; /* Flags controlling error messages */
18784 u32 nInitRow; /* Number of rows processed */
18785 Pgno mxPage; /* Maximum page number. 0 for no limit. */
18786} InitData;
18787
18788/*
18789** Allowed values for mInitFlags
18790*/
18791#define INITFLAG_AlterMask 0x0003 /* Types of ALTER */
18792#define INITFLAG_AlterRename 0x0001 /* Reparse after a RENAME */
18793#define INITFLAG_AlterDrop 0x0002 /* Reparse after a DROP COLUMN */
18794#define INITFLAG_AlterAdd 0x0003 /* Reparse after an ADD COLUMN */
18795
18796/* Tuning parameters are set using SQLITE_TESTCTRL_TUNE and are controlled
18797** on debug-builds of the CLI using ".testctrl tune ID VALUE". Tuning
18798** parameters are for temporary use during development, to help find
18799** optimial values for parameters in the query planner. The should not
18800** be used on trunk check-ins. They are a temporary mechanism available
18801** for transient development builds only.
18802**
18803** Tuning parameters are numbered starting with 1.
18804*/
18805#define SQLITE_NTUNE 6 /* Should be zero for all trunk check-ins */
18806#ifdef SQLITE_DEBUG
18807# define Tuning(X) (sqlite3Config.aTune[(X)-1])
18808#else
18809# define Tuning(X) 0
18810#endif
18811
18812/*
18813** Structure containing global configuration data for the SQLite library.
18814**
18815** This structure also contains some state information.
18816*/
18817struct Sqlite3Config {
18818 int bMemstat; /* True to enable memory status */
18819 u8 bCoreMutex; /* True to enable core mutexing */
18820 u8 bFullMutex; /* True to enable full mutexing */
18821 u8 bOpenUri; /* True to interpret filenames as URIs */
18822 u8 bUseCis; /* Use covering indices for full-scans */
18823 u8 bSmallMalloc; /* Avoid large memory allocations if true */
18824 u8 bExtraSchemaChecks; /* Verify type,name,tbl_name in schema */
18825 int mxStrlen; /* Maximum string length */
18826 int neverCorrupt; /* Database is always well-formed */
18827 int szLookaside; /* Default lookaside buffer size */
18828 int nLookaside; /* Default lookaside buffer count */
18829 int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
18830 sqlite3_mem_methods m; /* Low-level memory allocation interface */
18831 sqlite3_mutex_methods mutex; /* Low-level mutex interface */
18832 sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
18833 void *pHeap; /* Heap storage space */
18834 int nHeap; /* Size of pHeap[] */
18835 int mnReq, mxReq; /* Min and max heap requests sizes */
18836 sqlite3_int64 szMmap; /* mmap() space per open file */
18837 sqlite3_int64 mxMmap; /* Maximum value for szMmap */
18838 void *pPage; /* Page cache memory */
18839 int szPage; /* Size of each page in pPage[] */
18840 int nPage; /* Number of pages in pPage[] */
18841 int mxParserStack; /* maximum depth of the parser stack */
18842 int sharedCacheEnabled; /* true if shared-cache mode enabled */
18843 u32 szPma; /* Maximum Sorter PMA size */
18844 /* The above might be initialized to non-zero. The following need to always
18845 ** initially be zero, however. */
18846 int isInit; /* True after initialization has finished */
18847 int inProgress; /* True while initialization in progress */
18848 int isMutexInit; /* True after mutexes are initialized */
18849 int isMallocInit; /* True after malloc is initialized */
18850 int isPCacheInit; /* True after malloc is initialized */
18851 int nRefInitMutex; /* Number of users of pInitMutex */
18852 sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
18853 void (*xLog)(void*,int,const char*); /* Function for logging */
18854 void *pLogArg; /* First argument to xLog() */
18855#ifdef SQLITE_ENABLE_SQLLOG
18856 void(*xSqllog)(void*,sqlite3*,const char*, int);
18857 void *pSqllogArg;
18858#endif
18859#ifdef SQLITE_VDBE_COVERAGE
18860 /* The following callback (if not NULL) is invoked on every VDBE branch
18861 ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
18862 */
18863 void (*xVdbeBranch)(void*,unsigned iSrcLine,u8 eThis,u8 eMx); /* Callback */
18864 void *pVdbeBranchArg; /* 1st argument */
18865#endif
18866#ifndef SQLITE_OMIT_DESERIALIZE
18867 sqlite3_int64 mxMemdbSize; /* Default max memdb size */
18868#endif
18869#ifndef SQLITE_UNTESTABLE
18870 int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
18871#endif
18872 int bLocaltimeFault; /* True to fail localtime() calls */
18873 int iOnceResetThreshold; /* When to reset OP_Once counters */
18874 u32 szSorterRef; /* Min size in bytes to use sorter-refs */
18875 unsigned int iPrngSeed; /* Alternative fixed seed for the PRNG */
18876 /* vvvv--- must be last ---vvv */
18877#ifdef SQLITE_DEBUG
18878 sqlite3_int64 aTune[SQLITE_NTUNE]; /* Tuning parameters */
18879#endif
18880};
18881
18882/*
18883** This macro is used inside of assert() statements to indicate that
18884** the assert is only valid on a well-formed database. Instead of:
18885**
18886** assert( X );
18887**
18888** One writes:
18889**
18890** assert( X || CORRUPT_DB );
18891**
18892** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
18893** that the database is definitely corrupt, only that it might be corrupt.
18894** For most test cases, CORRUPT_DB is set to false using a special
18895** sqlite3_test_control(). This enables assert() statements to prove
18896** things that are always true for well-formed databases.
18897*/
18898#define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
18899
18900/*
18901** Context pointer passed down through the tree-walk.
18902*/
18903struct Walker {
18904 Parse *pParse; /* Parser context. */
18905 int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
18906 int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
18907 void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
18908 int walkerDepth; /* Number of subqueries */
18909 u16 eCode; /* A small processing code */
18910 union { /* Extra data for callback */
18911 NameContext *pNC; /* Naming context */
18912 int n; /* A counter */
18913 int iCur; /* A cursor number */
18914 SrcList *pSrcList; /* FROM clause */
18915 struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
18916 struct RefSrcList *pRefSrcList; /* sqlite3ReferencesSrcList() */
18917 int *aiCol; /* array of column indexes */
18918 struct IdxCover *pIdxCover; /* Check for index coverage */
18919 struct IdxExprTrans *pIdxTrans; /* Convert idxed expr to column */
18920 ExprList *pGroupBy; /* GROUP BY clause */
18921 Select *pSelect; /* HAVING to WHERE clause ctx */
18922 struct WindowRewrite *pRewrite; /* Window rewrite context */
18923 struct WhereConst *pConst; /* WHERE clause constants */
18924 struct RenameCtx *pRename; /* RENAME COLUMN context */
18925 struct Table *pTab; /* Table of generated column */
18926 SrcItem *pSrcItem; /* A single FROM clause item */
18927 DbFixer *pFix;
18928 } u;
18929};
18930
18931/*
18932** The following structure contains information used by the sqliteFix...
18933** routines as they walk the parse tree to make database references
18934** explicit.
18935*/
18936struct DbFixer {
18937 Parse *pParse; /* The parsing context. Error messages written here */
18938 Walker w; /* Walker object */
18939 Schema *pSchema; /* Fix items to this schema */
18940 u8 bTemp; /* True for TEMP schema entries */
18941 const char *zDb; /* Make sure all objects are contained in this database */
18942 const char *zType; /* Type of the container - used for error messages */
18943 const Token *pName; /* Name of the container - used for error messages */
18944};
18945
18946/* Forward declarations */
18947SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
18948SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
18949SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
18950SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
18951SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
18952SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
18953SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*);
18954SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker*, Select*);
18955SQLITE_PRIVATE int sqlite3WalkerDepthIncrease(Walker*,Select*);
18956SQLITE_PRIVATE void sqlite3WalkerDepthDecrease(Walker*,Select*);
18957SQLITE_PRIVATE void sqlite3WalkWinDefnDummyCallback(Walker*,Select*);
18958
18959#ifdef SQLITE_DEBUG
18960SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*);
18961#endif
18962
18963#ifndef SQLITE_OMIT_CTE
18964SQLITE_PRIVATE void sqlite3SelectPopWith(Walker*, Select*);
18965#else
18966# define sqlite3SelectPopWith 0
18967#endif
18968
18969/*
18970** Return code from the parse-tree walking primitives and their
18971** callbacks.
18972*/
18973#define WRC_Continue 0 /* Continue down into children */
18974#define WRC_Prune 1 /* Omit children but continue walking siblings */
18975#define WRC_Abort 2 /* Abandon the tree walk */
18976
18977/*
18978** A single common table expression
18979*/
18980struct Cte {
18981 char *zName; /* Name of this CTE */
18982 ExprList *pCols; /* List of explicit column names, or NULL */
18983 Select *pSelect; /* The definition of this CTE */
18984 const char *zCteErr; /* Error message for circular references */
18985 CteUse *pUse; /* Usage information for this CTE */
18986 u8 eM10d; /* The MATERIALIZED flag */
18987};
18988
18989/*
18990** Allowed values for the materialized flag (eM10d):
18991*/
18992#define M10d_Yes 0 /* AS MATERIALIZED */
18993#define M10d_Any 1 /* Not specified. Query planner's choice */
18994#define M10d_No 2 /* AS NOT MATERIALIZED */
18995
18996/*
18997** An instance of the With object represents a WITH clause containing
18998** one or more CTEs (common table expressions).
18999*/
19000struct With {
19001 int nCte; /* Number of CTEs in the WITH clause */
19002 int bView; /* Belongs to the outermost Select of a view */
19003 With *pOuter; /* Containing WITH clause, or NULL */
19004 Cte a[1]; /* For each CTE in the WITH clause.... */
19005};
19006
19007/*
19008** The Cte object is not guaranteed to persist for the entire duration
19009** of code generation. (The query flattener or other parser tree
19010** edits might delete it.) The following object records information
19011** about each Common Table Expression that must be preserved for the
19012** duration of the parse.
19013**
19014** The CteUse objects are freed using sqlite3ParserAddCleanup() rather
19015** than sqlite3SelectDelete(), which is what enables them to persist
19016** until the end of code generation.
19017*/
19018struct CteUse {
19019 int nUse; /* Number of users of this CTE */
19020 int addrM9e; /* Start of subroutine to compute materialization */
19021 int regRtn; /* Return address register for addrM9e subroutine */
19022 int iCur; /* Ephemeral table holding the materialization */
19023 LogEst nRowEst; /* Estimated number of rows in the table */
19024 u8 eM10d; /* The MATERIALIZED flag */
19025};
19026
19027
19028#ifdef SQLITE_DEBUG
19029/*
19030** An instance of the TreeView object is used for printing the content of
19031** data structures on sqlite3DebugPrintf() using a tree-like view.
19032*/
19033struct TreeView {
19034 int iLevel; /* Which level of the tree we are on */
19035 u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
19036};
19037#endif /* SQLITE_DEBUG */
19038
19039/*
19040** This object is used in various ways, most (but not all) related to window
19041** functions.
19042**
19043** (1) A single instance of this structure is attached to the
19044** the Expr.y.pWin field for each window function in an expression tree.
19045** This object holds the information contained in the OVER clause,
19046** plus additional fields used during code generation.
19047**
19048** (2) All window functions in a single SELECT form a linked-list
19049** attached to Select.pWin. The Window.pFunc and Window.pExpr
19050** fields point back to the expression that is the window function.
19051**
19052** (3) The terms of the WINDOW clause of a SELECT are instances of this
19053** object on a linked list attached to Select.pWinDefn.
19054**
19055** (4) For an aggregate function with a FILTER clause, an instance
19056** of this object is stored in Expr.y.pWin with eFrmType set to
19057** TK_FILTER. In this case the only field used is Window.pFilter.
19058**
19059** The uses (1) and (2) are really the same Window object that just happens
19060** to be accessible in two different ways. Use case (3) are separate objects.
19061*/
19062struct Window {
19063 char *zName; /* Name of window (may be NULL) */
19064 char *zBase; /* Name of base window for chaining (may be NULL) */
19065 ExprList *pPartition; /* PARTITION BY clause */
19066 ExprList *pOrderBy; /* ORDER BY clause */
19067 u8 eFrmType; /* TK_RANGE, TK_GROUPS, TK_ROWS, or 0 */
19068 u8 eStart; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
19069 u8 eEnd; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
19070 u8 bImplicitFrame; /* True if frame was implicitly specified */
19071 u8 eExclude; /* TK_NO, TK_CURRENT, TK_TIES, TK_GROUP, or 0 */
19072 Expr *pStart; /* Expression for "<expr> PRECEDING" */
19073 Expr *pEnd; /* Expression for "<expr> FOLLOWING" */
19074 Window **ppThis; /* Pointer to this object in Select.pWin list */
19075 Window *pNextWin; /* Next window function belonging to this SELECT */
19076 Expr *pFilter; /* The FILTER expression */
19077 FuncDef *pFunc; /* The function */
19078 int iEphCsr; /* Partition buffer or Peer buffer */
19079 int regAccum; /* Accumulator */
19080 int regResult; /* Interim result */
19081 int csrApp; /* Function cursor (used by min/max) */
19082 int regApp; /* Function register (also used by min/max) */
19083 int regPart; /* Array of registers for PARTITION BY values */
19084 Expr *pOwner; /* Expression object this window is attached to */
19085 int nBufferCol; /* Number of columns in buffer table */
19086 int iArgCol; /* Offset of first argument for this function */
19087 int regOne; /* Register containing constant value 1 */
19088 int regStartRowid;
19089 int regEndRowid;
19090 u8 bExprArgs; /* Defer evaluation of window function arguments
19091 ** due to the SQLITE_SUBTYPE flag */
19092};
19093
19094#ifndef SQLITE_OMIT_WINDOWFUNC
19095SQLITE_PRIVATE void sqlite3WindowDelete(sqlite3*, Window*);
19096SQLITE_PRIVATE void sqlite3WindowUnlinkFromSelect(Window*);
19097SQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p);
19098SQLITE_PRIVATE Window *sqlite3WindowAlloc(Parse*, int, int, Expr*, int , Expr*, u8);
19099SQLITE_PRIVATE void sqlite3WindowAttach(Parse*, Expr*, Window*);
19100SQLITE_PRIVATE void sqlite3WindowLink(Select *pSel, Window *pWin);
19101SQLITE_PRIVATE int sqlite3WindowCompare(const Parse*, const Window*, const Window*, int);
19102SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse*, Select*);
19103SQLITE_PRIVATE void sqlite3WindowCodeStep(Parse*, Select*, WhereInfo*, int, int);
19104SQLITE_PRIVATE int sqlite3WindowRewrite(Parse*, Select*);
19105SQLITE_PRIVATE void sqlite3WindowUpdate(Parse*, Window*, Window*, FuncDef*);
19106SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p);
19107SQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p);
19108SQLITE_PRIVATE void sqlite3WindowFunctions(void);
19109SQLITE_PRIVATE void sqlite3WindowChain(Parse*, Window*, Window*);
19110SQLITE_PRIVATE Window *sqlite3WindowAssemble(Parse*, Window*, ExprList*, ExprList*, Token*);
19111#else
19112# define sqlite3WindowDelete(a,b)
19113# define sqlite3WindowFunctions()
19114# define sqlite3WindowAttach(a,b,c)
19115#endif
19116
19117/*
19118** Assuming zIn points to the first byte of a UTF-8 character,
19119** advance zIn to point to the first byte of the next UTF-8 character.
19120*/
19121#define SQLITE_SKIP_UTF8(zIn) { \
19122 if( (*(zIn++))>=0xc0 ){ \
19123 while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
19124 } \
19125}
19126
19127/*
19128** The SQLITE_*_BKPT macros are substitutes for the error codes with
19129** the same name but without the _BKPT suffix. These macros invoke
19130** routines that report the line-number on which the error originated
19131** using sqlite3_log(). The routines also provide a convenient place
19132** to set a debugger breakpoint.
19133*/
19134SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType);
19135SQLITE_PRIVATE int sqlite3CorruptError(int);
19136SQLITE_PRIVATE int sqlite3MisuseError(int);
19137SQLITE_PRIVATE int sqlite3CantopenError(int);
19138#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
19139#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
19140#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
19141#ifdef SQLITE_DEBUG
19142SQLITE_PRIVATE int sqlite3NomemError(int);
19143SQLITE_PRIVATE int sqlite3IoerrnomemError(int);
19144# define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
19145# define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
19146#else
19147# define SQLITE_NOMEM_BKPT SQLITE_NOMEM
19148# define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
19149#endif
19150#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
19151SQLITE_PRIVATE int sqlite3CorruptPgnoError(int,Pgno);
19152# define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
19153#else
19154# define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)
19155#endif
19156
19157/*
19158** FTS3 and FTS4 both require virtual table support
19159*/
19160#if defined(SQLITE_OMIT_VIRTUALTABLE)
19161# undef SQLITE_ENABLE_FTS3
19162# undef SQLITE_ENABLE_FTS4
19163#endif
19164
19165/*
19166** FTS4 is really an extension for FTS3. It is enabled using the
19167** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
19168** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
19169*/
19170#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
19171# define SQLITE_ENABLE_FTS3 1
19172#endif
19173
19174/*
19175** The ctype.h header is needed for non-ASCII systems. It is also
19176** needed by FTS3 when FTS3 is included in the amalgamation.
19177*/
19178#if !defined(SQLITE_ASCII) || \
19179 (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
19180# include <ctype.h>
19181#endif
19182
19183/*
19184** The following macros mimic the standard library functions toupper(),
19185** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
19186** sqlite versions only work for ASCII characters, regardless of locale.
19187*/
19188#ifdef SQLITE_ASCII
19189# define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
19190# define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
19191# define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
19192# define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
19193# define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
19194# define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
19195# define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
19196# define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
19197#else
19198# define sqlite3Toupper(x) toupper((unsigned char)(x))
19199# define sqlite3Isspace(x) isspace((unsigned char)(x))
19200# define sqlite3Isalnum(x) isalnum((unsigned char)(x))
19201# define sqlite3Isalpha(x) isalpha((unsigned char)(x))
19202# define sqlite3Isdigit(x) isdigit((unsigned char)(x))
19203# define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
19204# define sqlite3Tolower(x) tolower((unsigned char)(x))
19205# define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
19206#endif
19207SQLITE_PRIVATE int sqlite3IsIdChar(u8);
19208
19209/*
19210** Internal function prototypes
19211*/
19212SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
19213SQLITE_PRIVATE int sqlite3Strlen30(const char*);
19214#define sqlite3Strlen30NN(C) (strlen(C)&0x3fffffff)
19215SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
19216#define sqlite3StrNICmp sqlite3_strnicmp
19217
19218SQLITE_PRIVATE int sqlite3MallocInit(void);
19219SQLITE_PRIVATE void sqlite3MallocEnd(void);
19220SQLITE_PRIVATE void *sqlite3Malloc(u64);
19221SQLITE_PRIVATE void *sqlite3MallocZero(u64);
19222SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
19223SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
19224SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
19225SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
19226SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
19227SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3*,const char*,const char*);
19228SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
19229SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
19230SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
19231SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
19232SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);
19233SQLITE_PRIVATE int sqlite3MallocSize(const void*);
19234SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, const void*);
19235SQLITE_PRIVATE void *sqlite3PageMalloc(int);
19236SQLITE_PRIVATE void sqlite3PageFree(void*);
19237SQLITE_PRIVATE void sqlite3MemSetDefault(void);
19238#ifndef SQLITE_UNTESTABLE
19239SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
19240#endif
19241SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
19242
19243/*
19244** On systems with ample stack space and that support alloca(), make
19245** use of alloca() to obtain space for large automatic objects. By default,
19246** obtain space from malloc().
19247**
19248** The alloca() routine never returns NULL. This will cause code paths
19249** that deal with sqlite3StackAlloc() failures to be unreachable.
19250*/
19251#ifdef SQLITE_USE_ALLOCA
19252# define sqlite3StackAllocRaw(D,N) alloca(N)
19253# define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
19254# define sqlite3StackFree(D,P)
19255#else
19256# define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
19257# define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
19258# define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
19259#endif
19260
19261/* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they
19262** are, disable MEMSYS3
19263*/
19264#ifdef SQLITE_ENABLE_MEMSYS5
19265SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
19266#undef SQLITE_ENABLE_MEMSYS3
19267#endif
19268#ifdef SQLITE_ENABLE_MEMSYS3
19269SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
19270#endif
19271
19272
19273#ifndef SQLITE_MUTEX_OMIT
19274SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
19275SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
19276SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
19277SQLITE_PRIVATE int sqlite3MutexInit(void);
19278SQLITE_PRIVATE int sqlite3MutexEnd(void);
19279#endif
19280#if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
19281SQLITE_PRIVATE void sqlite3MemoryBarrier(void);
19282#else
19283# define sqlite3MemoryBarrier()
19284#endif
19285
19286SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
19287SQLITE_PRIVATE void sqlite3StatusUp(int, int);
19288SQLITE_PRIVATE void sqlite3StatusDown(int, int);
19289SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
19290SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3*,int*);
19291
19292/* Access to mutexes used by sqlite3_status() */
19293SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
19294SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
19295
19296#if defined(SQLITE_ENABLE_MULTITHREADED_CHECKS) && !defined(SQLITE_MUTEX_OMIT)
19297SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex*);
19298#else
19299# define sqlite3MutexWarnOnContention(x)
19300#endif
19301
19302#ifndef SQLITE_OMIT_FLOATING_POINT
19303# define EXP754 (((u64)0x7ff)<<52)
19304# define MAN754 ((((u64)1)<<52)-1)
19305# define IsNaN(X) (((X)&EXP754)==EXP754 && ((X)&MAN754)!=0)
19306SQLITE_PRIVATE int sqlite3IsNaN(double);
19307#else
19308# define IsNaN(X) 0
19309# define sqlite3IsNaN(X) 0
19310#endif
19311
19312/*
19313** An instance of the following structure holds information about SQL
19314** functions arguments that are the parameters to the printf() function.
19315*/
19316struct PrintfArguments {
19317 int nArg; /* Total number of arguments */
19318 int nUsed; /* Number of arguments used so far */
19319 sqlite3_value **apArg; /* The argument values */
19320};
19321
19322SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
19323SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
19324#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
19325SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
19326#endif
19327#if defined(SQLITE_TEST)
19328SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
19329#endif
19330
19331#if defined(SQLITE_DEBUG)
19332SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
19333SQLITE_PRIVATE void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
19334SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
19335SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView*, const SrcList*);
19336SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
19337SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8);
19338#ifndef SQLITE_OMIT_WINDOWFUNC
19339SQLITE_PRIVATE void sqlite3TreeViewWindow(TreeView*, const Window*, u8);
19340SQLITE_PRIVATE void sqlite3TreeViewWinFunc(TreeView*, const Window*, u8);
19341#endif
19342#endif
19343
19344
19345SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
19346SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
19347SQLITE_PRIVATE int sqlite3ErrorToParser(sqlite3*,int);
19348SQLITE_PRIVATE void sqlite3Dequote(char*);
19349SQLITE_PRIVATE void sqlite3DequoteExpr(Expr*);
19350SQLITE_PRIVATE void sqlite3DequoteToken(Token*);
19351SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
19352SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
19353SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
19354SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
19355SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
19356SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
19357SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
19358SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
19359SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
19360#ifdef SQLITE_DEBUG
19361SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
19362#endif
19363SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
19364SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
19365SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
19366SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
19367SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
19368SQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse*,Expr*, Expr*);
19369SQLITE_PRIVATE Expr *sqlite3ExprSimplifiedAndOr(Expr*);
19370SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, const Token*, int);
19371SQLITE_PRIVATE void sqlite3ExprFunctionUsable(Parse*,const Expr*,const FuncDef*);
19372SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
19373SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
19374SQLITE_PRIVATE void sqlite3ExprDeferredDelete(Parse*, Expr*);
19375SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse*, Expr*);
19376SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
19377SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
19378SQLITE_PRIVATE Select *sqlite3ExprListToValues(Parse*, int, ExprList*);
19379SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int,int);
19380SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,const Token*,int);
19381SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);
19382SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
19383SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
19384SQLITE_PRIVATE int sqlite3IndexHasDuplicateRootPage(Index*);
19385SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
19386SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
19387SQLITE_PRIVATE int sqlite3InitOne(sqlite3*, int, char**, u32);
19388SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
19389#ifndef SQLITE_OMIT_VIRTUALTABLE
19390SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
19391#endif
19392SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
19393SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
19394SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
19395SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
19396SQLITE_PRIVATE void sqlite3ColumnSetExpr(Parse*,Table*,Column*,Expr*);
19397SQLITE_PRIVATE Expr *sqlite3ColumnExpr(Table*,Column*);
19398SQLITE_PRIVATE void sqlite3ColumnSetColl(sqlite3*,Column*,const char*zColl);
19399SQLITE_PRIVATE const char *sqlite3ColumnColl(Column*);
19400SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
19401SQLITE_PRIVATE void sqlite3GenerateColumnNames(Parse *pParse, Select *pSelect);
19402SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
19403SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*,char);
19404SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*,char);
19405SQLITE_PRIVATE void sqlite3OpenSchemaTable(Parse *, int);
19406SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
19407SQLITE_PRIVATE i16 sqlite3TableColumnToIndex(Index*, i16);
19408#ifdef SQLITE_OMIT_GENERATED_COLUMNS
19409# define sqlite3TableColumnToStorage(T,X) (X) /* No-op pass-through */
19410# define sqlite3StorageColumnToTable(T,X) (X) /* No-op pass-through */
19411#else
19412SQLITE_PRIVATE i16 sqlite3TableColumnToStorage(Table*, i16);
19413SQLITE_PRIVATE i16 sqlite3StorageColumnToTable(Table*, i16);
19414#endif
19415SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
19416#if SQLITE_ENABLE_HIDDEN_COLUMNS
19417SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*);
19418#else
19419# define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
19420#endif
19421SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token,Token);
19422SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
19423SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
19424SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*, const char*, const char*);
19425SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*);
19426SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
19427SQLITE_PRIVATE void sqlite3AddGenerated(Parse*,Expr*,Token*);
19428SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u32,Select*);
19429SQLITE_PRIVATE void sqlite3AddReturning(Parse*,ExprList*);
19430SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
19431 sqlite3_vfs**,char**,char **);
19432#define sqlite3CodecQueryParameters(A,B,C) 0
19433SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
19434
19435#ifdef SQLITE_UNTESTABLE
19436# define sqlite3FaultSim(X) SQLITE_OK
19437#else
19438SQLITE_PRIVATE int sqlite3FaultSim(int);
19439#endif
19440
19441SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
19442SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
19443SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
19444SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
19445SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
19446SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
19447SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
19448#ifndef SQLITE_UNTESTABLE
19449SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
19450#endif
19451
19452SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*);
19453SQLITE_PRIVATE void sqlite3RowSetDelete(void*);
19454SQLITE_PRIVATE void sqlite3RowSetClear(void*);
19455SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
19456SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
19457SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
19458
19459SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
19460
19461#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
19462SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
19463#else
19464# define sqlite3ViewGetColumnNames(A,B) 0
19465#endif
19466
19467#if SQLITE_MAX_ATTACHED>30
19468SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
19469#endif
19470SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
19471SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
19472SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
19473SQLITE_PRIVATE void sqlite3FreeIndex(sqlite3*, Index*);
19474#ifndef SQLITE_OMIT_AUTOINCREMENT
19475SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
19476SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
19477#else
19478# define sqlite3AutoincrementBegin(X)
19479# define sqlite3AutoincrementEnd(X)
19480#endif
19481SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int, Upsert*);
19482#ifndef SQLITE_OMIT_GENERATED_COLUMNS
19483SQLITE_PRIVATE void sqlite3ComputeGeneratedColumns(Parse*, int, Table*);
19484#endif
19485SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
19486SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse*, IdList*, Token*);
19487SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
19488SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(Parse*, SrcList*, int, int);
19489SQLITE_PRIVATE SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2);
19490SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(Parse*, SrcList*, Token*, Token*);
19491SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
19492 Token*, Select*, Expr*, IdList*);
19493SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
19494SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
19495SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, SrcItem *);
19496SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
19497SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
19498SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
19499SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
19500SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
19501SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
19502 Expr*, int, int, u8);
19503SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
19504SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
19505SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
19506 Expr*,ExprList*,u32,Expr*);
19507SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
19508SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
19509SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
19510SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
19511#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
19512SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);
19513#endif
19514SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*);
19515SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*,
19516 Upsert*);
19517SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
19518SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
19519SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
19520SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
19521SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
19522SQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo*);
19523SQLITE_PRIVATE void sqlite3WhereMinMaxOptEarlyOut(Vdbe*,WhereInfo*);
19524SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
19525SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
19526SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
19527SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
19528#define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
19529#define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
19530#define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
19531SQLITE_PRIVATE int sqlite3WhereUsesDeferredSeek(WhereInfo*);
19532SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
19533SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
19534SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
19535SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
19536SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
19537#ifndef SQLITE_OMIT_GENERATED_COLUMNS
19538SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(Parse*, Table*, Column*, int);
19539#endif
19540SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
19541SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
19542SQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce(Parse*, Expr*, int);
19543SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
19544SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
19545SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
19546#define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
19547#define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
19548#define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
19549#define SQLITE_ECEL_OMITREF 0x08 /* Omit if ExprList.u.x.iOrderByCol */
19550SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
19551SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
19552SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
19553SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
19554#define LOCATE_VIEW 0x01
19555#define LOCATE_NOERR 0x02
19556SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
19557SQLITE_PRIVATE const char *sqlite3PreferredTableName(const char*);
19558SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,SrcItem *);
19559SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
19560SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
19561SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
19562SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*,Expr*);
19563SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int, sqlite3_value*);
19564SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, const Token*);
19565SQLITE_PRIVATE int sqlite3ExprCompare(const Parse*,const Expr*,const Expr*, int);
19566SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*,Expr*,int);
19567SQLITE_PRIVATE int sqlite3ExprListCompare(const ExprList*,const ExprList*, int);
19568SQLITE_PRIVATE int sqlite3ExprImpliesExpr(const Parse*,const Expr*,const Expr*, int);
19569SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr*,int);
19570SQLITE_PRIVATE void sqlite3AggInfoPersistWalkerInit(Walker*,Parse*);
19571SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
19572SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
19573SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
19574SQLITE_PRIVATE int sqlite3ReferencesSrcList(Parse*, Expr*, SrcList*);
19575SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
19576#ifndef SQLITE_UNTESTABLE
19577SQLITE_PRIVATE void sqlite3PrngSaveState(void);
19578SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
19579#endif
19580SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
19581SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
19582SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
19583SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
19584SQLITE_PRIVATE void sqlite3EndTransaction(Parse*,int);
19585SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
19586SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
19587SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
19588SQLITE_PRIVATE u32 sqlite3IsTrueOrFalse(const char*);
19589SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr*);
19590SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr*);
19591SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
19592SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
19593SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
19594SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
19595SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
19596#ifdef SQLITE_ENABLE_CURSOR_HINTS
19597SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
19598#endif
19599SQLITE_PRIVATE int sqlite3ExprIsInteger(const Expr*, int*);
19600SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
19601SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
19602SQLITE_PRIVATE int sqlite3IsRowid(const char*);
19603SQLITE_PRIVATE void sqlite3GenerateRowDelete(
19604 Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
19605SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
19606SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
19607SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
19608SQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(Expr*,int*,int);
19609SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
19610 u8,u8,int,int*,int*,Upsert*);
19611#ifdef SQLITE_ENABLE_NULL_TRIM
19612SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe*,Table*);
19613#else
19614# define sqlite3SetMakeRecordP5(A,B)
19615#endif
19616SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
19617SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
19618SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
19619SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
19620SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
19621SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
19622SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
19623SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
19624SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,const Expr*,int);
19625SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,const ExprList*,int);
19626SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,const SrcList*,int);
19627SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,const IdList*);
19628SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,const Select*,int);
19629SQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(int,const char*);
19630SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
19631SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
19632SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
19633SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
19634SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
19635SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
19636SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
19637SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
19638SQLITE_PRIVATE With *sqlite3WithDup(sqlite3 *db, With *p);
19639
19640#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
19641SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int);
19642#endif
19643
19644#ifndef SQLITE_OMIT_TRIGGER
19645SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
19646 Expr*,int, int);
19647SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
19648SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
19649SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
19650SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
19651SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
19652SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
19653 int, int, int);
19654SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
19655 void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
19656SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
19657SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*,
19658 const char*,const char*);
19659SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(Parse*,Token*, IdList*,
19660 Select*,u8,Upsert*,
19661 const char*,const char*);
19662SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(Parse*,Token*,SrcList*,ExprList*,
19663 Expr*, u8, const char*,const char*);
19664SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(Parse*,Token*, Expr*,
19665 const char*,const char*);
19666SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
19667SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
19668SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
19669SQLITE_PRIVATE SrcList *sqlite3TriggerStepSrc(Parse*, TriggerStep*);
19670# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
19671# define sqlite3IsToplevel(p) ((p)->pToplevel==0)
19672#else
19673# define sqlite3TriggersExist(B,C,D,E,F) 0
19674# define sqlite3DeleteTrigger(A,B)
19675# define sqlite3DropTriggerPtr(A,B)
19676# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
19677# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
19678# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
19679# define sqlite3TriggerList(X, Y) 0
19680# define sqlite3ParseToplevel(p) p
19681# define sqlite3IsToplevel(p) 1
19682# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
19683# define sqlite3TriggerStepSrc(A,B) 0
19684#endif
19685
19686SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
19687SQLITE_PRIVATE int sqlite3ColumnIndex(Table *pTab, const char *zCol);
19688SQLITE_PRIVATE void sqlite3SetJoinExpr(Expr*,int);
19689SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
19690SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
19691#ifndef SQLITE_OMIT_AUTHORIZATION
19692SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
19693SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
19694SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
19695SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
19696SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
19697#else
19698# define sqlite3AuthRead(a,b,c,d)
19699# define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
19700# define sqlite3AuthContextPush(a,b,c)
19701# define sqlite3AuthContextPop(a) ((void)(a))
19702#endif
19703SQLITE_PRIVATE int sqlite3DbIsNamed(sqlite3 *db, int iDb, const char *zName);
19704SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
19705SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
19706SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
19707SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
19708SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
19709SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
19710SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
19711SQLITE_PRIVATE int sqlite3RealSameAsInt(double,sqlite3_int64);
19712SQLITE_PRIVATE void sqlite3Int64ToText(i64,char*);
19713SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
19714SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
19715SQLITE_PRIVATE int sqlite3GetUInt32(const char*, u32*);
19716SQLITE_PRIVATE int sqlite3Atoi(const char*);
19717#ifndef SQLITE_OMIT_UTF16
19718SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
19719#endif
19720SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
19721SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
19722SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
19723SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
19724#ifndef SQLITE_OMIT_VIRTUALTABLE
19725SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
19726#endif
19727#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
19728 defined(SQLITE_ENABLE_STAT4) || \
19729 defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
19730SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
19731#endif
19732SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
19733SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);
19734SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);
19735
19736/*
19737** Routines to read and write variable-length integers. These used to
19738** be defined locally, but now we use the varint routines in the util.c
19739** file.
19740*/
19741SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
19742SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
19743SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
19744SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
19745
19746/*
19747** The common case is for a varint to be a single byte. They following
19748** macros handle the common case without a procedure call, but then call
19749** the procedure for larger varints.
19750*/
19751#define getVarint32(A,B) \
19752 (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
19753#define getVarint32NR(A,B) \
19754 B=(u32)*(A);if(B>=0x80)sqlite3GetVarint32((A),(u32*)&(B))
19755#define putVarint32(A,B) \
19756 (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
19757 sqlite3PutVarint((A),(B)))
19758#define getVarint sqlite3GetVarint
19759#define putVarint sqlite3PutVarint
19760
19761
19762SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
19763SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
19764SQLITE_PRIVATE char sqlite3CompareAffinity(const Expr *pExpr, char aff2);
19765SQLITE_PRIVATE int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity);
19766SQLITE_PRIVATE char sqlite3TableColumnAffinity(const Table*,int);
19767SQLITE_PRIVATE char sqlite3ExprAffinity(const Expr *pExpr);
19768SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
19769SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
19770SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
19771SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
19772SQLITE_PRIVATE void sqlite3ErrorClear(sqlite3*);
19773SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
19774SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
19775SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
19776SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
19777
19778#if defined(SQLITE_NEED_ERR_NAME)
19779SQLITE_PRIVATE const char *sqlite3ErrName(int);
19780#endif
19781
19782#ifndef SQLITE_OMIT_DESERIALIZE
19783SQLITE_PRIVATE int sqlite3MemdbInit(void);
19784#endif
19785
19786SQLITE_PRIVATE const char *sqlite3ErrStr(int);
19787SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
19788SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
19789SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq*);
19790SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
19791SQLITE_PRIVATE void sqlite3SetTextEncoding(sqlite3 *db, u8);
19792SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr);
19793SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr);
19794SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,const Expr*,const Expr*);
19795SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(const Parse *pParse, Expr*, const Token*, int);
19796SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(const Parse*,Expr*,const char*);
19797SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
19798SQLITE_PRIVATE Expr *sqlite3ExprSkipCollateAndLikely(Expr*);
19799SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
19800SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3*);
19801SQLITE_PRIVATE int sqlite3CheckObjectName(Parse*, const char*,const char*,const char*);
19802SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, i64);
19803SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
19804SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
19805SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
19806SQLITE_PRIVATE int sqlite3AbsInt32(int);
19807#ifdef SQLITE_ENABLE_8_3_NAMES
19808SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
19809#else
19810# define sqlite3FileSuffix3(X,Y)
19811#endif
19812SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
19813
19814SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
19815SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
19816SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
19817 void(*)(void*));
19818SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
19819SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
19820#ifndef SQLITE_UNTESTABLE
19821SQLITE_PRIVATE void sqlite3ResultIntReal(sqlite3_context*);
19822#endif
19823SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
19824#ifndef SQLITE_OMIT_UTF16
19825SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
19826#endif
19827SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, const Expr *, u8, u8, sqlite3_value **);
19828SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
19829#ifndef SQLITE_AMALGAMATION
19830SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
19831SQLITE_PRIVATE const char sqlite3StrBINARY[];
19832SQLITE_PRIVATE const unsigned char sqlite3StdTypeLen[];
19833SQLITE_PRIVATE const char sqlite3StdTypeAffinity[];
19834SQLITE_PRIVATE const char sqlite3StdTypeMap[];
19835SQLITE_PRIVATE const char *sqlite3StdType[];
19836SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
19837SQLITE_PRIVATE const unsigned char *sqlite3aLTb;
19838SQLITE_PRIVATE const unsigned char *sqlite3aEQb;
19839SQLITE_PRIVATE const unsigned char *sqlite3aGTb;
19840SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
19841SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
19842SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
19843#ifndef SQLITE_OMIT_WSD
19844SQLITE_PRIVATE int sqlite3PendingByte;
19845#endif
19846#endif /* SQLITE_AMALGAMATION */
19847#ifdef VDBE_PROFILE
19848SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt;
19849#endif
19850SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, Pgno, Pgno);
19851SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
19852SQLITE_PRIVATE void sqlite3AlterFunctions(void);
19853SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
19854SQLITE_PRIVATE void sqlite3AlterRenameColumn(Parse*, SrcList*, Token*, Token*);
19855SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
19856SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
19857SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*, int);
19858SQLITE_PRIVATE void sqlite3CodeRhsOfIN(Parse*, Expr*, int);
19859SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr*);
19860SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
19861SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse*, SrcItem*);
19862SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
19863SQLITE_PRIVATE int sqlite3MatchEName(
19864 const struct ExprList_item*,
19865 const char*,
19866 const char*,
19867 const char*
19868);
19869SQLITE_PRIVATE Bitmask sqlite3ExprColUsed(Expr*);
19870SQLITE_PRIVATE u8 sqlite3StrIHash(const char*);
19871SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
19872SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
19873SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
19874SQLITE_PRIVATE int sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
19875SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
19876SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
19877SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
19878SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
19879SQLITE_PRIVATE void sqlite3AlterDropColumn(Parse*, SrcList*, const Token*);
19880SQLITE_PRIVATE const void *sqlite3RenameTokenMap(Parse*, const void*, const Token*);
19881SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse*, const void *pTo, const void *pFrom);
19882SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse*, Expr*);
19883SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse*, ExprList*);
19884SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
19885SQLITE_PRIVATE char sqlite3AffinityType(const char*, Column*);
19886SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
19887SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
19888SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
19889SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
19890SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
19891SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
19892SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
19893SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
19894SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
19895SQLITE_PRIVATE void sqlite3SchemaClear(void *);
19896SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
19897SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
19898SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
19899SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
19900SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
19901SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
19902SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList(Parse*, ExprList*, int, int);
19903SQLITE_PRIVATE const char *sqlite3SelectOpName(int);
19904SQLITE_PRIVATE int sqlite3HasExplicitNulls(Parse*, ExprList*);
19905
19906#ifdef SQLITE_DEBUG
19907SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
19908#endif
19909SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
19910 void (*)(sqlite3_context*,int,sqlite3_value **),
19911 void (*)(sqlite3_context*,int,sqlite3_value **),
19912 void (*)(sqlite3_context*),
19913 void (*)(sqlite3_context*),
19914 void (*)(sqlite3_context*,int,sqlite3_value **),
19915 FuncDestructor *pDestructor
19916);
19917SQLITE_PRIVATE void sqlite3NoopDestructor(void*);
19918SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
19919SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
19920SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
19921SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
19922
19923SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
19924SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
19925SQLITE_PRIVATE void sqlite3StrAccumSetError(StrAccum*, u8);
19926SQLITE_PRIVATE void sqlite3ResultStrAccum(sqlite3_context*,StrAccum*);
19927SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
19928SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
19929
19930SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
19931SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
19932
19933#ifndef SQLITE_OMIT_SUBQUERY
19934SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);
19935#else
19936# define sqlite3ExprCheckIN(x,y) SQLITE_OK
19937#endif
19938
19939#ifdef SQLITE_ENABLE_STAT4
19940SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
19941 Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
19942SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
19943SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
19944SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
19945SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
19946#endif
19947
19948/*
19949** The interface to the LEMON-generated parser
19950*/
19951#ifndef SQLITE_AMALGAMATION
19952SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64), Parse*);
19953SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
19954#endif
19955SQLITE_PRIVATE void sqlite3Parser(void*, int, Token);
19956SQLITE_PRIVATE int sqlite3ParserFallback(int);
19957#ifdef YYTRACKMAXSTACKDEPTH
19958SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
19959#endif
19960
19961SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
19962#ifndef SQLITE_OMIT_LOAD_EXTENSION
19963SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
19964#else
19965# define sqlite3CloseExtensions(X)
19966#endif
19967
19968#ifndef SQLITE_OMIT_SHARED_CACHE
19969SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, Pgno, u8, const char *);
19970#else
19971 #define sqlite3TableLock(v,w,x,y,z)
19972#endif
19973
19974#ifdef SQLITE_TEST
19975SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
19976#endif
19977
19978#ifdef SQLITE_OMIT_VIRTUALTABLE
19979# define sqlite3VtabClear(D,T)
19980# define sqlite3VtabSync(X,Y) SQLITE_OK
19981# define sqlite3VtabRollback(X)
19982# define sqlite3VtabCommit(X)
19983# define sqlite3VtabInSync(db) 0
19984# define sqlite3VtabLock(X)
19985# define sqlite3VtabUnlock(X)
19986# define sqlite3VtabModuleUnref(D,X)
19987# define sqlite3VtabUnlockList(X)
19988# define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
19989# define sqlite3GetVTable(X,Y) ((VTable*)0)
19990#else
19991SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
19992SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
19993SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
19994SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
19995SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
19996SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
19997SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
19998SQLITE_PRIVATE void sqlite3VtabModuleUnref(sqlite3*,Module*);
19999SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
20000SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
20001SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
20002SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
20003SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
20004 sqlite3*,
20005 const char*,
20006 const sqlite3_module*,
20007 void*,
20008 void(*)(void*)
20009 );
20010# define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
20011#endif
20012SQLITE_PRIVATE int sqlite3ReadOnlyShadowTables(sqlite3 *db);
20013#ifndef SQLITE_OMIT_VIRTUALTABLE
20014SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName);
20015SQLITE_PRIVATE int sqlite3IsShadowTableOf(sqlite3*,Table*,const char*);
20016SQLITE_PRIVATE void sqlite3MarkAllShadowTablesOf(sqlite3*, Table*);
20017#else
20018# define sqlite3ShadowTableName(A,B) 0
20019# define sqlite3IsShadowTableOf(A,B,C) 0
20020# define sqlite3MarkAllShadowTablesOf(A,B)
20021#endif
20022SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
20023SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
20024SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
20025SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
20026SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
20027SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
20028SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
20029SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
20030SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
20031SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
20032SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
20033SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
20034SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
20035SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
20036SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
20037SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
20038SQLITE_PRIVATE void *sqlite3ParserAddCleanup(Parse*,void(*)(sqlite3*,void*),void*);
20039#ifdef SQLITE_ENABLE_NORMALIZE
20040SQLITE_PRIVATE char *sqlite3Normalize(Vdbe*, const char*);
20041#endif
20042SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
20043SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
20044SQLITE_PRIVATE CollSeq *sqlite3ExprCompareCollSeq(Parse*,const Expr*);
20045SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, const Expr*, const Expr*);
20046SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
20047SQLITE_PRIVATE const char *sqlite3JournalModename(int);
20048#ifndef SQLITE_OMIT_WAL
20049SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
20050SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
20051#endif
20052#ifndef SQLITE_OMIT_CTE
20053SQLITE_PRIVATE Cte *sqlite3CteNew(Parse*,Token*,ExprList*,Select*,u8);
20054SQLITE_PRIVATE void sqlite3CteDelete(sqlite3*,Cte*);
20055SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Cte*);
20056SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
20057SQLITE_PRIVATE With *sqlite3WithPush(Parse*, With*, u8);
20058#else
20059# define sqlite3CteNew(P,T,E,S) ((void*)0)
20060# define sqlite3CteDelete(D,C)
20061# define sqlite3CteWithAdd(P,W,C) ((void*)0)
20062# define sqlite3WithDelete(x,y)
20063# define sqlite3WithPush(x,y,z) ((void*)0)
20064#endif
20065#ifndef SQLITE_OMIT_UPSERT
20066SQLITE_PRIVATE Upsert *sqlite3UpsertNew(sqlite3*,ExprList*,Expr*,ExprList*,Expr*,Upsert*);
20067SQLITE_PRIVATE void sqlite3UpsertDelete(sqlite3*,Upsert*);
20068SQLITE_PRIVATE Upsert *sqlite3UpsertDup(sqlite3*,Upsert*);
20069SQLITE_PRIVATE int sqlite3UpsertAnalyzeTarget(Parse*,SrcList*,Upsert*);
20070SQLITE_PRIVATE void sqlite3UpsertDoUpdate(Parse*,Upsert*,Table*,Index*,int);
20071SQLITE_PRIVATE Upsert *sqlite3UpsertOfIndex(Upsert*,Index*);
20072SQLITE_PRIVATE int sqlite3UpsertNextIsIPK(Upsert*);
20073#else
20074#define sqlite3UpsertNew(u,v,w,x,y,z) ((Upsert*)0)
20075#define sqlite3UpsertDelete(x,y)
20076#define sqlite3UpsertDup(x,y) ((Upsert*)0)
20077#define sqlite3UpsertOfIndex(x,y) ((Upsert*)0)
20078#define sqlite3UpsertNextIsIPK(x) 0
20079#endif
20080
20081
20082/* Declarations for functions in fkey.c. All of these are replaced by
20083** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
20084** key functionality is available. If OMIT_TRIGGER is defined but
20085** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
20086** this case foreign keys are parsed, but no other functionality is
20087** provided (enforcement of FK constraints requires the triggers sub-system).
20088*/
20089#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
20090SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
20091SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
20092SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
20093SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
20094SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
20095SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
20096SQLITE_PRIVATE void sqlite3FkClearTriggerCache(sqlite3*,int);
20097#else
20098 #define sqlite3FkActions(a,b,c,d,e,f)
20099 #define sqlite3FkCheck(a,b,c,d,e,f)
20100 #define sqlite3FkDropTable(a,b,c)
20101 #define sqlite3FkOldmask(a,b) 0
20102 #define sqlite3FkRequired(a,b,c,d) 0
20103 #define sqlite3FkReferences(a) 0
20104 #define sqlite3FkClearTriggerCache(a,b)
20105#endif
20106#ifndef SQLITE_OMIT_FOREIGN_KEY
20107SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
20108SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
20109#else
20110 #define sqlite3FkDelete(a,b)
20111 #define sqlite3FkLocateIndex(a,b,c,d,e)
20112#endif
20113
20114
20115/*
20116** Available fault injectors. Should be numbered beginning with 0.
20117*/
20118#define SQLITE_FAULTINJECTOR_MALLOC 0
20119#define SQLITE_FAULTINJECTOR_COUNT 1
20120
20121/*
20122** The interface to the code in fault.c used for identifying "benign"
20123** malloc failures. This is only present if SQLITE_UNTESTABLE
20124** is not defined.
20125*/
20126#ifndef SQLITE_UNTESTABLE
20127SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
20128SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
20129#else
20130 #define sqlite3BeginBenignMalloc()
20131 #define sqlite3EndBenignMalloc()
20132#endif
20133
20134/*
20135** Allowed return values from sqlite3FindInIndex()
20136*/
20137#define IN_INDEX_ROWID 1 /* Search the rowid of the table */
20138#define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
20139#define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
20140#define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
20141#define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
20142/*
20143** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
20144*/
20145#define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
20146#define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
20147#define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
20148SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*, int*);
20149
20150SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
20151SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
20152#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
20153 || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
20154SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
20155#endif
20156
20157SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
20158SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
20159
20160SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
20161#if SQLITE_MAX_EXPR_DEPTH>0
20162SQLITE_PRIVATE int sqlite3SelectExprHeight(const Select *);
20163SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
20164#else
20165 #define sqlite3SelectExprHeight(x) 0
20166 #define sqlite3ExprCheckHeight(x,y)
20167#endif
20168
20169SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
20170SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
20171
20172#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
20173SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
20174SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
20175SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
20176#else
20177 #define sqlite3ConnectionBlocked(x,y)
20178 #define sqlite3ConnectionUnlocked(x)
20179 #define sqlite3ConnectionClosed(x)
20180#endif
20181
20182#ifdef SQLITE_DEBUG
20183SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
20184#endif
20185#if defined(YYCOVERAGE)
20186SQLITE_PRIVATE int sqlite3ParserCoverage(FILE*);
20187#endif
20188
20189/*
20190** If the SQLITE_ENABLE IOTRACE exists then the global variable
20191** sqlite3IoTrace is a pointer to a printf-like routine used to
20192** print I/O tracing messages.
20193*/
20194#ifdef SQLITE_ENABLE_IOTRACE
20195# define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
20196SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
20197SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
20198#else
20199# define IOTRACE(A)
20200# define sqlite3VdbeIOTraceSql(X)
20201#endif
20202
20203/*
20204** These routines are available for the mem2.c debugging memory allocator
20205** only. They are used to verify that different "types" of memory
20206** allocations are properly tracked by the system.
20207**
20208** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
20209** the MEMTYPE_* macros defined below. The type must be a bitmask with
20210** a single bit set.
20211**
20212** sqlite3MemdebugHasType() returns true if any of the bits in its second
20213** argument match the type set by the previous sqlite3MemdebugSetType().
20214** sqlite3MemdebugHasType() is intended for use inside assert() statements.
20215**
20216** sqlite3MemdebugNoType() returns true if none of the bits in its second
20217** argument match the type set by the previous sqlite3MemdebugSetType().
20218**
20219** Perhaps the most important point is the difference between MEMTYPE_HEAP
20220** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
20221** it might have been allocated by lookaside, except the allocation was
20222** too large or lookaside was already full. It is important to verify
20223** that allocations that might have been satisfied by lookaside are not
20224** passed back to non-lookaside free() routines. Asserts such as the
20225** example above are placed on the non-lookaside free() routines to verify
20226** this constraint.
20227**
20228** All of this is no-op for a production build. It only comes into
20229** play when the SQLITE_MEMDEBUG compile-time option is used.
20230*/
20231#ifdef SQLITE_MEMDEBUG
20232SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
20233SQLITE_PRIVATE int sqlite3MemdebugHasType(const void*,u8);
20234SQLITE_PRIVATE int sqlite3MemdebugNoType(const void*,u8);
20235#else
20236# define sqlite3MemdebugSetType(X,Y) /* no-op */
20237# define sqlite3MemdebugHasType(X,Y) 1
20238# define sqlite3MemdebugNoType(X,Y) 1
20239#endif
20240#define MEMTYPE_HEAP 0x01 /* General heap allocations */
20241#define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
20242#define MEMTYPE_PCACHE 0x04 /* Page cache allocations */
20243
20244/*
20245** Threading interface
20246*/
20247#if SQLITE_MAX_WORKER_THREADS>0
20248SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
20249SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
20250#endif
20251
20252#if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)
20253SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3*);
20254#endif
20255#if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
20256SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
20257#endif
20258
20259SQLITE_PRIVATE int sqlite3ExprVectorSize(const Expr *pExpr);
20260SQLITE_PRIVATE int sqlite3ExprIsVector(const Expr *pExpr);
20261SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
20262SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int,int);
20263SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);
20264
20265#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
20266SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt);
20267#endif
20268
20269#endif /* SQLITEINT_H */
20270
20271/************** End of sqliteInt.h *******************************************/
20272/************** Begin file os_common.h ***************************************/
20273/*
20274** 2004 May 22
20275**
20276** The author disclaims copyright to this source code. In place of
20277** a legal notice, here is a blessing:
20278**
20279** May you do good and not evil.
20280** May you find forgiveness for yourself and forgive others.
20281** May you share freely, never taking more than you give.
20282**
20283******************************************************************************
20284**
20285** This file contains macros and a little bit of code that is common to
20286** all of the platform-specific files (os_*.c) and is #included into those
20287** files.
20288**
20289** This file should be #included by the os_*.c files only. It is not a
20290** general purpose header file.
20291*/
20292#ifndef _OS_COMMON_H_
20293#define _OS_COMMON_H_
20294
20295/*
20296** At least two bugs have slipped in because we changed the MEMORY_DEBUG
20297** macro to SQLITE_DEBUG and some older makefiles have not yet made the
20298** switch. The following code should catch this problem at compile-time.
20299*/
20300#ifdef MEMORY_DEBUG
20301# error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
20302#endif
20303
20304/*
20305** Macros for performance tracing. Normally turned off. Only works
20306** on i486 hardware.
20307*/
20308#ifdef SQLITE_PERFORMANCE_TRACE
20309
20310/*
20311** hwtime.h contains inline assembler code for implementing
20312** high-performance timing routines.
20313*/
20314/************** Include hwtime.h in the middle of os_common.h ****************/
20315/************** Begin file hwtime.h ******************************************/
20316/*
20317** 2008 May 27
20318**
20319** The author disclaims copyright to this source code. In place of
20320** a legal notice, here is a blessing:
20321**
20322** May you do good and not evil.
20323** May you find forgiveness for yourself and forgive others.
20324** May you share freely, never taking more than you give.
20325**
20326******************************************************************************
20327**
20328** This file contains inline asm code for retrieving "high-performance"
20329** counters for x86 and x86_64 class CPUs.
20330*/
20331#ifndef SQLITE_HWTIME_H
20332#define SQLITE_HWTIME_H
20333
20334/*
20335** The following routine only works on pentium-class (or newer) processors.
20336** It uses the RDTSC opcode to read the cycle count value out of the
20337** processor and returns that value. This can be used for high-res
20338** profiling.
20339*/
20340#if !defined(__STRICT_ANSI__) && \
20341 (defined(__GNUC__) || defined(_MSC_VER)) && \
20342 (defined(i386) || defined(__i386__) || defined(_M_IX86))
20343
20344 #if defined(__GNUC__)
20345
20346 __inline__ sqlite_uint64 sqlite3Hwtime(void){
20347 unsigned int lo, hi;
20348 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
20349 return (sqlite_uint64)hi << 32 | lo;
20350 }
20351
20352 #elif defined(_MSC_VER)
20353
20354 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
20355 __asm {
20356 rdtsc
20357 ret ; return value at EDX:EAX
20358 }
20359 }
20360
20361 #endif
20362
20363#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))
20364
20365 __inline__ sqlite_uint64 sqlite3Hwtime(void){
20366 unsigned long val;
20367 __asm__ __volatile__ ("rdtsc" : "=A" (val));
20368 return val;
20369 }
20370
20371#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))
20372
20373 __inline__ sqlite_uint64 sqlite3Hwtime(void){
20374 unsigned long long retval;
20375 unsigned long junk;
20376 __asm__ __volatile__ ("\n\
20377 1: mftbu %1\n\
20378 mftb %L0\n\
20379 mftbu %0\n\
20380 cmpw %0,%1\n\
20381 bne 1b"
20382 : "=r" (retval), "=r" (junk));
20383 return retval;
20384 }
20385
20386#else
20387
20388 /*
20389 ** asm() is needed for hardware timing support. Without asm(),
20390 ** disable the sqlite3Hwtime() routine.
20391 **
20392 ** sqlite3Hwtime() is only used for some obscure debugging
20393 ** and analysis configurations, not in any deliverable, so this
20394 ** should not be a great loss.
20395 */
20396SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
20397
20398#endif
20399
20400#endif /* !defined(SQLITE_HWTIME_H) */
20401
20402/************** End of hwtime.h **********************************************/
20403/************** Continuing where we left off in os_common.h ******************/
20404
20405static sqlite_uint64 g_start;
20406static sqlite_uint64 g_elapsed;
20407#define TIMER_START g_start=sqlite3Hwtime()
20408#define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
20409#define TIMER_ELAPSED g_elapsed
20410#else
20411#define TIMER_START
20412#define TIMER_END
20413#define TIMER_ELAPSED ((sqlite_uint64)0)
20414#endif
20415
20416/*
20417** If we compile with the SQLITE_TEST macro set, then the following block
20418** of code will give us the ability to simulate a disk I/O error. This
20419** is used for testing the I/O recovery logic.
20420*/
20421#if defined(SQLITE_TEST)
20422SQLITE_API extern int sqlite3_io_error_hit;
20423SQLITE_API extern int sqlite3_io_error_hardhit;
20424SQLITE_API extern int sqlite3_io_error_pending;
20425SQLITE_API extern int sqlite3_io_error_persist;
20426SQLITE_API extern int sqlite3_io_error_benign;
20427SQLITE_API extern int sqlite3_diskfull_pending;
20428SQLITE_API extern int sqlite3_diskfull;
20429#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
20430#define SimulateIOError(CODE) \
20431 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
20432 || sqlite3_io_error_pending-- == 1 ) \
20433 { local_ioerr(); CODE; }
20434static void local_ioerr(){
20435 IOTRACE(("IOERR\n"));
20436 sqlite3_io_error_hit++;
20437 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
20438}
20439#define SimulateDiskfullError(CODE) \
20440 if( sqlite3_diskfull_pending ){ \
20441 if( sqlite3_diskfull_pending == 1 ){ \
20442 local_ioerr(); \
20443 sqlite3_diskfull = 1; \
20444 sqlite3_io_error_hit = 1; \
20445 CODE; \
20446 }else{ \
20447 sqlite3_diskfull_pending--; \
20448 } \
20449 }
20450#else
20451#define SimulateIOErrorBenign(X)
20452#define SimulateIOError(A)
20453#define SimulateDiskfullError(A)
20454#endif /* defined(SQLITE_TEST) */
20455
20456/*
20457** When testing, keep a count of the number of open files.
20458*/
20459#if defined(SQLITE_TEST)
20460SQLITE_API extern int sqlite3_open_file_count;
20461#define OpenCounter(X) sqlite3_open_file_count+=(X)
20462#else
20463#define OpenCounter(X)
20464#endif /* defined(SQLITE_TEST) */
20465
20466#endif /* !defined(_OS_COMMON_H_) */
20467
20468/************** End of os_common.h *******************************************/
20469/************** Begin file ctime.c *******************************************/
20470/*
20471** 2010 February 23
20472**
20473** The author disclaims copyright to this source code. In place of
20474** a legal notice, here is a blessing:
20475**
20476** May you do good and not evil.
20477** May you find forgiveness for yourself and forgive others.
20478** May you share freely, never taking more than you give.
20479**
20480*************************************************************************
20481**
20482** This file implements routines used to report what compile-time options
20483** SQLite was built with.
20484*/
20485#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS /* IMP: R-16824-07538 */
20486
20487/*
20488** Include the configuration header output by 'configure' if we're using the
20489** autoconf-based build
20490*/
20491#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
20492/* #include "config.h" */
20493#define SQLITECONFIG_H 1
20494#endif
20495
20496/* These macros are provided to "stringify" the value of the define
20497** for those options in which the value is meaningful. */
20498#define CTIMEOPT_VAL_(opt) #opt
20499#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
20500
20501/* Like CTIMEOPT_VAL, but especially for SQLITE_DEFAULT_LOOKASIDE. This
20502** option requires a separate macro because legal values contain a single
20503** comma. e.g. (-DSQLITE_DEFAULT_LOOKASIDE="100,100") */
20504#define CTIMEOPT_VAL2_(opt1,opt2) #opt1 "," #opt2
20505#define CTIMEOPT_VAL2(opt) CTIMEOPT_VAL2_(opt)
20506/* #include "sqliteInt.h" */
20507
20508/*
20509** An array of names of all compile-time options. This array should
20510** be sorted A-Z.
20511**
20512** This array looks large, but in a typical installation actually uses
20513** only a handful of compile-time options, so most times this array is usually
20514** rather short and uses little memory space.
20515*/
20516static const char * const sqlite3azCompileOpt[] = {
20517
20518/*
20519** BEGIN CODE GENERATED BY tool/mkctime.tcl
20520*/
20521#ifdef SQLITE_32BIT_ROWID
20522 "32BIT_ROWID",
20523#endif
20524#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
20525 "4_BYTE_ALIGNED_MALLOC",
20526#endif
20527#ifdef SQLITE_64BIT_STATS
20528 "64BIT_STATS",
20529#endif
20530#ifdef SQLITE_ALLOW_COVERING_INDEX_SCAN
20531# if SQLITE_ALLOW_COVERING_INDEX_SCAN != 1
20532 "ALLOW_COVERING_INDEX_SCAN=" CTIMEOPT_VAL(SQLITE_ALLOW_COVERING_INDEX_SCAN),
20533# endif
20534#endif
20535#ifdef SQLITE_ALLOW_URI_AUTHORITY
20536 "ALLOW_URI_AUTHORITY",
20537#endif
20538#ifdef SQLITE_ATOMIC_INTRINSICS
20539 "ATOMIC_INTRINSICS=" CTIMEOPT_VAL(SQLITE_ATOMIC_INTRINSICS),
20540#endif
20541#ifdef SQLITE_BITMASK_TYPE
20542 "BITMASK_TYPE=" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE),
20543#endif
20544#ifdef SQLITE_BUG_COMPATIBLE_20160819
20545 "BUG_COMPATIBLE_20160819",
20546#endif
20547#ifdef SQLITE_CASE_SENSITIVE_LIKE
20548 "CASE_SENSITIVE_LIKE",
20549#endif
20550#ifdef SQLITE_CHECK_PAGES
20551 "CHECK_PAGES",
20552#endif
20553#if defined(__clang__) && defined(__clang_major__)
20554 "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
20555 CTIMEOPT_VAL(__clang_minor__) "."
20556 CTIMEOPT_VAL(__clang_patchlevel__),
20557#elif defined(_MSC_VER)
20558 "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
20559#elif defined(__GNUC__) && defined(__VERSION__)
20560 "COMPILER=gcc-" __VERSION__,
20561#endif
20562#ifdef SQLITE_COVERAGE_TEST
20563 "COVERAGE_TEST",
20564#endif
20565#ifdef SQLITE_DEBUG
20566 "DEBUG",
20567#endif
20568#ifdef SQLITE_DEFAULT_AUTOMATIC_INDEX
20569 "DEFAULT_AUTOMATIC_INDEX",
20570#endif
20571#ifdef SQLITE_DEFAULT_AUTOVACUUM
20572 "DEFAULT_AUTOVACUUM",
20573#endif
20574#ifdef SQLITE_DEFAULT_CACHE_SIZE
20575 "DEFAULT_CACHE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE),
20576#endif
20577#ifdef SQLITE_DEFAULT_CKPTFULLFSYNC
20578 "DEFAULT_CKPTFULLFSYNC",
20579#endif
20580#ifdef SQLITE_DEFAULT_FILE_FORMAT
20581 "DEFAULT_FILE_FORMAT=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT),
20582#endif
20583#ifdef SQLITE_DEFAULT_FILE_PERMISSIONS
20584 "DEFAULT_FILE_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS),
20585#endif
20586#ifdef SQLITE_DEFAULT_FOREIGN_KEYS
20587 "DEFAULT_FOREIGN_KEYS",
20588#endif
20589#ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
20590 "DEFAULT_JOURNAL_SIZE_LIMIT=" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT),
20591#endif
20592#ifdef SQLITE_DEFAULT_LOCKING_MODE
20593 "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
20594#endif
20595#ifdef SQLITE_DEFAULT_LOOKASIDE
20596 "DEFAULT_LOOKASIDE=" CTIMEOPT_VAL2(SQLITE_DEFAULT_LOOKASIDE),
20597#endif
20598#ifdef SQLITE_DEFAULT_MEMSTATUS
20599# if SQLITE_DEFAULT_MEMSTATUS != 1
20600 "DEFAULT_MEMSTATUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_MEMSTATUS),
20601# endif
20602#endif
20603#ifdef SQLITE_DEFAULT_MMAP_SIZE
20604 "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
20605#endif
20606#ifdef SQLITE_DEFAULT_PAGE_SIZE
20607 "DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE),
20608#endif
20609#ifdef SQLITE_DEFAULT_PCACHE_INITSZ
20610 "DEFAULT_PCACHE_INITSZ=" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ),
20611#endif
20612#ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
20613 "DEFAULT_PROXYDIR_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS),
20614#endif
20615#ifdef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
20616 "DEFAULT_RECURSIVE_TRIGGERS",
20617#endif
20618#ifdef SQLITE_DEFAULT_ROWEST
20619 "DEFAULT_ROWEST=" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST),
20620#endif
20621#ifdef SQLITE_DEFAULT_SECTOR_SIZE
20622 "DEFAULT_SECTOR_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE),
20623#endif
20624#ifdef SQLITE_DEFAULT_SYNCHRONOUS
20625 "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS),
20626#endif
20627#ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
20628 "DEFAULT_WAL_AUTOCHECKPOINT=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT),
20629#endif
20630#ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS
20631 "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS),
20632#endif
20633#ifdef SQLITE_DEFAULT_WORKER_THREADS
20634 "DEFAULT_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS),
20635#endif
20636#ifdef SQLITE_DIRECT_OVERFLOW_READ
20637 "DIRECT_OVERFLOW_READ",
20638#endif
20639#ifdef SQLITE_DISABLE_DIRSYNC
20640 "DISABLE_DIRSYNC",
20641#endif
20642#ifdef SQLITE_DISABLE_FTS3_UNICODE
20643 "DISABLE_FTS3_UNICODE",
20644#endif
20645#ifdef SQLITE_DISABLE_FTS4_DEFERRED
20646 "DISABLE_FTS4_DEFERRED",
20647#endif
20648#ifdef SQLITE_DISABLE_INTRINSIC
20649 "DISABLE_INTRINSIC",
20650#endif
20651#ifdef SQLITE_DISABLE_LFS
20652 "DISABLE_LFS",
20653#endif
20654#ifdef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
20655 "DISABLE_PAGECACHE_OVERFLOW_STATS",
20656#endif
20657#ifdef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
20658 "DISABLE_SKIPAHEAD_DISTINCT",
20659#endif
20660#ifdef SQLITE_ENABLE_8_3_NAMES
20661 "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
20662#endif
20663#ifdef SQLITE_ENABLE_API_ARMOR
20664 "ENABLE_API_ARMOR",
20665#endif
20666#ifdef SQLITE_ENABLE_ATOMIC_WRITE
20667 "ENABLE_ATOMIC_WRITE",
20668#endif
20669#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
20670 "ENABLE_BATCH_ATOMIC_WRITE",
20671#endif
20672#ifdef SQLITE_ENABLE_BYTECODE_VTAB
20673 "ENABLE_BYTECODE_VTAB",
20674#endif
20675#ifdef SQLITE_ENABLE_CEROD
20676 "ENABLE_CEROD=" CTIMEOPT_VAL(SQLITE_ENABLE_CEROD),
20677#endif
20678#ifdef SQLITE_ENABLE_COLUMN_METADATA
20679 "ENABLE_COLUMN_METADATA",
20680#endif
20681#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
20682 "ENABLE_COLUMN_USED_MASK",
20683#endif
20684#ifdef SQLITE_ENABLE_COSTMULT
20685 "ENABLE_COSTMULT",
20686#endif
20687#ifdef SQLITE_ENABLE_CURSOR_HINTS
20688 "ENABLE_CURSOR_HINTS",
20689#endif
20690#ifdef SQLITE_ENABLE_DBPAGE_VTAB
20691 "ENABLE_DBPAGE_VTAB",
20692#endif
20693#ifdef SQLITE_ENABLE_DBSTAT_VTAB
20694 "ENABLE_DBSTAT_VTAB",
20695#endif
20696#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
20697 "ENABLE_EXPENSIVE_ASSERT",
20698#endif
20699#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
20700 "ENABLE_EXPLAIN_COMMENTS",
20701#endif
20702#ifdef SQLITE_ENABLE_FTS3
20703 "ENABLE_FTS3",
20704#endif
20705#ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
20706 "ENABLE_FTS3_PARENTHESIS",
20707#endif
20708#ifdef SQLITE_ENABLE_FTS3_TOKENIZER
20709 "ENABLE_FTS3_TOKENIZER",
20710#endif
20711#ifdef SQLITE_ENABLE_FTS4
20712 "ENABLE_FTS4",
20713#endif
20714#ifdef SQLITE_ENABLE_FTS5
20715 "ENABLE_FTS5",
20716#endif
20717#ifdef SQLITE_ENABLE_GEOPOLY
20718 "ENABLE_GEOPOLY",
20719#endif
20720#ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
20721 "ENABLE_HIDDEN_COLUMNS",
20722#endif
20723#ifdef SQLITE_ENABLE_ICU
20724 "ENABLE_ICU",
20725#endif
20726#ifdef SQLITE_ENABLE_IOTRACE
20727 "ENABLE_IOTRACE",
20728#endif
20729#ifdef SQLITE_ENABLE_JSON1
20730 "ENABLE_JSON1",
20731#endif
20732#ifdef SQLITE_ENABLE_LOAD_EXTENSION
20733 "ENABLE_LOAD_EXTENSION",
20734#endif
20735#ifdef SQLITE_ENABLE_LOCKING_STYLE
20736 "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
20737#endif
20738#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
20739 "ENABLE_MATH_FUNCTIONS",
20740#endif
20741#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
20742 "ENABLE_MEMORY_MANAGEMENT",
20743#endif
20744#ifdef SQLITE_ENABLE_MEMSYS3
20745 "ENABLE_MEMSYS3",
20746#endif
20747#ifdef SQLITE_ENABLE_MEMSYS5
20748 "ENABLE_MEMSYS5",
20749#endif
20750#ifdef SQLITE_ENABLE_MULTIPLEX
20751 "ENABLE_MULTIPLEX",
20752#endif
20753#ifdef SQLITE_ENABLE_NORMALIZE
20754 "ENABLE_NORMALIZE",
20755#endif
20756#ifdef SQLITE_ENABLE_NULL_TRIM
20757 "ENABLE_NULL_TRIM",
20758#endif
20759#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
20760 "ENABLE_OFFSET_SQL_FUNC",
20761#endif
20762#ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
20763 "ENABLE_OVERSIZE_CELL_CHECK",
20764#endif
20765#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
20766 "ENABLE_PREUPDATE_HOOK",
20767#endif
20768#ifdef SQLITE_ENABLE_QPSG
20769 "ENABLE_QPSG",
20770#endif
20771#ifdef SQLITE_ENABLE_RBU
20772 "ENABLE_RBU",
20773#endif
20774#ifdef SQLITE_ENABLE_RTREE
20775 "ENABLE_RTREE",
20776#endif
20777#ifdef SQLITE_ENABLE_SELECTTRACE
20778 "ENABLE_SELECTTRACE",
20779#endif
20780#ifdef SQLITE_ENABLE_SESSION
20781 "ENABLE_SESSION",
20782#endif
20783#ifdef SQLITE_ENABLE_SNAPSHOT
20784 "ENABLE_SNAPSHOT",
20785#endif
20786#ifdef SQLITE_ENABLE_SORTER_REFERENCES
20787 "ENABLE_SORTER_REFERENCES",
20788#endif
20789#ifdef SQLITE_ENABLE_SQLLOG
20790 "ENABLE_SQLLOG",
20791#endif
20792#ifdef SQLITE_ENABLE_STAT4
20793 "ENABLE_STAT4",
20794#endif
20795#ifdef SQLITE_ENABLE_STMTVTAB
20796 "ENABLE_STMTVTAB",
20797#endif
20798#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
20799 "ENABLE_STMT_SCANSTATUS",
20800#endif
20801#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
20802 "ENABLE_UNKNOWN_SQL_FUNCTION",
20803#endif
20804#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
20805 "ENABLE_UNLOCK_NOTIFY",
20806#endif
20807#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
20808 "ENABLE_UPDATE_DELETE_LIMIT",
20809#endif
20810#ifdef SQLITE_ENABLE_URI_00_ERROR
20811 "ENABLE_URI_00_ERROR",
20812#endif
20813#ifdef SQLITE_ENABLE_VFSTRACE
20814 "ENABLE_VFSTRACE",
20815#endif
20816#ifdef SQLITE_ENABLE_WHERETRACE
20817 "ENABLE_WHERETRACE",
20818#endif
20819#ifdef SQLITE_ENABLE_ZIPVFS
20820 "ENABLE_ZIPVFS",
20821#endif
20822#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
20823 "EXPLAIN_ESTIMATED_ROWS",
20824#endif
20825#ifdef SQLITE_EXTRA_IFNULLROW
20826 "EXTRA_IFNULLROW",
20827#endif
20828#ifdef SQLITE_EXTRA_INIT
20829 "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),
20830#endif
20831#ifdef SQLITE_EXTRA_SHUTDOWN
20832 "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),
20833#endif
20834#ifdef SQLITE_FTS3_MAX_EXPR_DEPTH
20835 "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH),
20836#endif
20837#ifdef SQLITE_FTS5_ENABLE_TEST_MI
20838 "FTS5_ENABLE_TEST_MI",
20839#endif
20840#ifdef SQLITE_FTS5_NO_WITHOUT_ROWID
20841 "FTS5_NO_WITHOUT_ROWID",
20842#endif
20843#if HAVE_ISNAN || SQLITE_HAVE_ISNAN
20844 "HAVE_ISNAN",
20845#endif
20846#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
20847# if SQLITE_HOMEGROWN_RECURSIVE_MUTEX != 1
20848 "HOMEGROWN_RECURSIVE_MUTEX=" CTIMEOPT_VAL(SQLITE_HOMEGROWN_RECURSIVE_MUTEX),
20849# endif
20850#endif
20851#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
20852 "IGNORE_AFP_LOCK_ERRORS",
20853#endif
20854#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
20855 "IGNORE_FLOCK_LOCK_ERRORS",
20856#endif
20857#ifdef SQLITE_INLINE_MEMCPY
20858 "INLINE_MEMCPY",
20859#endif
20860#ifdef SQLITE_INT64_TYPE
20861 "INT64_TYPE",
20862#endif
20863#ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX
20864 "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX),
20865#endif
20866#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
20867 "LIKE_DOESNT_MATCH_BLOBS",
20868#endif
20869#ifdef SQLITE_LOCK_TRACE
20870 "LOCK_TRACE",
20871#endif
20872#ifdef SQLITE_LOG_CACHE_SPILL
20873 "LOG_CACHE_SPILL",
20874#endif
20875#ifdef SQLITE_MALLOC_SOFT_LIMIT
20876 "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT),
20877#endif
20878#ifdef SQLITE_MAX_ATTACHED
20879 "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED),
20880#endif
20881#ifdef SQLITE_MAX_COLUMN
20882 "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN),
20883#endif
20884#ifdef SQLITE_MAX_COMPOUND_SELECT
20885 "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT),
20886#endif
20887#ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE
20888 "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE),
20889#endif
20890#ifdef SQLITE_MAX_EXPR_DEPTH
20891 "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH),
20892#endif
20893#ifdef SQLITE_MAX_FUNCTION_ARG
20894 "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG),
20895#endif
20896#ifdef SQLITE_MAX_LENGTH
20897 "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH),
20898#endif
20899#ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH
20900 "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH),
20901#endif
20902#ifdef SQLITE_MAX_MEMORY
20903 "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY),
20904#endif
20905#ifdef SQLITE_MAX_MMAP_SIZE
20906 "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
20907#endif
20908#ifdef SQLITE_MAX_MMAP_SIZE_
20909 "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_),
20910#endif
20911#ifdef SQLITE_MAX_PAGE_COUNT
20912 "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
20913#endif
20914#ifdef SQLITE_MAX_PAGE_SIZE
20915 "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
20916#endif
20917#ifdef SQLITE_MAX_SCHEMA_RETRY
20918 "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
20919#endif
20920#ifdef SQLITE_MAX_SQL_LENGTH
20921 "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
20922#endif
20923#ifdef SQLITE_MAX_TRIGGER_DEPTH
20924 "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH),
20925#endif
20926#ifdef SQLITE_MAX_VARIABLE_NUMBER
20927 "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER),
20928#endif
20929#ifdef SQLITE_MAX_VDBE_OP
20930 "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP),
20931#endif
20932#ifdef SQLITE_MAX_WORKER_THREADS
20933 "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS),
20934#endif
20935#ifdef SQLITE_MEMDEBUG
20936 "MEMDEBUG",
20937#endif
20938#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
20939 "MIXED_ENDIAN_64BIT_FLOAT",
20940#endif
20941#ifdef SQLITE_MMAP_READWRITE
20942 "MMAP_READWRITE",
20943#endif
20944#ifdef SQLITE_MUTEX_NOOP
20945 "MUTEX_NOOP",
20946#endif
20947#ifdef SQLITE_MUTEX_OMIT
20948 "MUTEX_OMIT",
20949#endif
20950#ifdef SQLITE_MUTEX_PTHREADS
20951 "MUTEX_PTHREADS",
20952#endif
20953#ifdef SQLITE_MUTEX_W32
20954 "MUTEX_W32",
20955#endif
20956#ifdef SQLITE_NEED_ERR_NAME
20957 "NEED_ERR_NAME",
20958#endif
20959#ifdef SQLITE_NO_SYNC
20960 "NO_SYNC",
20961#endif
20962#ifdef SQLITE_OMIT_ALTERTABLE
20963 "OMIT_ALTERTABLE",
20964#endif
20965#ifdef SQLITE_OMIT_ANALYZE
20966 "OMIT_ANALYZE",
20967#endif
20968#ifdef SQLITE_OMIT_ATTACH
20969 "OMIT_ATTACH",
20970#endif
20971#ifdef SQLITE_OMIT_AUTHORIZATION
20972 "OMIT_AUTHORIZATION",
20973#endif
20974#ifdef SQLITE_OMIT_AUTOINCREMENT
20975 "OMIT_AUTOINCREMENT",
20976#endif
20977#ifdef SQLITE_OMIT_AUTOINIT
20978 "OMIT_AUTOINIT",
20979#endif
20980#ifdef SQLITE_OMIT_AUTOMATIC_INDEX
20981 "OMIT_AUTOMATIC_INDEX",
20982#endif
20983#ifdef SQLITE_OMIT_AUTORESET
20984 "OMIT_AUTORESET",
20985#endif
20986#ifdef SQLITE_OMIT_AUTOVACUUM
20987 "OMIT_AUTOVACUUM",
20988#endif
20989#ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
20990 "OMIT_BETWEEN_OPTIMIZATION",
20991#endif
20992#ifdef SQLITE_OMIT_BLOB_LITERAL
20993 "OMIT_BLOB_LITERAL",
20994#endif
20995#ifdef SQLITE_OMIT_CAST
20996 "OMIT_CAST",
20997#endif
20998#ifdef SQLITE_OMIT_CHECK
20999 "OMIT_CHECK",
21000#endif
21001#ifdef SQLITE_OMIT_COMPLETE
21002 "OMIT_COMPLETE",
21003#endif
21004#ifdef SQLITE_OMIT_COMPOUND_SELECT
21005 "OMIT_COMPOUND_SELECT",
21006#endif
21007#ifdef SQLITE_OMIT_CONFLICT_CLAUSE
21008 "OMIT_CONFLICT_CLAUSE",
21009#endif
21010#ifdef SQLITE_OMIT_CTE
21011 "OMIT_CTE",
21012#endif
21013#if defined(SQLITE_OMIT_DATETIME_FUNCS) || defined(SQLITE_OMIT_FLOATING_POINT)
21014 "OMIT_DATETIME_FUNCS",
21015#endif
21016#ifdef SQLITE_OMIT_DECLTYPE
21017 "OMIT_DECLTYPE",
21018#endif
21019#ifdef SQLITE_OMIT_DEPRECATED
21020 "OMIT_DEPRECATED",
21021#endif
21022#ifdef SQLITE_OMIT_DESERIALIZE
21023 "OMIT_DESERIALIZE",
21024#endif
21025#ifdef SQLITE_OMIT_DISKIO
21026 "OMIT_DISKIO",
21027#endif
21028#ifdef SQLITE_OMIT_EXPLAIN
21029 "OMIT_EXPLAIN",
21030#endif
21031#ifdef SQLITE_OMIT_FLAG_PRAGMAS
21032 "OMIT_FLAG_PRAGMAS",
21033#endif
21034#ifdef SQLITE_OMIT_FLOATING_POINT
21035 "OMIT_FLOATING_POINT",
21036#endif
21037#ifdef SQLITE_OMIT_FOREIGN_KEY
21038 "OMIT_FOREIGN_KEY",
21039#endif
21040#ifdef SQLITE_OMIT_GET_TABLE
21041 "OMIT_GET_TABLE",
21042#endif
21043#ifdef SQLITE_OMIT_HEX_INTEGER
21044 "OMIT_HEX_INTEGER",
21045#endif
21046#ifdef SQLITE_OMIT_INCRBLOB
21047 "OMIT_INCRBLOB",
21048#endif
21049#ifdef SQLITE_OMIT_INTEGRITY_CHECK
21050 "OMIT_INTEGRITY_CHECK",
21051#endif
21052#ifdef SQLITE_OMIT_INTROSPECTION_PRAGMAS
21053 "OMIT_INTROSPECTION_PRAGMAS",
21054#endif
21055#ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
21056 "OMIT_LIKE_OPTIMIZATION",
21057#endif
21058#ifdef SQLITE_OMIT_LOAD_EXTENSION
21059 "OMIT_LOAD_EXTENSION",
21060#endif
21061#ifdef SQLITE_OMIT_LOCALTIME
21062 "OMIT_LOCALTIME",
21063#endif
21064#ifdef SQLITE_OMIT_LOOKASIDE
21065 "OMIT_LOOKASIDE",
21066#endif
21067#ifdef SQLITE_OMIT_MEMORYDB
21068 "OMIT_MEMORYDB",
21069#endif
21070#ifdef SQLITE_OMIT_OR_OPTIMIZATION
21071 "OMIT_OR_OPTIMIZATION",
21072#endif
21073#ifdef SQLITE_OMIT_PAGER_PRAGMAS
21074 "OMIT_PAGER_PRAGMAS",
21075#endif
21076#ifdef SQLITE_OMIT_PARSER_TRACE
21077 "OMIT_PARSER_TRACE",
21078#endif
21079#ifdef SQLITE_OMIT_POPEN
21080 "OMIT_POPEN",
21081#endif
21082#ifdef SQLITE_OMIT_PRAGMA
21083 "OMIT_PRAGMA",
21084#endif
21085#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
21086 "OMIT_PROGRESS_CALLBACK",
21087#endif
21088#ifdef SQLITE_OMIT_QUICKBALANCE
21089 "OMIT_QUICKBALANCE",
21090#endif
21091#ifdef SQLITE_OMIT_REINDEX
21092 "OMIT_REINDEX",
21093#endif
21094#ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
21095 "OMIT_SCHEMA_PRAGMAS",
21096#endif
21097#ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
21098 "OMIT_SCHEMA_VERSION_PRAGMAS",
21099#endif
21100#ifdef SQLITE_OMIT_SHARED_CACHE
21101 "OMIT_SHARED_CACHE",
21102#endif
21103#ifdef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
21104 "OMIT_SHUTDOWN_DIRECTORIES",
21105#endif
21106#ifdef SQLITE_OMIT_SUBQUERY
21107 "OMIT_SUBQUERY",
21108#endif
21109#ifdef SQLITE_OMIT_TCL_VARIABLE
21110 "OMIT_TCL_VARIABLE",
21111#endif
21112#ifdef SQLITE_OMIT_TEMPDB
21113 "OMIT_TEMPDB",
21114#endif
21115#ifdef SQLITE_OMIT_TEST_CONTROL
21116 "OMIT_TEST_CONTROL",
21117#endif
21118#ifdef SQLITE_OMIT_TRACE
21119# if SQLITE_OMIT_TRACE != 1
21120 "OMIT_TRACE=" CTIMEOPT_VAL(SQLITE_OMIT_TRACE),
21121# endif
21122#endif
21123#ifdef SQLITE_OMIT_TRIGGER
21124 "OMIT_TRIGGER",
21125#endif
21126#ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
21127 "OMIT_TRUNCATE_OPTIMIZATION",
21128#endif
21129#ifdef SQLITE_OMIT_UTF16
21130 "OMIT_UTF16",
21131#endif
21132#ifdef SQLITE_OMIT_VACUUM
21133 "OMIT_VACUUM",
21134#endif
21135#ifdef SQLITE_OMIT_VIEW
21136 "OMIT_VIEW",
21137#endif
21138#ifdef SQLITE_OMIT_VIRTUALTABLE
21139 "OMIT_VIRTUALTABLE",
21140#endif
21141#ifdef SQLITE_OMIT_WAL
21142 "OMIT_WAL",
21143#endif
21144#ifdef SQLITE_OMIT_WSD
21145 "OMIT_WSD",
21146#endif
21147#ifdef SQLITE_OMIT_XFER_OPT
21148 "OMIT_XFER_OPT",
21149#endif
21150#ifdef SQLITE_PCACHE_SEPARATE_HEADER
21151 "PCACHE_SEPARATE_HEADER",
21152#endif
21153#ifdef SQLITE_PERFORMANCE_TRACE
21154 "PERFORMANCE_TRACE",
21155#endif
21156#ifdef SQLITE_POWERSAFE_OVERWRITE
21157# if SQLITE_POWERSAFE_OVERWRITE != 1
21158 "POWERSAFE_OVERWRITE=" CTIMEOPT_VAL(SQLITE_POWERSAFE_OVERWRITE),
21159# endif
21160#endif
21161#ifdef SQLITE_PREFER_PROXY_LOCKING
21162 "PREFER_PROXY_LOCKING",
21163#endif
21164#ifdef SQLITE_PROXY_DEBUG
21165 "PROXY_DEBUG",
21166#endif
21167#ifdef SQLITE_REVERSE_UNORDERED_SELECTS
21168 "REVERSE_UNORDERED_SELECTS",
21169#endif
21170#ifdef SQLITE_RTREE_INT_ONLY
21171 "RTREE_INT_ONLY",
21172#endif
21173#ifdef SQLITE_SECURE_DELETE
21174 "SECURE_DELETE",
21175#endif
21176#ifdef SQLITE_SMALL_STACK
21177 "SMALL_STACK",
21178#endif
21179#ifdef SQLITE_SORTER_PMASZ
21180 "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ),
21181#endif
21182#ifdef SQLITE_SOUNDEX
21183 "SOUNDEX",
21184#endif
21185#ifdef SQLITE_STAT4_SAMPLES
21186 "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES),
21187#endif
21188#ifdef SQLITE_STMTJRNL_SPILL
21189 "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL),
21190#endif
21191#ifdef SQLITE_SUBSTR_COMPATIBILITY
21192 "SUBSTR_COMPATIBILITY",
21193#endif
21194#if (!defined(SQLITE_WIN32_MALLOC) \
21195 && !defined(SQLITE_ZERO_MALLOC) \
21196 && !defined(SQLITE_MEMDEBUG) \
21197 ) || defined(SQLITE_SYSTEM_MALLOC)
21198 "SYSTEM_MALLOC",
21199#endif
21200#ifdef SQLITE_TCL
21201 "TCL",
21202#endif
21203#ifdef SQLITE_TEMP_STORE
21204 "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
21205#endif
21206#ifdef SQLITE_TEST
21207 "TEST",
21208#endif
21209#if defined(SQLITE_THREADSAFE)
21210 "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
21211#elif defined(THREADSAFE)
21212 "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE),
21213#else
21214 "THREADSAFE=1",
21215#endif
21216#ifdef SQLITE_UNLINK_AFTER_CLOSE
21217 "UNLINK_AFTER_CLOSE",
21218#endif
21219#ifdef SQLITE_UNTESTABLE
21220 "UNTESTABLE",
21221#endif
21222#ifdef SQLITE_USER_AUTHENTICATION
21223 "USER_AUTHENTICATION",
21224#endif
21225#ifdef SQLITE_USE_ALLOCA
21226 "USE_ALLOCA",
21227#endif
21228#ifdef SQLITE_USE_FCNTL_TRACE
21229 "USE_FCNTL_TRACE",
21230#endif
21231#ifdef SQLITE_USE_URI
21232 "USE_URI",
21233#endif
21234#ifdef SQLITE_VDBE_COVERAGE
21235 "VDBE_COVERAGE",
21236#endif
21237#ifdef SQLITE_WIN32_MALLOC
21238 "WIN32_MALLOC",
21239#endif
21240#ifdef SQLITE_ZERO_MALLOC
21241 "ZERO_MALLOC",
21242#endif
21243/*
21244** END CODE GENERATED BY tool/mkctime.tcl
21245*/
21246};
21247
21248SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
21249 *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]);
21250 return (const char**)sqlite3azCompileOpt;
21251}
21252
21253#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
21254
21255/************** End of ctime.c ***********************************************/
21256/************** Begin file global.c ******************************************/
21257/*
21258** 2008 June 13
21259**
21260** The author disclaims copyright to this source code. In place of
21261** a legal notice, here is a blessing:
21262**
21263** May you do good and not evil.
21264** May you find forgiveness for yourself and forgive others.
21265** May you share freely, never taking more than you give.
21266**
21267*************************************************************************
21268**
21269** This file contains definitions of global variables and constants.
21270*/
21271/* #include "sqliteInt.h" */
21272
21273/* An array to map all upper-case characters into their corresponding
21274** lower-case character.
21275**
21276** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
21277** handle case conversions for the UTF character set since the tables
21278** involved are nearly as big or bigger than SQLite itself.
21279*/
21280SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
21281#ifdef SQLITE_ASCII
21282 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
21283 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
21284 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
21285 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
21286 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
21287 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
21288 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
21289 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
21290 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
21291 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
21292 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
21293 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
21294 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
21295 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
21296 252,253,254,255,
21297#endif
21298#ifdef SQLITE_EBCDIC
21299 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
21300 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
21301 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
21302 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
21303 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
21304 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
21305 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
21306 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
21307 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
21308 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
21309 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
21310 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
21311 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
21312 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
21313 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
21314 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
21315#endif
21316/* All of the upper-to-lower conversion data is above. The following
21317** 18 integers are completely unrelated. They are appended to the
21318** sqlite3UpperToLower[] array to avoid UBSAN warnings. Here's what is
21319** going on:
21320**
21321** The SQL comparison operators (<>, =, >, <=, <, and >=) are implemented
21322** by invoking sqlite3MemCompare(A,B) which compares values A and B and
21323** returns negative, zero, or positive if A is less then, equal to, or
21324** greater than B, respectively. Then the true false results is found by
21325** consulting sqlite3aLTb[opcode], sqlite3aEQb[opcode], or
21326** sqlite3aGTb[opcode] depending on whether the result of compare(A,B)
21327** is negative, zero, or positive, where opcode is the specific opcode.
21328** The only works because the comparison opcodes are consecutive and in
21329** this order: NE EQ GT LE LT GE. Various assert()s throughout the code
21330** ensure that is the case.
21331**
21332** These elements must be appended to another array. Otherwise the
21333** index (here shown as [256-OP_Ne]) would be out-of-bounds and thus
21334** be undefined behavior. That's goofy, but the C-standards people thought
21335** it was a good idea, so here we are.
21336*/
21337/* NE EQ GT LE LT GE */
21338 1, 0, 0, 1, 1, 0, /* aLTb[]: Use when compare(A,B) less than zero */
21339 0, 1, 0, 1, 0, 1, /* aEQb[]: Use when compare(A,B) equals zero */
21340 1, 0, 1, 0, 0, 1 /* aGTb[]: Use when compare(A,B) greater than zero*/
21341};
21342SQLITE_PRIVATE const unsigned char *sqlite3aLTb = &sqlite3UpperToLower[256-OP_Ne];
21343SQLITE_PRIVATE const unsigned char *sqlite3aEQb = &sqlite3UpperToLower[256+6-OP_Ne];
21344SQLITE_PRIVATE const unsigned char *sqlite3aGTb = &sqlite3UpperToLower[256+12-OP_Ne];
21345
21346/*
21347** The following 256 byte lookup table is used to support SQLites built-in
21348** equivalents to the following standard library functions:
21349**
21350** isspace() 0x01
21351** isalpha() 0x02
21352** isdigit() 0x04
21353** isalnum() 0x06
21354** isxdigit() 0x08
21355** toupper() 0x20
21356** SQLite identifier character 0x40
21357** Quote character 0x80
21358**
21359** Bit 0x20 is set if the mapped character requires translation to upper
21360** case. i.e. if the character is a lower-case ASCII character.
21361** If x is a lower-case ASCII character, then its upper-case equivalent
21362** is (x - 0x20). Therefore toupper() can be implemented as:
21363**
21364** (x & ~(map[x]&0x20))
21365**
21366** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
21367** array. tolower() is used more often than toupper() by SQLite.
21368**
21369** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
21370** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
21371** non-ASCII UTF character. Hence the test for whether or not a character is
21372** part of an identifier is 0x46.
21373*/
21374SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
21375 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
21376 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
21377 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
21378 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
21379 0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */
21380 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
21381 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
21382 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
21383
21384 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
21385 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
21386 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
21387 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
21388 0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
21389 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
21390 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
21391 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
21392
21393 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
21394 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
21395 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
21396 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
21397 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
21398 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
21399 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
21400 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
21401
21402 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
21403 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
21404 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
21405 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
21406 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
21407 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
21408 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
21409 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
21410};
21411
21412/* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
21413** compatibility for legacy applications, the URI filename capability is
21414** disabled by default.
21415**
21416** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
21417** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
21418**
21419** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
21420** disabled. The default value may be changed by compiling with the
21421** SQLITE_USE_URI symbol defined.
21422*/
21423#ifndef SQLITE_USE_URI
21424# define SQLITE_USE_URI 0
21425#endif
21426
21427/* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
21428** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
21429** that compile-time option is omitted.
21430*/
21431#if !defined(SQLITE_ALLOW_COVERING_INDEX_SCAN)
21432# define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
21433#else
21434# if !SQLITE_ALLOW_COVERING_INDEX_SCAN
21435# error "Compile-time disabling of covering index scan using the\
21436 -DSQLITE_ALLOW_COVERING_INDEX_SCAN=0 option is deprecated.\
21437 Contact SQLite developers if this is a problem for you, and\
21438 delete this #error macro to continue with your build."
21439# endif
21440#endif
21441
21442/* The minimum PMA size is set to this value multiplied by the database
21443** page size in bytes.
21444*/
21445#ifndef SQLITE_SORTER_PMASZ
21446# define SQLITE_SORTER_PMASZ 250
21447#endif
21448
21449/* Statement journals spill to disk when their size exceeds the following
21450** threshold (in bytes). 0 means that statement journals are created and
21451** written to disk immediately (the default behavior for SQLite versions
21452** before 3.12.0). -1 means always keep the entire statement journal in
21453** memory. (The statement journal is also always held entirely in memory
21454** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
21455** setting.)
21456*/
21457#ifndef SQLITE_STMTJRNL_SPILL
21458# define SQLITE_STMTJRNL_SPILL (64*1024)
21459#endif
21460
21461/*
21462** The default lookaside-configuration, the format "SZ,N". SZ is the
21463** number of bytes in each lookaside slot (should be a multiple of 8)
21464** and N is the number of slots. The lookaside-configuration can be
21465** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
21466** or at run-time for an individual database connection using
21467** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
21468**
21469** With the two-size-lookaside enhancement, less lookaside is required.
21470** The default configuration of 1200,40 actually provides 30 1200-byte slots
21471** and 93 128-byte slots, which is more lookaside than is available
21472** using the older 1200,100 configuration without two-size-lookaside.
21473*/
21474#ifndef SQLITE_DEFAULT_LOOKASIDE
21475# ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE
21476# define SQLITE_DEFAULT_LOOKASIDE 1200,100 /* 120KB of memory */
21477# else
21478# define SQLITE_DEFAULT_LOOKASIDE 1200,40 /* 48KB of memory */
21479# endif
21480#endif
21481
21482
21483/* The default maximum size of an in-memory database created using
21484** sqlite3_deserialize()
21485*/
21486#ifndef SQLITE_MEMDB_DEFAULT_MAXSIZE
21487# define SQLITE_MEMDB_DEFAULT_MAXSIZE 1073741824
21488#endif
21489
21490/*
21491** The following singleton contains the global configuration for
21492** the SQLite library.
21493*/
21494SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
21495 SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
21496 1, /* bCoreMutex */
21497 SQLITE_THREADSAFE==1, /* bFullMutex */
21498 SQLITE_USE_URI, /* bOpenUri */
21499 SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
21500 0, /* bSmallMalloc */
21501 1, /* bExtraSchemaChecks */
21502 0x7ffffffe, /* mxStrlen */
21503 0, /* neverCorrupt */
21504 SQLITE_DEFAULT_LOOKASIDE, /* szLookaside, nLookaside */
21505 SQLITE_STMTJRNL_SPILL, /* nStmtSpill */
21506 {0,0,0,0,0,0,0,0}, /* m */
21507 {0,0,0,0,0,0,0,0,0}, /* mutex */
21508 {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
21509 (void*)0, /* pHeap */
21510 0, /* nHeap */
21511 0, 0, /* mnHeap, mxHeap */
21512 SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
21513 SQLITE_MAX_MMAP_SIZE, /* mxMmap */
21514 (void*)0, /* pPage */
21515 0, /* szPage */
21516 SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
21517 0, /* mxParserStack */
21518 0, /* sharedCacheEnabled */
21519 SQLITE_SORTER_PMASZ, /* szPma */
21520 /* All the rest should always be initialized to zero */
21521 0, /* isInit */
21522 0, /* inProgress */
21523 0, /* isMutexInit */
21524 0, /* isMallocInit */
21525 0, /* isPCacheInit */
21526 0, /* nRefInitMutex */
21527 0, /* pInitMutex */
21528 0, /* xLog */
21529 0, /* pLogArg */
21530#ifdef SQLITE_ENABLE_SQLLOG
21531 0, /* xSqllog */
21532 0, /* pSqllogArg */
21533#endif
21534#ifdef SQLITE_VDBE_COVERAGE
21535 0, /* xVdbeBranch */
21536 0, /* pVbeBranchArg */
21537#endif
21538#ifndef SQLITE_OMIT_DESERIALIZE
21539 SQLITE_MEMDB_DEFAULT_MAXSIZE, /* mxMemdbSize */
21540#endif
21541#ifndef SQLITE_UNTESTABLE
21542 0, /* xTestCallback */
21543#endif
21544 0, /* bLocaltimeFault */
21545 0x7ffffffe, /* iOnceResetThreshold */
21546 SQLITE_DEFAULT_SORTERREF_SIZE, /* szSorterRef */
21547 0, /* iPrngSeed */
21548};
21549
21550/*
21551** Hash table for global functions - functions common to all
21552** database connections. After initialization, this table is
21553** read-only.
21554*/
21555SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
21556
21557#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
21558/*
21559** Counter used for coverage testing. Does not come into play for
21560** release builds.
21561**
21562** Access to this global variable is not mutex protected. This might
21563** result in TSAN warnings. But as the variable does not exist in
21564** release builds, that should not be a concern.
21565*/
21566SQLITE_PRIVATE unsigned int sqlite3CoverageCounter;
21567#endif /* SQLITE_COVERAGE_TEST || SQLITE_DEBUG */
21568
21569#ifdef VDBE_PROFILE
21570/*
21571** The following performance counter can be used in place of
21572** sqlite3Hwtime() for profiling. This is a no-op on standard builds.
21573*/
21574SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt = 0;
21575#endif
21576
21577/*
21578** The value of the "pending" byte must be 0x40000000 (1 byte past the
21579** 1-gibabyte boundary) in a compatible database. SQLite never uses
21580** the database page that contains the pending byte. It never attempts
21581** to read or write that page. The pending byte page is set aside
21582** for use by the VFS layers as space for managing file locks.
21583**
21584** During testing, it is often desirable to move the pending byte to
21585** a different position in the file. This allows code that has to
21586** deal with the pending byte to run on files that are much smaller
21587** than 1 GiB. The sqlite3_test_control() interface can be used to
21588** move the pending byte.
21589**
21590** IMPORTANT: Changing the pending byte to any value other than
21591** 0x40000000 results in an incompatible database file format!
21592** Changing the pending byte during operation will result in undefined
21593** and incorrect behavior.
21594*/
21595#ifndef SQLITE_OMIT_WSD
21596SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
21597#endif
21598
21599/*
21600** Tracing flags set by SQLITE_TESTCTRL_TRACEFLAGS.
21601*/
21602SQLITE_PRIVATE u32 sqlite3SelectTrace = 0;
21603SQLITE_PRIVATE u32 sqlite3WhereTrace = 0;
21604
21605/* #include "opcodes.h" */
21606/*
21607** Properties of opcodes. The OPFLG_INITIALIZER macro is
21608** created by mkopcodeh.awk during compilation. Data is obtained
21609** from the comments following the "case OP_xxxx:" statements in
21610** the vdbe.c file.
21611*/
21612SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
21613
21614/*
21615** Name of the default collating sequence
21616*/
21617SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
21618
21619/*
21620** Standard typenames. These names must match the COLTYPE_* definitions.
21621** Adjust the SQLITE_N_STDTYPE value if adding or removing entries.
21622**
21623** sqlite3StdType[] The actual names of the datatypes.
21624**
21625** sqlite3StdTypeLen[] The length (in bytes) of each entry
21626** in sqlite3StdType[].
21627**
21628** sqlite3StdTypeAffinity[] The affinity associated with each entry
21629** in sqlite3StdType[].
21630**
21631** sqlite3StdTypeMap[] The type value (as returned from
21632** sqlite3_column_type() or sqlite3_value_type())
21633** for each entry in sqlite3StdType[].
21634*/
21635SQLITE_PRIVATE const unsigned char sqlite3StdTypeLen[] = { 3, 4, 3, 7, 4, 4 };
21636SQLITE_PRIVATE const char sqlite3StdTypeAffinity[] = {
21637 SQLITE_AFF_NUMERIC,
21638 SQLITE_AFF_BLOB,
21639 SQLITE_AFF_INTEGER,
21640 SQLITE_AFF_INTEGER,
21641 SQLITE_AFF_REAL,
21642 SQLITE_AFF_TEXT
21643};
21644SQLITE_PRIVATE const char sqlite3StdTypeMap[] = {
21645 0,
21646 SQLITE_BLOB,
21647 SQLITE_INTEGER,
21648 SQLITE_INTEGER,
21649 SQLITE_FLOAT,
21650 SQLITE_TEXT
21651};
21652SQLITE_PRIVATE const char *sqlite3StdType[] = {
21653 "ANY",
21654 "BLOB",
21655 "INT",
21656 "INTEGER",
21657 "REAL",
21658 "TEXT"
21659};
21660
21661/************** End of global.c **********************************************/
21662/************** Begin file status.c ******************************************/
21663/*
21664** 2008 June 18
21665**
21666** The author disclaims copyright to this source code. In place of
21667** a legal notice, here is a blessing:
21668**
21669** May you do good and not evil.
21670** May you find forgiveness for yourself and forgive others.
21671** May you share freely, never taking more than you give.
21672**
21673*************************************************************************
21674**
21675** This module implements the sqlite3_status() interface and related
21676** functionality.
21677*/
21678/* #include "sqliteInt.h" */
21679/************** Include vdbeInt.h in the middle of status.c ******************/
21680/************** Begin file vdbeInt.h *****************************************/
21681/*
21682** 2003 September 6
21683**
21684** The author disclaims copyright to this source code. In place of
21685** a legal notice, here is a blessing:
21686**
21687** May you do good and not evil.
21688** May you find forgiveness for yourself and forgive others.
21689** May you share freely, never taking more than you give.
21690**
21691*************************************************************************
21692** This is the header file for information that is private to the
21693** VDBE. This information used to all be at the top of the single
21694** source code file "vdbe.c". When that file became too big (over
21695** 6000 lines long) it was split up into several smaller files and
21696** this header information was factored out.
21697*/
21698#ifndef SQLITE_VDBEINT_H
21699#define SQLITE_VDBEINT_H
21700
21701/*
21702** The maximum number of times that a statement will try to reparse
21703** itself before giving up and returning SQLITE_SCHEMA.
21704*/
21705#ifndef SQLITE_MAX_SCHEMA_RETRY
21706# define SQLITE_MAX_SCHEMA_RETRY 50
21707#endif
21708
21709/*
21710** VDBE_DISPLAY_P4 is true or false depending on whether or not the
21711** "explain" P4 display logic is enabled.
21712*/
21713#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
21714 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) \
21715 || defined(SQLITE_ENABLE_BYTECODE_VTAB)
21716# define VDBE_DISPLAY_P4 1
21717#else
21718# define VDBE_DISPLAY_P4 0
21719#endif
21720
21721/*
21722** SQL is translated into a sequence of instructions to be
21723** executed by a virtual machine. Each instruction is an instance
21724** of the following structure.
21725*/
21726typedef struct VdbeOp Op;
21727
21728/*
21729** Boolean values
21730*/
21731typedef unsigned Bool;
21732
21733/* Opaque type used by code in vdbesort.c */
21734typedef struct VdbeSorter VdbeSorter;
21735
21736/* Elements of the linked list at Vdbe.pAuxData */
21737typedef struct AuxData AuxData;
21738
21739/* Types of VDBE cursors */
21740#define CURTYPE_BTREE 0
21741#define CURTYPE_SORTER 1
21742#define CURTYPE_VTAB 2
21743#define CURTYPE_PSEUDO 3
21744
21745/*
21746** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
21747**
21748** * A b-tree cursor
21749** - In the main database or in an ephemeral database
21750** - On either an index or a table
21751** * A sorter
21752** * A virtual table
21753** * A one-row "pseudotable" stored in a single register
21754*/
21755typedef struct VdbeCursor VdbeCursor;
21756struct VdbeCursor {
21757 u8 eCurType; /* One of the CURTYPE_* values above */
21758 i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
21759 u8 nullRow; /* True if pointing to a row with no data */
21760 u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
21761 u8 isTable; /* True for rowid tables. False for indexes */
21762#ifdef SQLITE_DEBUG
21763 u8 seekOp; /* Most recent seek operation on this cursor */
21764 u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */
21765#endif
21766 Bool isEphemeral:1; /* True for an ephemeral table */
21767 Bool useRandomRowid:1; /* Generate new record numbers semi-randomly */
21768 Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */
21769 Bool hasBeenDuped:1; /* This cursor was source or target of OP_OpenDup */
21770 u16 seekHit; /* See the OP_SeekHit and OP_IfNoHope opcodes */
21771 Btree *pBtx; /* Separate file holding temporary table */
21772 i64 seqCount; /* Sequence counter */
21773 u32 *aAltMap; /* Mapping from table to index column numbers */
21774
21775 /* Cached OP_Column parse information is only valid if cacheStatus matches
21776 ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
21777 ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that
21778 ** the cache is out of date. */
21779 u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
21780 int seekResult; /* Result of previous sqlite3BtreeMoveto() or 0
21781 ** if there have been no prior seeks on the cursor. */
21782 /* seekResult does not distinguish between "no seeks have ever occurred
21783 ** on this cursor" and "the most recent seek was an exact match".
21784 ** For CURTYPE_PSEUDO, seekResult is the register holding the record */
21785
21786 /* When a new VdbeCursor is allocated, only the fields above are zeroed.
21787 ** The fields that follow are uninitialized, and must be individually
21788 ** initialized prior to first use. */
21789 VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
21790 union {
21791 BtCursor *pCursor; /* CURTYPE_BTREE or _PSEUDO. Btree cursor */
21792 sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
21793 VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
21794 } uc;
21795 KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
21796 u32 iHdrOffset; /* Offset to next unparsed byte of the header */
21797 Pgno pgnoRoot; /* Root page of the open btree cursor */
21798 i16 nField; /* Number of fields in the header */
21799 u16 nHdrParsed; /* Number of header fields parsed so far */
21800 i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
21801 u32 *aOffset; /* Pointer to aType[nField] */
21802 const u8 *aRow; /* Data for the current row, if all on one page */
21803 u32 payloadSize; /* Total number of bytes in the record */
21804 u32 szRow; /* Byte available in aRow */
21805#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
21806 u64 maskUsed; /* Mask of columns used by this cursor */
21807#endif
21808
21809 /* 2*nField extra array elements allocated for aType[], beyond the one
21810 ** static element declared in the structure. nField total array slots for
21811 ** aType[] and nField+1 array slots for aOffset[] */
21812 u32 aType[1]; /* Type values record decode. MUST BE LAST */
21813};
21814
21815
21816/*
21817** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
21818*/
21819#define CACHE_STALE 0
21820
21821/*
21822** When a sub-program is executed (OP_Program), a structure of this type
21823** is allocated to store the current value of the program counter, as
21824** well as the current memory cell array and various other frame specific
21825** values stored in the Vdbe struct. When the sub-program is finished,
21826** these values are copied back to the Vdbe from the VdbeFrame structure,
21827** restoring the state of the VM to as it was before the sub-program
21828** began executing.
21829**
21830** The memory for a VdbeFrame object is allocated and managed by a memory
21831** cell in the parent (calling) frame. When the memory cell is deleted or
21832** overwritten, the VdbeFrame object is not freed immediately. Instead, it
21833** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
21834** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
21835** this instead of deleting the VdbeFrame immediately is to avoid recursive
21836** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
21837** child frame are released.
21838**
21839** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
21840** set to NULL if the currently executing frame is the main program.
21841*/
21842typedef struct VdbeFrame VdbeFrame;
21843struct VdbeFrame {
21844 Vdbe *v; /* VM this frame belongs to */
21845 VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
21846 Op *aOp; /* Program instructions for parent frame */
21847 i64 *anExec; /* Event counters from parent frame */
21848 Mem *aMem; /* Array of memory cells for parent frame */
21849 VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
21850 u8 *aOnce; /* Bitmask used by OP_Once */
21851 void *token; /* Copy of SubProgram.token */
21852 i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
21853 AuxData *pAuxData; /* Linked list of auxdata allocations */
21854#if SQLITE_DEBUG
21855 u32 iFrameMagic; /* magic number for sanity checking */
21856#endif
21857 int nCursor; /* Number of entries in apCsr */
21858 int pc; /* Program Counter in parent (calling) frame */
21859 int nOp; /* Size of aOp array */
21860 int nMem; /* Number of entries in aMem */
21861 int nChildMem; /* Number of memory cells for child frame */
21862 int nChildCsr; /* Number of cursors for child frame */
21863 i64 nChange; /* Statement changes (Vdbe.nChange) */
21864 i64 nDbChange; /* Value of db->nChange */
21865};
21866
21867/* Magic number for sanity checking on VdbeFrame objects */
21868#define SQLITE_FRAME_MAGIC 0x879fb71e
21869
21870/*
21871** Return a pointer to the array of registers allocated for use
21872** by a VdbeFrame.
21873*/
21874#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
21875
21876/*
21877** Internally, the vdbe manipulates nearly all SQL values as Mem
21878** structures. Each Mem struct may cache multiple representations (string,
21879** integer etc.) of the same value.
21880*/
21881struct sqlite3_value {
21882 union MemValue {
21883 double r; /* Real value used when MEM_Real is set in flags */
21884 i64 i; /* Integer value used when MEM_Int is set in flags */
21885 int nZero; /* Extra zero bytes when MEM_Zero and MEM_Blob set */
21886 const char *zPType; /* Pointer type when MEM_Term|MEM_Subtype|MEM_Null */
21887 FuncDef *pDef; /* Used only when flags==MEM_Agg */
21888 } u;
21889 u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
21890 u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
21891 u8 eSubtype; /* Subtype for this value */
21892 int n; /* Number of characters in string value, excluding '\0' */
21893 char *z; /* String or BLOB value */
21894 /* ShallowCopy only needs to copy the information above */
21895 char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
21896 int szMalloc; /* Size of the zMalloc allocation */
21897 u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
21898 sqlite3 *db; /* The associated database connection */
21899 void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
21900#ifdef SQLITE_DEBUG
21901 Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
21902 u16 mScopyFlags; /* flags value immediately after the shallow copy */
21903#endif
21904};
21905
21906/*
21907** Size of struct Mem not including the Mem.zMalloc member or anything that
21908** follows.
21909*/
21910#define MEMCELLSIZE offsetof(Mem,zMalloc)
21911
21912/* One or more of the following flags are set to indicate the validOK
21913** representations of the value stored in the Mem struct.
21914**
21915** If the MEM_Null flag is set, then the value is an SQL NULL value.
21916** For a pointer type created using sqlite3_bind_pointer() or
21917** sqlite3_result_pointer() the MEM_Term and MEM_Subtype flags are also set.
21918**
21919** If the MEM_Str flag is set then Mem.z points at a string representation.
21920** Usually this is encoded in the same unicode encoding as the main
21921** database (see below for exceptions). If the MEM_Term flag is also
21922** set, then the string is nul terminated. The MEM_Int and MEM_Real
21923** flags may coexist with the MEM_Str flag.
21924*/
21925#define MEM_Null 0x0001 /* Value is NULL (or a pointer) */
21926#define MEM_Str 0x0002 /* Value is a string */
21927#define MEM_Int 0x0004 /* Value is an integer */
21928#define MEM_Real 0x0008 /* Value is a real number */
21929#define MEM_Blob 0x0010 /* Value is a BLOB */
21930#define MEM_IntReal 0x0020 /* MEM_Int that stringifies like MEM_Real */
21931#define MEM_AffMask 0x003f /* Mask of affinity bits */
21932#define MEM_FromBind 0x0040 /* Value originates from sqlite3_bind() */
21933#define MEM_Undefined 0x0080 /* Value is undefined */
21934#define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
21935#define MEM_TypeMask 0xc1bf /* Mask of type bits */
21936
21937
21938/* Whenever Mem contains a valid string or blob representation, one of
21939** the following flags must be set to determine the memory management
21940** policy for Mem.z. The MEM_Term flag tells us whether or not the
21941** string is \000 or \u0000 terminated
21942*/
21943#define MEM_Term 0x0200 /* String in Mem.z is zero terminated */
21944#define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
21945#define MEM_Static 0x0800 /* Mem.z points to a static string */
21946#define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
21947#define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
21948#define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
21949#define MEM_Subtype 0x8000 /* Mem.eSubtype is valid */
21950#ifdef SQLITE_OMIT_INCRBLOB
21951 #undef MEM_Zero
21952 #define MEM_Zero 0x0000
21953#endif
21954
21955/* Return TRUE if Mem X contains dynamically allocated content - anything
21956** that needs to be deallocated to avoid a leak.
21957*/
21958#define VdbeMemDynamic(X) \
21959 (((X)->flags&(MEM_Agg|MEM_Dyn))!=0)
21960
21961/*
21962** Clear any existing type flags from a Mem and replace them with f
21963*/
21964#define MemSetTypeFlag(p, f) \
21965 ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
21966
21967/*
21968** True if Mem X is a NULL-nochng type.
21969*/
21970#define MemNullNochng(X) \
21971 (((X)->flags&MEM_TypeMask)==(MEM_Null|MEM_Zero) \
21972 && (X)->n==0 && (X)->u.nZero==0)
21973
21974/*
21975** Return true if a memory cell is not marked as invalid. This macro
21976** is for use inside assert() statements only.
21977*/
21978#ifdef SQLITE_DEBUG
21979#define memIsValid(M) ((M)->flags & MEM_Undefined)==0
21980#endif
21981
21982/*
21983** Each auxiliary data pointer stored by a user defined function
21984** implementation calling sqlite3_set_auxdata() is stored in an instance
21985** of this structure. All such structures associated with a single VM
21986** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
21987** when the VM is halted (if not before).
21988*/
21989struct AuxData {
21990 int iAuxOp; /* Instruction number of OP_Function opcode */
21991 int iAuxArg; /* Index of function argument. */
21992 void *pAux; /* Aux data pointer */
21993 void (*xDeleteAux)(void*); /* Destructor for the aux data */
21994 AuxData *pNextAux; /* Next element in list */
21995};
21996
21997/*
21998** The "context" argument for an installable function. A pointer to an
21999** instance of this structure is the first argument to the routines used
22000** implement the SQL functions.
22001**
22002** There is a typedef for this structure in sqlite.h. So all routines,
22003** even the public interface to SQLite, can use a pointer to this structure.
22004** But this file is the only place where the internal details of this
22005** structure are known.
22006**
22007** This structure is defined inside of vdbeInt.h because it uses substructures
22008** (Mem) which are only defined there.
22009*/
22010struct sqlite3_context {
22011 Mem *pOut; /* The return value is stored here */
22012 FuncDef *pFunc; /* Pointer to function information */
22013 Mem *pMem; /* Memory cell used to store aggregate context */
22014 Vdbe *pVdbe; /* The VM that owns this context */
22015 int iOp; /* Instruction number of OP_Function */
22016 int isError; /* Error code returned by the function. */
22017 u8 skipFlag; /* Skip accumulator loading if true */
22018 u8 argc; /* Number of arguments */
22019 sqlite3_value *argv[1]; /* Argument set */
22020};
22021
22022/* A bitfield type for use inside of structures. Always follow with :N where
22023** N is the number of bits.
22024*/
22025typedef unsigned bft; /* Bit Field Type */
22026
22027/* The ScanStatus object holds a single value for the
22028** sqlite3_stmt_scanstatus() interface.
22029*/
22030typedef struct ScanStatus ScanStatus;
22031struct ScanStatus {
22032 int addrExplain; /* OP_Explain for loop */
22033 int addrLoop; /* Address of "loops" counter */
22034 int addrVisit; /* Address of "rows visited" counter */
22035 int iSelectID; /* The "Select-ID" for this loop */
22036 LogEst nEst; /* Estimated output rows per loop */
22037 char *zName; /* Name of table or index */
22038};
22039
22040/* The DblquoteStr object holds the text of a double-quoted
22041** string for a prepared statement. A linked list of these objects
22042** is constructed during statement parsing and is held on Vdbe.pDblStr.
22043** When computing a normalized SQL statement for an SQL statement, that
22044** list is consulted for each double-quoted identifier to see if the
22045** identifier should really be a string literal.
22046*/
22047typedef struct DblquoteStr DblquoteStr;
22048struct DblquoteStr {
22049 DblquoteStr *pNextStr; /* Next string literal in the list */
22050 char z[8]; /* Dequoted value for the string */
22051};
22052
22053/*
22054** An instance of the virtual machine. This structure contains the complete
22055** state of the virtual machine.
22056**
22057** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
22058** is really a pointer to an instance of this structure.
22059*/
22060struct Vdbe {
22061 sqlite3 *db; /* The database connection that owns this statement */
22062 Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
22063 Parse *pParse; /* Parsing context used to create this Vdbe */
22064 ynVar nVar; /* Number of entries in aVar[] */
22065 u32 iVdbeMagic; /* Magic number defining state of the SQL statement */
22066 int nMem; /* Number of memory locations currently allocated */
22067 int nCursor; /* Number of slots in apCsr[] */
22068 u32 cacheCtr; /* VdbeCursor row cache generation counter */
22069 int pc; /* The program counter */
22070 int rc; /* Value to return */
22071 i64 nChange; /* Number of db changes made since last reset */
22072 int iStatement; /* Statement number (or 0 if has no opened stmt) */
22073 i64 iCurrentTime; /* Value of julianday('now') for this statement */
22074 i64 nFkConstraint; /* Number of imm. FK constraints this VM */
22075 i64 nStmtDefCons; /* Number of def. constraints when stmt started */
22076 i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
22077 Mem *aMem; /* The memory locations */
22078 Mem **apArg; /* Arguments to currently executing user function */
22079 VdbeCursor **apCsr; /* One element of this array for each open cursor */
22080 Mem *aVar; /* Values for the OP_Variable opcode. */
22081
22082 /* When allocating a new Vdbe object, all of the fields below should be
22083 ** initialized to zero or NULL */
22084
22085 Op *aOp; /* Space to hold the virtual machine's program */
22086 int nOp; /* Number of instructions in the program */
22087 int nOpAlloc; /* Slots allocated for aOp[] */
22088 Mem *aColName; /* Column names to return */
22089 Mem *pResultSet; /* Pointer to an array of results */
22090 char *zErrMsg; /* Error message written here */
22091 VList *pVList; /* Name of variables */
22092#ifndef SQLITE_OMIT_TRACE
22093 i64 startTime; /* Time when query started - used for profiling */
22094#endif
22095#ifdef SQLITE_DEBUG
22096 int rcApp; /* errcode set by sqlite3_result_error_code() */
22097 u32 nWrite; /* Number of write operations that have occurred */
22098#endif
22099 u16 nResColumn; /* Number of columns in one row of the result set */
22100 u8 errorAction; /* Recovery action to do in case of an error */
22101 u8 minWriteFileFormat; /* Minimum file format for writable database files */
22102 u8 prepFlags; /* SQLITE_PREPARE_* flags */
22103 u8 doingRerun; /* True if rerunning after an auto-reprepare */
22104 bft expired:2; /* 1: recompile VM immediately 2: when convenient */
22105 bft explain:2; /* True if EXPLAIN present on SQL command */
22106 bft changeCntOn:1; /* True to update the change-counter */
22107 bft runOnlyOnce:1; /* Automatically expire on reset */
22108 bft usesStmtJournal:1; /* True if uses a statement journal */
22109 bft readOnly:1; /* True for statements that do not write */
22110 bft bIsReader:1; /* True for statements that read */
22111 yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
22112 yDbMask lockMask; /* Subset of btreeMask that requires a lock */
22113 u32 aCounter[7]; /* Counters used by sqlite3_stmt_status() */
22114 char *zSql; /* Text of the SQL statement that generated this */
22115#ifdef SQLITE_ENABLE_NORMALIZE
22116 char *zNormSql; /* Normalization of the associated SQL statement */
22117 DblquoteStr *pDblStr; /* List of double-quoted string literals */
22118#endif
22119 void *pFree; /* Free this when deleting the vdbe */
22120 VdbeFrame *pFrame; /* Parent frame */
22121 VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
22122 int nFrame; /* Number of frames in pFrame list */
22123 u32 expmask; /* Binding to these vars invalidates VM */
22124 SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
22125 AuxData *pAuxData; /* Linked list of auxdata allocations */
22126#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
22127 i64 *anExec; /* Number of times each op has been executed */
22128 int nScan; /* Entries in aScan[] */
22129 ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
22130#endif
22131};
22132
22133/*
22134** The following are allowed values for Vdbe.magic
22135*/
22136#define VDBE_MAGIC_INIT 0x16bceaa5 /* Building a VDBE program */
22137#define VDBE_MAGIC_RUN 0x2df20da3 /* VDBE is ready to execute */
22138#define VDBE_MAGIC_HALT 0x319c2973 /* VDBE has completed execution */
22139#define VDBE_MAGIC_RESET 0x48fa9f76 /* Reset and ready to run again */
22140#define VDBE_MAGIC_DEAD 0x5606c3c8 /* The VDBE has been deallocated */
22141
22142/*
22143** Structure used to store the context required by the
22144** sqlite3_preupdate_*() API functions.
22145*/
22146struct PreUpdate {
22147 Vdbe *v;
22148 VdbeCursor *pCsr; /* Cursor to read old values from */
22149 int op; /* One of SQLITE_INSERT, UPDATE, DELETE */
22150 u8 *aRecord; /* old.* database record */
22151 KeyInfo keyinfo;
22152 UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */
22153 UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */
22154 int iNewReg; /* Register for new.* values */
22155 int iBlobWrite; /* Value returned by preupdate_blobwrite() */
22156 i64 iKey1; /* First key value passed to hook */
22157 i64 iKey2; /* Second key value passed to hook */
22158 Mem *aNew; /* Array of new.* values */
22159 Table *pTab; /* Schema object being upated */
22160 Index *pPk; /* PK index if pTab is WITHOUT ROWID */
22161};
22162
22163/*
22164** Function prototypes
22165*/
22166SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
22167SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
22168void sqliteVdbePopStack(Vdbe*,int);
22169SQLITE_PRIVATE int SQLITE_NOINLINE sqlite3VdbeFinishMoveto(VdbeCursor*);
22170SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, u32*);
22171SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
22172SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
22173SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
22174SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
22175SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
22176SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
22177
22178int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
22179SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
22180SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
22181SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
22182#if !defined(SQLITE_OMIT_EXPLAIN) || defined(SQLITE_ENABLE_BYTECODE_VTAB)
22183SQLITE_PRIVATE int sqlite3VdbeNextOpcode(Vdbe*,Mem*,int,int*,int*,Op**);
22184SQLITE_PRIVATE char *sqlite3VdbeDisplayP4(sqlite3*,Op*);
22185#endif
22186#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
22187SQLITE_PRIVATE char *sqlite3VdbeDisplayComment(sqlite3*,const Op*,const char*);
22188#endif
22189#if !defined(SQLITE_OMIT_EXPLAIN)
22190SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
22191#endif
22192SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
22193SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
22194SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
22195SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
22196SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
22197SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
22198SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
22199SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, i64, u8, void(*)(void*));
22200SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
22201#ifdef SQLITE_OMIT_FLOATING_POINT
22202# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
22203#else
22204SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
22205#endif
22206SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*));
22207SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
22208SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
22209#ifndef SQLITE_OMIT_INCRBLOB
22210SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
22211#else
22212SQLITE_PRIVATE int sqlite3VdbeMemSetZeroBlob(Mem*,int);
22213#endif
22214#ifdef SQLITE_DEBUG
22215SQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem*);
22216#endif
22217SQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem*);
22218SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
22219SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
22220SQLITE_PRIVATE int sqlite3IntFloatCompare(i64,double);
22221SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
22222SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
22223SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
22224SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem*, int ifNull);
22225SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
22226SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
22227SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
22228SQLITE_PRIVATE int sqlite3VdbeMemCast(Mem*,u8,u8);
22229SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
22230SQLITE_PRIVATE int sqlite3VdbeMemFromBtreeZeroOffset(BtCursor*,u32,Mem*);
22231SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
22232SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
22233#ifndef SQLITE_OMIT_WINDOWFUNC
22234SQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem*, Mem*, FuncDef*);
22235#endif
22236#if !defined(SQLITE_OMIT_EXPLAIN) || defined(SQLITE_ENABLE_BYTECODE_VTAB)
22237SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
22238#endif
22239SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
22240SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
22241SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
22242#ifdef SQLITE_DEBUG
22243SQLITE_PRIVATE int sqlite3VdbeFrameIsValid(VdbeFrame*);
22244#endif
22245SQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void*); /* Destructor on Mem */
22246SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*); /* Actually deletes the Frame */
22247SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
22248#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
22249SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
22250 Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int,int);
22251#endif
22252SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
22253
22254SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
22255SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
22256SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
22257SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
22258SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *);
22259SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
22260SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
22261SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
22262
22263#ifdef SQLITE_DEBUG
22264SQLITE_PRIVATE void sqlite3VdbeIncrWriteCounter(Vdbe*, VdbeCursor*);
22265SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe*);
22266#else
22267# define sqlite3VdbeIncrWriteCounter(V,C)
22268# define sqlite3VdbeAssertAbortable(V)
22269#endif
22270
22271#if !defined(SQLITE_OMIT_SHARED_CACHE)
22272SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
22273#else
22274# define sqlite3VdbeEnter(X)
22275#endif
22276
22277#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
22278SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
22279#else
22280# define sqlite3VdbeLeave(X)
22281#endif
22282
22283#ifdef SQLITE_DEBUG
22284SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
22285SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
22286#endif
22287
22288#ifndef SQLITE_OMIT_FOREIGN_KEY
22289SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
22290#else
22291# define sqlite3VdbeCheckFk(p,i) 0
22292#endif
22293
22294#ifdef SQLITE_DEBUG
22295SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
22296SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, StrAccum *pStr);
22297#endif
22298#ifndef SQLITE_OMIT_UTF16
22299SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
22300SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
22301#endif
22302
22303#ifndef SQLITE_OMIT_INCRBLOB
22304SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
22305 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
22306#else
22307 #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
22308 #define ExpandBlob(P) SQLITE_OK
22309#endif
22310
22311#endif /* !defined(SQLITE_VDBEINT_H) */
22312
22313/************** End of vdbeInt.h *********************************************/
22314/************** Continuing where we left off in status.c *********************/
22315
22316/*
22317** Variables in which to record status information.
22318*/
22319#if SQLITE_PTRSIZE>4
22320typedef sqlite3_int64 sqlite3StatValueType;
22321#else
22322typedef u32 sqlite3StatValueType;
22323#endif
22324typedef struct sqlite3StatType sqlite3StatType;
22325static SQLITE_WSD struct sqlite3StatType {
22326 sqlite3StatValueType nowValue[10]; /* Current value */
22327 sqlite3StatValueType mxValue[10]; /* Maximum value */
22328} sqlite3Stat = { {0,}, {0,} };
22329
22330/*
22331** Elements of sqlite3Stat[] are protected by either the memory allocator
22332** mutex, or by the pcache1 mutex. The following array determines which.
22333*/
22334static const char statMutex[] = {
22335 0, /* SQLITE_STATUS_MEMORY_USED */
22336 1, /* SQLITE_STATUS_PAGECACHE_USED */
22337 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
22338 0, /* SQLITE_STATUS_SCRATCH_USED */
22339 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
22340 0, /* SQLITE_STATUS_MALLOC_SIZE */
22341 0, /* SQLITE_STATUS_PARSER_STACK */
22342 1, /* SQLITE_STATUS_PAGECACHE_SIZE */
22343 0, /* SQLITE_STATUS_SCRATCH_SIZE */
22344 0, /* SQLITE_STATUS_MALLOC_COUNT */
22345};
22346
22347
22348/* The "wsdStat" macro will resolve to the status information
22349** state vector. If writable static data is unsupported on the target,
22350** we have to locate the state vector at run-time. In the more common
22351** case where writable static data is supported, wsdStat can refer directly
22352** to the "sqlite3Stat" state vector declared above.
22353*/
22354#ifdef SQLITE_OMIT_WSD
22355# define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
22356# define wsdStat x[0]
22357#else
22358# define wsdStatInit
22359# define wsdStat sqlite3Stat
22360#endif
22361
22362/*
22363** Return the current value of a status parameter. The caller must
22364** be holding the appropriate mutex.
22365*/
22366SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
22367 wsdStatInit;
22368 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
22369 assert( op>=0 && op<ArraySize(statMutex) );
22370 assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
22371 : sqlite3MallocMutex()) );
22372 return wsdStat.nowValue[op];
22373}
22374
22375/*
22376** Add N to the value of a status record. The caller must hold the
22377** appropriate mutex. (Locking is checked by assert()).
22378**
22379** The StatusUp() routine can accept positive or negative values for N.
22380** The value of N is added to the current status value and the high-water
22381** mark is adjusted if necessary.
22382**
22383** The StatusDown() routine lowers the current value by N. The highwater
22384** mark is unchanged. N must be non-negative for StatusDown().
22385*/
22386SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
22387 wsdStatInit;
22388 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
22389 assert( op>=0 && op<ArraySize(statMutex) );
22390 assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
22391 : sqlite3MallocMutex()) );
22392 wsdStat.nowValue[op] += N;
22393 if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
22394 wsdStat.mxValue[op] = wsdStat.nowValue[op];
22395 }
22396}
22397SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
22398 wsdStatInit;
22399 assert( N>=0 );
22400 assert( op>=0 && op<ArraySize(statMutex) );
22401 assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
22402 : sqlite3MallocMutex()) );
22403 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
22404 wsdStat.nowValue[op] -= N;
22405}
22406
22407/*
22408** Adjust the highwater mark if necessary.
22409** The caller must hold the appropriate mutex.
22410*/
22411SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
22412 sqlite3StatValueType newValue;
22413 wsdStatInit;
22414 assert( X>=0 );
22415 newValue = (sqlite3StatValueType)X;
22416 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
22417 assert( op>=0 && op<ArraySize(statMutex) );
22418 assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
22419 : sqlite3MallocMutex()) );
22420 assert( op==SQLITE_STATUS_MALLOC_SIZE
22421 || op==SQLITE_STATUS_PAGECACHE_SIZE
22422 || op==SQLITE_STATUS_PARSER_STACK );
22423 if( newValue>wsdStat.mxValue[op] ){
22424 wsdStat.mxValue[op] = newValue;
22425 }
22426}
22427
22428/*
22429** Query status information.
22430*/
22431SQLITE_API int sqlite3_status64(
22432 int op,
22433 sqlite3_int64 *pCurrent,
22434 sqlite3_int64 *pHighwater,
22435 int resetFlag
22436){
22437 sqlite3_mutex *pMutex;
22438 wsdStatInit;
22439 if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
22440 return SQLITE_MISUSE_BKPT;
22441 }
22442#ifdef SQLITE_ENABLE_API_ARMOR
22443 if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
22444#endif
22445 pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
22446 sqlite3_mutex_enter(pMutex);
22447 *pCurrent = wsdStat.nowValue[op];
22448 *pHighwater = wsdStat.mxValue[op];
22449 if( resetFlag ){
22450 wsdStat.mxValue[op] = wsdStat.nowValue[op];
22451 }
22452 sqlite3_mutex_leave(pMutex);
22453 (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
22454 return SQLITE_OK;
22455}
22456SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
22457 sqlite3_int64 iCur = 0, iHwtr = 0;
22458 int rc;
22459#ifdef SQLITE_ENABLE_API_ARMOR
22460 if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
22461#endif
22462 rc = sqlite3_status64(op, pCurrent: &iCur, pHighwater: &iHwtr, resetFlag);
22463 if( rc==0 ){
22464 *pCurrent = (int)iCur;
22465 *pHighwater = (int)iHwtr;
22466 }
22467 return rc;
22468}
22469
22470/*
22471** Return the number of LookasideSlot elements on the linked list
22472*/
22473static u32 countLookasideSlots(LookasideSlot *p){
22474 u32 cnt = 0;
22475 while( p ){
22476 p = p->pNext;
22477 cnt++;
22478 }
22479 return cnt;
22480}
22481
22482/*
22483** Count the number of slots of lookaside memory that are outstanding
22484*/
22485SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){
22486 u32 nInit = countLookasideSlots(p: db->lookaside.pInit);
22487 u32 nFree = countLookasideSlots(p: db->lookaside.pFree);
22488#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
22489 nInit += countLookasideSlots(p: db->lookaside.pSmallInit);
22490 nFree += countLookasideSlots(p: db->lookaside.pSmallFree);
22491#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
22492 if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit;
22493 return db->lookaside.nSlot - (nInit+nFree);
22494}
22495
22496/*
22497** Query status information for a single database connection
22498*/
22499SQLITE_API int sqlite3_db_status(
22500 sqlite3 *db, /* The database connection whose status is desired */
22501 int op, /* Status verb */
22502 int *pCurrent, /* Write current value here */
22503 int *pHighwater, /* Write high-water mark here */
22504 int resetFlag /* Reset high-water mark if true */
22505){
22506 int rc = SQLITE_OK; /* Return code */
22507#ifdef SQLITE_ENABLE_API_ARMOR
22508 if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
22509 return SQLITE_MISUSE_BKPT;
22510 }
22511#endif
22512 sqlite3_mutex_enter(db->mutex);
22513 switch( op ){
22514 case SQLITE_DBSTATUS_LOOKASIDE_USED: {
22515 *pCurrent = sqlite3LookasideUsed(db, pHighwater);
22516 if( resetFlag ){
22517 LookasideSlot *p = db->lookaside.pFree;
22518 if( p ){
22519 while( p->pNext ) p = p->pNext;
22520 p->pNext = db->lookaside.pInit;
22521 db->lookaside.pInit = db->lookaside.pFree;
22522 db->lookaside.pFree = 0;
22523 }
22524#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
22525 p = db->lookaside.pSmallFree;
22526 if( p ){
22527 while( p->pNext ) p = p->pNext;
22528 p->pNext = db->lookaside.pSmallInit;
22529 db->lookaside.pSmallInit = db->lookaside.pSmallFree;
22530 db->lookaside.pSmallFree = 0;
22531 }
22532#endif
22533 }
22534 break;
22535 }
22536
22537 case SQLITE_DBSTATUS_LOOKASIDE_HIT:
22538 case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
22539 case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
22540 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
22541 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
22542 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
22543 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
22544 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
22545 *pCurrent = 0;
22546 *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
22547 if( resetFlag ){
22548 db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
22549 }
22550 break;
22551 }
22552
22553 /*
22554 ** Return an approximation for the amount of memory currently used
22555 ** by all pagers associated with the given database connection. The
22556 ** highwater mark is meaningless and is returned as zero.
22557 */
22558 case SQLITE_DBSTATUS_CACHE_USED_SHARED:
22559 case SQLITE_DBSTATUS_CACHE_USED: {
22560 int totalUsed = 0;
22561 int i;
22562 sqlite3BtreeEnterAll(db);
22563 for(i=0; i<db->nDb; i++){
22564 Btree *pBt = db->aDb[i].pBt;
22565 if( pBt ){
22566 Pager *pPager = sqlite3BtreePager(pBt);
22567 int nByte = sqlite3PagerMemUsed(pPager);
22568 if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
22569 nByte = nByte / sqlite3BtreeConnectionCount(pBt);
22570 }
22571 totalUsed += nByte;
22572 }
22573 }
22574 sqlite3BtreeLeaveAll(db);
22575 *pCurrent = totalUsed;
22576 *pHighwater = 0;
22577 break;
22578 }
22579
22580 /*
22581 ** *pCurrent gets an accurate estimate of the amount of memory used
22582 ** to store the schema for all databases (main, temp, and any ATTACHed
22583 ** databases. *pHighwater is set to zero.
22584 */
22585 case SQLITE_DBSTATUS_SCHEMA_USED: {
22586 int i; /* Used to iterate through schemas */
22587 int nByte = 0; /* Used to accumulate return value */
22588
22589 sqlite3BtreeEnterAll(db);
22590 db->pnBytesFreed = &nByte;
22591 for(i=0; i<db->nDb; i++){
22592 Schema *pSchema = db->aDb[i].pSchema;
22593 if( ALWAYS(pSchema!=0) ){
22594 HashElem *p;
22595
22596 nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
22597 pSchema->tblHash.count
22598 + pSchema->trigHash.count
22599 + pSchema->idxHash.count
22600 + pSchema->fkeyHash.count
22601 );
22602 nByte += sqlite3_msize(pSchema->tblHash.ht);
22603 nByte += sqlite3_msize(pSchema->trigHash.ht);
22604 nByte += sqlite3_msize(pSchema->idxHash.ht);
22605 nByte += sqlite3_msize(pSchema->fkeyHash.ht);
22606
22607 for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
22608 sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
22609 }
22610 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
22611 sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
22612 }
22613 }
22614 }
22615 db->pnBytesFreed = 0;
22616 sqlite3BtreeLeaveAll(db);
22617
22618 *pHighwater = 0;
22619 *pCurrent = nByte;
22620 break;
22621 }
22622
22623 /*
22624 ** *pCurrent gets an accurate estimate of the amount of memory used
22625 ** to store all prepared statements.
22626 ** *pHighwater is set to zero.
22627 */
22628 case SQLITE_DBSTATUS_STMT_USED: {
22629 struct Vdbe *pVdbe; /* Used to iterate through VMs */
22630 int nByte = 0; /* Used to accumulate return value */
22631
22632 db->pnBytesFreed = &nByte;
22633 for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
22634 sqlite3VdbeClearObject(db, pVdbe);
22635 sqlite3DbFree(db, pVdbe);
22636 }
22637 db->pnBytesFreed = 0;
22638
22639 *pHighwater = 0; /* IMP: R-64479-57858 */
22640 *pCurrent = nByte;
22641
22642 break;
22643 }
22644
22645 /*
22646 ** Set *pCurrent to the total cache hits or misses encountered by all
22647 ** pagers the database handle is connected to. *pHighwater is always set
22648 ** to zero.
22649 */
22650 case SQLITE_DBSTATUS_CACHE_SPILL:
22651 op = SQLITE_DBSTATUS_CACHE_WRITE+1;
22652 /* no break */ deliberate_fall_through
22653 case SQLITE_DBSTATUS_CACHE_HIT:
22654 case SQLITE_DBSTATUS_CACHE_MISS:
22655 case SQLITE_DBSTATUS_CACHE_WRITE:{
22656 int i;
22657 int nRet = 0;
22658 assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
22659 assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
22660
22661 for(i=0; i<db->nDb; i++){
22662 if( db->aDb[i].pBt ){
22663 Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
22664 sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
22665 }
22666 }
22667 *pHighwater = 0; /* IMP: R-42420-56072 */
22668 /* IMP: R-54100-20147 */
22669 /* IMP: R-29431-39229 */
22670 *pCurrent = nRet;
22671 break;
22672 }
22673
22674 /* Set *pCurrent to non-zero if there are unresolved deferred foreign
22675 ** key constraints. Set *pCurrent to zero if all foreign key constraints
22676 ** have been satisfied. The *pHighwater is always set to zero.
22677 */
22678 case SQLITE_DBSTATUS_DEFERRED_FKS: {
22679 *pHighwater = 0; /* IMP: R-11967-56545 */
22680 *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
22681 break;
22682 }
22683
22684 default: {
22685 rc = SQLITE_ERROR;
22686 }
22687 }
22688 sqlite3_mutex_leave(db->mutex);
22689 return rc;
22690}
22691
22692/************** End of status.c **********************************************/
22693/************** Begin file date.c ********************************************/
22694/*
22695** 2003 October 31
22696**
22697** The author disclaims copyright to this source code. In place of
22698** a legal notice, here is a blessing:
22699**
22700** May you do good and not evil.
22701** May you find forgiveness for yourself and forgive others.
22702** May you share freely, never taking more than you give.
22703**
22704*************************************************************************
22705** This file contains the C functions that implement date and time
22706** functions for SQLite.
22707**
22708** There is only one exported symbol in this file - the function
22709** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
22710** All other code has file scope.
22711**
22712** SQLite processes all times and dates as julian day numbers. The
22713** dates and times are stored as the number of days since noon
22714** in Greenwich on November 24, 4714 B.C. according to the Gregorian
22715** calendar system.
22716**
22717** 1970-01-01 00:00:00 is JD 2440587.5
22718** 2000-01-01 00:00:00 is JD 2451544.5
22719**
22720** This implementation requires years to be expressed as a 4-digit number
22721** which means that only dates between 0000-01-01 and 9999-12-31 can
22722** be represented, even though julian day numbers allow a much wider
22723** range of dates.
22724**
22725** The Gregorian calendar system is used for all dates and times,
22726** even those that predate the Gregorian calendar. Historians usually
22727** use the julian calendar for dates prior to 1582-10-15 and for some
22728** dates afterwards, depending on locale. Beware of this difference.
22729**
22730** The conversion algorithms are implemented based on descriptions
22731** in the following text:
22732**
22733** Jean Meeus
22734** Astronomical Algorithms, 2nd Edition, 1998
22735** ISBN 0-943396-61-1
22736** Willmann-Bell, Inc
22737** Richmond, Virginia (USA)
22738*/
22739/* #include "sqliteInt.h" */
22740/* #include <stdlib.h> */
22741/* #include <assert.h> */
22742#include <time.h>
22743
22744#ifndef SQLITE_OMIT_DATETIME_FUNCS
22745
22746/*
22747** The MSVC CRT on Windows CE may not have a localtime() function.
22748** So declare a substitute. The substitute function itself is
22749** defined in "os_win.c".
22750*/
22751#if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
22752 (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
22753struct tm *__cdecl localtime(const time_t *);
22754#endif
22755
22756/*
22757** A structure for holding a single date and time.
22758*/
22759typedef struct DateTime DateTime;
22760struct DateTime {
22761 sqlite3_int64 iJD; /* The julian day number times 86400000 */
22762 int Y, M, D; /* Year, month, and day */
22763 int h, m; /* Hour and minutes */
22764 int tz; /* Timezone offset in minutes */
22765 double s; /* Seconds */
22766 char validJD; /* True (1) if iJD is valid */
22767 char rawS; /* Raw numeric value stored in s */
22768 char validYMD; /* True (1) if Y,M,D are valid */
22769 char validHMS; /* True (1) if h,m,s are valid */
22770 char validTZ; /* True (1) if tz is valid */
22771 char tzSet; /* Timezone was set explicitly */
22772 char isError; /* An overflow has occurred */
22773};
22774
22775
22776/*
22777** Convert zDate into one or more integers according to the conversion
22778** specifier zFormat.
22779**
22780** zFormat[] contains 4 characters for each integer converted, except for
22781** the last integer which is specified by three characters. The meaning
22782** of a four-character format specifiers ABCD is:
22783**
22784** A: number of digits to convert. Always "2" or "4".
22785** B: minimum value. Always "0" or "1".
22786** C: maximum value, decoded as:
22787** a: 12
22788** b: 14
22789** c: 24
22790** d: 31
22791** e: 59
22792** f: 9999
22793** D: the separator character, or \000 to indicate this is the
22794** last number to convert.
22795**
22796** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
22797** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
22798** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
22799** the 2-digit day which is the last integer in the set.
22800**
22801** The function returns the number of successful conversions.
22802*/
22803static int getDigits(const char *zDate, const char *zFormat, ...){
22804 /* The aMx[] array translates the 3rd character of each format
22805 ** spec into a max size: a b c d e f */
22806 static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
22807 va_list ap;
22808 int cnt = 0;
22809 char nextC;
22810 va_start(ap, zFormat);
22811 do{
22812 char N = zFormat[0] - '0';
22813 char min = zFormat[1] - '0';
22814 int val = 0;
22815 u16 max;
22816
22817 assert( zFormat[2]>='a' && zFormat[2]<='f' );
22818 max = aMx[zFormat[2] - 'a'];
22819 nextC = zFormat[3];
22820 val = 0;
22821 while( N-- ){
22822 if( !sqlite3Isdigit(*zDate) ){
22823 goto end_getDigits;
22824 }
22825 val = val*10 + *zDate - '0';
22826 zDate++;
22827 }
22828 if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
22829 goto end_getDigits;
22830 }
22831 *va_arg(ap,int*) = val;
22832 zDate++;
22833 cnt++;
22834 zFormat += 4;
22835 }while( nextC );
22836end_getDigits:
22837 va_end(ap);
22838 return cnt;
22839}
22840
22841/*
22842** Parse a timezone extension on the end of a date-time.
22843** The extension is of the form:
22844**
22845** (+/-)HH:MM
22846**
22847** Or the "zulu" notation:
22848**
22849** Z
22850**
22851** If the parse is successful, write the number of minutes
22852** of change in p->tz and return 0. If a parser error occurs,
22853** return non-zero.
22854**
22855** A missing specifier is not considered an error.
22856*/
22857static int parseTimezone(const char *zDate, DateTime *p){
22858 int sgn = 0;
22859 int nHr, nMn;
22860 int c;
22861 while( sqlite3Isspace(*zDate) ){ zDate++; }
22862 p->tz = 0;
22863 c = *zDate;
22864 if( c=='-' ){
22865 sgn = -1;
22866 }else if( c=='+' ){
22867 sgn = +1;
22868 }else if( c=='Z' || c=='z' ){
22869 zDate++;
22870 goto zulu_time;
22871 }else{
22872 return c!=0;
22873 }
22874 zDate++;
22875 if( getDigits(zDate, zFormat: "20b:20e", &nHr, &nMn)!=2 ){
22876 return 1;
22877 }
22878 zDate += 5;
22879 p->tz = sgn*(nMn + nHr*60);
22880zulu_time:
22881 while( sqlite3Isspace(*zDate) ){ zDate++; }
22882 p->tzSet = 1;
22883 return *zDate!=0;
22884}
22885
22886/*
22887** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
22888** The HH, MM, and SS must each be exactly 2 digits. The
22889** fractional seconds FFFF can be one or more digits.
22890**
22891** Return 1 if there is a parsing error and 0 on success.
22892*/
22893static int parseHhMmSs(const char *zDate, DateTime *p){
22894 int h, m, s;
22895 double ms = 0.0;
22896 if( getDigits(zDate, zFormat: "20c:20e", &h, &m)!=2 ){
22897 return 1;
22898 }
22899 zDate += 5;
22900 if( *zDate==':' ){
22901 zDate++;
22902 if( getDigits(zDate, zFormat: "20e", &s)!=1 ){
22903 return 1;
22904 }
22905 zDate += 2;
22906 if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
22907 double rScale = 1.0;
22908 zDate++;
22909 while( sqlite3Isdigit(*zDate) ){
22910 ms = ms*10.0 + *zDate - '0';
22911 rScale *= 10.0;
22912 zDate++;
22913 }
22914 ms /= rScale;
22915 }
22916 }else{
22917 s = 0;
22918 }
22919 p->validJD = 0;
22920 p->rawS = 0;
22921 p->validHMS = 1;
22922 p->h = h;
22923 p->m = m;
22924 p->s = s + ms;
22925 if( parseTimezone(zDate, p) ) return 1;
22926 p->validTZ = (p->tz!=0)?1:0;
22927 return 0;
22928}
22929
22930/*
22931** Put the DateTime object into its error state.
22932*/
22933static void datetimeError(DateTime *p){
22934 memset(s: p, c: 0, n: sizeof(*p));
22935 p->isError = 1;
22936}
22937
22938/*
22939** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
22940** that the YYYY-MM-DD is according to the Gregorian calendar.
22941**
22942** Reference: Meeus page 61
22943*/
22944static void computeJD(DateTime *p){
22945 int Y, M, D, A, B, X1, X2;
22946
22947 if( p->validJD ) return;
22948 if( p->validYMD ){
22949 Y = p->Y;
22950 M = p->M;
22951 D = p->D;
22952 }else{
22953 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
22954 M = 1;
22955 D = 1;
22956 }
22957 if( Y<-4713 || Y>9999 || p->rawS ){
22958 datetimeError(p);
22959 return;
22960 }
22961 if( M<=2 ){
22962 Y--;
22963 M += 12;
22964 }
22965 A = Y/100;
22966 B = 2 - A + (A/4);
22967 X1 = 36525*(Y+4716)/100;
22968 X2 = 306001*(M+1)/10000;
22969 p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
22970 p->validJD = 1;
22971 if( p->validHMS ){
22972 p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
22973 if( p->validTZ ){
22974 p->iJD -= p->tz*60000;
22975 p->validYMD = 0;
22976 p->validHMS = 0;
22977 p->validTZ = 0;
22978 }
22979 }
22980}
22981
22982/*
22983** Parse dates of the form
22984**
22985** YYYY-MM-DD HH:MM:SS.FFF
22986** YYYY-MM-DD HH:MM:SS
22987** YYYY-MM-DD HH:MM
22988** YYYY-MM-DD
22989**
22990** Write the result into the DateTime structure and return 0
22991** on success and 1 if the input string is not a well-formed
22992** date.
22993*/
22994static int parseYyyyMmDd(const char *zDate, DateTime *p){
22995 int Y, M, D, neg;
22996
22997 if( zDate[0]=='-' ){
22998 zDate++;
22999 neg = 1;
23000 }else{
23001 neg = 0;
23002 }
23003 if( getDigits(zDate, zFormat: "40f-21a-21d", &Y, &M, &D)!=3 ){
23004 return 1;
23005 }
23006 zDate += 10;
23007 while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
23008 if( parseHhMmSs(zDate, p)==0 ){
23009 /* We got the time */
23010 }else if( *zDate==0 ){
23011 p->validHMS = 0;
23012 }else{
23013 return 1;
23014 }
23015 p->validJD = 0;
23016 p->validYMD = 1;
23017 p->Y = neg ? -Y : Y;
23018 p->M = M;
23019 p->D = D;
23020 if( p->validTZ ){
23021 computeJD(p);
23022 }
23023 return 0;
23024}
23025
23026/*
23027** Set the time to the current time reported by the VFS.
23028**
23029** Return the number of errors.
23030*/
23031static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
23032 p->iJD = sqlite3StmtCurrentTime(context);
23033 if( p->iJD>0 ){
23034 p->validJD = 1;
23035 return 0;
23036 }else{
23037 return 1;
23038 }
23039}
23040
23041/*
23042** Input "r" is a numeric quantity which might be a julian day number,
23043** or the number of seconds since 1970. If the value if r is within
23044** range of a julian day number, install it as such and set validJD.
23045** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
23046*/
23047static void setRawDateNumber(DateTime *p, double r){
23048 p->s = r;
23049 p->rawS = 1;
23050 if( r>=0.0 && r<5373484.5 ){
23051 p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
23052 p->validJD = 1;
23053 }
23054}
23055
23056/*
23057** Attempt to parse the given string into a julian day number. Return
23058** the number of errors.
23059**
23060** The following are acceptable forms for the input string:
23061**
23062** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
23063** DDDD.DD
23064** now
23065**
23066** In the first form, the +/-HH:MM is always optional. The fractional
23067** seconds extension (the ".FFF") is optional. The seconds portion
23068** (":SS.FFF") is option. The year and date can be omitted as long
23069** as there is a time string. The time string can be omitted as long
23070** as there is a year and date.
23071*/
23072static int parseDateOrTime(
23073 sqlite3_context *context,
23074 const char *zDate,
23075 DateTime *p
23076){
23077 double r;
23078 if( parseYyyyMmDd(zDate,p)==0 ){
23079 return 0;
23080 }else if( parseHhMmSs(zDate, p)==0 ){
23081 return 0;
23082 }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
23083 return setDateTimeToCurrent(context, p);
23084 }else if( sqlite3AtoF(z: zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8)>0 ){
23085 setRawDateNumber(p, r);
23086 return 0;
23087 }
23088 return 1;
23089}
23090
23091/* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
23092** Multiplying this by 86400000 gives 464269060799999 as the maximum value
23093** for DateTime.iJD.
23094**
23095** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with
23096** such a large integer literal, so we have to encode it.
23097*/
23098#define INT_464269060799999 ((((i64)0x1a640)<<32)|0x1072fdff)
23099
23100/*
23101** Return TRUE if the given julian day number is within range.
23102**
23103** The input is the JulianDay times 86400000.
23104*/
23105static int validJulianDay(sqlite3_int64 iJD){
23106 return iJD>=0 && iJD<=INT_464269060799999;
23107}
23108
23109/*
23110** Compute the Year, Month, and Day from the julian day number.
23111*/
23112static void computeYMD(DateTime *p){
23113 int Z, A, B, C, D, E, X1;
23114 if( p->validYMD ) return;
23115 if( !p->validJD ){
23116 p->Y = 2000;
23117 p->M = 1;
23118 p->D = 1;
23119 }else if( !validJulianDay(iJD: p->iJD) ){
23120 datetimeError(p);
23121 return;
23122 }else{
23123 Z = (int)((p->iJD + 43200000)/86400000);
23124 A = (int)((Z - 1867216.25)/36524.25);
23125 A = Z + 1 + A - (A/4);
23126 B = A + 1524;
23127 C = (int)((B - 122.1)/365.25);
23128 D = (36525*(C&32767))/100;
23129 E = (int)((B-D)/30.6001);
23130 X1 = (int)(30.6001*E);
23131 p->D = B - D - X1;
23132 p->M = E<14 ? E-1 : E-13;
23133 p->Y = p->M>2 ? C - 4716 : C - 4715;
23134 }
23135 p->validYMD = 1;
23136}
23137
23138/*
23139** Compute the Hour, Minute, and Seconds from the julian day number.
23140*/
23141static void computeHMS(DateTime *p){
23142 int s;
23143 if( p->validHMS ) return;
23144 computeJD(p);
23145 s = (int)((p->iJD + 43200000) % 86400000);
23146 p->s = s/1000.0;
23147 s = (int)p->s;
23148 p->s -= s;
23149 p->h = s/3600;
23150 s -= p->h*3600;
23151 p->m = s/60;
23152 p->s += s - p->m*60;
23153 p->rawS = 0;
23154 p->validHMS = 1;
23155}
23156
23157/*
23158** Compute both YMD and HMS
23159*/
23160static void computeYMD_HMS(DateTime *p){
23161 computeYMD(p);
23162 computeHMS(p);
23163}
23164
23165/*
23166** Clear the YMD and HMS and the TZ
23167*/
23168static void clearYMD_HMS_TZ(DateTime *p){
23169 p->validYMD = 0;
23170 p->validHMS = 0;
23171 p->validTZ = 0;
23172}
23173
23174#ifndef SQLITE_OMIT_LOCALTIME
23175/*
23176** On recent Windows platforms, the localtime_s() function is available
23177** as part of the "Secure CRT". It is essentially equivalent to
23178** localtime_r() available under most POSIX platforms, except that the
23179** order of the parameters is reversed.
23180**
23181** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
23182**
23183** If the user has not indicated to use localtime_r() or localtime_s()
23184** already, check for an MSVC build environment that provides
23185** localtime_s().
23186*/
23187#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
23188 && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
23189#undef HAVE_LOCALTIME_S
23190#define HAVE_LOCALTIME_S 1
23191#endif
23192
23193/*
23194** The following routine implements the rough equivalent of localtime_r()
23195** using whatever operating-system specific localtime facility that
23196** is available. This routine returns 0 on success and
23197** non-zero on any kind of error.
23198**
23199** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
23200** routine will always fail.
23201**
23202** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
23203** library function localtime_r() is used to assist in the calculation of
23204** local time.
23205*/
23206static int osLocaltime(time_t *t, struct tm *pTm){
23207 int rc;
23208#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
23209 struct tm *pX;
23210#if SQLITE_THREADSAFE>0
23211 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
23212#endif
23213 sqlite3_mutex_enter(mutex);
23214 pX = localtime(timer: t);
23215#ifndef SQLITE_UNTESTABLE
23216 if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
23217#endif
23218 if( pX ) *pTm = *pX;
23219 sqlite3_mutex_leave(mutex);
23220 rc = pX==0;
23221#else
23222#ifndef SQLITE_UNTESTABLE
23223 if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
23224#endif
23225#if HAVE_LOCALTIME_R
23226 rc = localtime_r(t, pTm)==0;
23227#else
23228 rc = localtime_s(pTm, t);
23229#endif /* HAVE_LOCALTIME_R */
23230#endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
23231 return rc;
23232}
23233#endif /* SQLITE_OMIT_LOCALTIME */
23234
23235
23236#ifndef SQLITE_OMIT_LOCALTIME
23237/*
23238** Compute the difference (in milliseconds) between localtime and UTC
23239** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
23240** return this value and set *pRc to SQLITE_OK.
23241**
23242** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
23243** is undefined in this case.
23244*/
23245static sqlite3_int64 localtimeOffset(
23246 DateTime *p, /* Date at which to calculate offset */
23247 sqlite3_context *pCtx, /* Write error here if one occurs */
23248 int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
23249){
23250 DateTime x, y;
23251 time_t t;
23252 struct tm sLocal;
23253
23254 /* Initialize the contents of sLocal to avoid a compiler warning. */
23255 memset(s: &sLocal, c: 0, n: sizeof(sLocal));
23256
23257 x = *p;
23258 computeYMD_HMS(p: &x);
23259 if( x.Y<1971 || x.Y>=2038 ){
23260 /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
23261 ** works for years between 1970 and 2037. For dates outside this range,
23262 ** SQLite attempts to map the year into an equivalent year within this
23263 ** range, do the calculation, then map the year back.
23264 */
23265 x.Y = 2000;
23266 x.M = 1;
23267 x.D = 1;
23268 x.h = 0;
23269 x.m = 0;
23270 x.s = 0.0;
23271 } else {
23272 int s = (int)(x.s + 0.5);
23273 x.s = s;
23274 }
23275 x.tz = 0;
23276 x.validJD = 0;
23277 computeJD(p: &x);
23278 t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
23279 if( osLocaltime(t: &t, pTm: &sLocal) ){
23280 sqlite3_result_error(pCtx, "local time unavailable", -1);
23281 *pRc = SQLITE_ERROR;
23282 return 0;
23283 }
23284 y.Y = sLocal.tm_year + 1900;
23285 y.M = sLocal.tm_mon + 1;
23286 y.D = sLocal.tm_mday;
23287 y.h = sLocal.tm_hour;
23288 y.m = sLocal.tm_min;
23289 y.s = sLocal.tm_sec;
23290 y.validYMD = 1;
23291 y.validHMS = 1;
23292 y.validJD = 0;
23293 y.rawS = 0;
23294 y.validTZ = 0;
23295 y.isError = 0;
23296 computeJD(p: &y);
23297 *pRc = SQLITE_OK;
23298 return y.iJD - x.iJD;
23299}
23300#endif /* SQLITE_OMIT_LOCALTIME */
23301
23302/*
23303** The following table defines various date transformations of the form
23304**
23305** 'NNN days'
23306**
23307** Where NNN is an arbitrary floating-point number and "days" can be one
23308** of several units of time.
23309*/
23310static const struct {
23311 u8 eType; /* Transformation type code */
23312 u8 nName; /* Length of th name */
23313 char *zName; /* Name of the transformation */
23314 double rLimit; /* Maximum NNN value for this transform */
23315 double rXform; /* Constant used for this transform */
23316} aXformType[] = {
23317 { 0, 6, "second", 464269060800.0, 1000.0 },
23318 { 0, 6, "minute", 7737817680.0, 60000.0 },
23319 { 0, 4, "hour", 128963628.0, 3600000.0 },
23320 { 0, 3, "day", 5373485.0, 86400000.0 },
23321 { 1, 5, "month", 176546.0, 2592000000.0 },
23322 { 2, 4, "year", 14713.0, 31536000000.0 },
23323};
23324
23325/*
23326** Process a modifier to a date-time stamp. The modifiers are
23327** as follows:
23328**
23329** NNN days
23330** NNN hours
23331** NNN minutes
23332** NNN.NNNN seconds
23333** NNN months
23334** NNN years
23335** start of month
23336** start of year
23337** start of week
23338** start of day
23339** weekday N
23340** unixepoch
23341** localtime
23342** utc
23343**
23344** Return 0 on success and 1 if there is any kind of error. If the error
23345** is in a system call (i.e. localtime()), then an error message is written
23346** to context pCtx. If the error is an unrecognized modifier, no error is
23347** written to pCtx.
23348*/
23349static int parseModifier(
23350 sqlite3_context *pCtx, /* Function context */
23351 const char *z, /* The text of the modifier */
23352 int n, /* Length of zMod in bytes */
23353 DateTime *p /* The date/time value to be modified */
23354){
23355 int rc = 1;
23356 double r;
23357 switch(sqlite3UpperToLower[(u8)z[0]] ){
23358#ifndef SQLITE_OMIT_LOCALTIME
23359 case 'l': {
23360 /* localtime
23361 **
23362 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
23363 ** show local time.
23364 */
23365 if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){
23366 computeJD(p);
23367 p->iJD += localtimeOffset(p, pCtx, pRc: &rc);
23368 clearYMD_HMS_TZ(p);
23369 }
23370 break;
23371 }
23372#endif
23373 case 'u': {
23374 /*
23375 ** unixepoch
23376 **
23377 ** Treat the current value of p->s as the number of
23378 ** seconds since 1970. Convert to a real julian day number.
23379 */
23380 if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
23381 r = p->s*1000.0 + 210866760000000.0;
23382 if( r>=0.0 && r<464269060800000.0 ){
23383 clearYMD_HMS_TZ(p);
23384 p->iJD = (sqlite3_int64)(r + 0.5);
23385 p->validJD = 1;
23386 p->rawS = 0;
23387 rc = 0;
23388 }
23389 }
23390#ifndef SQLITE_OMIT_LOCALTIME
23391 else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){
23392 if( p->tzSet==0 ){
23393 sqlite3_int64 c1;
23394 computeJD(p);
23395 c1 = localtimeOffset(p, pCtx, pRc: &rc);
23396 if( rc==SQLITE_OK ){
23397 p->iJD -= c1;
23398 clearYMD_HMS_TZ(p);
23399 p->iJD += c1 - localtimeOffset(p, pCtx, pRc: &rc);
23400 }
23401 p->tzSet = 1;
23402 }else{
23403 rc = SQLITE_OK;
23404 }
23405 }
23406#endif
23407 break;
23408 }
23409 case 'w': {
23410 /*
23411 ** weekday N
23412 **
23413 ** Move the date to the same time on the next occurrence of
23414 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
23415 ** date is already on the appropriate weekday, this is a no-op.
23416 */
23417 if( sqlite3_strnicmp(z, "weekday ", 8)==0
23418 && sqlite3AtoF(z: &z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)>0
23419 && (n=(int)r)==r && n>=0 && r<7 ){
23420 sqlite3_int64 Z;
23421 computeYMD_HMS(p);
23422 p->validTZ = 0;
23423 p->validJD = 0;
23424 computeJD(p);
23425 Z = ((p->iJD + 129600000)/86400000) % 7;
23426 if( Z>n ) Z -= 7;
23427 p->iJD += (n - Z)*86400000;
23428 clearYMD_HMS_TZ(p);
23429 rc = 0;
23430 }
23431 break;
23432 }
23433 case 's': {
23434 /*
23435 ** start of TTTTT
23436 **
23437 ** Move the date backwards to the beginning of the current day,
23438 ** or month or year.
23439 */
23440 if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break;
23441 if( !p->validJD && !p->validYMD && !p->validHMS ) break;
23442 z += 9;
23443 computeYMD(p);
23444 p->validHMS = 1;
23445 p->h = p->m = 0;
23446 p->s = 0.0;
23447 p->rawS = 0;
23448 p->validTZ = 0;
23449 p->validJD = 0;
23450 if( sqlite3_stricmp(z,"month")==0 ){
23451 p->D = 1;
23452 rc = 0;
23453 }else if( sqlite3_stricmp(z,"year")==0 ){
23454 p->M = 1;
23455 p->D = 1;
23456 rc = 0;
23457 }else if( sqlite3_stricmp(z,"day")==0 ){
23458 rc = 0;
23459 }
23460 break;
23461 }
23462 case '+':
23463 case '-':
23464 case '0':
23465 case '1':
23466 case '2':
23467 case '3':
23468 case '4':
23469 case '5':
23470 case '6':
23471 case '7':
23472 case '8':
23473 case '9': {
23474 double rRounder;
23475 int i;
23476 for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
23477 if( sqlite3AtoF(z, &r, n, SQLITE_UTF8)<=0 ){
23478 rc = 1;
23479 break;
23480 }
23481 if( z[n]==':' ){
23482 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
23483 ** specified number of hours, minutes, seconds, and fractional seconds
23484 ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
23485 ** omitted.
23486 */
23487 const char *z2 = z;
23488 DateTime tx;
23489 sqlite3_int64 day;
23490 if( !sqlite3Isdigit(*z2) ) z2++;
23491 memset(s: &tx, c: 0, n: sizeof(tx));
23492 if( parseHhMmSs(zDate: z2, p: &tx) ) break;
23493 computeJD(p: &tx);
23494 tx.iJD -= 43200000;
23495 day = tx.iJD/86400000;
23496 tx.iJD -= day*86400000;
23497 if( z[0]=='-' ) tx.iJD = -tx.iJD;
23498 computeJD(p);
23499 clearYMD_HMS_TZ(p);
23500 p->iJD += tx.iJD;
23501 rc = 0;
23502 break;
23503 }
23504
23505 /* If control reaches this point, it means the transformation is
23506 ** one of the forms like "+NNN days". */
23507 z += n;
23508 while( sqlite3Isspace(*z) ) z++;
23509 n = sqlite3Strlen30(z);
23510 if( n>10 || n<3 ) break;
23511 if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
23512 computeJD(p);
23513 rc = 1;
23514 rRounder = r<0 ? -0.5 : +0.5;
23515 for(i=0; i<ArraySize(aXformType); i++){
23516 if( aXformType[i].nName==n
23517 && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
23518 && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
23519 ){
23520 switch( aXformType[i].eType ){
23521 case 1: { /* Special processing to add months */
23522 int x;
23523 computeYMD_HMS(p);
23524 p->M += (int)r;
23525 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
23526 p->Y += x;
23527 p->M -= x*12;
23528 p->validJD = 0;
23529 r -= (int)r;
23530 break;
23531 }
23532 case 2: { /* Special processing to add years */
23533 int y = (int)r;
23534 computeYMD_HMS(p);
23535 p->Y += y;
23536 p->validJD = 0;
23537 r -= (int)r;
23538 break;
23539 }
23540 }
23541 computeJD(p);
23542 p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);
23543 rc = 0;
23544 break;
23545 }
23546 }
23547 clearYMD_HMS_TZ(p);
23548 break;
23549 }
23550 default: {
23551 break;
23552 }
23553 }
23554 return rc;
23555}
23556
23557/*
23558** Process time function arguments. argv[0] is a date-time stamp.
23559** argv[1] and following are modifiers. Parse them all and write
23560** the resulting time into the DateTime structure p. Return 0
23561** on success and 1 if there are any errors.
23562**
23563** If there are zero parameters (if even argv[0] is undefined)
23564** then assume a default value of "now" for argv[0].
23565*/
23566static int isDate(
23567 sqlite3_context *context,
23568 int argc,
23569 sqlite3_value **argv,
23570 DateTime *p
23571){
23572 int i, n;
23573 const unsigned char *z;
23574 int eType;
23575 memset(s: p, c: 0, n: sizeof(*p));
23576 if( argc==0 ){
23577 if( !sqlite3NotPureFunc(context) ) return 1;
23578 return setDateTimeToCurrent(context, p);
23579 }
23580 if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
23581 || eType==SQLITE_INTEGER ){
23582 setRawDateNumber(p, r: sqlite3_value_double(argv[0]));
23583 }else{
23584 z = sqlite3_value_text(argv[0]);
23585 if( !z || parseDateOrTime(context, zDate: (char*)z, p) ){
23586 return 1;
23587 }
23588 }
23589 for(i=1; i<argc; i++){
23590 z = sqlite3_value_text(argv[i]);
23591 n = sqlite3_value_bytes(argv[i]);
23592 if( z==0 || parseModifier(pCtx: context, z: (char*)z, n, p) ) return 1;
23593 }
23594 computeJD(p);
23595 if( p->isError || !validJulianDay(iJD: p->iJD) ) return 1;
23596 return 0;
23597}
23598
23599
23600/*
23601** The following routines implement the various date and time functions
23602** of SQLite.
23603*/
23604
23605/*
23606** julianday( TIMESTRING, MOD, MOD, ...)
23607**
23608** Return the julian day number of the date specified in the arguments
23609*/
23610static void juliandayFunc(
23611 sqlite3_context *context,
23612 int argc,
23613 sqlite3_value **argv
23614){
23615 DateTime x;
23616 if( isDate(context, argc, argv, p: &x)==0 ){
23617 computeJD(p: &x);
23618 sqlite3_result_double(context, x.iJD/86400000.0);
23619 }
23620}
23621
23622/*
23623** datetime( TIMESTRING, MOD, MOD, ...)
23624**
23625** Return YYYY-MM-DD HH:MM:SS
23626*/
23627static void datetimeFunc(
23628 sqlite3_context *context,
23629 int argc,
23630 sqlite3_value **argv
23631){
23632 DateTime x;
23633 if( isDate(context, argc, argv, p: &x)==0 ){
23634 char zBuf[100];
23635 computeYMD_HMS(p: &x);
23636 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
23637 x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
23638 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
23639 }
23640}
23641
23642/*
23643** time( TIMESTRING, MOD, MOD, ...)
23644**
23645** Return HH:MM:SS
23646*/
23647static void timeFunc(
23648 sqlite3_context *context,
23649 int argc,
23650 sqlite3_value **argv
23651){
23652 DateTime x;
23653 if( isDate(context, argc, argv, p: &x)==0 ){
23654 char zBuf[100];
23655 computeHMS(p: &x);
23656 sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
23657 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
23658 }
23659}
23660
23661/*
23662** date( TIMESTRING, MOD, MOD, ...)
23663**
23664** Return YYYY-MM-DD
23665*/
23666static void dateFunc(
23667 sqlite3_context *context,
23668 int argc,
23669 sqlite3_value **argv
23670){
23671 DateTime x;
23672 if( isDate(context, argc, argv, p: &x)==0 ){
23673 char zBuf[100];
23674 computeYMD(p: &x);
23675 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
23676 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
23677 }
23678}
23679
23680/*
23681** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
23682**
23683** Return a string described by FORMAT. Conversions as follows:
23684**
23685** %d day of month
23686** %f ** fractional seconds SS.SSS
23687** %H hour 00-24
23688** %j day of year 000-366
23689** %J ** julian day number
23690** %m month 01-12
23691** %M minute 00-59
23692** %s seconds since 1970-01-01
23693** %S seconds 00-59
23694** %w day of week 0-6 sunday==0
23695** %W week of year 00-53
23696** %Y year 0000-9999
23697** %% %
23698*/
23699static void strftimeFunc(
23700 sqlite3_context *context,
23701 int argc,
23702 sqlite3_value **argv
23703){
23704 DateTime x;
23705 size_t i,j;
23706 sqlite3 *db;
23707 const char *zFmt;
23708 sqlite3_str sRes;
23709
23710
23711 if( argc==0 ) return;
23712 zFmt = (const char*)sqlite3_value_text(argv[0]);
23713 if( zFmt==0 || isDate(context, argc: argc-1, argv: argv+1, p: &x) ) return;
23714 db = sqlite3_context_db_handle(context);
23715 sqlite3StrAccumInit(&sRes, 0, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
23716
23717 computeJD(p: &x);
23718 computeYMD_HMS(p: &x);
23719 for(i=j=0; zFmt[i]; i++){
23720 if( zFmt[i]!='%' ) continue;
23721 if( j<i ) sqlite3_str_append(&sRes, zIn: zFmt+j, N: (int)(i-j));
23722 i++;
23723 j = i + 1;
23724 switch( zFmt[i] ){
23725 case 'd': {
23726 sqlite3_str_appendf(&sRes, zFormat: "%02d", x.D);
23727 break;
23728 }
23729 case 'f': {
23730 double s = x.s;
23731 if( s>59.999 ) s = 59.999;
23732 sqlite3_str_appendf(&sRes, zFormat: "%06.3f", s);
23733 break;
23734 }
23735 case 'H': {
23736 sqlite3_str_appendf(&sRes, zFormat: "%02d", x.h);
23737 break;
23738 }
23739 case 'W': /* Fall thru */
23740 case 'j': {
23741 int nDay; /* Number of days since 1st day of year */
23742 DateTime y = x;
23743 y.validJD = 0;
23744 y.M = 1;
23745 y.D = 1;
23746 computeJD(p: &y);
23747 nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
23748 if( zFmt[i]=='W' ){
23749 int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
23750 wd = (int)(((x.iJD+43200000)/86400000)%7);
23751 sqlite3_str_appendf(&sRes,zFormat: "%02d",(nDay+7-wd)/7);
23752 }else{
23753 sqlite3_str_appendf(&sRes,zFormat: "%03d",nDay+1);
23754 }
23755 break;
23756 }
23757 case 'J': {
23758 sqlite3_str_appendf(&sRes,zFormat: "%.16g",x.iJD/86400000.0);
23759 break;
23760 }
23761 case 'm': {
23762 sqlite3_str_appendf(&sRes,zFormat: "%02d",x.M);
23763 break;
23764 }
23765 case 'M': {
23766 sqlite3_str_appendf(&sRes,zFormat: "%02d",x.m);
23767 break;
23768 }
23769 case 's': {
23770 i64 iS = (i64)(x.iJD/1000 - 21086676*(i64)10000);
23771 sqlite3_str_appendf(&sRes,zFormat: "%lld",iS);
23772 break;
23773 }
23774 case 'S': {
23775 sqlite3_str_appendf(&sRes,zFormat: "%02d",(int)x.s);
23776 break;
23777 }
23778 case 'w': {
23779 sqlite3_str_appendchar(&sRes, N: 1,
23780 C: (char)(((x.iJD+129600000)/86400000) % 7) + '0');
23781 break;
23782 }
23783 case 'Y': {
23784 sqlite3_str_appendf(&sRes,zFormat: "%04d",x.Y);
23785 break;
23786 }
23787 case '%': {
23788 sqlite3_str_appendchar(&sRes, N: 1, C: '%');
23789 break;
23790 }
23791 default: {
23792 sqlite3_str_reset(&sRes);
23793 return;
23794 }
23795 }
23796 }
23797 if( j<i ) sqlite3_str_append(&sRes, zIn: zFmt+j, N: (int)(i-j));
23798 sqlite3ResultStrAccum(context, &sRes);
23799}
23800
23801/*
23802** current_time()
23803**
23804** This function returns the same value as time('now').
23805*/
23806static void ctimeFunc(
23807 sqlite3_context *context,
23808 int NotUsed,
23809 sqlite3_value **NotUsed2
23810){
23811 UNUSED_PARAMETER2(NotUsed, NotUsed2);
23812 timeFunc(context, argc: 0, argv: 0);
23813}
23814
23815/*
23816** current_date()
23817**
23818** This function returns the same value as date('now').
23819*/
23820static void cdateFunc(
23821 sqlite3_context *context,
23822 int NotUsed,
23823 sqlite3_value **NotUsed2
23824){
23825 UNUSED_PARAMETER2(NotUsed, NotUsed2);
23826 dateFunc(context, argc: 0, argv: 0);
23827}
23828
23829/*
23830** current_timestamp()
23831**
23832** This function returns the same value as datetime('now').
23833*/
23834static void ctimestampFunc(
23835 sqlite3_context *context,
23836 int NotUsed,
23837 sqlite3_value **NotUsed2
23838){
23839 UNUSED_PARAMETER2(NotUsed, NotUsed2);
23840 datetimeFunc(context, argc: 0, argv: 0);
23841}
23842#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
23843
23844#ifdef SQLITE_OMIT_DATETIME_FUNCS
23845/*
23846** If the library is compiled to omit the full-scale date and time
23847** handling (to get a smaller binary), the following minimal version
23848** of the functions current_time(), current_date() and current_timestamp()
23849** are included instead. This is to support column declarations that
23850** include "DEFAULT CURRENT_TIME" etc.
23851**
23852** This function uses the C-library functions time(), gmtime()
23853** and strftime(). The format string to pass to strftime() is supplied
23854** as the user-data for the function.
23855*/
23856static void currentTimeFunc(
23857 sqlite3_context *context,
23858 int argc,
23859 sqlite3_value **argv
23860){
23861 time_t t;
23862 char *zFormat = (char *)sqlite3_user_data(context);
23863 sqlite3_int64 iT;
23864 struct tm *pTm;
23865 struct tm sNow;
23866 char zBuf[20];
23867
23868 UNUSED_PARAMETER(argc);
23869 UNUSED_PARAMETER(argv);
23870
23871 iT = sqlite3StmtCurrentTime(context);
23872 if( iT<=0 ) return;
23873 t = iT/1000 - 10000*(sqlite3_int64)21086676;
23874#if HAVE_GMTIME_R
23875 pTm = gmtime_r(&t, &sNow);
23876#else
23877 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN));
23878 pTm = gmtime(&t);
23879 if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
23880 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN));
23881#endif
23882 if( pTm ){
23883 strftime(zBuf, 20, zFormat, &sNow);
23884 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
23885 }
23886}
23887#endif
23888
23889/*
23890** This function registered all of the above C functions as SQL
23891** functions. This should be the only routine in this file with
23892** external linkage.
23893*/
23894SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
23895 static FuncDef aDateTimeFuncs[] = {
23896#ifndef SQLITE_OMIT_DATETIME_FUNCS
23897 PURE_DATE(julianday, -1, 0, 0, juliandayFunc ),
23898 PURE_DATE(date, -1, 0, 0, dateFunc ),
23899 PURE_DATE(time, -1, 0, 0, timeFunc ),
23900 PURE_DATE(datetime, -1, 0, 0, datetimeFunc ),
23901 PURE_DATE(strftime, -1, 0, 0, strftimeFunc ),
23902 DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
23903 DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
23904 DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
23905#else
23906 STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
23907 STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
23908 STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
23909#endif
23910 };
23911 sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
23912}
23913
23914/************** End of date.c ************************************************/
23915/************** Begin file os.c **********************************************/
23916/*
23917** 2005 November 29
23918**
23919** The author disclaims copyright to this source code. In place of
23920** a legal notice, here is a blessing:
23921**
23922** May you do good and not evil.
23923** May you find forgiveness for yourself and forgive others.
23924** May you share freely, never taking more than you give.
23925**
23926******************************************************************************
23927**
23928** This file contains OS interface code that is common to all
23929** architectures.
23930*/
23931/* #include "sqliteInt.h" */
23932
23933/*
23934** If we compile with the SQLITE_TEST macro set, then the following block
23935** of code will give us the ability to simulate a disk I/O error. This
23936** is used for testing the I/O recovery logic.
23937*/
23938#if defined(SQLITE_TEST)
23939SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
23940SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
23941SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
23942SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
23943SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
23944SQLITE_API int sqlite3_diskfull_pending = 0;
23945SQLITE_API int sqlite3_diskfull = 0;
23946#endif /* defined(SQLITE_TEST) */
23947
23948/*
23949** When testing, also keep a count of the number of open files.
23950*/
23951#if defined(SQLITE_TEST)
23952SQLITE_API int sqlite3_open_file_count = 0;
23953#endif /* defined(SQLITE_TEST) */
23954
23955/*
23956** The default SQLite sqlite3_vfs implementations do not allocate
23957** memory (actually, os_unix.c allocates a small amount of memory
23958** from within OsOpen()), but some third-party implementations may.
23959** So we test the effects of a malloc() failing and the sqlite3OsXXX()
23960** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
23961**
23962** The following functions are instrumented for malloc() failure
23963** testing:
23964**
23965** sqlite3OsRead()
23966** sqlite3OsWrite()
23967** sqlite3OsSync()
23968** sqlite3OsFileSize()
23969** sqlite3OsLock()
23970** sqlite3OsCheckReservedLock()
23971** sqlite3OsFileControl()
23972** sqlite3OsShmMap()
23973** sqlite3OsOpen()
23974** sqlite3OsDelete()
23975** sqlite3OsAccess()
23976** sqlite3OsFullPathname()
23977**
23978*/
23979#if defined(SQLITE_TEST)
23980SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
23981 #define DO_OS_MALLOC_TEST(x) \
23982 if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
23983 void *pTstAlloc = sqlite3Malloc(10); \
23984 if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \
23985 sqlite3_free(pTstAlloc); \
23986 }
23987#else
23988 #define DO_OS_MALLOC_TEST(x)
23989#endif
23990
23991/*
23992** The following routines are convenience wrappers around methods
23993** of the sqlite3_file object. This is mostly just syntactic sugar. All
23994** of this would be completely automatic if SQLite were coded using
23995** C++ instead of plain old C.
23996*/
23997SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
23998 if( pId->pMethods ){
23999 pId->pMethods->xClose(pId);
24000 pId->pMethods = 0;
24001 }
24002}
24003SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
24004 DO_OS_MALLOC_TEST(id);
24005 return id->pMethods->xRead(id, pBuf, amt, offset);
24006}
24007SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
24008 DO_OS_MALLOC_TEST(id);
24009 return id->pMethods->xWrite(id, pBuf, amt, offset);
24010}
24011SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
24012 return id->pMethods->xTruncate(id, size);
24013}
24014SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
24015 DO_OS_MALLOC_TEST(id);
24016 return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK;
24017}
24018SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
24019 DO_OS_MALLOC_TEST(id);
24020 return id->pMethods->xFileSize(id, pSize);
24021}
24022SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
24023 DO_OS_MALLOC_TEST(id);
24024 return id->pMethods->xLock(id, lockType);
24025}
24026SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
24027 return id->pMethods->xUnlock(id, lockType);
24028}
24029SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
24030 DO_OS_MALLOC_TEST(id);
24031 return id->pMethods->xCheckReservedLock(id, pResOut);
24032}
24033
24034/*
24035** Use sqlite3OsFileControl() when we are doing something that might fail
24036** and we need to know about the failures. Use sqlite3OsFileControlHint()
24037** when simply tossing information over the wall to the VFS and we do not
24038** really care if the VFS receives and understands the information since it
24039** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
24040** routine has no return value since the return value would be meaningless.
24041*/
24042SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
24043 if( id->pMethods==0 ) return SQLITE_NOTFOUND;
24044#ifdef SQLITE_TEST
24045 if( op!=SQLITE_FCNTL_COMMIT_PHASETWO
24046 && op!=SQLITE_FCNTL_LOCK_TIMEOUT
24047 && op!=SQLITE_FCNTL_CKPT_DONE
24048 && op!=SQLITE_FCNTL_CKPT_START
24049 ){
24050 /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
24051 ** is using a regular VFS, it is called after the corresponding
24052 ** transaction has been committed. Injecting a fault at this point
24053 ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
24054 ** but the transaction is committed anyway.
24055 **
24056 ** The core must call OsFileControl() though, not OsFileControlHint(),
24057 ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
24058 ** means the commit really has failed and an error should be returned
24059 ** to the user.
24060 **
24061 ** The CKPT_DONE and CKPT_START file-controls are write-only signals
24062 ** to the cksumvfs. Their return code is meaningless and is ignored
24063 ** by the SQLite core, so there is no point in simulating OOMs for them.
24064 */
24065 DO_OS_MALLOC_TEST(id);
24066 }
24067#endif
24068 return id->pMethods->xFileControl(id, op, pArg);
24069}
24070SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
24071 if( id->pMethods ) (void)id->pMethods->xFileControl(id, op, pArg);
24072}
24073
24074SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
24075 int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
24076 return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
24077}
24078SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
24079 if( NEVER(id->pMethods==0) ) return 0;
24080 return id->pMethods->xDeviceCharacteristics(id);
24081}
24082#ifndef SQLITE_OMIT_WAL
24083SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
24084 return id->pMethods->xShmLock(id, offset, n, flags);
24085}
24086SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
24087 id->pMethods->xShmBarrier(id);
24088}
24089SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
24090 return id->pMethods->xShmUnmap(id, deleteFlag);
24091}
24092SQLITE_PRIVATE int sqlite3OsShmMap(
24093 sqlite3_file *id, /* Database file handle */
24094 int iPage,
24095 int pgsz,
24096 int bExtend, /* True to extend file if necessary */
24097 void volatile **pp /* OUT: Pointer to mapping */
24098){
24099 DO_OS_MALLOC_TEST(id);
24100 return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
24101}
24102#endif /* SQLITE_OMIT_WAL */
24103
24104#if SQLITE_MAX_MMAP_SIZE>0
24105/* The real implementation of xFetch and xUnfetch */
24106SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
24107 DO_OS_MALLOC_TEST(id);
24108 return id->pMethods->xFetch(id, iOff, iAmt, pp);
24109}
24110SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
24111 return id->pMethods->xUnfetch(id, iOff, p);
24112}
24113#else
24114/* No-op stubs to use when memory-mapped I/O is disabled */
24115SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
24116 *pp = 0;
24117 return SQLITE_OK;
24118}
24119SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
24120 return SQLITE_OK;
24121}
24122#endif
24123
24124/*
24125** The next group of routines are convenience wrappers around the
24126** VFS methods.
24127*/
24128SQLITE_PRIVATE int sqlite3OsOpen(
24129 sqlite3_vfs *pVfs,
24130 const char *zPath,
24131 sqlite3_file *pFile,
24132 int flags,
24133 int *pFlagsOut
24134){
24135 int rc;
24136 DO_OS_MALLOC_TEST(0);
24137 /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
24138 ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
24139 ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
24140 ** reaching the VFS. */
24141 rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x1087f7f, pFlagsOut);
24142 assert( rc==SQLITE_OK || pFile->pMethods==0 );
24143 return rc;
24144}
24145SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
24146 DO_OS_MALLOC_TEST(0);
24147 assert( dirSync==0 || dirSync==1 );
24148 return pVfs->xDelete!=0 ? pVfs->xDelete(pVfs, zPath, dirSync) : SQLITE_OK;
24149}
24150SQLITE_PRIVATE int sqlite3OsAccess(
24151 sqlite3_vfs *pVfs,
24152 const char *zPath,
24153 int flags,
24154 int *pResOut
24155){
24156 DO_OS_MALLOC_TEST(0);
24157 return pVfs->xAccess(pVfs, zPath, flags, pResOut);
24158}
24159SQLITE_PRIVATE int sqlite3OsFullPathname(
24160 sqlite3_vfs *pVfs,
24161 const char *zPath,
24162 int nPathOut,
24163 char *zPathOut
24164){
24165 DO_OS_MALLOC_TEST(0);
24166 zPathOut[0] = 0;
24167 return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
24168}
24169#ifndef SQLITE_OMIT_LOAD_EXTENSION
24170SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
24171 assert( zPath!=0 );
24172 assert( strlen(zPath)<=SQLITE_MAX_PATHLEN ); /* tag-20210611-1 */
24173 return pVfs->xDlOpen(pVfs, zPath);
24174}
24175SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
24176 pVfs->xDlError(pVfs, nByte, zBufOut);
24177}
24178SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
24179 return pVfs->xDlSym(pVfs, pHdle, zSym);
24180}
24181SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
24182 pVfs->xDlClose(pVfs, pHandle);
24183}
24184#endif /* SQLITE_OMIT_LOAD_EXTENSION */
24185SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
24186 if( sqlite3Config.iPrngSeed ){
24187 memset(s: zBufOut, c: 0, n: nByte);
24188 if( ALWAYS(nByte>(signed)sizeof(unsigned)) ) nByte = sizeof(unsigned int);
24189 memcpy(dest: zBufOut, src: &sqlite3Config.iPrngSeed, n: nByte);
24190 return SQLITE_OK;
24191 }else{
24192 return pVfs->xRandomness(pVfs, nByte, zBufOut);
24193 }
24194
24195}
24196SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
24197 return pVfs->xSleep(pVfs, nMicro);
24198}
24199SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
24200 return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
24201}
24202SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
24203 int rc;
24204 /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
24205 ** method to get the current date and time if that method is available
24206 ** (if iVersion is 2 or greater and the function pointer is not NULL) and
24207 ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
24208 ** unavailable.
24209 */
24210 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
24211 rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
24212 }else{
24213 double r;
24214 rc = pVfs->xCurrentTime(pVfs, &r);
24215 *pTimeOut = (sqlite3_int64)(r*86400000.0);
24216 }
24217 return rc;
24218}
24219
24220SQLITE_PRIVATE int sqlite3OsOpenMalloc(
24221 sqlite3_vfs *pVfs,
24222 const char *zFile,
24223 sqlite3_file **ppFile,
24224 int flags,
24225 int *pOutFlags
24226){
24227 int rc;
24228 sqlite3_file *pFile;
24229 pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
24230 if( pFile ){
24231 rc = sqlite3OsOpen(pVfs, zPath: zFile, pFile, flags, pFlagsOut: pOutFlags);
24232 if( rc!=SQLITE_OK ){
24233 sqlite3_free(pFile);
24234 *ppFile = 0;
24235 }else{
24236 *ppFile = pFile;
24237 }
24238 }else{
24239 *ppFile = 0;
24240 rc = SQLITE_NOMEM_BKPT;
24241 }
24242 assert( *ppFile!=0 || rc!=SQLITE_OK );
24243 return rc;
24244}
24245SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
24246 assert( pFile );
24247 sqlite3OsClose(pId: pFile);
24248 sqlite3_free(pFile);
24249}
24250
24251/*
24252** This function is a wrapper around the OS specific implementation of
24253** sqlite3_os_init(). The purpose of the wrapper is to provide the
24254** ability to simulate a malloc failure, so that the handling of an
24255** error in sqlite3_os_init() by the upper layers can be tested.
24256*/
24257SQLITE_PRIVATE int sqlite3OsInit(void){
24258 void *p = sqlite3_malloc(10);
24259 if( p==0 ) return SQLITE_NOMEM_BKPT;
24260 sqlite3_free(p);
24261 return sqlite3_os_init();
24262}
24263
24264/*
24265** The list of all registered VFS implementations.
24266*/
24267static sqlite3_vfs * SQLITE_WSD vfsList = 0;
24268#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
24269
24270/*
24271** Locate a VFS by name. If no name is given, simply return the
24272** first VFS on the list.
24273*/
24274SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
24275 sqlite3_vfs *pVfs = 0;
24276#if SQLITE_THREADSAFE
24277 sqlite3_mutex *mutex;
24278#endif
24279#ifndef SQLITE_OMIT_AUTOINIT
24280 int rc = sqlite3_initialize();
24281 if( rc ) return 0;
24282#endif
24283#if SQLITE_THREADSAFE
24284 mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
24285#endif
24286 sqlite3_mutex_enter(mutex);
24287 for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
24288 if( zVfs==0 ) break;
24289 if( strcmp(s1: zVfs, s2: pVfs->zName)==0 ) break;
24290 }
24291 sqlite3_mutex_leave(mutex);
24292 return pVfs;
24293}
24294
24295/*
24296** Unlink a VFS from the linked list
24297*/
24298static void vfsUnlink(sqlite3_vfs *pVfs){
24299 assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN)) );
24300 if( pVfs==0 ){
24301 /* No-op */
24302 }else if( vfsList==pVfs ){
24303 vfsList = pVfs->pNext;
24304 }else if( vfsList ){
24305 sqlite3_vfs *p = vfsList;
24306 while( p->pNext && p->pNext!=pVfs ){
24307 p = p->pNext;
24308 }
24309 if( p->pNext==pVfs ){
24310 p->pNext = pVfs->pNext;
24311 }
24312 }
24313}
24314
24315/*
24316** Register a VFS with the system. It is harmless to register the same
24317** VFS multiple times. The new VFS becomes the default if makeDflt is
24318** true.
24319*/
24320SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
24321 MUTEX_LOGIC(sqlite3_mutex *mutex;)
24322#ifndef SQLITE_OMIT_AUTOINIT
24323 int rc = sqlite3_initialize();
24324 if( rc ) return rc;
24325#endif
24326#ifdef SQLITE_ENABLE_API_ARMOR
24327 if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
24328#endif
24329
24330 MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
24331 sqlite3_mutex_enter(mutex);
24332 vfsUnlink(pVfs);
24333 if( makeDflt || vfsList==0 ){
24334 pVfs->pNext = vfsList;
24335 vfsList = pVfs;
24336 }else{
24337 pVfs->pNext = vfsList->pNext;
24338 vfsList->pNext = pVfs;
24339 }
24340 assert(vfsList);
24341 sqlite3_mutex_leave(mutex);
24342 return SQLITE_OK;
24343}
24344
24345/*
24346** Unregister a VFS so that it is no longer accessible.
24347*/
24348SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
24349 MUTEX_LOGIC(sqlite3_mutex *mutex;)
24350#ifndef SQLITE_OMIT_AUTOINIT
24351 int rc = sqlite3_initialize();
24352 if( rc ) return rc;
24353#endif
24354 MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
24355 sqlite3_mutex_enter(mutex);
24356 vfsUnlink(pVfs);
24357 sqlite3_mutex_leave(mutex);
24358 return SQLITE_OK;
24359}
24360
24361/************** End of os.c **************************************************/
24362/************** Begin file fault.c *******************************************/
24363/*
24364** 2008 Jan 22
24365**
24366** The author disclaims copyright to this source code. In place of
24367** a legal notice, here is a blessing:
24368**
24369** May you do good and not evil.
24370** May you find forgiveness for yourself and forgive others.
24371** May you share freely, never taking more than you give.
24372**
24373*************************************************************************
24374**
24375** This file contains code to support the concept of "benign"
24376** malloc failures (when the xMalloc() or xRealloc() method of the
24377** sqlite3_mem_methods structure fails to allocate a block of memory
24378** and returns 0).
24379**
24380** Most malloc failures are non-benign. After they occur, SQLite
24381** abandons the current operation and returns an error code (usually
24382** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
24383** fatal. For example, if a malloc fails while resizing a hash table, this
24384** is completely recoverable simply by not carrying out the resize. The
24385** hash table will continue to function normally. So a malloc failure
24386** during a hash table resize is a benign fault.
24387*/
24388
24389/* #include "sqliteInt.h" */
24390
24391#ifndef SQLITE_UNTESTABLE
24392
24393/*
24394** Global variables.
24395*/
24396typedef struct BenignMallocHooks BenignMallocHooks;
24397static SQLITE_WSD struct BenignMallocHooks {
24398 void (*xBenignBegin)(void);
24399 void (*xBenignEnd)(void);
24400} sqlite3Hooks = { 0, 0 };
24401
24402/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
24403** structure. If writable static data is unsupported on the target,
24404** we have to locate the state vector at run-time. In the more common
24405** case where writable static data is supported, wsdHooks can refer directly
24406** to the "sqlite3Hooks" state vector declared above.
24407*/
24408#ifdef SQLITE_OMIT_WSD
24409# define wsdHooksInit \
24410 BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
24411# define wsdHooks x[0]
24412#else
24413# define wsdHooksInit
24414# define wsdHooks sqlite3Hooks
24415#endif
24416
24417
24418/*
24419** Register hooks to call when sqlite3BeginBenignMalloc() and
24420** sqlite3EndBenignMalloc() are called, respectively.
24421*/
24422SQLITE_PRIVATE void sqlite3BenignMallocHooks(
24423 void (*xBenignBegin)(void),
24424 void (*xBenignEnd)(void)
24425){
24426 wsdHooksInit;
24427 wsdHooks.xBenignBegin = xBenignBegin;
24428 wsdHooks.xBenignEnd = xBenignEnd;
24429}
24430
24431/*
24432** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
24433** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
24434** indicates that subsequent malloc failures are non-benign.
24435*/
24436SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
24437 wsdHooksInit;
24438 if( wsdHooks.xBenignBegin ){
24439 wsdHooks.xBenignBegin();
24440 }
24441}
24442SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
24443 wsdHooksInit;
24444 if( wsdHooks.xBenignEnd ){
24445 wsdHooks.xBenignEnd();
24446 }
24447}
24448
24449#endif /* #ifndef SQLITE_UNTESTABLE */
24450
24451/************** End of fault.c ***********************************************/
24452/************** Begin file mem0.c ********************************************/
24453/*
24454** 2008 October 28
24455**
24456** The author disclaims copyright to this source code. In place of
24457** a legal notice, here is a blessing:
24458**
24459** May you do good and not evil.
24460** May you find forgiveness for yourself and forgive others.
24461** May you share freely, never taking more than you give.
24462**
24463*************************************************************************
24464**
24465** This file contains a no-op memory allocation drivers for use when
24466** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
24467** here always fail. SQLite will not operate with these drivers. These
24468** are merely placeholders. Real drivers must be substituted using
24469** sqlite3_config() before SQLite will operate.
24470*/
24471/* #include "sqliteInt.h" */
24472
24473/*
24474** This version of the memory allocator is the default. It is
24475** used when no other memory allocator is specified using compile-time
24476** macros.
24477*/
24478#ifdef SQLITE_ZERO_MALLOC
24479
24480/*
24481** No-op versions of all memory allocation routines
24482*/
24483static void *sqlite3MemMalloc(int nByte){ return 0; }
24484static void sqlite3MemFree(void *pPrior){ return; }
24485static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
24486static int sqlite3MemSize(void *pPrior){ return 0; }
24487static int sqlite3MemRoundup(int n){ return n; }
24488static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
24489static void sqlite3MemShutdown(void *NotUsed){ return; }
24490
24491/*
24492** This routine is the only routine in this file with external linkage.
24493**
24494** Populate the low-level memory allocation function pointers in
24495** sqlite3GlobalConfig.m with pointers to the routines in this file.
24496*/
24497SQLITE_PRIVATE void sqlite3MemSetDefault(void){
24498 static const sqlite3_mem_methods defaultMethods = {
24499 sqlite3MemMalloc,
24500 sqlite3MemFree,
24501 sqlite3MemRealloc,
24502 sqlite3MemSize,
24503 sqlite3MemRoundup,
24504 sqlite3MemInit,
24505 sqlite3MemShutdown,
24506 0
24507 };
24508 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
24509}
24510
24511#endif /* SQLITE_ZERO_MALLOC */
24512
24513/************** End of mem0.c ************************************************/
24514/************** Begin file mem1.c ********************************************/
24515/*
24516** 2007 August 14
24517**
24518** The author disclaims copyright to this source code. In place of
24519** a legal notice, here is a blessing:
24520**
24521** May you do good and not evil.
24522** May you find forgiveness for yourself and forgive others.
24523** May you share freely, never taking more than you give.
24524**
24525*************************************************************************
24526**
24527** This file contains low-level memory allocation drivers for when
24528** SQLite will use the standard C-library malloc/realloc/free interface
24529** to obtain the memory it needs.
24530**
24531** This file contains implementations of the low-level memory allocation
24532** routines specified in the sqlite3_mem_methods object. The content of
24533** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
24534** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
24535** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
24536** default configuration is to use memory allocation routines in this
24537** file.
24538**
24539** C-preprocessor macro summary:
24540**
24541** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
24542** the malloc_usable_size() interface exists
24543** on the target platform. Or, this symbol
24544** can be set manually, if desired.
24545** If an equivalent interface exists by
24546** a different name, using a separate -D
24547** option to rename it.
24548**
24549** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
24550** memory allocator. Set this symbol to enable
24551** building on older macs.
24552**
24553** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
24554** _msize() on windows systems. This might
24555** be necessary when compiling for Delphi,
24556** for example.
24557*/
24558/* #include "sqliteInt.h" */
24559
24560/*
24561** This version of the memory allocator is the default. It is
24562** used when no other memory allocator is specified using compile-time
24563** macros.
24564*/
24565#ifdef SQLITE_SYSTEM_MALLOC
24566#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
24567
24568/*
24569** Use the zone allocator available on apple products unless the
24570** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
24571*/
24572#include <sys/sysctl.h>
24573#include <malloc/malloc.h>
24574#ifdef SQLITE_MIGHT_BE_SINGLE_CORE
24575#include <libkern/OSAtomic.h>
24576#endif /* SQLITE_MIGHT_BE_SINGLE_CORE */
24577static malloc_zone_t* _sqliteZone_;
24578#define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
24579#define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
24580#define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
24581#define SQLITE_MALLOCSIZE(x) \
24582 (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
24583
24584#else /* if not __APPLE__ */
24585
24586/*
24587** Use standard C library malloc and free on non-Apple systems.
24588** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
24589*/
24590#define SQLITE_MALLOC(x) malloc(x)
24591#define SQLITE_FREE(x) free(x)
24592#define SQLITE_REALLOC(x,y) realloc((x),(y))
24593
24594/*
24595** The malloc.h header file is needed for malloc_usable_size() function
24596** on some systems (e.g. Linux).
24597*/
24598#if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
24599# define SQLITE_USE_MALLOC_H 1
24600# define SQLITE_USE_MALLOC_USABLE_SIZE 1
24601/*
24602** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
24603** use of _msize() is automatic, but can be disabled by compiling with
24604** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
24605** the malloc.h header file.
24606*/
24607#elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
24608# define SQLITE_USE_MALLOC_H
24609# define SQLITE_USE_MSIZE
24610#endif
24611
24612/*
24613** Include the malloc.h header file, if necessary. Also set define macro
24614** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
24615** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
24616** The memory size function can always be overridden manually by defining
24617** the macro SQLITE_MALLOCSIZE to the desired function name.
24618*/
24619#if defined(SQLITE_USE_MALLOC_H)
24620# include <malloc.h>
24621# if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
24622# if !defined(SQLITE_MALLOCSIZE)
24623# define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
24624# endif
24625# elif defined(SQLITE_USE_MSIZE)
24626# if !defined(SQLITE_MALLOCSIZE)
24627# define SQLITE_MALLOCSIZE _msize
24628# endif
24629# endif
24630#endif /* defined(SQLITE_USE_MALLOC_H) */
24631
24632#endif /* __APPLE__ or not __APPLE__ */
24633
24634/*
24635** Like malloc(), but remember the size of the allocation
24636** so that we can find it later using sqlite3MemSize().
24637**
24638** For this low-level routine, we are guaranteed that nByte>0 because
24639** cases of nByte<=0 will be intercepted and dealt with by higher level
24640** routines.
24641*/
24642static void *sqlite3MemMalloc(int nByte){
24643#ifdef SQLITE_MALLOCSIZE
24644 void *p;
24645 testcase( ROUND8(nByte)==nByte );
24646 p = SQLITE_MALLOC( nByte );
24647 if( p==0 ){
24648 testcase( sqlite3GlobalConfig.xLog!=0 );
24649 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
24650 }
24651 return p;
24652#else
24653 sqlite3_int64 *p;
24654 assert( nByte>0 );
24655 testcase( ROUND8(nByte)!=nByte );
24656 p = SQLITE_MALLOC( nByte+8 );
24657 if( p ){
24658 p[0] = nByte;
24659 p++;
24660 }else{
24661 testcase( sqlite3GlobalConfig.xLog!=0 );
24662 sqlite3_log(SQLITE_NOMEM, zFormat: "failed to allocate %u bytes of memory", nByte);
24663 }
24664 return (void *)p;
24665#endif
24666}
24667
24668/*
24669** Like free() but works for allocations obtained from sqlite3MemMalloc()
24670** or sqlite3MemRealloc().
24671**
24672** For this low-level routine, we already know that pPrior!=0 since
24673** cases where pPrior==0 will have been intecepted and dealt with
24674** by higher-level routines.
24675*/
24676static void sqlite3MemFree(void *pPrior){
24677#ifdef SQLITE_MALLOCSIZE
24678 SQLITE_FREE(pPrior);
24679#else
24680 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
24681 assert( pPrior!=0 );
24682 p--;
24683 SQLITE_FREE(p);
24684#endif
24685}
24686
24687/*
24688** Report the allocated size of a prior return from xMalloc()
24689** or xRealloc().
24690*/
24691static int sqlite3MemSize(void *pPrior){
24692#ifdef SQLITE_MALLOCSIZE
24693 assert( pPrior!=0 );
24694 return (int)SQLITE_MALLOCSIZE(pPrior);
24695#else
24696 sqlite3_int64 *p;
24697 assert( pPrior!=0 );
24698 p = (sqlite3_int64*)pPrior;
24699 p--;
24700 return (int)p[0];
24701#endif
24702}
24703
24704/*
24705** Like realloc(). Resize an allocation previously obtained from
24706** sqlite3MemMalloc().
24707**
24708** For this low-level interface, we know that pPrior!=0. Cases where
24709** pPrior==0 while have been intercepted by higher-level routine and
24710** redirected to xMalloc. Similarly, we know that nByte>0 because
24711** cases where nByte<=0 will have been intercepted by higher-level
24712** routines and redirected to xFree.
24713*/
24714static void *sqlite3MemRealloc(void *pPrior, int nByte){
24715#ifdef SQLITE_MALLOCSIZE
24716 void *p = SQLITE_REALLOC(pPrior, nByte);
24717 if( p==0 ){
24718 testcase( sqlite3GlobalConfig.xLog!=0 );
24719 sqlite3_log(SQLITE_NOMEM,
24720 "failed memory resize %u to %u bytes",
24721 SQLITE_MALLOCSIZE(pPrior), nByte);
24722 }
24723 return p;
24724#else
24725 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
24726 assert( pPrior!=0 && nByte>0 );
24727 assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
24728 p--;
24729 p = SQLITE_REALLOC(p, nByte+8 );
24730 if( p ){
24731 p[0] = nByte;
24732 p++;
24733 }else{
24734 testcase( sqlite3GlobalConfig.xLog!=0 );
24735 sqlite3_log(SQLITE_NOMEM,
24736 zFormat: "failed memory resize %u to %u bytes",
24737 sqlite3MemSize(pPrior), nByte);
24738 }
24739 return (void*)p;
24740#endif
24741}
24742
24743/*
24744** Round up a request size to the next valid allocation size.
24745*/
24746static int sqlite3MemRoundup(int n){
24747 return ROUND8(n);
24748}
24749
24750/*
24751** Initialize this module.
24752*/
24753static int sqlite3MemInit(void *NotUsed){
24754#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
24755 int cpuCount;
24756 size_t len;
24757 if( _sqliteZone_ ){
24758 return SQLITE_OK;
24759 }
24760 len = sizeof(cpuCount);
24761 /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
24762 sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
24763 if( cpuCount>1 ){
24764 /* defer MT decisions to system malloc */
24765 _sqliteZone_ = malloc_default_zone();
24766 }else{
24767 /* only 1 core, use our own zone to contention over global locks,
24768 ** e.g. we have our own dedicated locks */
24769 _sqliteZone_ = malloc_create_zone(4096, 0);
24770 malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap");
24771 }
24772#endif /* defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */
24773 UNUSED_PARAMETER(NotUsed);
24774 return SQLITE_OK;
24775}
24776
24777/*
24778** Deinitialize this module.
24779*/
24780static void sqlite3MemShutdown(void *NotUsed){
24781 UNUSED_PARAMETER(NotUsed);
24782 return;
24783}
24784
24785/*
24786** This routine is the only routine in this file with external linkage.
24787**
24788** Populate the low-level memory allocation function pointers in
24789** sqlite3GlobalConfig.m with pointers to the routines in this file.
24790*/
24791SQLITE_PRIVATE void sqlite3MemSetDefault(void){
24792 static const sqlite3_mem_methods defaultMethods = {
24793 sqlite3MemMalloc,
24794 sqlite3MemFree,
24795 sqlite3MemRealloc,
24796 sqlite3MemSize,
24797 sqlite3MemRoundup,
24798 sqlite3MemInit,
24799 sqlite3MemShutdown,
24800 0
24801 };
24802 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
24803}
24804
24805#endif /* SQLITE_SYSTEM_MALLOC */
24806
24807/************** End of mem1.c ************************************************/
24808/************** Begin file mem2.c ********************************************/
24809/*
24810** 2007 August 15
24811**
24812** The author disclaims copyright to this source code. In place of
24813** a legal notice, here is a blessing:
24814**
24815** May you do good and not evil.
24816** May you find forgiveness for yourself and forgive others.
24817** May you share freely, never taking more than you give.
24818**
24819*************************************************************************
24820**
24821** This file contains low-level memory allocation drivers for when
24822** SQLite will use the standard C-library malloc/realloc/free interface
24823** to obtain the memory it needs while adding lots of additional debugging
24824** information to each allocation in order to help detect and fix memory
24825** leaks and memory usage errors.
24826**
24827** This file contains implementations of the low-level memory allocation
24828** routines specified in the sqlite3_mem_methods object.
24829*/
24830/* #include "sqliteInt.h" */
24831
24832/*
24833** This version of the memory allocator is used only if the
24834** SQLITE_MEMDEBUG macro is defined
24835*/
24836#ifdef SQLITE_MEMDEBUG
24837
24838/*
24839** The backtrace functionality is only available with GLIBC
24840*/
24841#ifdef __GLIBC__
24842 extern int backtrace(void**,int);
24843 extern void backtrace_symbols_fd(void*const*,int,int);
24844#else
24845# define backtrace(A,B) 1
24846# define backtrace_symbols_fd(A,B,C)
24847#endif
24848/* #include <stdio.h> */
24849
24850/*
24851** Each memory allocation looks like this:
24852**
24853** ------------------------------------------------------------------------
24854** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
24855** ------------------------------------------------------------------------
24856**
24857** The application code sees only a pointer to the allocation. We have
24858** to back up from the allocation pointer to find the MemBlockHdr. The
24859** MemBlockHdr tells us the size of the allocation and the number of
24860** backtrace pointers. There is also a guard word at the end of the
24861** MemBlockHdr.
24862*/
24863struct MemBlockHdr {
24864 i64 iSize; /* Size of this allocation */
24865 struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
24866 char nBacktrace; /* Number of backtraces on this alloc */
24867 char nBacktraceSlots; /* Available backtrace slots */
24868 u8 nTitle; /* Bytes of title; includes '\0' */
24869 u8 eType; /* Allocation type code */
24870 int iForeGuard; /* Guard word for sanity */
24871};
24872
24873/*
24874** Guard words
24875*/
24876#define FOREGUARD 0x80F5E153
24877#define REARGUARD 0xE4676B53
24878
24879/*
24880** Number of malloc size increments to track.
24881*/
24882#define NCSIZE 1000
24883
24884/*
24885** All of the static variables used by this module are collected
24886** into a single structure named "mem". This is to keep the
24887** static variables organized and to reduce namespace pollution
24888** when this module is combined with other in the amalgamation.
24889*/
24890static struct {
24891
24892 /*
24893 ** Mutex to control access to the memory allocation subsystem.
24894 */
24895 sqlite3_mutex *mutex;
24896
24897 /*
24898 ** Head and tail of a linked list of all outstanding allocations
24899 */
24900 struct MemBlockHdr *pFirst;
24901 struct MemBlockHdr *pLast;
24902
24903 /*
24904 ** The number of levels of backtrace to save in new allocations.
24905 */
24906 int nBacktrace;
24907 void (*xBacktrace)(int, int, void **);
24908
24909 /*
24910 ** Title text to insert in front of each block
24911 */
24912 int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
24913 char zTitle[100]; /* The title text */
24914
24915 /*
24916 ** sqlite3MallocDisallow() increments the following counter.
24917 ** sqlite3MallocAllow() decrements it.
24918 */
24919 int disallow; /* Do not allow memory allocation */
24920
24921 /*
24922 ** Gather statistics on the sizes of memory allocations.
24923 ** nAlloc[i] is the number of allocation attempts of i*8
24924 ** bytes. i==NCSIZE is the number of allocation attempts for
24925 ** sizes more than NCSIZE*8 bytes.
24926 */
24927 int nAlloc[NCSIZE]; /* Total number of allocations */
24928 int nCurrent[NCSIZE]; /* Current number of allocations */
24929 int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
24930
24931} mem;
24932
24933
24934/*
24935** Adjust memory usage statistics
24936*/
24937static void adjustStats(int iSize, int increment){
24938 int i = ROUND8(iSize)/8;
24939 if( i>NCSIZE-1 ){
24940 i = NCSIZE - 1;
24941 }
24942 if( increment>0 ){
24943 mem.nAlloc[i]++;
24944 mem.nCurrent[i]++;
24945 if( mem.nCurrent[i]>mem.mxCurrent[i] ){
24946 mem.mxCurrent[i] = mem.nCurrent[i];
24947 }
24948 }else{
24949 mem.nCurrent[i]--;
24950 assert( mem.nCurrent[i]>=0 );
24951 }
24952}
24953
24954/*
24955** Given an allocation, find the MemBlockHdr for that allocation.
24956**
24957** This routine checks the guards at either end of the allocation and
24958** if they are incorrect it asserts.
24959*/
24960static struct MemBlockHdr *sqlite3MemsysGetHeader(const void *pAllocation){
24961 struct MemBlockHdr *p;
24962 int *pInt;
24963 u8 *pU8;
24964 int nReserve;
24965
24966 p = (struct MemBlockHdr*)pAllocation;
24967 p--;
24968 assert( p->iForeGuard==(int)FOREGUARD );
24969 nReserve = ROUND8(p->iSize);
24970 pInt = (int*)pAllocation;
24971 pU8 = (u8*)pAllocation;
24972 assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
24973 /* This checks any of the "extra" bytes allocated due
24974 ** to rounding up to an 8 byte boundary to ensure
24975 ** they haven't been overwritten.
24976 */
24977 while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
24978 return p;
24979}
24980
24981/*
24982** Return the number of bytes currently allocated at address p.
24983*/
24984static int sqlite3MemSize(void *p){
24985 struct MemBlockHdr *pHdr;
24986 if( !p ){
24987 return 0;
24988 }
24989 pHdr = sqlite3MemsysGetHeader(p);
24990 return (int)pHdr->iSize;
24991}
24992
24993/*
24994** Initialize the memory allocation subsystem.
24995*/
24996static int sqlite3MemInit(void *NotUsed){
24997 UNUSED_PARAMETER(NotUsed);
24998 assert( (sizeof(struct MemBlockHdr)&7) == 0 );
24999 if( !sqlite3GlobalConfig.bMemstat ){
25000 /* If memory status is enabled, then the malloc.c wrapper will already
25001 ** hold the STATIC_MEM mutex when the routines here are invoked. */
25002 mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
25003 }
25004 return SQLITE_OK;
25005}
25006
25007/*
25008** Deinitialize the memory allocation subsystem.
25009*/
25010static void sqlite3MemShutdown(void *NotUsed){
25011 UNUSED_PARAMETER(NotUsed);
25012 mem.mutex = 0;
25013}
25014
25015/*
25016** Round up a request size to the next valid allocation size.
25017*/
25018static int sqlite3MemRoundup(int n){
25019 return ROUND8(n);
25020}
25021
25022/*
25023** Fill a buffer with pseudo-random bytes. This is used to preset
25024** the content of a new memory allocation to unpredictable values and
25025** to clear the content of a freed allocation to unpredictable values.
25026*/
25027static void randomFill(char *pBuf, int nByte){
25028 unsigned int x, y, r;
25029 x = SQLITE_PTR_TO_INT(pBuf);
25030 y = nByte | 1;
25031 while( nByte >= 4 ){
25032 x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
25033 y = y*1103515245 + 12345;
25034 r = x ^ y;
25035 *(int*)pBuf = r;
25036 pBuf += 4;
25037 nByte -= 4;
25038 }
25039 while( nByte-- > 0 ){
25040 x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
25041 y = y*1103515245 + 12345;
25042 r = x ^ y;
25043 *(pBuf++) = r & 0xff;
25044 }
25045}
25046
25047/*
25048** Allocate nByte bytes of memory.
25049*/
25050static void *sqlite3MemMalloc(int nByte){
25051 struct MemBlockHdr *pHdr;
25052 void **pBt;
25053 char *z;
25054 int *pInt;
25055 void *p = 0;
25056 int totalSize;
25057 int nReserve;
25058 sqlite3_mutex_enter(mem.mutex);
25059 assert( mem.disallow==0 );
25060 nReserve = ROUND8(nByte);
25061 totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
25062 mem.nBacktrace*sizeof(void*) + mem.nTitle;
25063 p = malloc(totalSize);
25064 if( p ){
25065 z = p;
25066 pBt = (void**)&z[mem.nTitle];
25067 pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
25068 pHdr->pNext = 0;
25069 pHdr->pPrev = mem.pLast;
25070 if( mem.pLast ){
25071 mem.pLast->pNext = pHdr;
25072 }else{
25073 mem.pFirst = pHdr;
25074 }
25075 mem.pLast = pHdr;
25076 pHdr->iForeGuard = FOREGUARD;
25077 pHdr->eType = MEMTYPE_HEAP;
25078 pHdr->nBacktraceSlots = mem.nBacktrace;
25079 pHdr->nTitle = mem.nTitle;
25080 if( mem.nBacktrace ){
25081 void *aAddr[40];
25082 pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
25083 memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
25084 assert(pBt[0]);
25085 if( mem.xBacktrace ){
25086 mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
25087 }
25088 }else{
25089 pHdr->nBacktrace = 0;
25090 }
25091 if( mem.nTitle ){
25092 memcpy(z, mem.zTitle, mem.nTitle);
25093 }
25094 pHdr->iSize = nByte;
25095 adjustStats(nByte, +1);
25096 pInt = (int*)&pHdr[1];
25097 pInt[nReserve/sizeof(int)] = REARGUARD;
25098 randomFill((char*)pInt, nByte);
25099 memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
25100 p = (void*)pInt;
25101 }
25102 sqlite3_mutex_leave(mem.mutex);
25103 return p;
25104}
25105
25106/*
25107** Free memory.
25108*/
25109static void sqlite3MemFree(void *pPrior){
25110 struct MemBlockHdr *pHdr;
25111 void **pBt;
25112 char *z;
25113 assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
25114 || mem.mutex!=0 );
25115 pHdr = sqlite3MemsysGetHeader(pPrior);
25116 pBt = (void**)pHdr;
25117 pBt -= pHdr->nBacktraceSlots;
25118 sqlite3_mutex_enter(mem.mutex);
25119 if( pHdr->pPrev ){
25120 assert( pHdr->pPrev->pNext==pHdr );
25121 pHdr->pPrev->pNext = pHdr->pNext;
25122 }else{
25123 assert( mem.pFirst==pHdr );
25124 mem.pFirst = pHdr->pNext;
25125 }
25126 if( pHdr->pNext ){
25127 assert( pHdr->pNext->pPrev==pHdr );
25128 pHdr->pNext->pPrev = pHdr->pPrev;
25129 }else{
25130 assert( mem.pLast==pHdr );
25131 mem.pLast = pHdr->pPrev;
25132 }
25133 z = (char*)pBt;
25134 z -= pHdr->nTitle;
25135 adjustStats((int)pHdr->iSize, -1);
25136 randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
25137 (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
25138 free(z);
25139 sqlite3_mutex_leave(mem.mutex);
25140}
25141
25142/*
25143** Change the size of an existing memory allocation.
25144**
25145** For this debugging implementation, we *always* make a copy of the
25146** allocation into a new place in memory. In this way, if the
25147** higher level code is using pointer to the old allocation, it is
25148** much more likely to break and we are much more liking to find
25149** the error.
25150*/
25151static void *sqlite3MemRealloc(void *pPrior, int nByte){
25152 struct MemBlockHdr *pOldHdr;
25153 void *pNew;
25154 assert( mem.disallow==0 );
25155 assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
25156 pOldHdr = sqlite3MemsysGetHeader(pPrior);
25157 pNew = sqlite3MemMalloc(nByte);
25158 if( pNew ){
25159 memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
25160 if( nByte>pOldHdr->iSize ){
25161 randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
25162 }
25163 sqlite3MemFree(pPrior);
25164 }
25165 return pNew;
25166}
25167
25168/*
25169** Populate the low-level memory allocation function pointers in
25170** sqlite3GlobalConfig.m with pointers to the routines in this file.
25171*/
25172SQLITE_PRIVATE void sqlite3MemSetDefault(void){
25173 static const sqlite3_mem_methods defaultMethods = {
25174 sqlite3MemMalloc,
25175 sqlite3MemFree,
25176 sqlite3MemRealloc,
25177 sqlite3MemSize,
25178 sqlite3MemRoundup,
25179 sqlite3MemInit,
25180 sqlite3MemShutdown,
25181 0
25182 };
25183 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
25184}
25185
25186/*
25187** Set the "type" of an allocation.
25188*/
25189SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
25190 if( p && sqlite3GlobalConfig.m.xFree==sqlite3MemFree ){
25191 struct MemBlockHdr *pHdr;
25192 pHdr = sqlite3MemsysGetHeader(p);
25193 assert( pHdr->iForeGuard==FOREGUARD );
25194 pHdr->eType = eType;
25195 }
25196}
25197
25198/*
25199** Return TRUE if the mask of type in eType matches the type of the
25200** allocation p. Also return true if p==NULL.
25201**
25202** This routine is designed for use within an assert() statement, to
25203** verify the type of an allocation. For example:
25204**
25205** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
25206*/
25207SQLITE_PRIVATE int sqlite3MemdebugHasType(const void *p, u8 eType){
25208 int rc = 1;
25209 if( p && sqlite3GlobalConfig.m.xFree==sqlite3MemFree ){
25210 struct MemBlockHdr *pHdr;
25211 pHdr = sqlite3MemsysGetHeader(p);
25212 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
25213 if( (pHdr->eType&eType)==0 ){
25214 rc = 0;
25215 }
25216 }
25217 return rc;
25218}
25219
25220/*
25221** Return TRUE if the mask of type in eType matches no bits of the type of the
25222** allocation p. Also return true if p==NULL.
25223**
25224** This routine is designed for use within an assert() statement, to
25225** verify the type of an allocation. For example:
25226**
25227** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
25228*/
25229SQLITE_PRIVATE int sqlite3MemdebugNoType(const void *p, u8 eType){
25230 int rc = 1;
25231 if( p && sqlite3GlobalConfig.m.xFree==sqlite3MemFree ){
25232 struct MemBlockHdr *pHdr;
25233 pHdr = sqlite3MemsysGetHeader(p);
25234 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
25235 if( (pHdr->eType&eType)!=0 ){
25236 rc = 0;
25237 }
25238 }
25239 return rc;
25240}
25241
25242/*
25243** Set the number of backtrace levels kept for each allocation.
25244** A value of zero turns off backtracing. The number is always rounded
25245** up to a multiple of 2.
25246*/
25247SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
25248 if( depth<0 ){ depth = 0; }
25249 if( depth>20 ){ depth = 20; }
25250 depth = (depth+1)&0xfe;
25251 mem.nBacktrace = depth;
25252}
25253
25254SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
25255 mem.xBacktrace = xBacktrace;
25256}
25257
25258/*
25259** Set the title string for subsequent allocations.
25260*/
25261SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
25262 unsigned int n = sqlite3Strlen30(zTitle) + 1;
25263 sqlite3_mutex_enter(mem.mutex);
25264 if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
25265 memcpy(mem.zTitle, zTitle, n);
25266 mem.zTitle[n] = 0;
25267 mem.nTitle = ROUND8(n);
25268 sqlite3_mutex_leave(mem.mutex);
25269}
25270
25271SQLITE_PRIVATE void sqlite3MemdebugSync(){
25272 struct MemBlockHdr *pHdr;
25273 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
25274 void **pBt = (void**)pHdr;
25275 pBt -= pHdr->nBacktraceSlots;
25276 mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
25277 }
25278}
25279
25280/*
25281** Open the file indicated and write a log of all unfreed memory
25282** allocations into that log.
25283*/
25284SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
25285 FILE *out;
25286 struct MemBlockHdr *pHdr;
25287 void **pBt;
25288 int i;
25289 out = fopen(zFilename, "w");
25290 if( out==0 ){
25291 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
25292 zFilename);
25293 return;
25294 }
25295 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
25296 char *z = (char*)pHdr;
25297 z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
25298 fprintf(out, "**** %lld bytes at %p from %s ****\n",
25299 pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
25300 if( pHdr->nBacktrace ){
25301 fflush(out);
25302 pBt = (void**)pHdr;
25303 pBt -= pHdr->nBacktraceSlots;
25304 backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
25305 fprintf(out, "\n");
25306 }
25307 }
25308 fprintf(out, "COUNTS:\n");
25309 for(i=0; i<NCSIZE-1; i++){
25310 if( mem.nAlloc[i] ){
25311 fprintf(out, " %5d: %10d %10d %10d\n",
25312 i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
25313 }
25314 }
25315 if( mem.nAlloc[NCSIZE-1] ){
25316 fprintf(out, " %5d: %10d %10d %10d\n",
25317 NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
25318 mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
25319 }
25320 fclose(out);
25321}
25322
25323/*
25324** Return the number of times sqlite3MemMalloc() has been called.
25325*/
25326SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
25327 int i;
25328 int nTotal = 0;
25329 for(i=0; i<NCSIZE; i++){
25330 nTotal += mem.nAlloc[i];
25331 }
25332 return nTotal;
25333}
25334
25335
25336#endif /* SQLITE_MEMDEBUG */
25337
25338/************** End of mem2.c ************************************************/
25339/************** Begin file mem3.c ********************************************/
25340/*
25341** 2007 October 14
25342**
25343** The author disclaims copyright to this source code. In place of
25344** a legal notice, here is a blessing:
25345**
25346** May you do good and not evil.
25347** May you find forgiveness for yourself and forgive others.
25348** May you share freely, never taking more than you give.
25349**
25350*************************************************************************
25351** This file contains the C functions that implement a memory
25352** allocation subsystem for use by SQLite.
25353**
25354** This version of the memory allocation subsystem omits all
25355** use of malloc(). The SQLite user supplies a block of memory
25356** before calling sqlite3_initialize() from which allocations
25357** are made and returned by the xMalloc() and xRealloc()
25358** implementations. Once sqlite3_initialize() has been called,
25359** the amount of memory available to SQLite is fixed and cannot
25360** be changed.
25361**
25362** This version of the memory allocation subsystem is included
25363** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
25364*/
25365/* #include "sqliteInt.h" */
25366
25367/*
25368** This version of the memory allocator is only built into the library
25369** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
25370** mean that the library will use a memory-pool by default, just that
25371** it is available. The mempool allocator is activated by calling
25372** sqlite3_config().
25373*/
25374#ifdef SQLITE_ENABLE_MEMSYS3
25375
25376/*
25377** Maximum size (in Mem3Blocks) of a "small" chunk.
25378*/
25379#define MX_SMALL 10
25380
25381
25382/*
25383** Number of freelist hash slots
25384*/
25385#define N_HASH 61
25386
25387/*
25388** A memory allocation (also called a "chunk") consists of two or
25389** more blocks where each block is 8 bytes. The first 8 bytes are
25390** a header that is not returned to the user.
25391**
25392** A chunk is two or more blocks that is either checked out or
25393** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
25394** size of the allocation in blocks if the allocation is free.
25395** The u.hdr.size4x&1 bit is true if the chunk is checked out and
25396** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
25397** is true if the previous chunk is checked out and false if the
25398** previous chunk is free. The u.hdr.prevSize field is the size of
25399** the previous chunk in blocks if the previous chunk is on the
25400** freelist. If the previous chunk is checked out, then
25401** u.hdr.prevSize can be part of the data for that chunk and should
25402** not be read or written.
25403**
25404** We often identify a chunk by its index in mem3.aPool[]. When
25405** this is done, the chunk index refers to the second block of
25406** the chunk. In this way, the first chunk has an index of 1.
25407** A chunk index of 0 means "no such chunk" and is the equivalent
25408** of a NULL pointer.
25409**
25410** The second block of free chunks is of the form u.list. The
25411** two fields form a double-linked list of chunks of related sizes.
25412** Pointers to the head of the list are stored in mem3.aiSmall[]
25413** for smaller chunks and mem3.aiHash[] for larger chunks.
25414**
25415** The second block of a chunk is user data if the chunk is checked
25416** out. If a chunk is checked out, the user data may extend into
25417** the u.hdr.prevSize value of the following chunk.
25418*/
25419typedef struct Mem3Block Mem3Block;
25420struct Mem3Block {
25421 union {
25422 struct {
25423 u32 prevSize; /* Size of previous chunk in Mem3Block elements */
25424 u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
25425 } hdr;
25426 struct {
25427 u32 next; /* Index in mem3.aPool[] of next free chunk */
25428 u32 prev; /* Index in mem3.aPool[] of previous free chunk */
25429 } list;
25430 } u;
25431};
25432
25433/*
25434** All of the static variables used by this module are collected
25435** into a single structure named "mem3". This is to keep the
25436** static variables organized and to reduce namespace pollution
25437** when this module is combined with other in the amalgamation.
25438*/
25439static SQLITE_WSD struct Mem3Global {
25440 /*
25441 ** Memory available for allocation. nPool is the size of the array
25442 ** (in Mem3Blocks) pointed to by aPool less 2.
25443 */
25444 u32 nPool;
25445 Mem3Block *aPool;
25446
25447 /*
25448 ** True if we are evaluating an out-of-memory callback.
25449 */
25450 int alarmBusy;
25451
25452 /*
25453 ** Mutex to control access to the memory allocation subsystem.
25454 */
25455 sqlite3_mutex *mutex;
25456
25457 /*
25458 ** The minimum amount of free space that we have seen.
25459 */
25460 u32 mnKeyBlk;
25461
25462 /*
25463 ** iKeyBlk is the index of the key chunk. Most new allocations
25464 ** occur off of this chunk. szKeyBlk is the size (in Mem3Blocks)
25465 ** of the current key chunk. iKeyBlk is 0 if there is no key chunk.
25466 ** The key chunk is not in either the aiHash[] or aiSmall[].
25467 */
25468 u32 iKeyBlk;
25469 u32 szKeyBlk;
25470
25471 /*
25472 ** Array of lists of free blocks according to the block size
25473 ** for smaller chunks, or a hash on the block size for larger
25474 ** chunks.
25475 */
25476 u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
25477 u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
25478} mem3 = { 97535575 };
25479
25480#define mem3 GLOBAL(struct Mem3Global, mem3)
25481
25482/*
25483** Unlink the chunk at mem3.aPool[i] from list it is currently
25484** on. *pRoot is the list that i is a member of.
25485*/
25486static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
25487 u32 next = mem3.aPool[i].u.list.next;
25488 u32 prev = mem3.aPool[i].u.list.prev;
25489 assert( sqlite3_mutex_held(mem3.mutex) );
25490 if( prev==0 ){
25491 *pRoot = next;
25492 }else{
25493 mem3.aPool[prev].u.list.next = next;
25494 }
25495 if( next ){
25496 mem3.aPool[next].u.list.prev = prev;
25497 }
25498 mem3.aPool[i].u.list.next = 0;
25499 mem3.aPool[i].u.list.prev = 0;
25500}
25501
25502/*
25503** Unlink the chunk at index i from
25504** whatever list is currently a member of.
25505*/
25506static void memsys3Unlink(u32 i){
25507 u32 size, hash;
25508 assert( sqlite3_mutex_held(mem3.mutex) );
25509 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
25510 assert( i>=1 );
25511 size = mem3.aPool[i-1].u.hdr.size4x/4;
25512 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
25513 assert( size>=2 );
25514 if( size <= MX_SMALL ){
25515 memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
25516 }else{
25517 hash = size % N_HASH;
25518 memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
25519 }
25520}
25521
25522/*
25523** Link the chunk at mem3.aPool[i] so that is on the list rooted
25524** at *pRoot.
25525*/
25526static void memsys3LinkIntoList(u32 i, u32 *pRoot){
25527 assert( sqlite3_mutex_held(mem3.mutex) );
25528 mem3.aPool[i].u.list.next = *pRoot;
25529 mem3.aPool[i].u.list.prev = 0;
25530 if( *pRoot ){
25531 mem3.aPool[*pRoot].u.list.prev = i;
25532 }
25533 *pRoot = i;
25534}
25535
25536/*
25537** Link the chunk at index i into either the appropriate
25538** small chunk list, or into the large chunk hash table.
25539*/
25540static void memsys3Link(u32 i){
25541 u32 size, hash;
25542 assert( sqlite3_mutex_held(mem3.mutex) );
25543 assert( i>=1 );
25544 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
25545 size = mem3.aPool[i-1].u.hdr.size4x/4;
25546 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
25547 assert( size>=2 );
25548 if( size <= MX_SMALL ){
25549 memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
25550 }else{
25551 hash = size % N_HASH;
25552 memsys3LinkIntoList(i, &mem3.aiHash[hash]);
25553 }
25554}
25555
25556/*
25557** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
25558** will already be held (obtained by code in malloc.c) if
25559** sqlite3GlobalConfig.bMemStat is true.
25560*/
25561static void memsys3Enter(void){
25562 if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
25563 mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
25564 }
25565 sqlite3_mutex_enter(mem3.mutex);
25566}
25567static void memsys3Leave(void){
25568 sqlite3_mutex_leave(mem3.mutex);
25569}
25570
25571/*
25572** Called when we are unable to satisfy an allocation of nBytes.
25573*/
25574static void memsys3OutOfMemory(int nByte){
25575 if( !mem3.alarmBusy ){
25576 mem3.alarmBusy = 1;
25577 assert( sqlite3_mutex_held(mem3.mutex) );
25578 sqlite3_mutex_leave(mem3.mutex);
25579 sqlite3_release_memory(nByte);
25580 sqlite3_mutex_enter(mem3.mutex);
25581 mem3.alarmBusy = 0;
25582 }
25583}
25584
25585
25586/*
25587** Chunk i is a free chunk that has been unlinked. Adjust its
25588** size parameters for check-out and return a pointer to the
25589** user portion of the chunk.
25590*/
25591static void *memsys3Checkout(u32 i, u32 nBlock){
25592 u32 x;
25593 assert( sqlite3_mutex_held(mem3.mutex) );
25594 assert( i>=1 );
25595 assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
25596 assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
25597 x = mem3.aPool[i-1].u.hdr.size4x;
25598 mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
25599 mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
25600 mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
25601 return &mem3.aPool[i];
25602}
25603
25604/*
25605** Carve a piece off of the end of the mem3.iKeyBlk free chunk.
25606** Return a pointer to the new allocation. Or, if the key chunk
25607** is not large enough, return 0.
25608*/
25609static void *memsys3FromKeyBlk(u32 nBlock){
25610 assert( sqlite3_mutex_held(mem3.mutex) );
25611 assert( mem3.szKeyBlk>=nBlock );
25612 if( nBlock>=mem3.szKeyBlk-1 ){
25613 /* Use the entire key chunk */
25614 void *p = memsys3Checkout(mem3.iKeyBlk, mem3.szKeyBlk);
25615 mem3.iKeyBlk = 0;
25616 mem3.szKeyBlk = 0;
25617 mem3.mnKeyBlk = 0;
25618 return p;
25619 }else{
25620 /* Split the key block. Return the tail. */
25621 u32 newi, x;
25622 newi = mem3.iKeyBlk + mem3.szKeyBlk - nBlock;
25623 assert( newi > mem3.iKeyBlk+1 );
25624 mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = nBlock;
25625 mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x |= 2;
25626 mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
25627 mem3.szKeyBlk -= nBlock;
25628 mem3.aPool[newi-1].u.hdr.prevSize = mem3.szKeyBlk;
25629 x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2;
25630 mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x;
25631 if( mem3.szKeyBlk < mem3.mnKeyBlk ){
25632 mem3.mnKeyBlk = mem3.szKeyBlk;
25633 }
25634 return (void*)&mem3.aPool[newi];
25635 }
25636}
25637
25638/*
25639** *pRoot is the head of a list of free chunks of the same size
25640** or same size hash. In other words, *pRoot is an entry in either
25641** mem3.aiSmall[] or mem3.aiHash[].
25642**
25643** This routine examines all entries on the given list and tries
25644** to coalesce each entries with adjacent free chunks.
25645**
25646** If it sees a chunk that is larger than mem3.iKeyBlk, it replaces
25647** the current mem3.iKeyBlk with the new larger chunk. In order for
25648** this mem3.iKeyBlk replacement to work, the key chunk must be
25649** linked into the hash tables. That is not the normal state of
25650** affairs, of course. The calling routine must link the key
25651** chunk before invoking this routine, then must unlink the (possibly
25652** changed) key chunk once this routine has finished.
25653*/
25654static void memsys3Merge(u32 *pRoot){
25655 u32 iNext, prev, size, i, x;
25656
25657 assert( sqlite3_mutex_held(mem3.mutex) );
25658 for(i=*pRoot; i>0; i=iNext){
25659 iNext = mem3.aPool[i].u.list.next;
25660 size = mem3.aPool[i-1].u.hdr.size4x;
25661 assert( (size&1)==0 );
25662 if( (size&2)==0 ){
25663 memsys3UnlinkFromList(i, pRoot);
25664 assert( i > mem3.aPool[i-1].u.hdr.prevSize );
25665 prev = i - mem3.aPool[i-1].u.hdr.prevSize;
25666 if( prev==iNext ){
25667 iNext = mem3.aPool[prev].u.list.next;
25668 }
25669 memsys3Unlink(prev);
25670 size = i + size/4 - prev;
25671 x = mem3.aPool[prev-1].u.hdr.size4x & 2;
25672 mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
25673 mem3.aPool[prev+size-1].u.hdr.prevSize = size;
25674 memsys3Link(prev);
25675 i = prev;
25676 }else{
25677 size /= 4;
25678 }
25679 if( size>mem3.szKeyBlk ){
25680 mem3.iKeyBlk = i;
25681 mem3.szKeyBlk = size;
25682 }
25683 }
25684}
25685
25686/*
25687** Return a block of memory of at least nBytes in size.
25688** Return NULL if unable.
25689**
25690** This function assumes that the necessary mutexes, if any, are
25691** already held by the caller. Hence "Unsafe".
25692*/
25693static void *memsys3MallocUnsafe(int nByte){
25694 u32 i;
25695 u32 nBlock;
25696 u32 toFree;
25697
25698 assert( sqlite3_mutex_held(mem3.mutex) );
25699 assert( sizeof(Mem3Block)==8 );
25700 if( nByte<=12 ){
25701 nBlock = 2;
25702 }else{
25703 nBlock = (nByte + 11)/8;
25704 }
25705 assert( nBlock>=2 );
25706
25707 /* STEP 1:
25708 ** Look for an entry of the correct size in either the small
25709 ** chunk table or in the large chunk hash table. This is
25710 ** successful most of the time (about 9 times out of 10).
25711 */
25712 if( nBlock <= MX_SMALL ){
25713 i = mem3.aiSmall[nBlock-2];
25714 if( i>0 ){
25715 memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
25716 return memsys3Checkout(i, nBlock);
25717 }
25718 }else{
25719 int hash = nBlock % N_HASH;
25720 for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
25721 if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
25722 memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
25723 return memsys3Checkout(i, nBlock);
25724 }
25725 }
25726 }
25727
25728 /* STEP 2:
25729 ** Try to satisfy the allocation by carving a piece off of the end
25730 ** of the key chunk. This step usually works if step 1 fails.
25731 */
25732 if( mem3.szKeyBlk>=nBlock ){
25733 return memsys3FromKeyBlk(nBlock);
25734 }
25735
25736
25737 /* STEP 3:
25738 ** Loop through the entire memory pool. Coalesce adjacent free
25739 ** chunks. Recompute the key chunk as the largest free chunk.
25740 ** Then try again to satisfy the allocation by carving a piece off
25741 ** of the end of the key chunk. This step happens very
25742 ** rarely (we hope!)
25743 */
25744 for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
25745 memsys3OutOfMemory(toFree);
25746 if( mem3.iKeyBlk ){
25747 memsys3Link(mem3.iKeyBlk);
25748 mem3.iKeyBlk = 0;
25749 mem3.szKeyBlk = 0;
25750 }
25751 for(i=0; i<N_HASH; i++){
25752 memsys3Merge(&mem3.aiHash[i]);
25753 }
25754 for(i=0; i<MX_SMALL-1; i++){
25755 memsys3Merge(&mem3.aiSmall[i]);
25756 }
25757 if( mem3.szKeyBlk ){
25758 memsys3Unlink(mem3.iKeyBlk);
25759 if( mem3.szKeyBlk>=nBlock ){
25760 return memsys3FromKeyBlk(nBlock);
25761 }
25762 }
25763 }
25764
25765 /* If none of the above worked, then we fail. */
25766 return 0;
25767}
25768
25769/*
25770** Free an outstanding memory allocation.
25771**
25772** This function assumes that the necessary mutexes, if any, are
25773** already held by the caller. Hence "Unsafe".
25774*/
25775static void memsys3FreeUnsafe(void *pOld){
25776 Mem3Block *p = (Mem3Block*)pOld;
25777 int i;
25778 u32 size, x;
25779 assert( sqlite3_mutex_held(mem3.mutex) );
25780 assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
25781 i = p - mem3.aPool;
25782 assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
25783 size = mem3.aPool[i-1].u.hdr.size4x/4;
25784 assert( i+size<=mem3.nPool+1 );
25785 mem3.aPool[i-1].u.hdr.size4x &= ~1;
25786 mem3.aPool[i+size-1].u.hdr.prevSize = size;
25787 mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
25788 memsys3Link(i);
25789
25790 /* Try to expand the key using the newly freed chunk */
25791 if( mem3.iKeyBlk ){
25792 while( (mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x&2)==0 ){
25793 size = mem3.aPool[mem3.iKeyBlk-1].u.hdr.prevSize;
25794 mem3.iKeyBlk -= size;
25795 mem3.szKeyBlk += size;
25796 memsys3Unlink(mem3.iKeyBlk);
25797 x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2;
25798 mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x;
25799 mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = mem3.szKeyBlk;
25800 }
25801 x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2;
25802 while( (mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x&1)==0 ){
25803 memsys3Unlink(mem3.iKeyBlk+mem3.szKeyBlk);
25804 mem3.szKeyBlk += mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x/4;
25805 mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x;
25806 mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = mem3.szKeyBlk;
25807 }
25808 }
25809}
25810
25811/*
25812** Return the size of an outstanding allocation, in bytes. The
25813** size returned omits the 8-byte header overhead. This only
25814** works for chunks that are currently checked out.
25815*/
25816static int memsys3Size(void *p){
25817 Mem3Block *pBlock;
25818 assert( p!=0 );
25819 pBlock = (Mem3Block*)p;
25820 assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
25821 return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
25822}
25823
25824/*
25825** Round up a request size to the next valid allocation size.
25826*/
25827static int memsys3Roundup(int n){
25828 if( n<=12 ){
25829 return 12;
25830 }else{
25831 return ((n+11)&~7) - 4;
25832 }
25833}
25834
25835/*
25836** Allocate nBytes of memory.
25837*/
25838static void *memsys3Malloc(int nBytes){
25839 sqlite3_int64 *p;
25840 assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
25841 memsys3Enter();
25842 p = memsys3MallocUnsafe(nBytes);
25843 memsys3Leave();
25844 return (void*)p;
25845}
25846
25847/*
25848** Free memory.
25849*/
25850static void memsys3Free(void *pPrior){
25851 assert( pPrior );
25852 memsys3Enter();
25853 memsys3FreeUnsafe(pPrior);
25854 memsys3Leave();
25855}
25856
25857/*
25858** Change the size of an existing memory allocation
25859*/
25860static void *memsys3Realloc(void *pPrior, int nBytes){
25861 int nOld;
25862 void *p;
25863 if( pPrior==0 ){
25864 return sqlite3_malloc(nBytes);
25865 }
25866 if( nBytes<=0 ){
25867 sqlite3_free(pPrior);
25868 return 0;
25869 }
25870 nOld = memsys3Size(pPrior);
25871 if( nBytes<=nOld && nBytes>=nOld-128 ){
25872 return pPrior;
25873 }
25874 memsys3Enter();
25875 p = memsys3MallocUnsafe(nBytes);
25876 if( p ){
25877 if( nOld<nBytes ){
25878 memcpy(p, pPrior, nOld);
25879 }else{
25880 memcpy(p, pPrior, nBytes);
25881 }
25882 memsys3FreeUnsafe(pPrior);
25883 }
25884 memsys3Leave();
25885 return p;
25886}
25887
25888/*
25889** Initialize this module.
25890*/
25891static int memsys3Init(void *NotUsed){
25892 UNUSED_PARAMETER(NotUsed);
25893 if( !sqlite3GlobalConfig.pHeap ){
25894 return SQLITE_ERROR;
25895 }
25896
25897 /* Store a pointer to the memory block in global structure mem3. */
25898 assert( sizeof(Mem3Block)==8 );
25899 mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
25900 mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
25901
25902 /* Initialize the key block. */
25903 mem3.szKeyBlk = mem3.nPool;
25904 mem3.mnKeyBlk = mem3.szKeyBlk;
25905 mem3.iKeyBlk = 1;
25906 mem3.aPool[0].u.hdr.size4x = (mem3.szKeyBlk<<2) + 2;
25907 mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
25908 mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
25909
25910 return SQLITE_OK;
25911}
25912
25913/*
25914** Deinitialize this module.
25915*/
25916static void memsys3Shutdown(void *NotUsed){
25917 UNUSED_PARAMETER(NotUsed);
25918 mem3.mutex = 0;
25919 return;
25920}
25921
25922
25923
25924/*
25925** Open the file indicated and write a log of all unfreed memory
25926** allocations into that log.
25927*/
25928SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
25929#ifdef SQLITE_DEBUG
25930 FILE *out;
25931 u32 i, j;
25932 u32 size;
25933 if( zFilename==0 || zFilename[0]==0 ){
25934 out = stdout;
25935 }else{
25936 out = fopen(zFilename, "w");
25937 if( out==0 ){
25938 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
25939 zFilename);
25940 return;
25941 }
25942 }
25943 memsys3Enter();
25944 fprintf(out, "CHUNKS:\n");
25945 for(i=1; i<=mem3.nPool; i+=size/4){
25946 size = mem3.aPool[i-1].u.hdr.size4x;
25947 if( size/4<=1 ){
25948 fprintf(out, "%p size error\n", &mem3.aPool[i]);
25949 assert( 0 );
25950 break;
25951 }
25952 if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
25953 fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
25954 assert( 0 );
25955 break;
25956 }
25957 if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
25958 fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
25959 assert( 0 );
25960 break;
25961 }
25962 if( size&1 ){
25963 fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
25964 }else{
25965 fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
25966 i==mem3.iKeyBlk ? " **key**" : "");
25967 }
25968 }
25969 for(i=0; i<MX_SMALL-1; i++){
25970 if( mem3.aiSmall[i]==0 ) continue;
25971 fprintf(out, "small(%2d):", i);
25972 for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
25973 fprintf(out, " %p(%d)", &mem3.aPool[j],
25974 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
25975 }
25976 fprintf(out, "\n");
25977 }
25978 for(i=0; i<N_HASH; i++){
25979 if( mem3.aiHash[i]==0 ) continue;
25980 fprintf(out, "hash(%2d):", i);
25981 for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
25982 fprintf(out, " %p(%d)", &mem3.aPool[j],
25983 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
25984 }
25985 fprintf(out, "\n");
25986 }
25987 fprintf(out, "key=%d\n", mem3.iKeyBlk);
25988 fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szKeyBlk*8);
25989 fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnKeyBlk*8);
25990 sqlite3_mutex_leave(mem3.mutex);
25991 if( out==stdout ){
25992 fflush(stdout);
25993 }else{
25994 fclose(out);
25995 }
25996#else
25997 UNUSED_PARAMETER(zFilename);
25998#endif
25999}
26000
26001/*
26002** This routine is the only routine in this file with external
26003** linkage.
26004**
26005** Populate the low-level memory allocation function pointers in
26006** sqlite3GlobalConfig.m with pointers to the routines in this file. The
26007** arguments specify the block of memory to manage.
26008**
26009** This routine is only called by sqlite3_config(), and therefore
26010** is not required to be threadsafe (it is not).
26011*/
26012SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
26013 static const sqlite3_mem_methods mempoolMethods = {
26014 memsys3Malloc,
26015 memsys3Free,
26016 memsys3Realloc,
26017 memsys3Size,
26018 memsys3Roundup,
26019 memsys3Init,
26020 memsys3Shutdown,
26021 0
26022 };
26023 return &mempoolMethods;
26024}
26025
26026#endif /* SQLITE_ENABLE_MEMSYS3 */
26027
26028/************** End of mem3.c ************************************************/
26029/************** Begin file mem5.c ********************************************/
26030/*
26031** 2007 October 14
26032**
26033** The author disclaims copyright to this source code. In place of
26034** a legal notice, here is a blessing:
26035**
26036** May you do good and not evil.
26037** May you find forgiveness for yourself and forgive others.
26038** May you share freely, never taking more than you give.
26039**
26040*************************************************************************
26041** This file contains the C functions that implement a memory
26042** allocation subsystem for use by SQLite.
26043**
26044** This version of the memory allocation subsystem omits all
26045** use of malloc(). The application gives SQLite a block of memory
26046** before calling sqlite3_initialize() from which allocations
26047** are made and returned by the xMalloc() and xRealloc()
26048** implementations. Once sqlite3_initialize() has been called,
26049** the amount of memory available to SQLite is fixed and cannot
26050** be changed.
26051**
26052** This version of the memory allocation subsystem is included
26053** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
26054**
26055** This memory allocator uses the following algorithm:
26056**
26057** 1. All memory allocation sizes are rounded up to a power of 2.
26058**
26059** 2. If two adjacent free blocks are the halves of a larger block,
26060** then the two blocks are coalesced into the single larger block.
26061**
26062** 3. New memory is allocated from the first available free block.
26063**
26064** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
26065** Concerning Dynamic Storage Allocation". Journal of the Association for
26066** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
26067**
26068** Let n be the size of the largest allocation divided by the minimum
26069** allocation size (after rounding all sizes up to a power of 2.) Let M
26070** be the maximum amount of memory ever outstanding at one time. Let
26071** N be the total amount of memory available for allocation. Robson
26072** proved that this memory allocator will never breakdown due to
26073** fragmentation as long as the following constraint holds:
26074**
26075** N >= M*(1 + log2(n)/2) - n + 1
26076**
26077** The sqlite3_status() logic tracks the maximum values of n and M so
26078** that an application can, at any time, verify this constraint.
26079*/
26080/* #include "sqliteInt.h" */
26081
26082/*
26083** This version of the memory allocator is used only when
26084** SQLITE_ENABLE_MEMSYS5 is defined.
26085*/
26086#ifdef SQLITE_ENABLE_MEMSYS5
26087
26088/*
26089** A minimum allocation is an instance of the following structure.
26090** Larger allocations are an array of these structures where the
26091** size of the array is a power of 2.
26092**
26093** The size of this object must be a power of two. That fact is
26094** verified in memsys5Init().
26095*/
26096typedef struct Mem5Link Mem5Link;
26097struct Mem5Link {
26098 int next; /* Index of next free chunk */
26099 int prev; /* Index of previous free chunk */
26100};
26101
26102/*
26103** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
26104** mem5.szAtom is always at least 8 and 32-bit integers are used,
26105** it is not actually possible to reach this limit.
26106*/
26107#define LOGMAX 30
26108
26109/*
26110** Masks used for mem5.aCtrl[] elements.
26111*/
26112#define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
26113#define CTRL_FREE 0x20 /* True if not checked out */
26114
26115/*
26116** All of the static variables used by this module are collected
26117** into a single structure named "mem5". This is to keep the
26118** static variables organized and to reduce namespace pollution
26119** when this module is combined with other in the amalgamation.
26120*/
26121static SQLITE_WSD struct Mem5Global {
26122 /*
26123 ** Memory available for allocation
26124 */
26125 int szAtom; /* Smallest possible allocation in bytes */
26126 int nBlock; /* Number of szAtom sized blocks in zPool */
26127 u8 *zPool; /* Memory available to be allocated */
26128
26129 /*
26130 ** Mutex to control access to the memory allocation subsystem.
26131 */
26132 sqlite3_mutex *mutex;
26133
26134#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
26135 /*
26136 ** Performance statistics
26137 */
26138 u64 nAlloc; /* Total number of calls to malloc */
26139 u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
26140 u64 totalExcess; /* Total internal fragmentation */
26141 u32 currentOut; /* Current checkout, including internal fragmentation */
26142 u32 currentCount; /* Current number of distinct checkouts */
26143 u32 maxOut; /* Maximum instantaneous currentOut */
26144 u32 maxCount; /* Maximum instantaneous currentCount */
26145 u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
26146#endif
26147
26148 /*
26149 ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
26150 ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
26151 ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth.
26152 */
26153 int aiFreelist[LOGMAX+1];
26154
26155 /*
26156 ** Space for tracking which blocks are checked out and the size
26157 ** of each block. One byte per block.
26158 */
26159 u8 *aCtrl;
26160
26161} mem5;
26162
26163/*
26164** Access the static variable through a macro for SQLITE_OMIT_WSD.
26165*/
26166#define mem5 GLOBAL(struct Mem5Global, mem5)
26167
26168/*
26169** Assuming mem5.zPool is divided up into an array of Mem5Link
26170** structures, return a pointer to the idx-th such link.
26171*/
26172#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
26173
26174/*
26175** Unlink the chunk at mem5.aPool[i] from list it is currently
26176** on. It should be found on mem5.aiFreelist[iLogsize].
26177*/
26178static void memsys5Unlink(int i, int iLogsize){
26179 int next, prev;
26180 assert( i>=0 && i<mem5.nBlock );
26181 assert( iLogsize>=0 && iLogsize<=LOGMAX );
26182 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
26183
26184 next = MEM5LINK(i)->next;
26185 prev = MEM5LINK(i)->prev;
26186 if( prev<0 ){
26187 mem5.aiFreelist[iLogsize] = next;
26188 }else{
26189 MEM5LINK(prev)->next = next;
26190 }
26191 if( next>=0 ){
26192 MEM5LINK(next)->prev = prev;
26193 }
26194}
26195
26196/*
26197** Link the chunk at mem5.aPool[i] so that is on the iLogsize
26198** free list.
26199*/
26200static void memsys5Link(int i, int iLogsize){
26201 int x;
26202 assert( sqlite3_mutex_held(mem5.mutex) );
26203 assert( i>=0 && i<mem5.nBlock );
26204 assert( iLogsize>=0 && iLogsize<=LOGMAX );
26205 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
26206
26207 x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
26208 MEM5LINK(i)->prev = -1;
26209 if( x>=0 ){
26210 assert( x<mem5.nBlock );
26211 MEM5LINK(x)->prev = i;
26212 }
26213 mem5.aiFreelist[iLogsize] = i;
26214}
26215
26216/*
26217** Obtain or release the mutex needed to access global data structures.
26218*/
26219static void memsys5Enter(void){
26220 sqlite3_mutex_enter(mem5.mutex);
26221}
26222static void memsys5Leave(void){
26223 sqlite3_mutex_leave(mem5.mutex);
26224}
26225
26226/*
26227** Return the size of an outstanding allocation, in bytes.
26228** This only works for chunks that are currently checked out.
26229*/
26230static int memsys5Size(void *p){
26231 int iSize, i;
26232 assert( p!=0 );
26233 i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
26234 assert( i>=0 && i<mem5.nBlock );
26235 iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
26236 return iSize;
26237}
26238
26239/*
26240** Return a block of memory of at least nBytes in size.
26241** Return NULL if unable. Return NULL if nBytes==0.
26242**
26243** The caller guarantees that nByte is positive.
26244**
26245** The caller has obtained a mutex prior to invoking this
26246** routine so there is never any chance that two or more
26247** threads can be in this routine at the same time.
26248*/
26249static void *memsys5MallocUnsafe(int nByte){
26250 int i; /* Index of a mem5.aPool[] slot */
26251 int iBin; /* Index into mem5.aiFreelist[] */
26252 int iFullSz; /* Size of allocation rounded up to power of 2 */
26253 int iLogsize; /* Log2 of iFullSz/POW2_MIN */
26254
26255 /* nByte must be a positive */
26256 assert( nByte>0 );
26257
26258 /* No more than 1GiB per allocation */
26259 if( nByte > 0x40000000 ) return 0;
26260
26261#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
26262 /* Keep track of the maximum allocation request. Even unfulfilled
26263 ** requests are counted */
26264 if( (u32)nByte>mem5.maxRequest ){
26265 mem5.maxRequest = nByte;
26266 }
26267#endif
26268
26269
26270 /* Round nByte up to the next valid power of two */
26271 for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
26272
26273 /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
26274 ** block. If not, then split a block of the next larger power of
26275 ** two in order to create a new free block of size iLogsize.
26276 */
26277 for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
26278 if( iBin>LOGMAX ){
26279 testcase( sqlite3GlobalConfig.xLog!=0 );
26280 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
26281 return 0;
26282 }
26283 i = mem5.aiFreelist[iBin];
26284 memsys5Unlink(i, iBin);
26285 while( iBin>iLogsize ){
26286 int newSize;
26287
26288 iBin--;
26289 newSize = 1 << iBin;
26290 mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
26291 memsys5Link(i+newSize, iBin);
26292 }
26293 mem5.aCtrl[i] = iLogsize;
26294
26295#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
26296 /* Update allocator performance statistics. */
26297 mem5.nAlloc++;
26298 mem5.totalAlloc += iFullSz;
26299 mem5.totalExcess += iFullSz - nByte;
26300 mem5.currentCount++;
26301 mem5.currentOut += iFullSz;
26302 if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
26303 if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
26304#endif
26305
26306#ifdef SQLITE_DEBUG
26307 /* Make sure the allocated memory does not assume that it is set to zero
26308 ** or retains a value from a previous allocation */
26309 memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
26310#endif
26311
26312 /* Return a pointer to the allocated memory. */
26313 return (void*)&mem5.zPool[i*mem5.szAtom];
26314}
26315
26316/*
26317** Free an outstanding memory allocation.
26318*/
26319static void memsys5FreeUnsafe(void *pOld){
26320 u32 size, iLogsize;
26321 int iBlock;
26322
26323 /* Set iBlock to the index of the block pointed to by pOld in
26324 ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
26325 */
26326 iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
26327
26328 /* Check that the pointer pOld points to a valid, non-free block. */
26329 assert( iBlock>=0 && iBlock<mem5.nBlock );
26330 assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
26331 assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
26332
26333 iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
26334 size = 1<<iLogsize;
26335 assert( iBlock+size-1<(u32)mem5.nBlock );
26336
26337 mem5.aCtrl[iBlock] |= CTRL_FREE;
26338 mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
26339
26340#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
26341 assert( mem5.currentCount>0 );
26342 assert( mem5.currentOut>=(size*mem5.szAtom) );
26343 mem5.currentCount--;
26344 mem5.currentOut -= size*mem5.szAtom;
26345 assert( mem5.currentOut>0 || mem5.currentCount==0 );
26346 assert( mem5.currentCount>0 || mem5.currentOut==0 );
26347#endif
26348
26349 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
26350 while( ALWAYS(iLogsize<LOGMAX) ){
26351 int iBuddy;
26352 if( (iBlock>>iLogsize) & 1 ){
26353 iBuddy = iBlock - size;
26354 assert( iBuddy>=0 );
26355 }else{
26356 iBuddy = iBlock + size;
26357 if( iBuddy>=mem5.nBlock ) break;
26358 }
26359 if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
26360 memsys5Unlink(iBuddy, iLogsize);
26361 iLogsize++;
26362 if( iBuddy<iBlock ){
26363 mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
26364 mem5.aCtrl[iBlock] = 0;
26365 iBlock = iBuddy;
26366 }else{
26367 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
26368 mem5.aCtrl[iBuddy] = 0;
26369 }
26370 size *= 2;
26371 }
26372
26373#ifdef SQLITE_DEBUG
26374 /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
26375 ** not used after being freed */
26376 memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
26377#endif
26378
26379 memsys5Link(iBlock, iLogsize);
26380}
26381
26382/*
26383** Allocate nBytes of memory.
26384*/
26385static void *memsys5Malloc(int nBytes){
26386 sqlite3_int64 *p = 0;
26387 if( nBytes>0 ){
26388 memsys5Enter();
26389 p = memsys5MallocUnsafe(nBytes);
26390 memsys5Leave();
26391 }
26392 return (void*)p;
26393}
26394
26395/*
26396** Free memory.
26397**
26398** The outer layer memory allocator prevents this routine from
26399** being called with pPrior==0.
26400*/
26401static void memsys5Free(void *pPrior){
26402 assert( pPrior!=0 );
26403 memsys5Enter();
26404 memsys5FreeUnsafe(pPrior);
26405 memsys5Leave();
26406}
26407
26408/*
26409** Change the size of an existing memory allocation.
26410**
26411** The outer layer memory allocator prevents this routine from
26412** being called with pPrior==0.
26413**
26414** nBytes is always a value obtained from a prior call to
26415** memsys5Round(). Hence nBytes is always a non-negative power
26416** of two. If nBytes==0 that means that an oversize allocation
26417** (an allocation larger than 0x40000000) was requested and this
26418** routine should return 0 without freeing pPrior.
26419*/
26420static void *memsys5Realloc(void *pPrior, int nBytes){
26421 int nOld;
26422 void *p;
26423 assert( pPrior!=0 );
26424 assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
26425 assert( nBytes>=0 );
26426 if( nBytes==0 ){
26427 return 0;
26428 }
26429 nOld = memsys5Size(pPrior);
26430 if( nBytes<=nOld ){
26431 return pPrior;
26432 }
26433 p = memsys5Malloc(nBytes);
26434 if( p ){
26435 memcpy(p, pPrior, nOld);
26436 memsys5Free(pPrior);
26437 }
26438 return p;
26439}
26440
26441/*
26442** Round up a request size to the next valid allocation size. If
26443** the allocation is too large to be handled by this allocation system,
26444** return 0.
26445**
26446** All allocations must be a power of two and must be expressed by a
26447** 32-bit signed integer. Hence the largest allocation is 0x40000000
26448** or 1073741824 bytes.
26449*/
26450static int memsys5Roundup(int n){
26451 int iFullSz;
26452 if( n > 0x40000000 ) return 0;
26453 for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
26454 return iFullSz;
26455}
26456
26457/*
26458** Return the ceiling of the logarithm base 2 of iValue.
26459**
26460** Examples: memsys5Log(1) -> 0
26461** memsys5Log(2) -> 1
26462** memsys5Log(4) -> 2
26463** memsys5Log(5) -> 3
26464** memsys5Log(8) -> 3
26465** memsys5Log(9) -> 4
26466*/
26467static int memsys5Log(int iValue){
26468 int iLog;
26469 for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
26470 return iLog;
26471}
26472
26473/*
26474** Initialize the memory allocator.
26475**
26476** This routine is not threadsafe. The caller must be holding a mutex
26477** to prevent multiple threads from entering at the same time.
26478*/
26479static int memsys5Init(void *NotUsed){
26480 int ii; /* Loop counter */
26481 int nByte; /* Number of bytes of memory available to this allocator */
26482 u8 *zByte; /* Memory usable by this allocator */
26483 int nMinLog; /* Log base 2 of minimum allocation size in bytes */
26484 int iOffset; /* An offset into mem5.aCtrl[] */
26485
26486 UNUSED_PARAMETER(NotUsed);
26487
26488 /* For the purposes of this routine, disable the mutex */
26489 mem5.mutex = 0;
26490
26491 /* The size of a Mem5Link object must be a power of two. Verify that
26492 ** this is case.
26493 */
26494 assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
26495
26496 nByte = sqlite3GlobalConfig.nHeap;
26497 zByte = (u8*)sqlite3GlobalConfig.pHeap;
26498 assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
26499
26500 /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
26501 nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
26502 mem5.szAtom = (1<<nMinLog);
26503 while( (int)sizeof(Mem5Link)>mem5.szAtom ){
26504 mem5.szAtom = mem5.szAtom << 1;
26505 }
26506
26507 mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
26508 mem5.zPool = zByte;
26509 mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
26510
26511 for(ii=0; ii<=LOGMAX; ii++){
26512 mem5.aiFreelist[ii] = -1;
26513 }
26514
26515 iOffset = 0;
26516 for(ii=LOGMAX; ii>=0; ii--){
26517 int nAlloc = (1<<ii);
26518 if( (iOffset+nAlloc)<=mem5.nBlock ){
26519 mem5.aCtrl[iOffset] = ii | CTRL_FREE;
26520 memsys5Link(iOffset, ii);
26521 iOffset += nAlloc;
26522 }
26523 assert((iOffset+nAlloc)>mem5.nBlock);
26524 }
26525
26526 /* If a mutex is required for normal operation, allocate one */
26527 if( sqlite3GlobalConfig.bMemstat==0 ){
26528 mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
26529 }
26530
26531 return SQLITE_OK;
26532}
26533
26534/*
26535** Deinitialize this module.
26536*/
26537static void memsys5Shutdown(void *NotUsed){
26538 UNUSED_PARAMETER(NotUsed);
26539 mem5.mutex = 0;
26540 return;
26541}
26542
26543#ifdef SQLITE_TEST
26544/*
26545** Open the file indicated and write a log of all unfreed memory
26546** allocations into that log.
26547*/
26548SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
26549 FILE *out;
26550 int i, j, n;
26551 int nMinLog;
26552
26553 if( zFilename==0 || zFilename[0]==0 ){
26554 out = stdout;
26555 }else{
26556 out = fopen(zFilename, "w");
26557 if( out==0 ){
26558 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
26559 zFilename);
26560 return;
26561 }
26562 }
26563 memsys5Enter();
26564 nMinLog = memsys5Log(mem5.szAtom);
26565 for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
26566 for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
26567 fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
26568 }
26569 fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
26570 fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
26571 fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
26572 fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
26573 fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
26574 fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
26575 fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
26576 fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
26577 memsys5Leave();
26578 if( out==stdout ){
26579 fflush(stdout);
26580 }else{
26581 fclose(out);
26582 }
26583}
26584#endif
26585
26586/*
26587** This routine is the only routine in this file with external
26588** linkage. It returns a pointer to a static sqlite3_mem_methods
26589** struct populated with the memsys5 methods.
26590*/
26591SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
26592 static const sqlite3_mem_methods memsys5Methods = {
26593 memsys5Malloc,
26594 memsys5Free,
26595 memsys5Realloc,
26596 memsys5Size,
26597 memsys5Roundup,
26598 memsys5Init,
26599 memsys5Shutdown,
26600 0
26601 };
26602 return &memsys5Methods;
26603}
26604
26605#endif /* SQLITE_ENABLE_MEMSYS5 */
26606
26607/************** End of mem5.c ************************************************/
26608/************** Begin file mutex.c *******************************************/
26609/*
26610** 2007 August 14
26611**
26612** The author disclaims copyright to this source code. In place of
26613** a legal notice, here is a blessing:
26614**
26615** May you do good and not evil.
26616** May you find forgiveness for yourself and forgive others.
26617** May you share freely, never taking more than you give.
26618**
26619*************************************************************************
26620** This file contains the C functions that implement mutexes.
26621**
26622** This file contains code that is common across all mutex implementations.
26623*/
26624/* #include "sqliteInt.h" */
26625
26626#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
26627/*
26628** For debugging purposes, record when the mutex subsystem is initialized
26629** and uninitialized so that we can assert() if there is an attempt to
26630** allocate a mutex while the system is uninitialized.
26631*/
26632static SQLITE_WSD int mutexIsInit = 0;
26633#endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
26634
26635
26636#ifndef SQLITE_MUTEX_OMIT
26637
26638#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
26639/*
26640** This block (enclosed by SQLITE_ENABLE_MULTITHREADED_CHECKS) contains
26641** the implementation of a wrapper around the system default mutex
26642** implementation (sqlite3DefaultMutex()).
26643**
26644** Most calls are passed directly through to the underlying default
26645** mutex implementation. Except, if a mutex is configured by calling
26646** sqlite3MutexWarnOnContention() on it, then if contention is ever
26647** encountered within xMutexEnter() a warning is emitted via sqlite3_log().
26648**
26649** This type of mutex is used as the database handle mutex when testing
26650** apps that usually use SQLITE_CONFIG_MULTITHREAD mode.
26651*/
26652
26653/*
26654** Type for all mutexes used when SQLITE_ENABLE_MULTITHREADED_CHECKS
26655** is defined. Variable CheckMutex.mutex is a pointer to the real mutex
26656** allocated by the system mutex implementation. Variable iType is usually set
26657** to the type of mutex requested - SQLITE_MUTEX_RECURSIVE, SQLITE_MUTEX_FAST
26658** or one of the static mutex identifiers. Or, if this is a recursive mutex
26659** that has been configured using sqlite3MutexWarnOnContention(), it is
26660** set to SQLITE_MUTEX_WARNONCONTENTION.
26661*/
26662typedef struct CheckMutex CheckMutex;
26663struct CheckMutex {
26664 int iType;
26665 sqlite3_mutex *mutex;
26666};
26667
26668#define SQLITE_MUTEX_WARNONCONTENTION (-1)
26669
26670/*
26671** Pointer to real mutex methods object used by the CheckMutex
26672** implementation. Set by checkMutexInit().
26673*/
26674static SQLITE_WSD const sqlite3_mutex_methods *pGlobalMutexMethods;
26675
26676#ifdef SQLITE_DEBUG
26677static int checkMutexHeld(sqlite3_mutex *p){
26678 return pGlobalMutexMethods->xMutexHeld(((CheckMutex*)p)->mutex);
26679}
26680static int checkMutexNotheld(sqlite3_mutex *p){
26681 return pGlobalMutexMethods->xMutexNotheld(((CheckMutex*)p)->mutex);
26682}
26683#endif
26684
26685/*
26686** Initialize and deinitialize the mutex subsystem.
26687*/
26688static int checkMutexInit(void){
26689 pGlobalMutexMethods = sqlite3DefaultMutex();
26690 return SQLITE_OK;
26691}
26692static int checkMutexEnd(void){
26693 pGlobalMutexMethods = 0;
26694 return SQLITE_OK;
26695}
26696
26697/*
26698** Allocate a mutex.
26699*/
26700static sqlite3_mutex *checkMutexAlloc(int iType){
26701 static CheckMutex staticMutexes[] = {
26702 {2, 0}, {3, 0}, {4, 0}, {5, 0},
26703 {6, 0}, {7, 0}, {8, 0}, {9, 0},
26704 {10, 0}, {11, 0}, {12, 0}, {13, 0}
26705 };
26706 CheckMutex *p = 0;
26707
26708 assert( SQLITE_MUTEX_RECURSIVE==1 && SQLITE_MUTEX_FAST==0 );
26709 if( iType<2 ){
26710 p = sqlite3MallocZero(sizeof(CheckMutex));
26711 if( p==0 ) return 0;
26712 p->iType = iType;
26713 }else{
26714#ifdef SQLITE_ENABLE_API_ARMOR
26715 if( iType-2>=ArraySize(staticMutexes) ){
26716 (void)SQLITE_MISUSE_BKPT;
26717 return 0;
26718 }
26719#endif
26720 p = &staticMutexes[iType-2];
26721 }
26722
26723 if( p->mutex==0 ){
26724 p->mutex = pGlobalMutexMethods->xMutexAlloc(iType);
26725 if( p->mutex==0 ){
26726 if( iType<2 ){
26727 sqlite3_free(p);
26728 }
26729 p = 0;
26730 }
26731 }
26732
26733 return (sqlite3_mutex*)p;
26734}
26735
26736/*
26737** Free a mutex.
26738*/
26739static void checkMutexFree(sqlite3_mutex *p){
26740 assert( SQLITE_MUTEX_RECURSIVE<2 );
26741 assert( SQLITE_MUTEX_FAST<2 );
26742 assert( SQLITE_MUTEX_WARNONCONTENTION<2 );
26743
26744#if SQLITE_ENABLE_API_ARMOR
26745 if( ((CheckMutex*)p)->iType<2 )
26746#endif
26747 {
26748 CheckMutex *pCheck = (CheckMutex*)p;
26749 pGlobalMutexMethods->xMutexFree(pCheck->mutex);
26750 sqlite3_free(pCheck);
26751 }
26752#ifdef SQLITE_ENABLE_API_ARMOR
26753 else{
26754 (void)SQLITE_MISUSE_BKPT;
26755 }
26756#endif
26757}
26758
26759/*
26760** Enter the mutex.
26761*/
26762static void checkMutexEnter(sqlite3_mutex *p){
26763 CheckMutex *pCheck = (CheckMutex*)p;
26764 if( pCheck->iType==SQLITE_MUTEX_WARNONCONTENTION ){
26765 if( SQLITE_OK==pGlobalMutexMethods->xMutexTry(pCheck->mutex) ){
26766 return;
26767 }
26768 sqlite3_log(SQLITE_MISUSE,
26769 "illegal multi-threaded access to database connection"
26770 );
26771 }
26772 pGlobalMutexMethods->xMutexEnter(pCheck->mutex);
26773}
26774
26775/*
26776** Enter the mutex (do not block).
26777*/
26778static int checkMutexTry(sqlite3_mutex *p){
26779 CheckMutex *pCheck = (CheckMutex*)p;
26780 return pGlobalMutexMethods->xMutexTry(pCheck->mutex);
26781}
26782
26783/*
26784** Leave the mutex.
26785*/
26786static void checkMutexLeave(sqlite3_mutex *p){
26787 CheckMutex *pCheck = (CheckMutex*)p;
26788 pGlobalMutexMethods->xMutexLeave(pCheck->mutex);
26789}
26790
26791sqlite3_mutex_methods const *multiThreadedCheckMutex(void){
26792 static const sqlite3_mutex_methods sMutex = {
26793 checkMutexInit,
26794 checkMutexEnd,
26795 checkMutexAlloc,
26796 checkMutexFree,
26797 checkMutexEnter,
26798 checkMutexTry,
26799 checkMutexLeave,
26800#ifdef SQLITE_DEBUG
26801 checkMutexHeld,
26802 checkMutexNotheld
26803#else
26804 0,
26805 0
26806#endif
26807 };
26808 return &sMutex;
26809}
26810
26811/*
26812** Mark the SQLITE_MUTEX_RECURSIVE mutex passed as the only argument as
26813** one on which there should be no contention.
26814*/
26815SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex *p){
26816 if( sqlite3GlobalConfig.mutex.xMutexAlloc==checkMutexAlloc ){
26817 CheckMutex *pCheck = (CheckMutex*)p;
26818 assert( pCheck->iType==SQLITE_MUTEX_RECURSIVE );
26819 pCheck->iType = SQLITE_MUTEX_WARNONCONTENTION;
26820 }
26821}
26822#endif /* ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS */
26823
26824/*
26825** Initialize the mutex system.
26826*/
26827SQLITE_PRIVATE int sqlite3MutexInit(void){
26828 int rc = SQLITE_OK;
26829 if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
26830 /* If the xMutexAlloc method has not been set, then the user did not
26831 ** install a mutex implementation via sqlite3_config() prior to
26832 ** sqlite3_initialize() being called. This block copies pointers to
26833 ** the default implementation into the sqlite3GlobalConfig structure.
26834 */
26835 sqlite3_mutex_methods const *pFrom;
26836 sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
26837
26838 if( sqlite3GlobalConfig.bCoreMutex ){
26839#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
26840 pFrom = multiThreadedCheckMutex();
26841#else
26842 pFrom = sqlite3DefaultMutex();
26843#endif
26844 }else{
26845 pFrom = sqlite3NoopMutex();
26846 }
26847 pTo->xMutexInit = pFrom->xMutexInit;
26848 pTo->xMutexEnd = pFrom->xMutexEnd;
26849 pTo->xMutexFree = pFrom->xMutexFree;
26850 pTo->xMutexEnter = pFrom->xMutexEnter;
26851 pTo->xMutexTry = pFrom->xMutexTry;
26852 pTo->xMutexLeave = pFrom->xMutexLeave;
26853 pTo->xMutexHeld = pFrom->xMutexHeld;
26854 pTo->xMutexNotheld = pFrom->xMutexNotheld;
26855 sqlite3MemoryBarrier();
26856 pTo->xMutexAlloc = pFrom->xMutexAlloc;
26857 }
26858 assert( sqlite3GlobalConfig.mutex.xMutexInit );
26859 rc = sqlite3GlobalConfig.mutex.xMutexInit();
26860
26861#ifdef SQLITE_DEBUG
26862 GLOBAL(int, mutexIsInit) = 1;
26863#endif
26864
26865 sqlite3MemoryBarrier();
26866 return rc;
26867}
26868
26869/*
26870** Shutdown the mutex system. This call frees resources allocated by
26871** sqlite3MutexInit().
26872*/
26873SQLITE_PRIVATE int sqlite3MutexEnd(void){
26874 int rc = SQLITE_OK;
26875 if( sqlite3GlobalConfig.mutex.xMutexEnd ){
26876 rc = sqlite3GlobalConfig.mutex.xMutexEnd();
26877 }
26878
26879#ifdef SQLITE_DEBUG
26880 GLOBAL(int, mutexIsInit) = 0;
26881#endif
26882
26883 return rc;
26884}
26885
26886/*
26887** Retrieve a pointer to a static mutex or allocate a new dynamic one.
26888*/
26889SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
26890#ifndef SQLITE_OMIT_AUTOINIT
26891 if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
26892 if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
26893#endif
26894 assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
26895 return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
26896}
26897
26898SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
26899 if( !sqlite3GlobalConfig.bCoreMutex ){
26900 return 0;
26901 }
26902 assert( GLOBAL(int, mutexIsInit) );
26903 assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
26904 return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
26905}
26906
26907/*
26908** Free a dynamic mutex.
26909*/
26910SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
26911 if( p ){
26912 assert( sqlite3GlobalConfig.mutex.xMutexFree );
26913 sqlite3GlobalConfig.mutex.xMutexFree(p);
26914 }
26915}
26916
26917/*
26918** Obtain the mutex p. If some other thread already has the mutex, block
26919** until it can be obtained.
26920*/
26921SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
26922 if( p ){
26923 assert( sqlite3GlobalConfig.mutex.xMutexEnter );
26924 sqlite3GlobalConfig.mutex.xMutexEnter(p);
26925 }
26926}
26927
26928/*
26929** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
26930** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
26931*/
26932SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
26933 int rc = SQLITE_OK;
26934 if( p ){
26935 assert( sqlite3GlobalConfig.mutex.xMutexTry );
26936 return sqlite3GlobalConfig.mutex.xMutexTry(p);
26937 }
26938 return rc;
26939}
26940
26941/*
26942** The sqlite3_mutex_leave() routine exits a mutex that was previously
26943** entered by the same thread. The behavior is undefined if the mutex
26944** is not currently entered. If a NULL pointer is passed as an argument
26945** this function is a no-op.
26946*/
26947SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
26948 if( p ){
26949 assert( sqlite3GlobalConfig.mutex.xMutexLeave );
26950 sqlite3GlobalConfig.mutex.xMutexLeave(p);
26951 }
26952}
26953
26954#ifndef NDEBUG
26955/*
26956** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
26957** intended for use inside assert() statements.
26958*/
26959SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
26960 assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
26961 return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
26962}
26963SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
26964 assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
26965 return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
26966}
26967#endif
26968
26969#endif /* !defined(SQLITE_MUTEX_OMIT) */
26970
26971/************** End of mutex.c ***********************************************/
26972/************** Begin file mutex_noop.c **************************************/
26973/*
26974** 2008 October 07
26975**
26976** The author disclaims copyright to this source code. In place of
26977** a legal notice, here is a blessing:
26978**
26979** May you do good and not evil.
26980** May you find forgiveness for yourself and forgive others.
26981** May you share freely, never taking more than you give.
26982**
26983*************************************************************************
26984** This file contains the C functions that implement mutexes.
26985**
26986** This implementation in this file does not provide any mutual
26987** exclusion and is thus suitable for use only in applications
26988** that use SQLite in a single thread. The routines defined
26989** here are place-holders. Applications can substitute working
26990** mutex routines at start-time using the
26991**
26992** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
26993**
26994** interface.
26995**
26996** If compiled with SQLITE_DEBUG, then additional logic is inserted
26997** that does error checking on mutexes to make sure they are being
26998** called correctly.
26999*/
27000/* #include "sqliteInt.h" */
27001
27002#ifndef SQLITE_MUTEX_OMIT
27003
27004#ifndef SQLITE_DEBUG
27005/*
27006** Stub routines for all mutex methods.
27007**
27008** This routines provide no mutual exclusion or error checking.
27009*/
27010static int noopMutexInit(void){ return SQLITE_OK; }
27011static int noopMutexEnd(void){ return SQLITE_OK; }
27012static sqlite3_mutex *noopMutexAlloc(int id){
27013 UNUSED_PARAMETER(id);
27014 return (sqlite3_mutex*)8;
27015}
27016static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
27017static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
27018static int noopMutexTry(sqlite3_mutex *p){
27019 UNUSED_PARAMETER(p);
27020 return SQLITE_OK;
27021}
27022static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
27023
27024SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
27025 static const sqlite3_mutex_methods sMutex = {
27026 noopMutexInit,
27027 noopMutexEnd,
27028 noopMutexAlloc,
27029 noopMutexFree,
27030 noopMutexEnter,
27031 noopMutexTry,
27032 noopMutexLeave,
27033
27034 0,
27035 0,
27036 };
27037
27038 return &sMutex;
27039}
27040#endif /* !SQLITE_DEBUG */
27041
27042#ifdef SQLITE_DEBUG
27043/*
27044** In this implementation, error checking is provided for testing
27045** and debugging purposes. The mutexes still do not provide any
27046** mutual exclusion.
27047*/
27048
27049/*
27050** The mutex object
27051*/
27052typedef struct sqlite3_debug_mutex {
27053 int id; /* The mutex type */
27054 int cnt; /* Number of entries without a matching leave */
27055} sqlite3_debug_mutex;
27056
27057/*
27058** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
27059** intended for use inside assert() statements.
27060*/
27061static int debugMutexHeld(sqlite3_mutex *pX){
27062 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
27063 return p==0 || p->cnt>0;
27064}
27065static int debugMutexNotheld(sqlite3_mutex *pX){
27066 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
27067 return p==0 || p->cnt==0;
27068}
27069
27070/*
27071** Initialize and deinitialize the mutex subsystem.
27072*/
27073static int debugMutexInit(void){ return SQLITE_OK; }
27074static int debugMutexEnd(void){ return SQLITE_OK; }
27075
27076/*
27077** The sqlite3_mutex_alloc() routine allocates a new
27078** mutex and returns a pointer to it. If it returns NULL
27079** that means that a mutex could not be allocated.
27080*/
27081static sqlite3_mutex *debugMutexAlloc(int id){
27082 static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
27083 sqlite3_debug_mutex *pNew = 0;
27084 switch( id ){
27085 case SQLITE_MUTEX_FAST:
27086 case SQLITE_MUTEX_RECURSIVE: {
27087 pNew = sqlite3Malloc(sizeof(*pNew));
27088 if( pNew ){
27089 pNew->id = id;
27090 pNew->cnt = 0;
27091 }
27092 break;
27093 }
27094 default: {
27095#ifdef SQLITE_ENABLE_API_ARMOR
27096 if( id-2<0 || id-2>=ArraySize(aStatic) ){
27097 (void)SQLITE_MISUSE_BKPT;
27098 return 0;
27099 }
27100#endif
27101 pNew = &aStatic[id-2];
27102 pNew->id = id;
27103 break;
27104 }
27105 }
27106 return (sqlite3_mutex*)pNew;
27107}
27108
27109/*
27110** This routine deallocates a previously allocated mutex.
27111*/
27112static void debugMutexFree(sqlite3_mutex *pX){
27113 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
27114 assert( p->cnt==0 );
27115 if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
27116 sqlite3_free(p);
27117 }else{
27118#ifdef SQLITE_ENABLE_API_ARMOR
27119 (void)SQLITE_MISUSE_BKPT;
27120#endif
27121 }
27122}
27123
27124/*
27125** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
27126** to enter a mutex. If another thread is already within the mutex,
27127** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
27128** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
27129** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
27130** be entered multiple times by the same thread. In such cases the,
27131** mutex must be exited an equal number of times before another thread
27132** can enter. If the same thread tries to enter any other kind of mutex
27133** more than once, the behavior is undefined.
27134*/
27135static void debugMutexEnter(sqlite3_mutex *pX){
27136 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
27137 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
27138 p->cnt++;
27139}
27140static int debugMutexTry(sqlite3_mutex *pX){
27141 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
27142 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
27143 p->cnt++;
27144 return SQLITE_OK;
27145}
27146
27147/*
27148** The sqlite3_mutex_leave() routine exits a mutex that was
27149** previously entered by the same thread. The behavior
27150** is undefined if the mutex is not currently entered or
27151** is not currently allocated. SQLite will never do either.
27152*/
27153static void debugMutexLeave(sqlite3_mutex *pX){
27154 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
27155 assert( debugMutexHeld(pX) );
27156 p->cnt--;
27157 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
27158}
27159
27160SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
27161 static const sqlite3_mutex_methods sMutex = {
27162 debugMutexInit,
27163 debugMutexEnd,
27164 debugMutexAlloc,
27165 debugMutexFree,
27166 debugMutexEnter,
27167 debugMutexTry,
27168 debugMutexLeave,
27169
27170 debugMutexHeld,
27171 debugMutexNotheld
27172 };
27173
27174 return &sMutex;
27175}
27176#endif /* SQLITE_DEBUG */
27177
27178/*
27179** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
27180** is used regardless of the run-time threadsafety setting.
27181*/
27182#ifdef SQLITE_MUTEX_NOOP
27183SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
27184 return sqlite3NoopMutex();
27185}
27186#endif /* defined(SQLITE_MUTEX_NOOP) */
27187#endif /* !defined(SQLITE_MUTEX_OMIT) */
27188
27189/************** End of mutex_noop.c ******************************************/
27190/************** Begin file mutex_unix.c **************************************/
27191/*
27192** 2007 August 28
27193**
27194** The author disclaims copyright to this source code. In place of
27195** a legal notice, here is a blessing:
27196**
27197** May you do good and not evil.
27198** May you find forgiveness for yourself and forgive others.
27199** May you share freely, never taking more than you give.
27200**
27201*************************************************************************
27202** This file contains the C functions that implement mutexes for pthreads
27203*/
27204/* #include "sqliteInt.h" */
27205
27206/*
27207** The code in this file is only used if we are compiling threadsafe
27208** under unix with pthreads.
27209**
27210** Note that this implementation requires a version of pthreads that
27211** supports recursive mutexes.
27212*/
27213#ifdef SQLITE_MUTEX_PTHREADS
27214
27215#include <pthread.h>
27216
27217/*
27218** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
27219** are necessary under two condidtions: (1) Debug builds and (2) using
27220** home-grown mutexes. Encapsulate these conditions into a single #define.
27221*/
27222#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
27223# define SQLITE_MUTEX_NREF 1
27224#else
27225# define SQLITE_MUTEX_NREF 0
27226#endif
27227
27228/*
27229** Each recursive mutex is an instance of the following structure.
27230*/
27231struct sqlite3_mutex {
27232 pthread_mutex_t mutex; /* Mutex controlling the lock */
27233#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
27234 int id; /* Mutex type */
27235#endif
27236#if SQLITE_MUTEX_NREF
27237 volatile int nRef; /* Number of entrances */
27238 volatile pthread_t owner; /* Thread that is within this mutex */
27239 int trace; /* True to trace changes */
27240#endif
27241};
27242#if SQLITE_MUTEX_NREF
27243# define SQLITE3_MUTEX_INITIALIZER(id) \
27244 {PTHREAD_MUTEX_INITIALIZER,id,0,(pthread_t)0,0}
27245#elif defined(SQLITE_ENABLE_API_ARMOR)
27246# define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER, id }
27247#else
27248#define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER }
27249#endif
27250
27251/*
27252** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
27253** intended for use only inside assert() statements. On some platforms,
27254** there might be race conditions that can cause these routines to
27255** deliver incorrect results. In particular, if pthread_equal() is
27256** not an atomic operation, then these routines might delivery
27257** incorrect results. On most platforms, pthread_equal() is a
27258** comparison of two integers and is therefore atomic. But we are
27259** told that HPUX is not such a platform. If so, then these routines
27260** will not always work correctly on HPUX.
27261**
27262** On those platforms where pthread_equal() is not atomic, SQLite
27263** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
27264** make sure no assert() statements are evaluated and hence these
27265** routines are never called.
27266*/
27267#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
27268static int pthreadMutexHeld(sqlite3_mutex *p){
27269 return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
27270}
27271static int pthreadMutexNotheld(sqlite3_mutex *p){
27272 return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
27273}
27274#endif
27275
27276/*
27277** Try to provide a memory barrier operation, needed for initialization
27278** and also for the implementation of xShmBarrier in the VFS in cases
27279** where SQLite is compiled without mutexes.
27280*/
27281SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
27282#if defined(SQLITE_MEMORY_BARRIER)
27283 SQLITE_MEMORY_BARRIER;
27284#elif defined(__GNUC__) && GCC_VERSION>=4001000
27285 __sync_synchronize();
27286#endif
27287}
27288
27289/*
27290** Initialize and deinitialize the mutex subsystem.
27291*/
27292static int pthreadMutexInit(void){ return SQLITE_OK; }
27293static int pthreadMutexEnd(void){ return SQLITE_OK; }
27294
27295/*
27296** The sqlite3_mutex_alloc() routine allocates a new
27297** mutex and returns a pointer to it. If it returns NULL
27298** that means that a mutex could not be allocated. SQLite
27299** will unwind its stack and return an error. The argument
27300** to sqlite3_mutex_alloc() is one of these integer constants:
27301**
27302** <ul>
27303** <li> SQLITE_MUTEX_FAST
27304** <li> SQLITE_MUTEX_RECURSIVE
27305** <li> SQLITE_MUTEX_STATIC_MAIN
27306** <li> SQLITE_MUTEX_STATIC_MEM
27307** <li> SQLITE_MUTEX_STATIC_OPEN
27308** <li> SQLITE_MUTEX_STATIC_PRNG
27309** <li> SQLITE_MUTEX_STATIC_LRU
27310** <li> SQLITE_MUTEX_STATIC_PMEM
27311** <li> SQLITE_MUTEX_STATIC_APP1
27312** <li> SQLITE_MUTEX_STATIC_APP2
27313** <li> SQLITE_MUTEX_STATIC_APP3
27314** <li> SQLITE_MUTEX_STATIC_VFS1
27315** <li> SQLITE_MUTEX_STATIC_VFS2
27316** <li> SQLITE_MUTEX_STATIC_VFS3
27317** </ul>
27318**
27319** The first two constants cause sqlite3_mutex_alloc() to create
27320** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
27321** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
27322** The mutex implementation does not need to make a distinction
27323** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
27324** not want to. But SQLite will only request a recursive mutex in
27325** cases where it really needs one. If a faster non-recursive mutex
27326** implementation is available on the host platform, the mutex subsystem
27327** might return such a mutex in response to SQLITE_MUTEX_FAST.
27328**
27329** The other allowed parameters to sqlite3_mutex_alloc() each return
27330** a pointer to a static preexisting mutex. Six static mutexes are
27331** used by the current version of SQLite. Future versions of SQLite
27332** may add additional static mutexes. Static mutexes are for internal
27333** use by SQLite only. Applications that use SQLite mutexes should
27334** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
27335** SQLITE_MUTEX_RECURSIVE.
27336**
27337** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
27338** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
27339** returns a different mutex on every call. But for the static
27340** mutex types, the same mutex is returned on every call that has
27341** the same type number.
27342*/
27343static sqlite3_mutex *pthreadMutexAlloc(int iType){
27344 static sqlite3_mutex staticMutexes[] = {
27345 SQLITE3_MUTEX_INITIALIZER(2),
27346 SQLITE3_MUTEX_INITIALIZER(3),
27347 SQLITE3_MUTEX_INITIALIZER(4),
27348 SQLITE3_MUTEX_INITIALIZER(5),
27349 SQLITE3_MUTEX_INITIALIZER(6),
27350 SQLITE3_MUTEX_INITIALIZER(7),
27351 SQLITE3_MUTEX_INITIALIZER(8),
27352 SQLITE3_MUTEX_INITIALIZER(9),
27353 SQLITE3_MUTEX_INITIALIZER(10),
27354 SQLITE3_MUTEX_INITIALIZER(11),
27355 SQLITE3_MUTEX_INITIALIZER(12),
27356 SQLITE3_MUTEX_INITIALIZER(13)
27357 };
27358 sqlite3_mutex *p;
27359 switch( iType ){
27360 case SQLITE_MUTEX_RECURSIVE: {
27361 p = sqlite3MallocZero( sizeof(*p) );
27362 if( p ){
27363#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
27364 /* If recursive mutexes are not available, we will have to
27365 ** build our own. See below. */
27366 pthread_mutex_init(&p->mutex, 0);
27367#else
27368 /* Use a recursive mutex if it is available */
27369 pthread_mutexattr_t recursiveAttr;
27370 pthread_mutexattr_init(attr: &recursiveAttr);
27371 pthread_mutexattr_settype(attr: &recursiveAttr, kind: PTHREAD_MUTEX_RECURSIVE);
27372 pthread_mutex_init(mutex: &p->mutex, mutexattr: &recursiveAttr);
27373 pthread_mutexattr_destroy(attr: &recursiveAttr);
27374#endif
27375#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
27376 p->id = SQLITE_MUTEX_RECURSIVE;
27377#endif
27378 }
27379 break;
27380 }
27381 case SQLITE_MUTEX_FAST: {
27382 p = sqlite3MallocZero( sizeof(*p) );
27383 if( p ){
27384 pthread_mutex_init(mutex: &p->mutex, mutexattr: 0);
27385#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
27386 p->id = SQLITE_MUTEX_FAST;
27387#endif
27388 }
27389 break;
27390 }
27391 default: {
27392#ifdef SQLITE_ENABLE_API_ARMOR
27393 if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
27394 (void)SQLITE_MISUSE_BKPT;
27395 return 0;
27396 }
27397#endif
27398 p = &staticMutexes[iType-2];
27399 break;
27400 }
27401 }
27402#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
27403 assert( p==0 || p->id==iType );
27404#endif
27405 return p;
27406}
27407
27408
27409/*
27410** This routine deallocates a previously
27411** allocated mutex. SQLite is careful to deallocate every
27412** mutex that it allocates.
27413*/
27414static void pthreadMutexFree(sqlite3_mutex *p){
27415 assert( p->nRef==0 );
27416#if SQLITE_ENABLE_API_ARMOR
27417 if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
27418#endif
27419 {
27420 pthread_mutex_destroy(mutex: &p->mutex);
27421 sqlite3_free(p);
27422 }
27423#ifdef SQLITE_ENABLE_API_ARMOR
27424 else{
27425 (void)SQLITE_MISUSE_BKPT;
27426 }
27427#endif
27428}
27429
27430/*
27431** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
27432** to enter a mutex. If another thread is already within the mutex,
27433** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
27434** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
27435** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
27436** be entered multiple times by the same thread. In such cases the,
27437** mutex must be exited an equal number of times before another thread
27438** can enter. If the same thread tries to enter any other kind of mutex
27439** more than once, the behavior is undefined.
27440*/
27441static void pthreadMutexEnter(sqlite3_mutex *p){
27442 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
27443
27444#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
27445 /* If recursive mutexes are not available, then we have to grow
27446 ** our own. This implementation assumes that pthread_equal()
27447 ** is atomic - that it cannot be deceived into thinking self
27448 ** and p->owner are equal if p->owner changes between two values
27449 ** that are not equal to self while the comparison is taking place.
27450 ** This implementation also assumes a coherent cache - that
27451 ** separate processes cannot read different values from the same
27452 ** address at the same time. If either of these two conditions
27453 ** are not met, then the mutexes will fail and problems will result.
27454 */
27455 {
27456 pthread_t self = pthread_self();
27457 if( p->nRef>0 && pthread_equal(p->owner, self) ){
27458 p->nRef++;
27459 }else{
27460 pthread_mutex_lock(&p->mutex);
27461 assert( p->nRef==0 );
27462 p->owner = self;
27463 p->nRef = 1;
27464 }
27465 }
27466#else
27467 /* Use the built-in recursive mutexes if they are available.
27468 */
27469 pthread_mutex_lock(mutex: &p->mutex);
27470#if SQLITE_MUTEX_NREF
27471 assert( p->nRef>0 || p->owner==0 );
27472 p->owner = pthread_self();
27473 p->nRef++;
27474#endif
27475#endif
27476
27477#ifdef SQLITE_DEBUG
27478 if( p->trace ){
27479 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
27480 }
27481#endif
27482}
27483static int pthreadMutexTry(sqlite3_mutex *p){
27484 int rc;
27485 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
27486
27487#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
27488 /* If recursive mutexes are not available, then we have to grow
27489 ** our own. This implementation assumes that pthread_equal()
27490 ** is atomic - that it cannot be deceived into thinking self
27491 ** and p->owner are equal if p->owner changes between two values
27492 ** that are not equal to self while the comparison is taking place.
27493 ** This implementation also assumes a coherent cache - that
27494 ** separate processes cannot read different values from the same
27495 ** address at the same time. If either of these two conditions
27496 ** are not met, then the mutexes will fail and problems will result.
27497 */
27498 {
27499 pthread_t self = pthread_self();
27500 if( p->nRef>0 && pthread_equal(p->owner, self) ){
27501 p->nRef++;
27502 rc = SQLITE_OK;
27503 }else if( pthread_mutex_trylock(&p->mutex)==0 ){
27504 assert( p->nRef==0 );
27505 p->owner = self;
27506 p->nRef = 1;
27507 rc = SQLITE_OK;
27508 }else{
27509 rc = SQLITE_BUSY;
27510 }
27511 }
27512#else
27513 /* Use the built-in recursive mutexes if they are available.
27514 */
27515 if( pthread_mutex_trylock(mutex: &p->mutex)==0 ){
27516#if SQLITE_MUTEX_NREF
27517 p->owner = pthread_self();
27518 p->nRef++;
27519#endif
27520 rc = SQLITE_OK;
27521 }else{
27522 rc = SQLITE_BUSY;
27523 }
27524#endif
27525
27526#ifdef SQLITE_DEBUG
27527 if( rc==SQLITE_OK && p->trace ){
27528 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
27529 }
27530#endif
27531 return rc;
27532}
27533
27534/*
27535** The sqlite3_mutex_leave() routine exits a mutex that was
27536** previously entered by the same thread. The behavior
27537** is undefined if the mutex is not currently entered or
27538** is not currently allocated. SQLite will never do either.
27539*/
27540static void pthreadMutexLeave(sqlite3_mutex *p){
27541 assert( pthreadMutexHeld(p) );
27542#if SQLITE_MUTEX_NREF
27543 p->nRef--;
27544 if( p->nRef==0 ) p->owner = 0;
27545#endif
27546 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
27547
27548#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
27549 if( p->nRef==0 ){
27550 pthread_mutex_unlock(&p->mutex);
27551 }
27552#else
27553 pthread_mutex_unlock(mutex: &p->mutex);
27554#endif
27555
27556#ifdef SQLITE_DEBUG
27557 if( p->trace ){
27558 printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
27559 }
27560#endif
27561}
27562
27563SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
27564 static const sqlite3_mutex_methods sMutex = {
27565 pthreadMutexInit,
27566 pthreadMutexEnd,
27567 pthreadMutexAlloc,
27568 pthreadMutexFree,
27569 pthreadMutexEnter,
27570 pthreadMutexTry,
27571 pthreadMutexLeave,
27572#ifdef SQLITE_DEBUG
27573 pthreadMutexHeld,
27574 pthreadMutexNotheld
27575#else
27576 0,
27577 0
27578#endif
27579 };
27580
27581 return &sMutex;
27582}
27583
27584#endif /* SQLITE_MUTEX_PTHREADS */
27585
27586/************** End of mutex_unix.c ******************************************/
27587/************** Begin file mutex_w32.c ***************************************/
27588/*
27589** 2007 August 14
27590**
27591** The author disclaims copyright to this source code. In place of
27592** a legal notice, here is a blessing:
27593**
27594** May you do good and not evil.
27595** May you find forgiveness for yourself and forgive others.
27596** May you share freely, never taking more than you give.
27597**
27598*************************************************************************
27599** This file contains the C functions that implement mutexes for Win32.
27600*/
27601/* #include "sqliteInt.h" */
27602
27603#if SQLITE_OS_WIN
27604/*
27605** Include code that is common to all os_*.c files
27606*/
27607/* #include "os_common.h" */
27608
27609/*
27610** Include the header file for the Windows VFS.
27611*/
27612/************** Include os_win.h in the middle of mutex_w32.c ****************/
27613/************** Begin file os_win.h ******************************************/
27614/*
27615** 2013 November 25
27616**
27617** The author disclaims copyright to this source code. In place of
27618** a legal notice, here is a blessing:
27619**
27620** May you do good and not evil.
27621** May you find forgiveness for yourself and forgive others.
27622** May you share freely, never taking more than you give.
27623**
27624******************************************************************************
27625**
27626** This file contains code that is specific to Windows.
27627*/
27628#ifndef SQLITE_OS_WIN_H
27629#define SQLITE_OS_WIN_H
27630
27631/*
27632** Include the primary Windows SDK header file.
27633*/
27634#include "windows.h"
27635
27636#ifdef __CYGWIN__
27637# include <sys/cygwin.h>
27638# include <errno.h> /* amalgamator: dontcache */
27639#endif
27640
27641/*
27642** Determine if we are dealing with Windows NT.
27643**
27644** We ought to be able to determine if we are compiling for Windows 9x or
27645** Windows NT using the _WIN32_WINNT macro as follows:
27646**
27647** #if defined(_WIN32_WINNT)
27648** # define SQLITE_OS_WINNT 1
27649** #else
27650** # define SQLITE_OS_WINNT 0
27651** #endif
27652**
27653** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
27654** it ought to, so the above test does not work. We'll just assume that
27655** everything is Windows NT unless the programmer explicitly says otherwise
27656** by setting SQLITE_OS_WINNT to 0.
27657*/
27658#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
27659# define SQLITE_OS_WINNT 1
27660#endif
27661
27662/*
27663** Determine if we are dealing with Windows CE - which has a much reduced
27664** API.
27665*/
27666#if defined(_WIN32_WCE)
27667# define SQLITE_OS_WINCE 1
27668#else
27669# define SQLITE_OS_WINCE 0
27670#endif
27671
27672/*
27673** Determine if we are dealing with WinRT, which provides only a subset of
27674** the full Win32 API.
27675*/
27676#if !defined(SQLITE_OS_WINRT)
27677# define SQLITE_OS_WINRT 0
27678#endif
27679
27680/*
27681** For WinCE, some API function parameters do not appear to be declared as
27682** volatile.
27683*/
27684#if SQLITE_OS_WINCE
27685# define SQLITE_WIN32_VOLATILE
27686#else
27687# define SQLITE_WIN32_VOLATILE volatile
27688#endif
27689
27690/*
27691** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
27692** functions are not available (e.g. those not using MSVC, Cygwin, etc).
27693*/
27694#if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
27695 SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
27696# define SQLITE_OS_WIN_THREADS 1
27697#else
27698# define SQLITE_OS_WIN_THREADS 0
27699#endif
27700
27701#endif /* SQLITE_OS_WIN_H */
27702
27703/************** End of os_win.h **********************************************/
27704/************** Continuing where we left off in mutex_w32.c ******************/
27705#endif
27706
27707/*
27708** The code in this file is only used if we are compiling multithreaded
27709** on a Win32 system.
27710*/
27711#ifdef SQLITE_MUTEX_W32
27712
27713/*
27714** Each recursive mutex is an instance of the following structure.
27715*/
27716struct sqlite3_mutex {
27717 CRITICAL_SECTION mutex; /* Mutex controlling the lock */
27718 int id; /* Mutex type */
27719#ifdef SQLITE_DEBUG
27720 volatile int nRef; /* Number of enterances */
27721 volatile DWORD owner; /* Thread holding this mutex */
27722 volatile LONG trace; /* True to trace changes */
27723#endif
27724};
27725
27726/*
27727** These are the initializer values used when declaring a "static" mutex
27728** on Win32. It should be noted that all mutexes require initialization
27729** on the Win32 platform.
27730*/
27731#define SQLITE_W32_MUTEX_INITIALIZER { 0 }
27732
27733#ifdef SQLITE_DEBUG
27734#define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id, \
27735 0L, (DWORD)0, 0 }
27736#else
27737#define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id }
27738#endif
27739
27740#ifdef SQLITE_DEBUG
27741/*
27742** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
27743** intended for use only inside assert() statements.
27744*/
27745static int winMutexHeld(sqlite3_mutex *p){
27746 return p->nRef!=0 && p->owner==GetCurrentThreadId();
27747}
27748
27749static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
27750 return p->nRef==0 || p->owner!=tid;
27751}
27752
27753static int winMutexNotheld(sqlite3_mutex *p){
27754 DWORD tid = GetCurrentThreadId();
27755 return winMutexNotheld2(p, tid);
27756}
27757#endif
27758
27759/*
27760** Try to provide a memory barrier operation, needed for initialization
27761** and also for the xShmBarrier method of the VFS in cases when SQLite is
27762** compiled without mutexes (SQLITE_THREADSAFE=0).
27763*/
27764SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
27765#if defined(SQLITE_MEMORY_BARRIER)
27766 SQLITE_MEMORY_BARRIER;
27767#elif defined(__GNUC__)
27768 __sync_synchronize();
27769#elif MSVC_VERSION>=1300
27770 _ReadWriteBarrier();
27771#elif defined(MemoryBarrier)
27772 MemoryBarrier();
27773#endif
27774}
27775
27776/*
27777** Initialize and deinitialize the mutex subsystem.
27778*/
27779static sqlite3_mutex winMutex_staticMutexes[] = {
27780 SQLITE3_MUTEX_INITIALIZER(2),
27781 SQLITE3_MUTEX_INITIALIZER(3),
27782 SQLITE3_MUTEX_INITIALIZER(4),
27783 SQLITE3_MUTEX_INITIALIZER(5),
27784 SQLITE3_MUTEX_INITIALIZER(6),
27785 SQLITE3_MUTEX_INITIALIZER(7),
27786 SQLITE3_MUTEX_INITIALIZER(8),
27787 SQLITE3_MUTEX_INITIALIZER(9),
27788 SQLITE3_MUTEX_INITIALIZER(10),
27789 SQLITE3_MUTEX_INITIALIZER(11),
27790 SQLITE3_MUTEX_INITIALIZER(12),
27791 SQLITE3_MUTEX_INITIALIZER(13)
27792};
27793
27794static int winMutex_isInit = 0;
27795static int winMutex_isNt = -1; /* <0 means "need to query" */
27796
27797/* As the winMutexInit() and winMutexEnd() functions are called as part
27798** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
27799** "interlocked" magic used here is probably not strictly necessary.
27800*/
27801static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
27802
27803SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
27804SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
27805
27806static int winMutexInit(void){
27807 /* The first to increment to 1 does actual initialization */
27808 if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
27809 int i;
27810 for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
27811#if SQLITE_OS_WINRT
27812 InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
27813#else
27814 InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
27815#endif
27816 }
27817 winMutex_isInit = 1;
27818 }else{
27819 /* Another thread is (in the process of) initializing the static
27820 ** mutexes */
27821 while( !winMutex_isInit ){
27822 sqlite3_win32_sleep(1);
27823 }
27824 }
27825 return SQLITE_OK;
27826}
27827
27828static int winMutexEnd(void){
27829 /* The first to decrement to 0 does actual shutdown
27830 ** (which should be the last to shutdown.) */
27831 if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
27832 if( winMutex_isInit==1 ){
27833 int i;
27834 for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
27835 DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
27836 }
27837 winMutex_isInit = 0;
27838 }
27839 }
27840 return SQLITE_OK;
27841}
27842
27843/*
27844** The sqlite3_mutex_alloc() routine allocates a new
27845** mutex and returns a pointer to it. If it returns NULL
27846** that means that a mutex could not be allocated. SQLite
27847** will unwind its stack and return an error. The argument
27848** to sqlite3_mutex_alloc() is one of these integer constants:
27849**
27850** <ul>
27851** <li> SQLITE_MUTEX_FAST
27852** <li> SQLITE_MUTEX_RECURSIVE
27853** <li> SQLITE_MUTEX_STATIC_MAIN
27854** <li> SQLITE_MUTEX_STATIC_MEM
27855** <li> SQLITE_MUTEX_STATIC_OPEN
27856** <li> SQLITE_MUTEX_STATIC_PRNG
27857** <li> SQLITE_MUTEX_STATIC_LRU
27858** <li> SQLITE_MUTEX_STATIC_PMEM
27859** <li> SQLITE_MUTEX_STATIC_APP1
27860** <li> SQLITE_MUTEX_STATIC_APP2
27861** <li> SQLITE_MUTEX_STATIC_APP3
27862** <li> SQLITE_MUTEX_STATIC_VFS1
27863** <li> SQLITE_MUTEX_STATIC_VFS2
27864** <li> SQLITE_MUTEX_STATIC_VFS3
27865** </ul>
27866**
27867** The first two constants cause sqlite3_mutex_alloc() to create
27868** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
27869** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
27870** The mutex implementation does not need to make a distinction
27871** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
27872** not want to. But SQLite will only request a recursive mutex in
27873** cases where it really needs one. If a faster non-recursive mutex
27874** implementation is available on the host platform, the mutex subsystem
27875** might return such a mutex in response to SQLITE_MUTEX_FAST.
27876**
27877** The other allowed parameters to sqlite3_mutex_alloc() each return
27878** a pointer to a static preexisting mutex. Six static mutexes are
27879** used by the current version of SQLite. Future versions of SQLite
27880** may add additional static mutexes. Static mutexes are for internal
27881** use by SQLite only. Applications that use SQLite mutexes should
27882** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
27883** SQLITE_MUTEX_RECURSIVE.
27884**
27885** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
27886** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
27887** returns a different mutex on every call. But for the static
27888** mutex types, the same mutex is returned on every call that has
27889** the same type number.
27890*/
27891static sqlite3_mutex *winMutexAlloc(int iType){
27892 sqlite3_mutex *p;
27893
27894 switch( iType ){
27895 case SQLITE_MUTEX_FAST:
27896 case SQLITE_MUTEX_RECURSIVE: {
27897 p = sqlite3MallocZero( sizeof(*p) );
27898 if( p ){
27899 p->id = iType;
27900#ifdef SQLITE_DEBUG
27901#ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
27902 p->trace = 1;
27903#endif
27904#endif
27905#if SQLITE_OS_WINRT
27906 InitializeCriticalSectionEx(&p->mutex, 0, 0);
27907#else
27908 InitializeCriticalSection(&p->mutex);
27909#endif
27910 }
27911 break;
27912 }
27913 default: {
27914#ifdef SQLITE_ENABLE_API_ARMOR
27915 if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
27916 (void)SQLITE_MISUSE_BKPT;
27917 return 0;
27918 }
27919#endif
27920 p = &winMutex_staticMutexes[iType-2];
27921#ifdef SQLITE_DEBUG
27922#ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
27923 InterlockedCompareExchange(&p->trace, 1, 0);
27924#endif
27925#endif
27926 break;
27927 }
27928 }
27929 assert( p==0 || p->id==iType );
27930 return p;
27931}
27932
27933
27934/*
27935** This routine deallocates a previously
27936** allocated mutex. SQLite is careful to deallocate every
27937** mutex that it allocates.
27938*/
27939static void winMutexFree(sqlite3_mutex *p){
27940 assert( p );
27941 assert( p->nRef==0 && p->owner==0 );
27942 if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
27943 DeleteCriticalSection(&p->mutex);
27944 sqlite3_free(p);
27945 }else{
27946#ifdef SQLITE_ENABLE_API_ARMOR
27947 (void)SQLITE_MISUSE_BKPT;
27948#endif
27949 }
27950}
27951
27952/*
27953** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
27954** to enter a mutex. If another thread is already within the mutex,
27955** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
27956** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
27957** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
27958** be entered multiple times by the same thread. In such cases the,
27959** mutex must be exited an equal number of times before another thread
27960** can enter. If the same thread tries to enter any other kind of mutex
27961** more than once, the behavior is undefined.
27962*/
27963static void winMutexEnter(sqlite3_mutex *p){
27964#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
27965 DWORD tid = GetCurrentThreadId();
27966#endif
27967#ifdef SQLITE_DEBUG
27968 assert( p );
27969 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
27970#else
27971 assert( p );
27972#endif
27973 assert( winMutex_isInit==1 );
27974 EnterCriticalSection(&p->mutex);
27975#ifdef SQLITE_DEBUG
27976 assert( p->nRef>0 || p->owner==0 );
27977 p->owner = tid;
27978 p->nRef++;
27979 if( p->trace ){
27980 OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
27981 tid, p->id, p, p->trace, p->nRef));
27982 }
27983#endif
27984}
27985
27986static int winMutexTry(sqlite3_mutex *p){
27987#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
27988 DWORD tid = GetCurrentThreadId();
27989#endif
27990 int rc = SQLITE_BUSY;
27991 assert( p );
27992 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
27993 /*
27994 ** The sqlite3_mutex_try() routine is very rarely used, and when it
27995 ** is used it is merely an optimization. So it is OK for it to always
27996 ** fail.
27997 **
27998 ** The TryEnterCriticalSection() interface is only available on WinNT.
27999 ** And some windows compilers complain if you try to use it without
28000 ** first doing some #defines that prevent SQLite from building on Win98.
28001 ** For that reason, we will omit this optimization for now. See
28002 ** ticket #2685.
28003 */
28004#if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
28005 assert( winMutex_isInit==1 );
28006 assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
28007 if( winMutex_isNt<0 ){
28008 winMutex_isNt = sqlite3_win32_is_nt();
28009 }
28010 assert( winMutex_isNt==0 || winMutex_isNt==1 );
28011 if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
28012#ifdef SQLITE_DEBUG
28013 p->owner = tid;
28014 p->nRef++;
28015#endif
28016 rc = SQLITE_OK;
28017 }
28018#else
28019 UNUSED_PARAMETER(p);
28020#endif
28021#ifdef SQLITE_DEBUG
28022 if( p->trace ){
28023 OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
28024 tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
28025 }
28026#endif
28027 return rc;
28028}
28029
28030/*
28031** The sqlite3_mutex_leave() routine exits a mutex that was
28032** previously entered by the same thread. The behavior
28033** is undefined if the mutex is not currently entered or
28034** is not currently allocated. SQLite will never do either.
28035*/
28036static void winMutexLeave(sqlite3_mutex *p){
28037#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
28038 DWORD tid = GetCurrentThreadId();
28039#endif
28040 assert( p );
28041#ifdef SQLITE_DEBUG
28042 assert( p->nRef>0 );
28043 assert( p->owner==tid );
28044 p->nRef--;
28045 if( p->nRef==0 ) p->owner = 0;
28046 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
28047#endif
28048 assert( winMutex_isInit==1 );
28049 LeaveCriticalSection(&p->mutex);
28050#ifdef SQLITE_DEBUG
28051 if( p->trace ){
28052 OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
28053 tid, p->id, p, p->trace, p->nRef));
28054 }
28055#endif
28056}
28057
28058SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
28059 static const sqlite3_mutex_methods sMutex = {
28060 winMutexInit,
28061 winMutexEnd,
28062 winMutexAlloc,
28063 winMutexFree,
28064 winMutexEnter,
28065 winMutexTry,
28066 winMutexLeave,
28067#ifdef SQLITE_DEBUG
28068 winMutexHeld,
28069 winMutexNotheld
28070#else
28071 0,
28072 0
28073#endif
28074 };
28075 return &sMutex;
28076}
28077
28078#endif /* SQLITE_MUTEX_W32 */
28079
28080/************** End of mutex_w32.c *******************************************/
28081/************** Begin file malloc.c ******************************************/
28082/*
28083** 2001 September 15
28084**
28085** The author disclaims copyright to this source code. In place of
28086** a legal notice, here is a blessing:
28087**
28088** May you do good and not evil.
28089** May you find forgiveness for yourself and forgive others.
28090** May you share freely, never taking more than you give.
28091**
28092*************************************************************************
28093**
28094** Memory allocation functions used throughout sqlite.
28095*/
28096/* #include "sqliteInt.h" */
28097/* #include <stdarg.h> */
28098
28099/*
28100** Attempt to release up to n bytes of non-essential memory currently
28101** held by SQLite. An example of non-essential memory is memory used to
28102** cache database pages that are not currently in use.
28103*/
28104SQLITE_API int sqlite3_release_memory(int n){
28105#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
28106 return sqlite3PcacheReleaseMemory(n);
28107#else
28108 /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
28109 ** is a no-op returning zero if SQLite is not compiled with
28110 ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
28111 UNUSED_PARAMETER(n);
28112 return 0;
28113#endif
28114}
28115
28116/*
28117** Default value of the hard heap limit. 0 means "no limit".
28118*/
28119#ifndef SQLITE_MAX_MEMORY
28120# define SQLITE_MAX_MEMORY 0
28121#endif
28122
28123/*
28124** State information local to the memory allocation subsystem.
28125*/
28126static SQLITE_WSD struct Mem0Global {
28127 sqlite3_mutex *mutex; /* Mutex to serialize access */
28128 sqlite3_int64 alarmThreshold; /* The soft heap limit */
28129 sqlite3_int64 hardLimit; /* The hard upper bound on memory */
28130
28131 /*
28132 ** True if heap is nearly "full" where "full" is defined by the
28133 ** sqlite3_soft_heap_limit() setting.
28134 */
28135 int nearlyFull;
28136} mem0 = { 0, SQLITE_MAX_MEMORY, SQLITE_MAX_MEMORY, 0 };
28137
28138#define mem0 GLOBAL(struct Mem0Global, mem0)
28139
28140/*
28141** Return the memory allocator mutex. sqlite3_status() needs it.
28142*/
28143SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
28144 return mem0.mutex;
28145}
28146
28147#ifndef SQLITE_OMIT_DEPRECATED
28148/*
28149** Deprecated external interface. It used to set an alarm callback
28150** that was invoked when memory usage grew too large. Now it is a
28151** no-op.
28152*/
28153SQLITE_API int sqlite3_memory_alarm(
28154 void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
28155 void *pArg,
28156 sqlite3_int64 iThreshold
28157){
28158 (void)xCallback;
28159 (void)pArg;
28160 (void)iThreshold;
28161 return SQLITE_OK;
28162}
28163#endif
28164
28165/*
28166** Set the soft heap-size limit for the library. An argument of
28167** zero disables the limit. A negative argument is a no-op used to
28168** obtain the return value.
28169**
28170** The return value is the value of the heap limit just before this
28171** interface was called.
28172**
28173** If the hard heap limit is enabled, then the soft heap limit cannot
28174** be disabled nor raised above the hard heap limit.
28175*/
28176SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
28177 sqlite3_int64 priorLimit;
28178 sqlite3_int64 excess;
28179 sqlite3_int64 nUsed;
28180#ifndef SQLITE_OMIT_AUTOINIT
28181 int rc = sqlite3_initialize();
28182 if( rc ) return -1;
28183#endif
28184 sqlite3_mutex_enter(mem0.mutex);
28185 priorLimit = mem0.alarmThreshold;
28186 if( n<0 ){
28187 sqlite3_mutex_leave(mem0.mutex);
28188 return priorLimit;
28189 }
28190 if( mem0.hardLimit>0 && (n>mem0.hardLimit || n==0) ){
28191 n = mem0.hardLimit;
28192 }
28193 mem0.alarmThreshold = n;
28194 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
28195 AtomicStore(&mem0.nearlyFull, n>0 && n<=nUsed);
28196 sqlite3_mutex_leave(mem0.mutex);
28197 excess = sqlite3_memory_used() - n;
28198 if( excess>0 ) sqlite3_release_memory(n: (int)(excess & 0x7fffffff));
28199 return priorLimit;
28200}
28201SQLITE_API void sqlite3_soft_heap_limit(int n){
28202 if( n<0 ) n = 0;
28203 sqlite3_soft_heap_limit64(n);
28204}
28205
28206/*
28207** Set the hard heap-size limit for the library. An argument of zero
28208** disables the hard heap limit. A negative argument is a no-op used
28209** to obtain the return value without affecting the hard heap limit.
28210**
28211** The return value is the value of the hard heap limit just prior to
28212** calling this interface.
28213**
28214** Setting the hard heap limit will also activate the soft heap limit
28215** and constrain the soft heap limit to be no more than the hard heap
28216** limit.
28217*/
28218SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 n){
28219 sqlite3_int64 priorLimit;
28220#ifndef SQLITE_OMIT_AUTOINIT
28221 int rc = sqlite3_initialize();
28222 if( rc ) return -1;
28223#endif
28224 sqlite3_mutex_enter(mem0.mutex);
28225 priorLimit = mem0.hardLimit;
28226 if( n>=0 ){
28227 mem0.hardLimit = n;
28228 if( n<mem0.alarmThreshold || mem0.alarmThreshold==0 ){
28229 mem0.alarmThreshold = n;
28230 }
28231 }
28232 sqlite3_mutex_leave(mem0.mutex);
28233 return priorLimit;
28234}
28235
28236
28237/*
28238** Initialize the memory allocation subsystem.
28239*/
28240SQLITE_PRIVATE int sqlite3MallocInit(void){
28241 int rc;
28242 if( sqlite3GlobalConfig.m.xMalloc==0 ){
28243 sqlite3MemSetDefault();
28244 }
28245 mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
28246 if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
28247 || sqlite3GlobalConfig.nPage<=0 ){
28248 sqlite3GlobalConfig.pPage = 0;
28249 sqlite3GlobalConfig.szPage = 0;
28250 }
28251 rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
28252 if( rc!=SQLITE_OK ) memset(s: &mem0, c: 0, n: sizeof(mem0));
28253 return rc;
28254}
28255
28256/*
28257** Return true if the heap is currently under memory pressure - in other
28258** words if the amount of heap used is close to the limit set by
28259** sqlite3_soft_heap_limit().
28260*/
28261SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
28262 return AtomicLoad(&mem0.nearlyFull);
28263}
28264
28265/*
28266** Deinitialize the memory allocation subsystem.
28267*/
28268SQLITE_PRIVATE void sqlite3MallocEnd(void){
28269 if( sqlite3GlobalConfig.m.xShutdown ){
28270 sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
28271 }
28272 memset(s: &mem0, c: 0, n: sizeof(mem0));
28273}
28274
28275/*
28276** Return the amount of memory currently checked out.
28277*/
28278SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
28279 sqlite3_int64 res, mx;
28280 sqlite3_status64(SQLITE_STATUS_MEMORY_USED, pCurrent: &res, pHighwater: &mx, resetFlag: 0);
28281 return res;
28282}
28283
28284/*
28285** Return the maximum amount of memory that has ever been
28286** checked out since either the beginning of this process
28287** or since the most recent reset.
28288*/
28289SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
28290 sqlite3_int64 res, mx;
28291 sqlite3_status64(SQLITE_STATUS_MEMORY_USED, pCurrent: &res, pHighwater: &mx, resetFlag);
28292 return mx;
28293}
28294
28295/*
28296** Trigger the alarm
28297*/
28298static void sqlite3MallocAlarm(int nByte){
28299 if( mem0.alarmThreshold<=0 ) return;
28300 sqlite3_mutex_leave(mem0.mutex);
28301 sqlite3_release_memory(n: nByte);
28302 sqlite3_mutex_enter(mem0.mutex);
28303}
28304
28305/*
28306** Do a memory allocation with statistics and alarms. Assume the
28307** lock is already held.
28308*/
28309static void mallocWithAlarm(int n, void **pp){
28310 void *p;
28311 int nFull;
28312 assert( sqlite3_mutex_held(mem0.mutex) );
28313 assert( n>0 );
28314
28315 /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
28316 ** implementation of malloc_good_size(), which must be called in debug
28317 ** mode and specifically when the DMD "Dark Matter Detector" is enabled
28318 ** or else a crash results. Hence, do not attempt to optimize out the
28319 ** following xRoundup() call. */
28320 nFull = sqlite3GlobalConfig.m.xRoundup(n);
28321
28322 sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, X: n);
28323 if( mem0.alarmThreshold>0 ){
28324 sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
28325 if( nUsed >= mem0.alarmThreshold - nFull ){
28326 AtomicStore(&mem0.nearlyFull, 1);
28327 sqlite3MallocAlarm(nByte: nFull);
28328 if( mem0.hardLimit ){
28329 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
28330 if( nUsed >= mem0.hardLimit - nFull ){
28331 *pp = 0;
28332 return;
28333 }
28334 }
28335 }else{
28336 AtomicStore(&mem0.nearlyFull, 0);
28337 }
28338 }
28339 p = sqlite3GlobalConfig.m.xMalloc(nFull);
28340#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
28341 if( p==0 && mem0.alarmThreshold>0 ){
28342 sqlite3MallocAlarm(nFull);
28343 p = sqlite3GlobalConfig.m.xMalloc(nFull);
28344 }
28345#endif
28346 if( p ){
28347 nFull = sqlite3MallocSize(p);
28348 sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, N: nFull);
28349 sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, N: 1);
28350 }
28351 *pp = p;
28352}
28353
28354/*
28355** Allocate memory. This routine is like sqlite3_malloc() except that it
28356** assumes the memory subsystem has already been initialized.
28357*/
28358SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
28359 void *p;
28360 if( n==0 || n>=0x7fffff00 ){
28361 /* A memory allocation of a number of bytes which is near the maximum
28362 ** signed integer value might cause an integer overflow inside of the
28363 ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
28364 ** 255 bytes of overhead. SQLite itself will never use anything near
28365 ** this amount. The only way to reach the limit is with sqlite3_malloc() */
28366 p = 0;
28367 }else if( sqlite3GlobalConfig.bMemstat ){
28368 sqlite3_mutex_enter(mem0.mutex);
28369 mallocWithAlarm(n: (int)n, pp: &p);
28370 sqlite3_mutex_leave(mem0.mutex);
28371 }else{
28372 p = sqlite3GlobalConfig.m.xMalloc((int)n);
28373 }
28374 assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
28375 return p;
28376}
28377
28378/*
28379** This version of the memory allocation is for use by the application.
28380** First make sure the memory subsystem is initialized, then do the
28381** allocation.
28382*/
28383SQLITE_API void *sqlite3_malloc(int n){
28384#ifndef SQLITE_OMIT_AUTOINIT
28385 if( sqlite3_initialize() ) return 0;
28386#endif
28387 return n<=0 ? 0 : sqlite3Malloc(n);
28388}
28389SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
28390#ifndef SQLITE_OMIT_AUTOINIT
28391 if( sqlite3_initialize() ) return 0;
28392#endif
28393 return sqlite3Malloc(n);
28394}
28395
28396/*
28397** TRUE if p is a lookaside memory allocation from db
28398*/
28399#ifndef SQLITE_OMIT_LOOKASIDE
28400static int isLookaside(sqlite3 *db, const void *p){
28401 return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
28402}
28403#else
28404#define isLookaside(A,B) 0
28405#endif
28406
28407/*
28408** Return the size of a memory allocation previously obtained from
28409** sqlite3Malloc() or sqlite3_malloc().
28410*/
28411SQLITE_PRIVATE int sqlite3MallocSize(const void *p){
28412 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
28413 return sqlite3GlobalConfig.m.xSize((void*)p);
28414}
28415static int lookasideMallocSize(sqlite3 *db, const void *p){
28416#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
28417 return p<db->lookaside.pMiddle ? db->lookaside.szTrue : LOOKASIDE_SMALL;
28418#else
28419 return db->lookaside.szTrue;
28420#endif
28421}
28422SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, const void *p){
28423 assert( p!=0 );
28424#ifdef SQLITE_DEBUG
28425 if( db==0 || !isLookaside(db,p) ){
28426 if( db==0 ){
28427 assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
28428 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
28429 }else{
28430 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
28431 assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
28432 }
28433 }
28434#endif
28435 if( db ){
28436 if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){
28437#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
28438 if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){
28439 assert( sqlite3_mutex_held(db->mutex) );
28440 return LOOKASIDE_SMALL;
28441 }
28442#endif
28443 if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){
28444 assert( sqlite3_mutex_held(db->mutex) );
28445 return db->lookaside.szTrue;
28446 }
28447 }
28448 }
28449 return sqlite3GlobalConfig.m.xSize((void*)p);
28450}
28451SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
28452 assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
28453 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
28454 return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
28455}
28456
28457/*
28458** Free memory previously obtained from sqlite3Malloc().
28459*/
28460SQLITE_API void sqlite3_free(void *p){
28461 if( p==0 ) return; /* IMP: R-49053-54554 */
28462 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
28463 assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
28464 if( sqlite3GlobalConfig.bMemstat ){
28465 sqlite3_mutex_enter(mem0.mutex);
28466 sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, N: sqlite3MallocSize(p));
28467 sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, N: 1);
28468 sqlite3GlobalConfig.m.xFree(p);
28469 sqlite3_mutex_leave(mem0.mutex);
28470 }else{
28471 sqlite3GlobalConfig.m.xFree(p);
28472 }
28473}
28474
28475/*
28476** Add the size of memory allocation "p" to the count in
28477** *db->pnBytesFreed.
28478*/
28479static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
28480 *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
28481}
28482
28483/*
28484** Free memory that might be associated with a particular database
28485** connection. Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
28486** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
28487*/
28488SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){
28489 assert( db==0 || sqlite3_mutex_held(db->mutex) );
28490 assert( p!=0 );
28491 if( db ){
28492 if( db->pnBytesFreed ){
28493 measureAllocationSize(db, p);
28494 return;
28495 }
28496 if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){
28497#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
28498 if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){
28499 LookasideSlot *pBuf = (LookasideSlot*)p;
28500#ifdef SQLITE_DEBUG
28501 memset(p, 0xaa, LOOKASIDE_SMALL); /* Trash freed content */
28502#endif
28503 pBuf->pNext = db->lookaside.pSmallFree;
28504 db->lookaside.pSmallFree = pBuf;
28505 return;
28506 }
28507#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
28508 if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){
28509 LookasideSlot *pBuf = (LookasideSlot*)p;
28510#ifdef SQLITE_DEBUG
28511 memset(p, 0xaa, db->lookaside.szTrue); /* Trash freed content */
28512#endif
28513 pBuf->pNext = db->lookaside.pFree;
28514 db->lookaside.pFree = pBuf;
28515 return;
28516 }
28517 }
28518 }
28519 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
28520 assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
28521 assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
28522 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
28523 sqlite3_free(p);
28524}
28525SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
28526 assert( db==0 || sqlite3_mutex_held(db->mutex) );
28527 if( p ) sqlite3DbFreeNN(db, p);
28528}
28529
28530/*
28531** Change the size of an existing memory allocation
28532*/
28533SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
28534 int nOld, nNew, nDiff;
28535 void *pNew;
28536 assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
28537 assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
28538 if( pOld==0 ){
28539 return sqlite3Malloc(n: nBytes); /* IMP: R-04300-56712 */
28540 }
28541 if( nBytes==0 ){
28542 sqlite3_free(p: pOld); /* IMP: R-26507-47431 */
28543 return 0;
28544 }
28545 if( nBytes>=0x7fffff00 ){
28546 /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
28547 return 0;
28548 }
28549 nOld = sqlite3MallocSize(p: pOld);
28550 /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
28551 ** argument to xRealloc is always a value returned by a prior call to
28552 ** xRoundup. */
28553 nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
28554 if( nOld==nNew ){
28555 pNew = pOld;
28556 }else if( sqlite3GlobalConfig.bMemstat ){
28557 sqlite3_int64 nUsed;
28558 sqlite3_mutex_enter(mem0.mutex);
28559 sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, X: (int)nBytes);
28560 nDiff = nNew - nOld;
28561 if( nDiff>0 && (nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)) >=
28562 mem0.alarmThreshold-nDiff ){
28563 sqlite3MallocAlarm(nByte: nDiff);
28564 if( mem0.hardLimit>0 && nUsed >= mem0.hardLimit - nDiff ){
28565 sqlite3_mutex_leave(mem0.mutex);
28566 return 0;
28567 }
28568 }
28569 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
28570#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
28571 if( pNew==0 && mem0.alarmThreshold>0 ){
28572 sqlite3MallocAlarm((int)nBytes);
28573 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
28574 }
28575#endif
28576 if( pNew ){
28577 nNew = sqlite3MallocSize(p: pNew);
28578 sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, N: nNew-nOld);
28579 }
28580 sqlite3_mutex_leave(mem0.mutex);
28581 }else{
28582 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
28583 }
28584 assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
28585 return pNew;
28586}
28587
28588/*
28589** The public interface to sqlite3Realloc. Make sure that the memory
28590** subsystem is initialized prior to invoking sqliteRealloc.
28591*/
28592SQLITE_API void *sqlite3_realloc(void *pOld, int n){
28593#ifndef SQLITE_OMIT_AUTOINIT
28594 if( sqlite3_initialize() ) return 0;
28595#endif
28596 if( n<0 ) n = 0; /* IMP: R-26507-47431 */
28597 return sqlite3Realloc(pOld, nBytes: n);
28598}
28599SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
28600#ifndef SQLITE_OMIT_AUTOINIT
28601 if( sqlite3_initialize() ) return 0;
28602#endif
28603 return sqlite3Realloc(pOld, nBytes: n);
28604}
28605
28606
28607/*
28608** Allocate and zero memory.
28609*/
28610SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
28611 void *p = sqlite3Malloc(n);
28612 if( p ){
28613 memset(s: p, c: 0, n: (size_t)n);
28614 }
28615 return p;
28616}
28617
28618/*
28619** Allocate and zero memory. If the allocation fails, make
28620** the mallocFailed flag in the connection pointer.
28621*/
28622SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
28623 void *p;
28624 testcase( db==0 );
28625 p = sqlite3DbMallocRaw(db, n);
28626 if( p ) memset(s: p, c: 0, n: (size_t)n);
28627 return p;
28628}
28629
28630
28631/* Finish the work of sqlite3DbMallocRawNN for the unusual and
28632** slower case when the allocation cannot be fulfilled using lookaside.
28633*/
28634static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
28635 void *p;
28636 assert( db!=0 );
28637 p = sqlite3Malloc(n);
28638 if( !p ) sqlite3OomFault(db);
28639 sqlite3MemdebugSetType(p,
28640 (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
28641 return p;
28642}
28643
28644/*
28645** Allocate memory, either lookaside (if possible) or heap.
28646** If the allocation fails, set the mallocFailed flag in
28647** the connection pointer.
28648**
28649** If db!=0 and db->mallocFailed is true (indicating a prior malloc
28650** failure on the same database connection) then always return 0.
28651** Hence for a particular database connection, once malloc starts
28652** failing, it fails consistently until mallocFailed is reset.
28653** This is an important assumption. There are many places in the
28654** code that do things like this:
28655**
28656** int *a = (int*)sqlite3DbMallocRaw(db, 100);
28657** int *b = (int*)sqlite3DbMallocRaw(db, 200);
28658** if( b ) a[10] = 9;
28659**
28660** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
28661** that all prior mallocs (ex: "a") worked too.
28662**
28663** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
28664** not a NULL pointer.
28665*/
28666SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
28667 void *p;
28668 if( db ) return sqlite3DbMallocRawNN(db, n);
28669 p = sqlite3Malloc(n);
28670 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
28671 return p;
28672}
28673SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
28674#ifndef SQLITE_OMIT_LOOKASIDE
28675 LookasideSlot *pBuf;
28676 assert( db!=0 );
28677 assert( sqlite3_mutex_held(db->mutex) );
28678 assert( db->pnBytesFreed==0 );
28679 if( n>db->lookaside.sz ){
28680 if( !db->lookaside.bDisable ){
28681 db->lookaside.anStat[1]++;
28682 }else if( db->mallocFailed ){
28683 return 0;
28684 }
28685 return dbMallocRawFinish(db, n);
28686 }
28687#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
28688 if( n<=LOOKASIDE_SMALL ){
28689 if( (pBuf = db->lookaside.pSmallFree)!=0 ){
28690 db->lookaside.pSmallFree = pBuf->pNext;
28691 db->lookaside.anStat[0]++;
28692 return (void*)pBuf;
28693 }else if( (pBuf = db->lookaside.pSmallInit)!=0 ){
28694 db->lookaside.pSmallInit = pBuf->pNext;
28695 db->lookaside.anStat[0]++;
28696 return (void*)pBuf;
28697 }
28698 }
28699#endif
28700 if( (pBuf = db->lookaside.pFree)!=0 ){
28701 db->lookaside.pFree = pBuf->pNext;
28702 db->lookaside.anStat[0]++;
28703 return (void*)pBuf;
28704 }else if( (pBuf = db->lookaside.pInit)!=0 ){
28705 db->lookaside.pInit = pBuf->pNext;
28706 db->lookaside.anStat[0]++;
28707 return (void*)pBuf;
28708 }else{
28709 db->lookaside.anStat[2]++;
28710 }
28711#else
28712 assert( db!=0 );
28713 assert( sqlite3_mutex_held(db->mutex) );
28714 assert( db->pnBytesFreed==0 );
28715 if( db->mallocFailed ){
28716 return 0;
28717 }
28718#endif
28719 return dbMallocRawFinish(db, n);
28720}
28721
28722/* Forward declaration */
28723static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
28724
28725/*
28726** Resize the block of memory pointed to by p to n bytes. If the
28727** resize fails, set the mallocFailed flag in the connection object.
28728*/
28729SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
28730 assert( db!=0 );
28731 if( p==0 ) return sqlite3DbMallocRawNN(db, n);
28732 assert( sqlite3_mutex_held(db->mutex) );
28733 if( ((uptr)p)<(uptr)db->lookaside.pEnd ){
28734#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
28735 if( ((uptr)p)>=(uptr)db->lookaside.pMiddle ){
28736 if( n<=LOOKASIDE_SMALL ) return p;
28737 }else
28738#endif
28739 if( ((uptr)p)>=(uptr)db->lookaside.pStart ){
28740 if( n<=db->lookaside.szTrue ) return p;
28741 }
28742 }
28743 return dbReallocFinish(db, p, n);
28744}
28745static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
28746 void *pNew = 0;
28747 assert( db!=0 );
28748 assert( p!=0 );
28749 if( db->mallocFailed==0 ){
28750 if( isLookaside(db, p) ){
28751 pNew = sqlite3DbMallocRawNN(db, n);
28752 if( pNew ){
28753 memcpy(dest: pNew, src: p, n: lookasideMallocSize(db, p));
28754 sqlite3DbFree(db, p);
28755 }
28756 }else{
28757 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
28758 assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
28759 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
28760 pNew = sqlite3Realloc(pOld: p, nBytes: n);
28761 if( !pNew ){
28762 sqlite3OomFault(db);
28763 }
28764 sqlite3MemdebugSetType(pNew,
28765 (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
28766 }
28767 }
28768 return pNew;
28769}
28770
28771/*
28772** Attempt to reallocate p. If the reallocation fails, then free p
28773** and set the mallocFailed flag in the database connection.
28774*/
28775SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
28776 void *pNew;
28777 pNew = sqlite3DbRealloc(db, p, n);
28778 if( !pNew ){
28779 sqlite3DbFree(db, p);
28780 }
28781 return pNew;
28782}
28783
28784/*
28785** Make a copy of a string in memory obtained from sqliteMalloc(). These
28786** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
28787** is because when memory debugging is turned on, these two functions are
28788** called via macros that record the current file and line number in the
28789** ThreadData structure.
28790*/
28791SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
28792 char *zNew;
28793 size_t n;
28794 if( z==0 ){
28795 return 0;
28796 }
28797 n = strlen(s: z) + 1;
28798 zNew = sqlite3DbMallocRaw(db, n);
28799 if( zNew ){
28800 memcpy(dest: zNew, src: z, n: n);
28801 }
28802 return zNew;
28803}
28804SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
28805 char *zNew;
28806 assert( db!=0 );
28807 assert( z!=0 || n==0 );
28808 assert( (n&0x7fffffff)==n );
28809 zNew = z ? sqlite3DbMallocRawNN(db, n: n+1) : 0;
28810 if( zNew ){
28811 memcpy(dest: zNew, src: z, n: (size_t)n);
28812 zNew[n] = 0;
28813 }
28814 return zNew;
28815}
28816
28817/*
28818** The text between zStart and zEnd represents a phrase within a larger
28819** SQL statement. Make a copy of this phrase in space obtained form
28820** sqlite3DbMalloc(). Omit leading and trailing whitespace.
28821*/
28822SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
28823 int n;
28824 while( sqlite3Isspace(zStart[0]) ) zStart++;
28825 n = (int)(zEnd - zStart);
28826 while( ALWAYS(n>0) && sqlite3Isspace(zStart[n-1]) ) n--;
28827 return sqlite3DbStrNDup(db, z: zStart, n);
28828}
28829
28830/*
28831** Free any prior content in *pz and replace it with a copy of zNew.
28832*/
28833SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
28834 sqlite3DbFree(db, p: *pz);
28835 *pz = sqlite3DbStrDup(db, z: zNew);
28836}
28837
28838/*
28839** Call this routine to record the fact that an OOM (out-of-memory) error
28840** has happened. This routine will set db->mallocFailed, and also
28841** temporarily disable the lookaside memory allocator and interrupt
28842** any running VDBEs.
28843*/
28844SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
28845 if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
28846 db->mallocFailed = 1;
28847 if( db->nVdbeExec>0 ){
28848 AtomicStore(&db->u1.isInterrupted, 1);
28849 }
28850 DisableLookaside;
28851 if( db->pParse ){
28852 db->pParse->rc = SQLITE_NOMEM_BKPT;
28853 }
28854 }
28855}
28856
28857/*
28858** This routine reactivates the memory allocator and clears the
28859** db->mallocFailed flag as necessary.
28860**
28861** The memory allocator is not restarted if there are running
28862** VDBEs.
28863*/
28864SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
28865 if( db->mallocFailed && db->nVdbeExec==0 ){
28866 db->mallocFailed = 0;
28867 AtomicStore(&db->u1.isInterrupted, 0);
28868 assert( db->lookaside.bDisable>0 );
28869 EnableLookaside;
28870 }
28871}
28872
28873/*
28874** Take actions at the end of an API call to deal with error codes.
28875*/
28876static SQLITE_NOINLINE int apiHandleError(sqlite3 *db, int rc){
28877 if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
28878 sqlite3OomClear(db);
28879 sqlite3Error(db, SQLITE_NOMEM);
28880 return SQLITE_NOMEM_BKPT;
28881 }
28882 return rc & db->errMask;
28883}
28884
28885/*
28886** This function must be called before exiting any API function (i.e.
28887** returning control to the user) that has called sqlite3_malloc or
28888** sqlite3_realloc.
28889**
28890** The returned value is normally a copy of the second argument to this
28891** function. However, if a malloc() failure has occurred since the previous
28892** invocation SQLITE_NOMEM is returned instead.
28893**
28894** If an OOM as occurred, then the connection error-code (the value
28895** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
28896*/
28897SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
28898 /* If the db handle must hold the connection handle mutex here.
28899 ** Otherwise the read (and possible write) of db->mallocFailed
28900 ** is unsafe, as is the call to sqlite3Error().
28901 */
28902 assert( db!=0 );
28903 assert( sqlite3_mutex_held(db->mutex) );
28904 if( db->mallocFailed || rc ){
28905 return apiHandleError(db, rc);
28906 }
28907 return rc & db->errMask;
28908}
28909
28910/************** End of malloc.c **********************************************/
28911/************** Begin file printf.c ******************************************/
28912/*
28913** The "printf" code that follows dates from the 1980's. It is in
28914** the public domain.
28915**
28916**************************************************************************
28917**
28918** This file contains code for a set of "printf"-like routines. These
28919** routines format strings much like the printf() from the standard C
28920** library, though the implementation here has enhancements to support
28921** SQLite.
28922*/
28923/* #include "sqliteInt.h" */
28924
28925/*
28926** Conversion types fall into various categories as defined by the
28927** following enumeration.
28928*/
28929#define etRADIX 0 /* non-decimal integer types. %x %o */
28930#define etFLOAT 1 /* Floating point. %f */
28931#define etEXP 2 /* Exponentional notation. %e and %E */
28932#define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
28933#define etSIZE 4 /* Return number of characters processed so far. %n */
28934#define etSTRING 5 /* Strings. %s */
28935#define etDYNSTRING 6 /* Dynamically allocated strings. %z */
28936#define etPERCENT 7 /* Percent symbol. %% */
28937#define etCHARX 8 /* Characters. %c */
28938/* The rest are extensions, not normally found in printf() */
28939#define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
28940#define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
28941 NULL pointers replaced by SQL NULL. %Q */
28942#define etTOKEN 11 /* a pointer to a Token structure */
28943#define etSRCITEM 12 /* a pointer to a SrcItem */
28944#define etPOINTER 13 /* The %p conversion */
28945#define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
28946#define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
28947#define etDECIMAL 16 /* %d or %u, but not %x, %o */
28948
28949#define etINVALID 17 /* Any unrecognized conversion type */
28950
28951
28952/*
28953** An "etByte" is an 8-bit unsigned value.
28954*/
28955typedef unsigned char etByte;
28956
28957/*
28958** Each builtin conversion character (ex: the 'd' in "%d") is described
28959** by an instance of the following structure
28960*/
28961typedef struct et_info { /* Information about each format field */
28962 char fmttype; /* The format field code letter */
28963 etByte base; /* The base for radix conversion */
28964 etByte flags; /* One or more of FLAG_ constants below */
28965 etByte type; /* Conversion paradigm */
28966 etByte charset; /* Offset into aDigits[] of the digits string */
28967 etByte prefix; /* Offset into aPrefix[] of the prefix string */
28968} et_info;
28969
28970/*
28971** Allowed values for et_info.flags
28972*/
28973#define FLAG_SIGNED 1 /* True if the value to convert is signed */
28974#define FLAG_STRING 4 /* Allow infinite precision */
28975
28976
28977/*
28978** The following table is searched linearly, so it is good to put the
28979** most frequently used conversion types first.
28980*/
28981static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
28982static const char aPrefix[] = "-x0\000X0";
28983static const et_info fmtinfo[] = {
28984 { 'd', 10, 1, etDECIMAL, 0, 0 },
28985 { 's', 0, 4, etSTRING, 0, 0 },
28986 { 'g', 0, 1, etGENERIC, 30, 0 },
28987 { 'z', 0, 4, etDYNSTRING, 0, 0 },
28988 { 'q', 0, 4, etSQLESCAPE, 0, 0 },
28989 { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
28990 { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
28991 { 'c', 0, 0, etCHARX, 0, 0 },
28992 { 'o', 8, 0, etRADIX, 0, 2 },
28993 { 'u', 10, 0, etDECIMAL, 0, 0 },
28994 { 'x', 16, 0, etRADIX, 16, 1 },
28995 { 'X', 16, 0, etRADIX, 0, 4 },
28996#ifndef SQLITE_OMIT_FLOATING_POINT
28997 { 'f', 0, 1, etFLOAT, 0, 0 },
28998 { 'e', 0, 1, etEXP, 30, 0 },
28999 { 'E', 0, 1, etEXP, 14, 0 },
29000 { 'G', 0, 1, etGENERIC, 14, 0 },
29001#endif
29002 { 'i', 10, 1, etDECIMAL, 0, 0 },
29003 { 'n', 0, 0, etSIZE, 0, 0 },
29004 { '%', 0, 0, etPERCENT, 0, 0 },
29005 { 'p', 16, 0, etPOINTER, 0, 1 },
29006
29007 /* All the rest are undocumented and are for internal use only */
29008 { 'T', 0, 0, etTOKEN, 0, 0 },
29009 { 'S', 0, 0, etSRCITEM, 0, 0 },
29010 { 'r', 10, 1, etORDINAL, 0, 0 },
29011};
29012
29013/* Notes:
29014**
29015** %S Takes a pointer to SrcItem. Shows name or database.name
29016** %!S Like %S but prefer the zName over the zAlias
29017*/
29018
29019/* Floating point constants used for rounding */
29020static const double arRound[] = {
29021 5.0e-01, 5.0e-02, 5.0e-03, 5.0e-04, 5.0e-05,
29022 5.0e-06, 5.0e-07, 5.0e-08, 5.0e-09, 5.0e-10,
29023};
29024
29025/*
29026** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
29027** conversions will work.
29028*/
29029#ifndef SQLITE_OMIT_FLOATING_POINT
29030/*
29031** "*val" is a double such that 0.1 <= *val < 10.0
29032** Return the ascii code for the leading digit of *val, then
29033** multiply "*val" by 10.0 to renormalize.
29034**
29035** Example:
29036** input: *val = 3.14159
29037** output: *val = 1.4159 function return = '3'
29038**
29039** The counter *cnt is incremented each time. After counter exceeds
29040** 16 (the number of significant digits in a 64-bit float) '0' is
29041** always returned.
29042*/
29043static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
29044 int digit;
29045 LONGDOUBLE_TYPE d;
29046 if( (*cnt)<=0 ) return '0';
29047 (*cnt)--;
29048 digit = (int)*val;
29049 d = digit;
29050 digit += '0';
29051 *val = (*val - d)*10.0;
29052 return (char)digit;
29053}
29054#endif /* SQLITE_OMIT_FLOATING_POINT */
29055
29056/*
29057** Set the StrAccum object to an error mode.
29058*/
29059SQLITE_PRIVATE void sqlite3StrAccumSetError(StrAccum *p, u8 eError){
29060 assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG );
29061 p->accError = eError;
29062 if( p->mxAlloc ) sqlite3_str_reset(p);
29063 if( eError==SQLITE_TOOBIG ) sqlite3ErrorToParser(p->db, eError);
29064}
29065
29066/*
29067** Extra argument values from a PrintfArguments object
29068*/
29069static sqlite3_int64 getIntArg(PrintfArguments *p){
29070 if( p->nArg<=p->nUsed ) return 0;
29071 return sqlite3_value_int64(p->apArg[p->nUsed++]);
29072}
29073static double getDoubleArg(PrintfArguments *p){
29074 if( p->nArg<=p->nUsed ) return 0.0;
29075 return sqlite3_value_double(p->apArg[p->nUsed++]);
29076}
29077static char *getTextArg(PrintfArguments *p){
29078 if( p->nArg<=p->nUsed ) return 0;
29079 return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
29080}
29081
29082/*
29083** Allocate memory for a temporary buffer needed for printf rendering.
29084**
29085** If the requested size of the temp buffer is larger than the size
29086** of the output buffer in pAccum, then cause an SQLITE_TOOBIG error.
29087** Do the size check before the memory allocation to prevent rogue
29088** SQL from requesting large allocations using the precision or width
29089** field of the printf() function.
29090*/
29091static char *printfTempBuf(sqlite3_str *pAccum, sqlite3_int64 n){
29092 char *z;
29093 if( pAccum->accError ) return 0;
29094 if( n>pAccum->nAlloc && n>pAccum->mxAlloc ){
29095 sqlite3StrAccumSetError(p: pAccum, SQLITE_TOOBIG);
29096 return 0;
29097 }
29098 z = sqlite3DbMallocRaw(db: pAccum->db, n);
29099 if( z==0 ){
29100 sqlite3StrAccumSetError(p: pAccum, SQLITE_NOMEM);
29101 }
29102 return z;
29103}
29104
29105/*
29106** On machines with a small stack size, you can redefine the
29107** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
29108*/
29109#ifndef SQLITE_PRINT_BUF_SIZE
29110# define SQLITE_PRINT_BUF_SIZE 70
29111#endif
29112#define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
29113
29114/*
29115** Hard limit on the precision of floating-point conversions.
29116*/
29117#ifndef SQLITE_PRINTF_PRECISION_LIMIT
29118# define SQLITE_FP_PRECISION_LIMIT 100000000
29119#endif
29120
29121/*
29122** Render a string given by "fmt" into the StrAccum object.
29123*/
29124SQLITE_API void sqlite3_str_vappendf(
29125 sqlite3_str *pAccum, /* Accumulate results here */
29126 const char *fmt, /* Format string */
29127 va_list ap /* arguments */
29128){
29129 int c; /* Next character in the format string */
29130 char *bufpt; /* Pointer to the conversion buffer */
29131 int precision; /* Precision of the current field */
29132 int length; /* Length of the field */
29133 int idx; /* A general purpose loop counter */
29134 int width; /* Width of the current field */
29135 etByte flag_leftjustify; /* True if "-" flag is present */
29136 etByte flag_prefix; /* '+' or ' ' or 0 for prefix */
29137 etByte flag_alternateform; /* True if "#" flag is present */
29138 etByte flag_altform2; /* True if "!" flag is present */
29139 etByte flag_zeropad; /* True if field width constant starts with zero */
29140 etByte flag_long; /* 1 for the "l" flag, 2 for "ll", 0 by default */
29141 etByte done; /* Loop termination flag */
29142 etByte cThousand; /* Thousands separator for %d and %u */
29143 etByte xtype = etINVALID; /* Conversion paradigm */
29144 u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
29145 char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
29146 sqlite_uint64 longvalue; /* Value for integer types */
29147 LONGDOUBLE_TYPE realvalue; /* Value for real types */
29148 const et_info *infop; /* Pointer to the appropriate info structure */
29149 char *zOut; /* Rendering buffer */
29150 int nOut; /* Size of the rendering buffer */
29151 char *zExtra = 0; /* Malloced memory used by some conversion */
29152#ifndef SQLITE_OMIT_FLOATING_POINT
29153 int exp, e2; /* exponent of real numbers */
29154 int nsd; /* Number of significant digits returned */
29155 double rounder; /* Used for rounding floating point values */
29156 etByte flag_dp; /* True if decimal point should be shown */
29157 etByte flag_rtz; /* True if trailing zeros should be removed */
29158#endif
29159 PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
29160 char buf[etBUFSIZE]; /* Conversion buffer */
29161
29162 /* pAccum never starts out with an empty buffer that was obtained from
29163 ** malloc(). This precondition is required by the mprintf("%z...")
29164 ** optimization. */
29165 assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
29166
29167 bufpt = 0;
29168 if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
29169 pArgList = va_arg(ap, PrintfArguments*);
29170 bArgList = 1;
29171 }else{
29172 bArgList = 0;
29173 }
29174 for(; (c=(*fmt))!=0; ++fmt){
29175 if( c!='%' ){
29176 bufpt = (char *)fmt;
29177#if HAVE_STRCHRNUL
29178 fmt = strchrnul(fmt, '%');
29179#else
29180 do{ fmt++; }while( *fmt && *fmt != '%' );
29181#endif
29182 sqlite3_str_append(pAccum, zIn: bufpt, N: (int)(fmt - bufpt));
29183 if( *fmt==0 ) break;
29184 }
29185 if( (c=(*++fmt))==0 ){
29186 sqlite3_str_append(pAccum, zIn: "%", N: 1);
29187 break;
29188 }
29189 /* Find out what flags are present */
29190 flag_leftjustify = flag_prefix = cThousand =
29191 flag_alternateform = flag_altform2 = flag_zeropad = 0;
29192 done = 0;
29193 width = 0;
29194 flag_long = 0;
29195 precision = -1;
29196 do{
29197 switch( c ){
29198 case '-': flag_leftjustify = 1; break;
29199 case '+': flag_prefix = '+'; break;
29200 case ' ': flag_prefix = ' '; break;
29201 case '#': flag_alternateform = 1; break;
29202 case '!': flag_altform2 = 1; break;
29203 case '0': flag_zeropad = 1; break;
29204 case ',': cThousand = ','; break;
29205 default: done = 1; break;
29206 case 'l': {
29207 flag_long = 1;
29208 c = *++fmt;
29209 if( c=='l' ){
29210 c = *++fmt;
29211 flag_long = 2;
29212 }
29213 done = 1;
29214 break;
29215 }
29216 case '1': case '2': case '3': case '4': case '5':
29217 case '6': case '7': case '8': case '9': {
29218 unsigned wx = c - '0';
29219 while( (c = *++fmt)>='0' && c<='9' ){
29220 wx = wx*10 + c - '0';
29221 }
29222 testcase( wx>0x7fffffff );
29223 width = wx & 0x7fffffff;
29224#ifdef SQLITE_PRINTF_PRECISION_LIMIT
29225 if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
29226 width = SQLITE_PRINTF_PRECISION_LIMIT;
29227 }
29228#endif
29229 if( c!='.' && c!='l' ){
29230 done = 1;
29231 }else{
29232 fmt--;
29233 }
29234 break;
29235 }
29236 case '*': {
29237 if( bArgList ){
29238 width = (int)getIntArg(p: pArgList);
29239 }else{
29240 width = va_arg(ap,int);
29241 }
29242 if( width<0 ){
29243 flag_leftjustify = 1;
29244 width = width >= -2147483647 ? -width : 0;
29245 }
29246#ifdef SQLITE_PRINTF_PRECISION_LIMIT
29247 if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
29248 width = SQLITE_PRINTF_PRECISION_LIMIT;
29249 }
29250#endif
29251 if( (c = fmt[1])!='.' && c!='l' ){
29252 c = *++fmt;
29253 done = 1;
29254 }
29255 break;
29256 }
29257 case '.': {
29258 c = *++fmt;
29259 if( c=='*' ){
29260 if( bArgList ){
29261 precision = (int)getIntArg(p: pArgList);
29262 }else{
29263 precision = va_arg(ap,int);
29264 }
29265 if( precision<0 ){
29266 precision = precision >= -2147483647 ? -precision : -1;
29267 }
29268 c = *++fmt;
29269 }else{
29270 unsigned px = 0;
29271 while( c>='0' && c<='9' ){
29272 px = px*10 + c - '0';
29273 c = *++fmt;
29274 }
29275 testcase( px>0x7fffffff );
29276 precision = px & 0x7fffffff;
29277 }
29278#ifdef SQLITE_PRINTF_PRECISION_LIMIT
29279 if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
29280 precision = SQLITE_PRINTF_PRECISION_LIMIT;
29281 }
29282#endif
29283 if( c=='l' ){
29284 --fmt;
29285 }else{
29286 done = 1;
29287 }
29288 break;
29289 }
29290 }
29291 }while( !done && (c=(*++fmt))!=0 );
29292
29293 /* Fetch the info entry for the field */
29294 infop = &fmtinfo[0];
29295 xtype = etINVALID;
29296 for(idx=0; idx<ArraySize(fmtinfo); idx++){
29297 if( c==fmtinfo[idx].fmttype ){
29298 infop = &fmtinfo[idx];
29299 xtype = infop->type;
29300 break;
29301 }
29302 }
29303
29304 /*
29305 ** At this point, variables are initialized as follows:
29306 **
29307 ** flag_alternateform TRUE if a '#' is present.
29308 ** flag_altform2 TRUE if a '!' is present.
29309 ** flag_prefix '+' or ' ' or zero
29310 ** flag_leftjustify TRUE if a '-' is present or if the
29311 ** field width was negative.
29312 ** flag_zeropad TRUE if the width began with 0.
29313 ** flag_long 1 for "l", 2 for "ll"
29314 ** width The specified field width. This is
29315 ** always non-negative. Zero is the default.
29316 ** precision The specified precision. The default
29317 ** is -1.
29318 ** xtype The class of the conversion.
29319 ** infop Pointer to the appropriate info struct.
29320 */
29321 assert( width>=0 );
29322 assert( precision>=(-1) );
29323 switch( xtype ){
29324 case etPOINTER:
29325 flag_long = sizeof(char*)==sizeof(i64) ? 2 :
29326 sizeof(char*)==sizeof(long int) ? 1 : 0;
29327 /* no break */ deliberate_fall_through
29328 case etORDINAL:
29329 case etRADIX:
29330 cThousand = 0;
29331 /* no break */ deliberate_fall_through
29332 case etDECIMAL:
29333 if( infop->flags & FLAG_SIGNED ){
29334 i64 v;
29335 if( bArgList ){
29336 v = getIntArg(p: pArgList);
29337 }else if( flag_long ){
29338 if( flag_long==2 ){
29339 v = va_arg(ap,i64) ;
29340 }else{
29341 v = va_arg(ap,long int);
29342 }
29343 }else{
29344 v = va_arg(ap,int);
29345 }
29346 if( v<0 ){
29347 testcase( v==SMALLEST_INT64 );
29348 testcase( v==(-1) );
29349 longvalue = ~v;
29350 longvalue++;
29351 prefix = '-';
29352 }else{
29353 longvalue = v;
29354 prefix = flag_prefix;
29355 }
29356 }else{
29357 if( bArgList ){
29358 longvalue = (u64)getIntArg(p: pArgList);
29359 }else if( flag_long ){
29360 if( flag_long==2 ){
29361 longvalue = va_arg(ap,u64);
29362 }else{
29363 longvalue = va_arg(ap,unsigned long int);
29364 }
29365 }else{
29366 longvalue = va_arg(ap,unsigned int);
29367 }
29368 prefix = 0;
29369 }
29370 if( longvalue==0 ) flag_alternateform = 0;
29371 if( flag_zeropad && precision<width-(prefix!=0) ){
29372 precision = width-(prefix!=0);
29373 }
29374 if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
29375 nOut = etBUFSIZE;
29376 zOut = buf;
29377 }else{
29378 u64 n;
29379 n = (u64)precision + 10;
29380 if( cThousand ) n += precision/3;
29381 zOut = zExtra = printfTempBuf(pAccum, n);
29382 if( zOut==0 ) return;
29383 nOut = (int)n;
29384 }
29385 bufpt = &zOut[nOut-1];
29386 if( xtype==etORDINAL ){
29387 static const char zOrd[] = "thstndrd";
29388 int x = (int)(longvalue % 10);
29389 if( x>=4 || (longvalue/10)%10==1 ){
29390 x = 0;
29391 }
29392 *(--bufpt) = zOrd[x*2+1];
29393 *(--bufpt) = zOrd[x*2];
29394 }
29395 {
29396 const char *cset = &aDigits[infop->charset];
29397 u8 base = infop->base;
29398 do{ /* Convert to ascii */
29399 *(--bufpt) = cset[longvalue%base];
29400 longvalue = longvalue/base;
29401 }while( longvalue>0 );
29402 }
29403 length = (int)(&zOut[nOut-1]-bufpt);
29404 while( precision>length ){
29405 *(--bufpt) = '0'; /* Zero pad */
29406 length++;
29407 }
29408 if( cThousand ){
29409 int nn = (length - 1)/3; /* Number of "," to insert */
29410 int ix = (length - 1)%3 + 1;
29411 bufpt -= nn;
29412 for(idx=0; nn>0; idx++){
29413 bufpt[idx] = bufpt[idx+nn];
29414 ix--;
29415 if( ix==0 ){
29416 bufpt[++idx] = cThousand;
29417 nn--;
29418 ix = 3;
29419 }
29420 }
29421 }
29422 if( prefix ) *(--bufpt) = prefix; /* Add sign */
29423 if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
29424 const char *pre;
29425 char x;
29426 pre = &aPrefix[infop->prefix];
29427 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
29428 }
29429 length = (int)(&zOut[nOut-1]-bufpt);
29430 break;
29431 case etFLOAT:
29432 case etEXP:
29433 case etGENERIC:
29434 if( bArgList ){
29435 realvalue = getDoubleArg(p: pArgList);
29436 }else{
29437 realvalue = va_arg(ap,double);
29438 }
29439#ifdef SQLITE_OMIT_FLOATING_POINT
29440 length = 0;
29441#else
29442 if( precision<0 ) precision = 6; /* Set default precision */
29443#ifdef SQLITE_FP_PRECISION_LIMIT
29444 if( precision>SQLITE_FP_PRECISION_LIMIT ){
29445 precision = SQLITE_FP_PRECISION_LIMIT;
29446 }
29447#endif
29448 if( realvalue<0.0 ){
29449 realvalue = -realvalue;
29450 prefix = '-';
29451 }else{
29452 prefix = flag_prefix;
29453 }
29454 if( xtype==etGENERIC && precision>0 ) precision--;
29455 testcase( precision>0xfff );
29456 idx = precision & 0xfff;
29457 rounder = arRound[idx%10];
29458 while( idx>=10 ){ rounder *= 1.0e-10; idx -= 10; }
29459 if( xtype==etFLOAT ){
29460 double rx = (double)realvalue;
29461 sqlite3_uint64 u;
29462 int ex;
29463 memcpy(dest: &u, src: &rx, n: sizeof(u));
29464 ex = -1023 + (int)((u>>52)&0x7ff);
29465 if( precision+(ex/3) < 15 ) rounder += realvalue*3e-16;
29466 realvalue += rounder;
29467 }
29468 /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
29469 exp = 0;
29470 if( sqlite3IsNaN((double)realvalue) ){
29471 bufpt = "NaN";
29472 length = 3;
29473 break;
29474 }
29475 if( realvalue>0.0 ){
29476 LONGDOUBLE_TYPE scale = 1.0;
29477 while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
29478 while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
29479 while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
29480 realvalue /= scale;
29481 while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
29482 while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
29483 if( exp>350 ){
29484 bufpt = buf;
29485 buf[0] = prefix;
29486 memcpy(dest: buf+(prefix!=0),src: "Inf",n: 4);
29487 length = 3+(prefix!=0);
29488 break;
29489 }
29490 }
29491 bufpt = buf;
29492 /*
29493 ** If the field type is etGENERIC, then convert to either etEXP
29494 ** or etFLOAT, as appropriate.
29495 */
29496 if( xtype!=etFLOAT ){
29497 realvalue += rounder;
29498 if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
29499 }
29500 if( xtype==etGENERIC ){
29501 flag_rtz = !flag_alternateform;
29502 if( exp<-4 || exp>precision ){
29503 xtype = etEXP;
29504 }else{
29505 precision = precision - exp;
29506 xtype = etFLOAT;
29507 }
29508 }else{
29509 flag_rtz = flag_altform2;
29510 }
29511 if( xtype==etEXP ){
29512 e2 = 0;
29513 }else{
29514 e2 = exp;
29515 }
29516 {
29517 i64 szBufNeeded; /* Size of a temporary buffer needed */
29518 szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+15;
29519 if( szBufNeeded > etBUFSIZE ){
29520 bufpt = zExtra = printfTempBuf(pAccum, n: szBufNeeded);
29521 if( bufpt==0 ) return;
29522 }
29523 }
29524 zOut = bufpt;
29525 nsd = 16 + flag_altform2*10;
29526 flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
29527 /* The sign in front of the number */
29528 if( prefix ){
29529 *(bufpt++) = prefix;
29530 }
29531 /* Digits prior to the decimal point */
29532 if( e2<0 ){
29533 *(bufpt++) = '0';
29534 }else{
29535 for(; e2>=0; e2--){
29536 *(bufpt++) = et_getdigit(val: &realvalue,cnt: &nsd);
29537 }
29538 }
29539 /* The decimal point */
29540 if( flag_dp ){
29541 *(bufpt++) = '.';
29542 }
29543 /* "0" digits after the decimal point but before the first
29544 ** significant digit of the number */
29545 for(e2++; e2<0; precision--, e2++){
29546 assert( precision>0 );
29547 *(bufpt++) = '0';
29548 }
29549 /* Significant digits after the decimal point */
29550 while( (precision--)>0 ){
29551 *(bufpt++) = et_getdigit(val: &realvalue,cnt: &nsd);
29552 }
29553 /* Remove trailing zeros and the "." if no digits follow the "." */
29554 if( flag_rtz && flag_dp ){
29555 while( bufpt[-1]=='0' ) *(--bufpt) = 0;
29556 assert( bufpt>zOut );
29557 if( bufpt[-1]=='.' ){
29558 if( flag_altform2 ){
29559 *(bufpt++) = '0';
29560 }else{
29561 *(--bufpt) = 0;
29562 }
29563 }
29564 }
29565 /* Add the "eNNN" suffix */
29566 if( xtype==etEXP ){
29567 *(bufpt++) = aDigits[infop->charset];
29568 if( exp<0 ){
29569 *(bufpt++) = '-'; exp = -exp;
29570 }else{
29571 *(bufpt++) = '+';
29572 }
29573 if( exp>=100 ){
29574 *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
29575 exp %= 100;
29576 }
29577 *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
29578 *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
29579 }
29580 *bufpt = 0;
29581
29582 /* The converted number is in buf[] and zero terminated. Output it.
29583 ** Note that the number is in the usual order, not reversed as with
29584 ** integer conversions. */
29585 length = (int)(bufpt-zOut);
29586 bufpt = zOut;
29587
29588 /* Special case: Add leading zeros if the flag_zeropad flag is
29589 ** set and we are not left justified */
29590 if( flag_zeropad && !flag_leftjustify && length < width){
29591 int i;
29592 int nPad = width - length;
29593 for(i=width; i>=nPad; i--){
29594 bufpt[i] = bufpt[i-nPad];
29595 }
29596 i = prefix!=0;
29597 while( nPad-- ) bufpt[i++] = '0';
29598 length = width;
29599 }
29600#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
29601 break;
29602 case etSIZE:
29603 if( !bArgList ){
29604 *(va_arg(ap,int*)) = pAccum->nChar;
29605 }
29606 length = width = 0;
29607 break;
29608 case etPERCENT:
29609 buf[0] = '%';
29610 bufpt = buf;
29611 length = 1;
29612 break;
29613 case etCHARX:
29614 if( bArgList ){
29615 bufpt = getTextArg(p: pArgList);
29616 length = 1;
29617 if( bufpt ){
29618 buf[0] = c = *(bufpt++);
29619 if( (c&0xc0)==0xc0 ){
29620 while( length<4 && (bufpt[0]&0xc0)==0x80 ){
29621 buf[length++] = *(bufpt++);
29622 }
29623 }
29624 }else{
29625 buf[0] = 0;
29626 }
29627 }else{
29628 unsigned int ch = va_arg(ap,unsigned int);
29629 if( ch<0x00080 ){
29630 buf[0] = ch & 0xff;
29631 length = 1;
29632 }else if( ch<0x00800 ){
29633 buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);
29634 buf[1] = 0x80 + (u8)(ch & 0x3f);
29635 length = 2;
29636 }else if( ch<0x10000 ){
29637 buf[0] = 0xe0 + (u8)((ch>>12)&0x0f);
29638 buf[1] = 0x80 + (u8)((ch>>6) & 0x3f);
29639 buf[2] = 0x80 + (u8)(ch & 0x3f);
29640 length = 3;
29641 }else{
29642 buf[0] = 0xf0 + (u8)((ch>>18) & 0x07);
29643 buf[1] = 0x80 + (u8)((ch>>12) & 0x3f);
29644 buf[2] = 0x80 + (u8)((ch>>6) & 0x3f);
29645 buf[3] = 0x80 + (u8)(ch & 0x3f);
29646 length = 4;
29647 }
29648 }
29649 if( precision>1 ){
29650 width -= precision-1;
29651 if( width>1 && !flag_leftjustify ){
29652 sqlite3_str_appendchar(pAccum, N: width-1, C: ' ');
29653 width = 0;
29654 }
29655 while( precision-- > 1 ){
29656 sqlite3_str_append(pAccum, zIn: buf, N: length);
29657 }
29658 }
29659 bufpt = buf;
29660 flag_altform2 = 1;
29661 goto adjust_width_for_utf8;
29662 case etSTRING:
29663 case etDYNSTRING:
29664 if( bArgList ){
29665 bufpt = getTextArg(p: pArgList);
29666 xtype = etSTRING;
29667 }else{
29668 bufpt = va_arg(ap,char*);
29669 }
29670 if( bufpt==0 ){
29671 bufpt = "";
29672 }else if( xtype==etDYNSTRING ){
29673 if( pAccum->nChar==0
29674 && pAccum->mxAlloc
29675 && width==0
29676 && precision<0
29677 && pAccum->accError==0
29678 ){
29679 /* Special optimization for sqlite3_mprintf("%z..."):
29680 ** Extend an existing memory allocation rather than creating
29681 ** a new one. */
29682 assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
29683 pAccum->zText = bufpt;
29684 pAccum->nAlloc = sqlite3DbMallocSize(db: pAccum->db, p: bufpt);
29685 pAccum->nChar = 0x7fffffff & (int)strlen(s: bufpt);
29686 pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED;
29687 length = 0;
29688 break;
29689 }
29690 zExtra = bufpt;
29691 }
29692 if( precision>=0 ){
29693 if( flag_altform2 ){
29694 /* Set length to the number of bytes needed in order to display
29695 ** precision characters */
29696 unsigned char *z = (unsigned char*)bufpt;
29697 while( precision-- > 0 && z[0] ){
29698 SQLITE_SKIP_UTF8(z);
29699 }
29700 length = (int)(z - (unsigned char*)bufpt);
29701 }else{
29702 for(length=0; length<precision && bufpt[length]; length++){}
29703 }
29704 }else{
29705 length = 0x7fffffff & (int)strlen(s: bufpt);
29706 }
29707 adjust_width_for_utf8:
29708 if( flag_altform2 && width>0 ){
29709 /* Adjust width to account for extra bytes in UTF-8 characters */
29710 int ii = length - 1;
29711 while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
29712 }
29713 break;
29714 case etSQLESCAPE: /* %q: Escape ' characters */
29715 case etSQLESCAPE2: /* %Q: Escape ' and enclose in '...' */
29716 case etSQLESCAPE3: { /* %w: Escape " characters */
29717 int i, j, k, n, isnull;
29718 int needQuote;
29719 char ch;
29720 char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
29721 char *escarg;
29722
29723 if( bArgList ){
29724 escarg = getTextArg(p: pArgList);
29725 }else{
29726 escarg = va_arg(ap,char*);
29727 }
29728 isnull = escarg==0;
29729 if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
29730 /* For %q, %Q, and %w, the precision is the number of bytes (or
29731 ** characters if the ! flags is present) to use from the input.
29732 ** Because of the extra quoting characters inserted, the number
29733 ** of output characters may be larger than the precision.
29734 */
29735 k = precision;
29736 for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
29737 if( ch==q ) n++;
29738 if( flag_altform2 && (ch&0xc0)==0xc0 ){
29739 while( (escarg[i+1]&0xc0)==0x80 ){ i++; }
29740 }
29741 }
29742 needQuote = !isnull && xtype==etSQLESCAPE2;
29743 n += i + 3;
29744 if( n>etBUFSIZE ){
29745 bufpt = zExtra = printfTempBuf(pAccum, n);
29746 if( bufpt==0 ) return;
29747 }else{
29748 bufpt = buf;
29749 }
29750 j = 0;
29751 if( needQuote ) bufpt[j++] = q;
29752 k = i;
29753 for(i=0; i<k; i++){
29754 bufpt[j++] = ch = escarg[i];
29755 if( ch==q ) bufpt[j++] = ch;
29756 }
29757 if( needQuote ) bufpt[j++] = q;
29758 bufpt[j] = 0;
29759 length = j;
29760 goto adjust_width_for_utf8;
29761 }
29762 case etTOKEN: {
29763 Token *pToken;
29764 if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
29765 pToken = va_arg(ap, Token*);
29766 assert( bArgList==0 );
29767 if( pToken && pToken->n ){
29768 sqlite3_str_append(pAccum, zIn: (const char*)pToken->z, N: pToken->n);
29769 }
29770 length = width = 0;
29771 break;
29772 }
29773 case etSRCITEM: {
29774 SrcItem *pItem;
29775 if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
29776 pItem = va_arg(ap, SrcItem*);
29777 assert( bArgList==0 );
29778 if( pItem->zAlias && !flag_altform2 ){
29779 sqlite3_str_appendall(pAccum, zIn: pItem->zAlias);
29780 }else if( pItem->zName ){
29781 if( pItem->zDatabase ){
29782 sqlite3_str_appendall(pAccum, zIn: pItem->zDatabase);
29783 sqlite3_str_append(pAccum, zIn: ".", N: 1);
29784 }
29785 sqlite3_str_appendall(pAccum, zIn: pItem->zName);
29786 }else if( pItem->zAlias ){
29787 sqlite3_str_appendall(pAccum, zIn: pItem->zAlias);
29788 }else if( ALWAYS(pItem->pSelect) ){
29789 sqlite3_str_appendf(pAccum, zFormat: "SUBQUERY %u", pItem->pSelect->selId);
29790 }
29791 length = width = 0;
29792 break;
29793 }
29794 default: {
29795 assert( xtype==etINVALID );
29796 return;
29797 }
29798 }/* End switch over the format type */
29799 /*
29800 ** The text of the conversion is pointed to by "bufpt" and is
29801 ** "length" characters long. The field width is "width". Do
29802 ** the output. Both length and width are in bytes, not characters,
29803 ** at this point. If the "!" flag was present on string conversions
29804 ** indicating that width and precision should be expressed in characters,
29805 ** then the values have been translated prior to reaching this point.
29806 */
29807 width -= length;
29808 if( width>0 ){
29809 if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, N: width, C: ' ');
29810 sqlite3_str_append(pAccum, zIn: bufpt, N: length);
29811 if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, N: width, C: ' ');
29812 }else{
29813 sqlite3_str_append(pAccum, zIn: bufpt, N: length);
29814 }
29815
29816 if( zExtra ){
29817 sqlite3DbFree(db: pAccum->db, p: zExtra);
29818 zExtra = 0;
29819 }
29820 }/* End for loop over the format string */
29821} /* End of function */
29822
29823/*
29824** Enlarge the memory allocation on a StrAccum object so that it is
29825** able to accept at least N more bytes of text.
29826**
29827** Return the number of bytes of text that StrAccum is able to accept
29828** after the attempted enlargement. The value returned might be zero.
29829*/
29830static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
29831 char *zNew;
29832 assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
29833 if( p->accError ){
29834 testcase(p->accError==SQLITE_TOOBIG);
29835 testcase(p->accError==SQLITE_NOMEM);
29836 return 0;
29837 }
29838 if( p->mxAlloc==0 ){
29839 sqlite3StrAccumSetError(p, SQLITE_TOOBIG);
29840 return p->nAlloc - p->nChar - 1;
29841 }else{
29842 char *zOld = isMalloced(p) ? p->zText : 0;
29843 i64 szNew = p->nChar;
29844 szNew += (sqlite3_int64)N + 1;
29845 if( szNew+p->nChar<=p->mxAlloc ){
29846 /* Force exponential buffer size growth as long as it does not overflow,
29847 ** to avoid having to call this routine too often */
29848 szNew += p->nChar;
29849 }
29850 if( szNew > p->mxAlloc ){
29851 sqlite3_str_reset(p);
29852 sqlite3StrAccumSetError(p, SQLITE_TOOBIG);
29853 return 0;
29854 }else{
29855 p->nAlloc = (int)szNew;
29856 }
29857 if( p->db ){
29858 zNew = sqlite3DbRealloc(db: p->db, p: zOld, n: p->nAlloc);
29859 }else{
29860 zNew = sqlite3Realloc(pOld: zOld, nBytes: p->nAlloc);
29861 }
29862 if( zNew ){
29863 assert( p->zText!=0 || p->nChar==0 );
29864 if( !isMalloced(p) && p->nChar>0 ) memcpy(dest: zNew, src: p->zText, n: p->nChar);
29865 p->zText = zNew;
29866 p->nAlloc = sqlite3DbMallocSize(db: p->db, p: zNew);
29867 p->printfFlags |= SQLITE_PRINTF_MALLOCED;
29868 }else{
29869 sqlite3_str_reset(p);
29870 sqlite3StrAccumSetError(p, SQLITE_NOMEM);
29871 return 0;
29872 }
29873 }
29874 return N;
29875}
29876
29877/*
29878** Append N copies of character c to the given string buffer.
29879*/
29880SQLITE_API void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){
29881 testcase( p->nChar + (i64)N > 0x7fffffff );
29882 if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
29883 return;
29884 }
29885 while( (N--)>0 ) p->zText[p->nChar++] = c;
29886}
29887
29888/*
29889** The StrAccum "p" is not large enough to accept N new bytes of z[].
29890** So enlarge if first, then do the append.
29891**
29892** This is a helper routine to sqlite3_str_append() that does special-case
29893** work (enlarging the buffer) using tail recursion, so that the
29894** sqlite3_str_append() routine can use fast calling semantics.
29895*/
29896static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
29897 N = sqlite3StrAccumEnlarge(p, N);
29898 if( N>0 ){
29899 memcpy(dest: &p->zText[p->nChar], src: z, n: N);
29900 p->nChar += N;
29901 }
29902}
29903
29904/*
29905** Append N bytes of text from z to the StrAccum object. Increase the
29906** size of the memory allocation for StrAccum if necessary.
29907*/
29908SQLITE_API void sqlite3_str_append(sqlite3_str *p, const char *z, int N){
29909 assert( z!=0 || N==0 );
29910 assert( p->zText!=0 || p->nChar==0 || p->accError );
29911 assert( N>=0 );
29912 assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 );
29913 if( p->nChar+N >= p->nAlloc ){
29914 enlargeAndAppend(p,z,N);
29915 }else if( N ){
29916 assert( p->zText );
29917 p->nChar += N;
29918 memcpy(dest: &p->zText[p->nChar-N], src: z, n: N);
29919 }
29920}
29921
29922/*
29923** Append the complete text of zero-terminated string z[] to the p string.
29924*/
29925SQLITE_API void sqlite3_str_appendall(sqlite3_str *p, const char *z){
29926 sqlite3_str_append(p, z, N: sqlite3Strlen30(z));
29927}
29928
29929
29930/*
29931** Finish off a string by making sure it is zero-terminated.
29932** Return a pointer to the resulting string. Return a NULL
29933** pointer if any kind of error was encountered.
29934*/
29935static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
29936 char *zText;
29937 assert( p->mxAlloc>0 && !isMalloced(p) );
29938 zText = sqlite3DbMallocRaw(db: p->db, n: p->nChar+1 );
29939 if( zText ){
29940 memcpy(dest: zText, src: p->zText, n: p->nChar+1);
29941 p->printfFlags |= SQLITE_PRINTF_MALLOCED;
29942 }else{
29943 sqlite3StrAccumSetError(p, SQLITE_NOMEM);
29944 }
29945 p->zText = zText;
29946 return zText;
29947}
29948SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
29949 if( p->zText ){
29950 p->zText[p->nChar] = 0;
29951 if( p->mxAlloc>0 && !isMalloced(p) ){
29952 return strAccumFinishRealloc(p);
29953 }
29954 }
29955 return p->zText;
29956}
29957
29958/*
29959** Use the content of the StrAccum passed as the second argument
29960** as the result of an SQL function.
29961*/
29962SQLITE_PRIVATE void sqlite3ResultStrAccum(sqlite3_context *pCtx, StrAccum *p){
29963 if( p->accError ){
29964 sqlite3_result_error_code(pCtx, p->accError);
29965 sqlite3_str_reset(p);
29966 }else if( isMalloced(p) ){
29967 sqlite3_result_text(pCtx, p->zText, p->nChar, SQLITE_DYNAMIC);
29968 }else{
29969 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
29970 sqlite3_str_reset(p);
29971 }
29972}
29973
29974/*
29975** This singleton is an sqlite3_str object that is returned if
29976** sqlite3_malloc() fails to provide space for a real one. This
29977** sqlite3_str object accepts no new text and always returns
29978** an SQLITE_NOMEM error.
29979*/
29980static sqlite3_str sqlite3OomStr = {
29981 0, 0, 0, 0, 0, SQLITE_NOMEM, 0
29982};
29983
29984/* Finalize a string created using sqlite3_str_new().
29985*/
29986SQLITE_API char *sqlite3_str_finish(sqlite3_str *p){
29987 char *z;
29988 if( p!=0 && p!=&sqlite3OomStr ){
29989 z = sqlite3StrAccumFinish(p);
29990 sqlite3_free(p);
29991 }else{
29992 z = 0;
29993 }
29994 return z;
29995}
29996
29997/* Return any error code associated with p */
29998SQLITE_API int sqlite3_str_errcode(sqlite3_str *p){
29999 return p ? p->accError : SQLITE_NOMEM;
30000}
30001
30002/* Return the current length of p in bytes */
30003SQLITE_API int sqlite3_str_length(sqlite3_str *p){
30004 return p ? p->nChar : 0;
30005}
30006
30007/* Return the current value for p */
30008SQLITE_API char *sqlite3_str_value(sqlite3_str *p){
30009 if( p==0 || p->nChar==0 ) return 0;
30010 p->zText[p->nChar] = 0;
30011 return p->zText;
30012}
30013
30014/*
30015** Reset an StrAccum string. Reclaim all malloced memory.
30016*/
30017SQLITE_API void sqlite3_str_reset(StrAccum *p){
30018 if( isMalloced(p) ){
30019 sqlite3DbFree(db: p->db, p: p->zText);
30020 p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
30021 }
30022 p->nAlloc = 0;
30023 p->nChar = 0;
30024 p->zText = 0;
30025}
30026
30027/*
30028** Initialize a string accumulator.
30029**
30030** p: The accumulator to be initialized.
30031** db: Pointer to a database connection. May be NULL. Lookaside
30032** memory is used if not NULL. db->mallocFailed is set appropriately
30033** when not NULL.
30034** zBase: An initial buffer. May be NULL in which case the initial buffer
30035** is malloced.
30036** n: Size of zBase in bytes. If total space requirements never exceed
30037** n then no memory allocations ever occur.
30038** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
30039** allocations will ever occur.
30040*/
30041SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
30042 p->zText = zBase;
30043 p->db = db;
30044 p->nAlloc = n;
30045 p->mxAlloc = mx;
30046 p->nChar = 0;
30047 p->accError = 0;
30048 p->printfFlags = 0;
30049}
30050
30051/* Allocate and initialize a new dynamic string object */
30052SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3 *db){
30053 sqlite3_str *p = sqlite3_malloc64(n: sizeof(*p));
30054 if( p ){
30055 sqlite3StrAccumInit(p, db: 0, zBase: 0, n: 0,
30056 mx: db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
30057 }else{
30058 p = &sqlite3OomStr;
30059 }
30060 return p;
30061}
30062
30063/*
30064** Print into memory obtained from sqliteMalloc(). Use the internal
30065** %-conversion extensions.
30066*/
30067SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
30068 char *z;
30069 char zBase[SQLITE_PRINT_BUF_SIZE];
30070 StrAccum acc;
30071 assert( db!=0 );
30072 sqlite3StrAccumInit(p: &acc, db, zBase, n: sizeof(zBase),
30073 mx: db->aLimit[SQLITE_LIMIT_LENGTH]);
30074 acc.printfFlags = SQLITE_PRINTF_INTERNAL;
30075 sqlite3_str_vappendf(pAccum: &acc, fmt: zFormat, ap);
30076 z = sqlite3StrAccumFinish(p: &acc);
30077 if( acc.accError==SQLITE_NOMEM ){
30078 sqlite3OomFault(db);
30079 }
30080 return z;
30081}
30082
30083/*
30084** Print into memory obtained from sqliteMalloc(). Use the internal
30085** %-conversion extensions.
30086*/
30087SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
30088 va_list ap;
30089 char *z;
30090 va_start(ap, zFormat);
30091 z = sqlite3VMPrintf(db, zFormat, ap);
30092 va_end(ap);
30093 return z;
30094}
30095
30096/*
30097** Print into memory obtained from sqlite3_malloc(). Omit the internal
30098** %-conversion extensions.
30099*/
30100SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
30101 char *z;
30102 char zBase[SQLITE_PRINT_BUF_SIZE];
30103 StrAccum acc;
30104
30105#ifdef SQLITE_ENABLE_API_ARMOR
30106 if( zFormat==0 ){
30107 (void)SQLITE_MISUSE_BKPT;
30108 return 0;
30109 }
30110#endif
30111#ifndef SQLITE_OMIT_AUTOINIT
30112 if( sqlite3_initialize() ) return 0;
30113#endif
30114 sqlite3StrAccumInit(p: &acc, db: 0, zBase, n: sizeof(zBase), SQLITE_MAX_LENGTH);
30115 sqlite3_str_vappendf(pAccum: &acc, fmt: zFormat, ap);
30116 z = sqlite3StrAccumFinish(p: &acc);
30117 return z;
30118}
30119
30120/*
30121** Print into memory obtained from sqlite3_malloc()(). Omit the internal
30122** %-conversion extensions.
30123*/
30124SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
30125 va_list ap;
30126 char *z;
30127#ifndef SQLITE_OMIT_AUTOINIT
30128 if( sqlite3_initialize() ) return 0;
30129#endif
30130 va_start(ap, zFormat);
30131 z = sqlite3_vmprintf(zFormat, ap);
30132 va_end(ap);
30133 return z;
30134}
30135
30136/*
30137** sqlite3_snprintf() works like snprintf() except that it ignores the
30138** current locale settings. This is important for SQLite because we
30139** are not able to use a "," as the decimal point in place of "." as
30140** specified by some locales.
30141**
30142** Oops: The first two arguments of sqlite3_snprintf() are backwards
30143** from the snprintf() standard. Unfortunately, it is too late to change
30144** this without breaking compatibility, so we just have to live with the
30145** mistake.
30146**
30147** sqlite3_vsnprintf() is the varargs version.
30148*/
30149SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
30150 StrAccum acc;
30151 if( n<=0 ) return zBuf;
30152#ifdef SQLITE_ENABLE_API_ARMOR
30153 if( zBuf==0 || zFormat==0 ) {
30154 (void)SQLITE_MISUSE_BKPT;
30155 if( zBuf ) zBuf[0] = 0;
30156 return zBuf;
30157 }
30158#endif
30159 sqlite3StrAccumInit(p: &acc, db: 0, zBase: zBuf, n, mx: 0);
30160 sqlite3_str_vappendf(pAccum: &acc, fmt: zFormat, ap);
30161 zBuf[acc.nChar] = 0;
30162 return zBuf;
30163}
30164SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
30165 char *z;
30166 va_list ap;
30167 va_start(ap,zFormat);
30168 z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
30169 va_end(ap);
30170 return z;
30171}
30172
30173/*
30174** This is the routine that actually formats the sqlite3_log() message.
30175** We house it in a separate routine from sqlite3_log() to avoid using
30176** stack space on small-stack systems when logging is disabled.
30177**
30178** sqlite3_log() must render into a static buffer. It cannot dynamically
30179** allocate memory because it might be called while the memory allocator
30180** mutex is held.
30181**
30182** sqlite3_str_vappendf() might ask for *temporary* memory allocations for
30183** certain format characters (%q) or for very large precisions or widths.
30184** Care must be taken that any sqlite3_log() calls that occur while the
30185** memory mutex is held do not use these mechanisms.
30186*/
30187static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
30188 StrAccum acc; /* String accumulator */
30189 char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
30190
30191 sqlite3StrAccumInit(p: &acc, db: 0, zBase: zMsg, n: sizeof(zMsg), mx: 0);
30192 sqlite3_str_vappendf(pAccum: &acc, fmt: zFormat, ap);
30193 sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
30194 sqlite3StrAccumFinish(p: &acc));
30195}
30196
30197/*
30198** Format and write a message to the log if logging is enabled.
30199*/
30200SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
30201 va_list ap; /* Vararg list */
30202 if( sqlite3GlobalConfig.xLog ){
30203 va_start(ap, zFormat);
30204 renderLogMsg(iErrCode, zFormat, ap);
30205 va_end(ap);
30206 }
30207}
30208
30209#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
30210/*
30211** A version of printf() that understands %lld. Used for debugging.
30212** The printf() built into some versions of windows does not understand %lld
30213** and segfaults if you give it a long long int.
30214*/
30215SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
30216 va_list ap;
30217 StrAccum acc;
30218 char zBuf[SQLITE_PRINT_BUF_SIZE*10];
30219 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
30220 va_start(ap,zFormat);
30221 sqlite3_str_vappendf(&acc, zFormat, ap);
30222 va_end(ap);
30223 sqlite3StrAccumFinish(&acc);
30224#ifdef SQLITE_OS_TRACE_PROC
30225 {
30226 extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf);
30227 SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf));
30228 }
30229#else
30230 fprintf(stdout,"%s", zBuf);
30231 fflush(stdout);
30232#endif
30233}
30234#endif
30235
30236
30237/*
30238** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument
30239** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
30240*/
30241SQLITE_API void sqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){
30242 va_list ap;
30243 va_start(ap,zFormat);
30244 sqlite3_str_vappendf(pAccum: p, fmt: zFormat, ap);
30245 va_end(ap);
30246}
30247
30248/************** End of printf.c **********************************************/
30249/************** Begin file treeview.c ****************************************/
30250/*
30251** 2015-06-08
30252**
30253** The author disclaims copyright to this source code. In place of
30254** a legal notice, here is a blessing:
30255**
30256** May you do good and not evil.
30257** May you find forgiveness for yourself and forgive others.
30258** May you share freely, never taking more than you give.
30259**
30260*************************************************************************
30261**
30262** This file contains C code to implement the TreeView debugging routines.
30263** These routines print a parse tree to standard output for debugging and
30264** analysis.
30265**
30266** The interfaces in this file is only available when compiling
30267** with SQLITE_DEBUG.
30268*/
30269/* #include "sqliteInt.h" */
30270#ifdef SQLITE_DEBUG
30271
30272/*
30273** Add a new subitem to the tree. The moreToFollow flag indicates that this
30274** is not the last item in the tree.
30275*/
30276static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
30277 if( p==0 ){
30278 p = sqlite3_malloc64( sizeof(*p) );
30279 if( p==0 ) return 0;
30280 memset(p, 0, sizeof(*p));
30281 }else{
30282 p->iLevel++;
30283 }
30284 assert( moreToFollow==0 || moreToFollow==1 );
30285 if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
30286 return p;
30287}
30288
30289/*
30290** Finished with one layer of the tree
30291*/
30292static void sqlite3TreeViewPop(TreeView *p){
30293 if( p==0 ) return;
30294 p->iLevel--;
30295 if( p->iLevel<0 ) sqlite3_free(p);
30296}
30297
30298/*
30299** Generate a single line of output for the tree, with a prefix that contains
30300** all the appropriate tree lines
30301*/
30302static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
30303 va_list ap;
30304 int i;
30305 StrAccum acc;
30306 char zBuf[500];
30307 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
30308 if( p ){
30309 for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
30310 sqlite3_str_append(&acc, p->bLine[i] ? "| " : " ", 4);
30311 }
30312 sqlite3_str_append(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
30313 }
30314 if( zFormat!=0 ){
30315 va_start(ap, zFormat);
30316 sqlite3_str_vappendf(&acc, zFormat, ap);
30317 va_end(ap);
30318 assert( acc.nChar>0 || acc.accError );
30319 sqlite3_str_append(&acc, "\n", 1);
30320 }
30321 sqlite3StrAccumFinish(&acc);
30322 fprintf(stdout,"%s", zBuf);
30323 fflush(stdout);
30324}
30325
30326/*
30327** Shorthand for starting a new tree item that consists of a single label
30328*/
30329static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
30330 p = sqlite3TreeViewPush(p, moreFollows);
30331 sqlite3TreeViewLine(p, "%s", zLabel);
30332}
30333
30334/*
30335** Generate a human-readable description of a WITH clause.
30336*/
30337SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
30338 int i;
30339 if( pWith==0 ) return;
30340 if( pWith->nCte==0 ) return;
30341 if( pWith->pOuter ){
30342 sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
30343 }else{
30344 sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
30345 }
30346 if( pWith->nCte>0 ){
30347 pView = sqlite3TreeViewPush(pView, 1);
30348 for(i=0; i<pWith->nCte; i++){
30349 StrAccum x;
30350 char zLine[1000];
30351 const struct Cte *pCte = &pWith->a[i];
30352 sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
30353 sqlite3_str_appendf(&x, "%s", pCte->zName);
30354 if( pCte->pCols && pCte->pCols->nExpr>0 ){
30355 char cSep = '(';
30356 int j;
30357 for(j=0; j<pCte->pCols->nExpr; j++){
30358 sqlite3_str_appendf(&x, "%c%s", cSep, pCte->pCols->a[j].zEName);
30359 cSep = ',';
30360 }
30361 sqlite3_str_appendf(&x, ")");
30362 }
30363 if( pCte->pUse ){
30364 sqlite3_str_appendf(&x, " (pUse=0x%p, nUse=%d)", pCte->pUse,
30365 pCte->pUse->nUse);
30366 }
30367 sqlite3StrAccumFinish(&x);
30368 sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
30369 sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
30370 sqlite3TreeViewPop(pView);
30371 }
30372 sqlite3TreeViewPop(pView);
30373 }
30374}
30375
30376/*
30377** Generate a human-readable description of a SrcList object.
30378*/
30379SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc){
30380 int i;
30381 for(i=0; i<pSrc->nSrc; i++){
30382 const SrcItem *pItem = &pSrc->a[i];
30383 StrAccum x;
30384 char zLine[100];
30385 sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
30386 x.printfFlags |= SQLITE_PRINTF_INTERNAL;
30387 sqlite3_str_appendf(&x, "{%d:*} %!S", pItem->iCursor, pItem);
30388 if( pItem->pTab ){
30389 sqlite3_str_appendf(&x, " tab=%Q nCol=%d ptr=%p used=%llx",
30390 pItem->pTab->zName, pItem->pTab->nCol, pItem->pTab, pItem->colUsed);
30391 }
30392 if( pItem->fg.jointype & JT_LEFT ){
30393 sqlite3_str_appendf(&x, " LEFT-JOIN");
30394 }else if( pItem->fg.jointype & JT_CROSS ){
30395 sqlite3_str_appendf(&x, " CROSS-JOIN");
30396 }
30397 if( pItem->fg.fromDDL ){
30398 sqlite3_str_appendf(&x, " DDL");
30399 }
30400 if( pItem->fg.isCte ){
30401 sqlite3_str_appendf(&x, " CteUse=0x%p", pItem->u2.pCteUse);
30402 }
30403 sqlite3StrAccumFinish(&x);
30404 sqlite3TreeViewItem(pView, zLine, i<pSrc->nSrc-1);
30405 if( pItem->pSelect ){
30406 sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
30407 }
30408 if( pItem->fg.isTabFunc ){
30409 sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
30410 }
30411 sqlite3TreeViewPop(pView);
30412 }
30413}
30414
30415/*
30416** Generate a human-readable description of a Select object.
30417*/
30418SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
30419 int n = 0;
30420 int cnt = 0;
30421 if( p==0 ){
30422 sqlite3TreeViewLine(pView, "nil-SELECT");
30423 return;
30424 }
30425 pView = sqlite3TreeViewPush(pView, moreToFollow);
30426 if( p->pWith ){
30427 sqlite3TreeViewWith(pView, p->pWith, 1);
30428 cnt = 1;
30429 sqlite3TreeViewPush(pView, 1);
30430 }
30431 do{
30432 if( p->selFlags & SF_WhereBegin ){
30433 sqlite3TreeViewLine(pView, "sqlite3WhereBegin()");
30434 }else{
30435 sqlite3TreeViewLine(pView,
30436 "SELECT%s%s (%u/%p) selFlags=0x%x nSelectRow=%d",
30437 ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
30438 ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""),
30439 p->selId, p, p->selFlags,
30440 (int)p->nSelectRow
30441 );
30442 }
30443 if( cnt++ ) sqlite3TreeViewPop(pView);
30444 if( p->pPrior ){
30445 n = 1000;
30446 }else{
30447 n = 0;
30448 if( p->pSrc && p->pSrc->nSrc ) n++;
30449 if( p->pWhere ) n++;
30450 if( p->pGroupBy ) n++;
30451 if( p->pHaving ) n++;
30452 if( p->pOrderBy ) n++;
30453 if( p->pLimit ) n++;
30454#ifndef SQLITE_OMIT_WINDOWFUNC
30455 if( p->pWin ) n++;
30456 if( p->pWinDefn ) n++;
30457#endif
30458 }
30459 if( p->pEList ){
30460 sqlite3TreeViewExprList(pView, p->pEList, n>0, "result-set");
30461 }
30462 n--;
30463#ifndef SQLITE_OMIT_WINDOWFUNC
30464 if( p->pWin ){
30465 Window *pX;
30466 pView = sqlite3TreeViewPush(pView, (n--)>0);
30467 sqlite3TreeViewLine(pView, "window-functions");
30468 for(pX=p->pWin; pX; pX=pX->pNextWin){
30469 sqlite3TreeViewWinFunc(pView, pX, pX->pNextWin!=0);
30470 }
30471 sqlite3TreeViewPop(pView);
30472 }
30473#endif
30474 if( p->pSrc && p->pSrc->nSrc ){
30475 pView = sqlite3TreeViewPush(pView, (n--)>0);
30476 sqlite3TreeViewLine(pView, "FROM");
30477 sqlite3TreeViewSrcList(pView, p->pSrc);
30478 sqlite3TreeViewPop(pView);
30479 }
30480 if( p->pWhere ){
30481 sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
30482 sqlite3TreeViewExpr(pView, p->pWhere, 0);
30483 sqlite3TreeViewPop(pView);
30484 }
30485 if( p->pGroupBy ){
30486 sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
30487 }
30488 if( p->pHaving ){
30489 sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
30490 sqlite3TreeViewExpr(pView, p->pHaving, 0);
30491 sqlite3TreeViewPop(pView);
30492 }
30493#ifndef SQLITE_OMIT_WINDOWFUNC
30494 if( p->pWinDefn ){
30495 Window *pX;
30496 sqlite3TreeViewItem(pView, "WINDOW", (n--)>0);
30497 for(pX=p->pWinDefn; pX; pX=pX->pNextWin){
30498 sqlite3TreeViewWindow(pView, pX, pX->pNextWin!=0);
30499 }
30500 sqlite3TreeViewPop(pView);
30501 }
30502#endif
30503 if( p->pOrderBy ){
30504 sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
30505 }
30506 if( p->pLimit ){
30507 sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
30508 sqlite3TreeViewExpr(pView, p->pLimit->pLeft, p->pLimit->pRight!=0);
30509 if( p->pLimit->pRight ){
30510 sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
30511 sqlite3TreeViewExpr(pView, p->pLimit->pRight, 0);
30512 sqlite3TreeViewPop(pView);
30513 }
30514 sqlite3TreeViewPop(pView);
30515 }
30516 if( p->pPrior ){
30517 const char *zOp = "UNION";
30518 switch( p->op ){
30519 case TK_ALL: zOp = "UNION ALL"; break;
30520 case TK_INTERSECT: zOp = "INTERSECT"; break;
30521 case TK_EXCEPT: zOp = "EXCEPT"; break;
30522 }
30523 sqlite3TreeViewItem(pView, zOp, 1);
30524 }
30525 p = p->pPrior;
30526 }while( p!=0 );
30527 sqlite3TreeViewPop(pView);
30528}
30529
30530#ifndef SQLITE_OMIT_WINDOWFUNC
30531/*
30532** Generate a description of starting or stopping bounds
30533*/
30534SQLITE_PRIVATE void sqlite3TreeViewBound(
30535 TreeView *pView, /* View context */
30536 u8 eBound, /* UNBOUNDED, CURRENT, PRECEDING, FOLLOWING */
30537 Expr *pExpr, /* Value for PRECEDING or FOLLOWING */
30538 u8 moreToFollow /* True if more to follow */
30539){
30540 switch( eBound ){
30541 case TK_UNBOUNDED: {
30542 sqlite3TreeViewItem(pView, "UNBOUNDED", moreToFollow);
30543 sqlite3TreeViewPop(pView);
30544 break;
30545 }
30546 case TK_CURRENT: {
30547 sqlite3TreeViewItem(pView, "CURRENT", moreToFollow);
30548 sqlite3TreeViewPop(pView);
30549 break;
30550 }
30551 case TK_PRECEDING: {
30552 sqlite3TreeViewItem(pView, "PRECEDING", moreToFollow);
30553 sqlite3TreeViewExpr(pView, pExpr, 0);
30554 sqlite3TreeViewPop(pView);
30555 break;
30556 }
30557 case TK_FOLLOWING: {
30558 sqlite3TreeViewItem(pView, "FOLLOWING", moreToFollow);
30559 sqlite3TreeViewExpr(pView, pExpr, 0);
30560 sqlite3TreeViewPop(pView);
30561 break;
30562 }
30563 }
30564}
30565#endif /* SQLITE_OMIT_WINDOWFUNC */
30566
30567#ifndef SQLITE_OMIT_WINDOWFUNC
30568/*
30569** Generate a human-readable explanation for a Window object
30570*/
30571SQLITE_PRIVATE void sqlite3TreeViewWindow(TreeView *pView, const Window *pWin, u8 more){
30572 int nElement = 0;
30573 if( pWin->pFilter ){
30574 sqlite3TreeViewItem(pView, "FILTER", 1);
30575 sqlite3TreeViewExpr(pView, pWin->pFilter, 0);
30576 sqlite3TreeViewPop(pView);
30577 }
30578 pView = sqlite3TreeViewPush(pView, more);
30579 if( pWin->zName ){
30580 sqlite3TreeViewLine(pView, "OVER %s (%p)", pWin->zName, pWin);
30581 }else{
30582 sqlite3TreeViewLine(pView, "OVER (%p)", pWin);
30583 }
30584 if( pWin->zBase ) nElement++;
30585 if( pWin->pOrderBy ) nElement++;
30586 if( pWin->eFrmType ) nElement++;
30587 if( pWin->eExclude ) nElement++;
30588 if( pWin->zBase ){
30589 sqlite3TreeViewPush(pView, (--nElement)>0);
30590 sqlite3TreeViewLine(pView, "window: %s", pWin->zBase);
30591 sqlite3TreeViewPop(pView);
30592 }
30593 if( pWin->pPartition ){
30594 sqlite3TreeViewExprList(pView, pWin->pPartition, nElement>0,"PARTITION-BY");
30595 }
30596 if( pWin->pOrderBy ){
30597 sqlite3TreeViewExprList(pView, pWin->pOrderBy, (--nElement)>0, "ORDER-BY");
30598 }
30599 if( pWin->eFrmType ){
30600 char zBuf[30];
30601 const char *zFrmType = "ROWS";
30602 if( pWin->eFrmType==TK_RANGE ) zFrmType = "RANGE";
30603 if( pWin->eFrmType==TK_GROUPS ) zFrmType = "GROUPS";
30604 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s%s",zFrmType,
30605 pWin->bImplicitFrame ? " (implied)" : "");
30606 sqlite3TreeViewItem(pView, zBuf, (--nElement)>0);
30607 sqlite3TreeViewBound(pView, pWin->eStart, pWin->pStart, 1);
30608 sqlite3TreeViewBound(pView, pWin->eEnd, pWin->pEnd, 0);
30609 sqlite3TreeViewPop(pView);
30610 }
30611 if( pWin->eExclude ){
30612 char zBuf[30];
30613 const char *zExclude;
30614 switch( pWin->eExclude ){
30615 case TK_NO: zExclude = "NO OTHERS"; break;
30616 case TK_CURRENT: zExclude = "CURRENT ROW"; break;
30617 case TK_GROUP: zExclude = "GROUP"; break;
30618 case TK_TIES: zExclude = "TIES"; break;
30619 default:
30620 sqlite3_snprintf(sizeof(zBuf),zBuf,"invalid(%d)", pWin->eExclude);
30621 zExclude = zBuf;
30622 break;
30623 }
30624 sqlite3TreeViewPush(pView, 0);
30625 sqlite3TreeViewLine(pView, "EXCLUDE %s", zExclude);
30626 sqlite3TreeViewPop(pView);
30627 }
30628 sqlite3TreeViewPop(pView);
30629}
30630#endif /* SQLITE_OMIT_WINDOWFUNC */
30631
30632#ifndef SQLITE_OMIT_WINDOWFUNC
30633/*
30634** Generate a human-readable explanation for a Window Function object
30635*/
30636SQLITE_PRIVATE void sqlite3TreeViewWinFunc(TreeView *pView, const Window *pWin, u8 more){
30637 pView = sqlite3TreeViewPush(pView, more);
30638 sqlite3TreeViewLine(pView, "WINFUNC %s(%d)",
30639 pWin->pFunc->zName, pWin->pFunc->nArg);
30640 sqlite3TreeViewWindow(pView, pWin, 0);
30641 sqlite3TreeViewPop(pView);
30642}
30643#endif /* SQLITE_OMIT_WINDOWFUNC */
30644
30645/*
30646** Generate a human-readable explanation of an expression tree.
30647*/
30648SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
30649 const char *zBinOp = 0; /* Binary operator */
30650 const char *zUniOp = 0; /* Unary operator */
30651 char zFlgs[200];
30652 pView = sqlite3TreeViewPush(pView, moreToFollow);
30653 if( pExpr==0 ){
30654 sqlite3TreeViewLine(pView, "nil");
30655 sqlite3TreeViewPop(pView);
30656 return;
30657 }
30658 if( pExpr->flags || pExpr->affExpr || pExpr->vvaFlags ){
30659 StrAccum x;
30660 sqlite3StrAccumInit(&x, 0, zFlgs, sizeof(zFlgs), 0);
30661 sqlite3_str_appendf(&x, " fg.af=%x.%c",
30662 pExpr->flags, pExpr->affExpr ? pExpr->affExpr : 'n');
30663 if( ExprHasProperty(pExpr, EP_FromJoin) ){
30664 sqlite3_str_appendf(&x, " iRJT=%d", pExpr->iRightJoinTable);
30665 }
30666 if( ExprHasProperty(pExpr, EP_FromDDL) ){
30667 sqlite3_str_appendf(&x, " DDL");
30668 }
30669 if( ExprHasVVAProperty(pExpr, EP_Immutable) ){
30670 sqlite3_str_appendf(&x, " IMMUTABLE");
30671 }
30672 sqlite3StrAccumFinish(&x);
30673 }else{
30674 zFlgs[0] = 0;
30675 }
30676 switch( pExpr->op ){
30677 case TK_AGG_COLUMN: {
30678 sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
30679 pExpr->iTable, pExpr->iColumn, zFlgs);
30680 break;
30681 }
30682 case TK_COLUMN: {
30683 if( pExpr->iTable<0 ){
30684 /* This only happens when coding check constraints */
30685 char zOp2[16];
30686 if( pExpr->op2 ){
30687 sqlite3_snprintf(sizeof(zOp2),zOp2," op2=0x%02x",pExpr->op2);
30688 }else{
30689 zOp2[0] = 0;
30690 }
30691 sqlite3TreeViewLine(pView, "COLUMN(%d)%s%s",
30692 pExpr->iColumn, zFlgs, zOp2);
30693 }else{
30694 assert( ExprUseYTab(pExpr) );
30695 sqlite3TreeViewLine(pView, "{%d:%d} pTab=%p%s",
30696 pExpr->iTable, pExpr->iColumn,
30697 pExpr->y.pTab, zFlgs);
30698 }
30699 if( ExprHasProperty(pExpr, EP_FixedCol) ){
30700 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
30701 }
30702 break;
30703 }
30704 case TK_INTEGER: {
30705 if( pExpr->flags & EP_IntValue ){
30706 sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
30707 }else{
30708 sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
30709 }
30710 break;
30711 }
30712#ifndef SQLITE_OMIT_FLOATING_POINT
30713 case TK_FLOAT: {
30714 assert( !ExprHasProperty(pExpr, EP_IntValue) );
30715 sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
30716 break;
30717 }
30718#endif
30719 case TK_STRING: {
30720 assert( !ExprHasProperty(pExpr, EP_IntValue) );
30721 sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
30722 break;
30723 }
30724 case TK_NULL: {
30725 sqlite3TreeViewLine(pView,"NULL");
30726 break;
30727 }
30728 case TK_TRUEFALSE: {
30729 sqlite3TreeViewLine(pView,"%s%s",
30730 sqlite3ExprTruthValue(pExpr) ? "TRUE" : "FALSE", zFlgs);
30731 break;
30732 }
30733#ifndef SQLITE_OMIT_BLOB_LITERAL
30734 case TK_BLOB: {
30735 assert( !ExprHasProperty(pExpr, EP_IntValue) );
30736 sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
30737 break;
30738 }
30739#endif
30740 case TK_VARIABLE: {
30741 assert( !ExprHasProperty(pExpr, EP_IntValue) );
30742 sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
30743 pExpr->u.zToken, pExpr->iColumn);
30744 break;
30745 }
30746 case TK_REGISTER: {
30747 sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
30748 break;
30749 }
30750 case TK_ID: {
30751 assert( !ExprHasProperty(pExpr, EP_IntValue) );
30752 sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
30753 break;
30754 }
30755#ifndef SQLITE_OMIT_CAST
30756 case TK_CAST: {
30757 /* Expressions of the form: CAST(pLeft AS token) */
30758 assert( !ExprHasProperty(pExpr, EP_IntValue) );
30759 sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
30760 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
30761 break;
30762 }
30763#endif /* SQLITE_OMIT_CAST */
30764 case TK_LT: zBinOp = "LT"; break;
30765 case TK_LE: zBinOp = "LE"; break;
30766 case TK_GT: zBinOp = "GT"; break;
30767 case TK_GE: zBinOp = "GE"; break;
30768 case TK_NE: zBinOp = "NE"; break;
30769 case TK_EQ: zBinOp = "EQ"; break;
30770 case TK_IS: zBinOp = "IS"; break;
30771 case TK_ISNOT: zBinOp = "ISNOT"; break;
30772 case TK_AND: zBinOp = "AND"; break;
30773 case TK_OR: zBinOp = "OR"; break;
30774 case TK_PLUS: zBinOp = "ADD"; break;
30775 case TK_STAR: zBinOp = "MUL"; break;
30776 case TK_MINUS: zBinOp = "SUB"; break;
30777 case TK_REM: zBinOp = "REM"; break;
30778 case TK_BITAND: zBinOp = "BITAND"; break;
30779 case TK_BITOR: zBinOp = "BITOR"; break;
30780 case TK_SLASH: zBinOp = "DIV"; break;
30781 case TK_LSHIFT: zBinOp = "LSHIFT"; break;
30782 case TK_RSHIFT: zBinOp = "RSHIFT"; break;
30783 case TK_CONCAT: zBinOp = "CONCAT"; break;
30784 case TK_DOT: zBinOp = "DOT"; break;
30785 case TK_LIMIT: zBinOp = "LIMIT"; break;
30786
30787 case TK_UMINUS: zUniOp = "UMINUS"; break;
30788 case TK_UPLUS: zUniOp = "UPLUS"; break;
30789 case TK_BITNOT: zUniOp = "BITNOT"; break;
30790 case TK_NOT: zUniOp = "NOT"; break;
30791 case TK_ISNULL: zUniOp = "ISNULL"; break;
30792 case TK_NOTNULL: zUniOp = "NOTNULL"; break;
30793
30794 case TK_TRUTH: {
30795 int x;
30796 const char *azOp[] = {
30797 "IS-FALSE", "IS-TRUE", "IS-NOT-FALSE", "IS-NOT-TRUE"
30798 };
30799 assert( pExpr->op2==TK_IS || pExpr->op2==TK_ISNOT );
30800 assert( pExpr->pRight );
30801 assert( sqlite3ExprSkipCollate(pExpr->pRight)->op==TK_TRUEFALSE );
30802 x = (pExpr->op2==TK_ISNOT)*2 + sqlite3ExprTruthValue(pExpr->pRight);
30803 zUniOp = azOp[x];
30804 break;
30805 }
30806
30807 case TK_SPAN: {
30808 assert( !ExprHasProperty(pExpr, EP_IntValue) );
30809 sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
30810 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
30811 break;
30812 }
30813
30814 case TK_COLLATE: {
30815 /* COLLATE operators without the EP_Collate flag are intended to
30816 ** emulate collation associated with a table column. These show
30817 ** up in the treeview output as "SOFT-COLLATE". Explicit COLLATE
30818 ** operators that appear in the original SQL always have the
30819 ** EP_Collate bit set and appear in treeview output as just "COLLATE" */
30820 assert( !ExprHasProperty(pExpr, EP_IntValue) );
30821 sqlite3TreeViewLine(pView, "%sCOLLATE %Q%s",
30822 !ExprHasProperty(pExpr, EP_Collate) ? "SOFT-" : "",
30823 pExpr->u.zToken, zFlgs);
30824 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
30825 break;
30826 }
30827
30828 case TK_AGG_FUNCTION:
30829 case TK_FUNCTION: {
30830 ExprList *pFarg; /* List of function arguments */
30831 Window *pWin;
30832 if( ExprHasProperty(pExpr, EP_TokenOnly) ){
30833 pFarg = 0;
30834 pWin = 0;
30835 }else{
30836 assert( ExprUseXList(pExpr) );
30837 pFarg = pExpr->x.pList;
30838#ifndef SQLITE_OMIT_WINDOWFUNC
30839 pWin = ExprHasProperty(pExpr, EP_WinFunc) ? pExpr->y.pWin : 0;
30840#else
30841 pWin = 0;
30842#endif
30843 }
30844 assert( !ExprHasProperty(pExpr, EP_IntValue) );
30845 if( pExpr->op==TK_AGG_FUNCTION ){
30846 sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q%s agg=%d[%d]/%p",
30847 pExpr->op2, pExpr->u.zToken, zFlgs,
30848 pExpr->pAggInfo ? pExpr->pAggInfo->selId : 0,
30849 pExpr->iAgg, pExpr->pAggInfo);
30850 }else if( pExpr->op2!=0 ){
30851 const char *zOp2;
30852 char zBuf[8];
30853 sqlite3_snprintf(sizeof(zBuf),zBuf,"0x%02x",pExpr->op2);
30854 zOp2 = zBuf;
30855 if( pExpr->op2==NC_IsCheck ) zOp2 = "NC_IsCheck";
30856 if( pExpr->op2==NC_IdxExpr ) zOp2 = "NC_IdxExpr";
30857 if( pExpr->op2==NC_PartIdx ) zOp2 = "NC_PartIdx";
30858 if( pExpr->op2==NC_GenCol ) zOp2 = "NC_GenCol";
30859 sqlite3TreeViewLine(pView, "FUNCTION %Q%s op2=%s",
30860 pExpr->u.zToken, zFlgs, zOp2);
30861 }else{
30862 sqlite3TreeViewLine(pView, "FUNCTION %Q%s", pExpr->u.zToken, zFlgs);
30863 }
30864 if( pFarg ){
30865 sqlite3TreeViewExprList(pView, pFarg, pWin!=0, 0);
30866 }
30867#ifndef SQLITE_OMIT_WINDOWFUNC
30868 if( pWin ){
30869 sqlite3TreeViewWindow(pView, pWin, 0);
30870 }
30871#endif
30872 break;
30873 }
30874#ifndef SQLITE_OMIT_SUBQUERY
30875 case TK_EXISTS: {
30876 assert( ExprUseXSelect(pExpr) );
30877 sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags);
30878 sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
30879 break;
30880 }
30881 case TK_SELECT: {
30882 assert( ExprUseXSelect(pExpr) );
30883 sqlite3TreeViewLine(pView, "subquery-expr flags=0x%x", pExpr->flags);
30884 sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
30885 break;
30886 }
30887 case TK_IN: {
30888 sqlite3TreeViewLine(pView, "IN flags=0x%x", pExpr->flags);
30889 sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
30890 if( ExprUseXSelect(pExpr) ){
30891 sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
30892 }else{
30893 sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
30894 }
30895 break;
30896 }
30897#endif /* SQLITE_OMIT_SUBQUERY */
30898
30899 /*
30900 ** x BETWEEN y AND z
30901 **
30902 ** This is equivalent to
30903 **
30904 ** x>=y AND x<=z
30905 **
30906 ** X is stored in pExpr->pLeft.
30907 ** Y is stored in pExpr->pList->a[0].pExpr.
30908 ** Z is stored in pExpr->pList->a[1].pExpr.
30909 */
30910 case TK_BETWEEN: {
30911 const Expr *pX, *pY, *pZ;
30912 pX = pExpr->pLeft;
30913 assert( ExprUseXList(pExpr) );
30914 assert( pExpr->x.pList->nExpr==2 );
30915 pY = pExpr->x.pList->a[0].pExpr;
30916 pZ = pExpr->x.pList->a[1].pExpr;
30917 sqlite3TreeViewLine(pView, "BETWEEN");
30918 sqlite3TreeViewExpr(pView, pX, 1);
30919 sqlite3TreeViewExpr(pView, pY, 1);
30920 sqlite3TreeViewExpr(pView, pZ, 0);
30921 break;
30922 }
30923 case TK_TRIGGER: {
30924 /* If the opcode is TK_TRIGGER, then the expression is a reference
30925 ** to a column in the new.* or old.* pseudo-tables available to
30926 ** trigger programs. In this case Expr.iTable is set to 1 for the
30927 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
30928 ** is set to the column of the pseudo-table to read, or to -1 to
30929 ** read the rowid field.
30930 */
30931 sqlite3TreeViewLine(pView, "%s(%d)",
30932 pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
30933 break;
30934 }
30935 case TK_CASE: {
30936 sqlite3TreeViewLine(pView, "CASE");
30937 sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
30938 assert( ExprUseXList(pExpr) );
30939 sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
30940 break;
30941 }
30942#ifndef SQLITE_OMIT_TRIGGER
30943 case TK_RAISE: {
30944 const char *zType = "unk";
30945 switch( pExpr->affExpr ){
30946 case OE_Rollback: zType = "rollback"; break;
30947 case OE_Abort: zType = "abort"; break;
30948 case OE_Fail: zType = "fail"; break;
30949 case OE_Ignore: zType = "ignore"; break;
30950 }
30951 assert( !ExprHasProperty(pExpr, EP_IntValue) );
30952 sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
30953 break;
30954 }
30955#endif
30956 case TK_MATCH: {
30957 sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
30958 pExpr->iTable, pExpr->iColumn, zFlgs);
30959 sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
30960 break;
30961 }
30962 case TK_VECTOR: {
30963 char *z = sqlite3_mprintf("VECTOR%s",zFlgs);
30964 assert( ExprUseXList(pExpr) );
30965 sqlite3TreeViewBareExprList(pView, pExpr->x.pList, z);
30966 sqlite3_free(z);
30967 break;
30968 }
30969 case TK_SELECT_COLUMN: {
30970 sqlite3TreeViewLine(pView, "SELECT-COLUMN %d of [0..%d]%s",
30971 pExpr->iColumn, pExpr->iTable-1,
30972 pExpr->pRight==pExpr->pLeft ? " (SELECT-owner)" : "");
30973 assert( ExprUseXSelect(pExpr->pLeft) );
30974 sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
30975 break;
30976 }
30977 case TK_IF_NULL_ROW: {
30978 sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable);
30979 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
30980 break;
30981 }
30982 case TK_ERROR: {
30983 Expr tmp;
30984 sqlite3TreeViewLine(pView, "ERROR");
30985 tmp = *pExpr;
30986 tmp.op = pExpr->op2;
30987 sqlite3TreeViewExpr(pView, &tmp, 0);
30988 break;
30989 }
30990 case TK_ROW: {
30991 if( pExpr->iColumn<=0 ){
30992 sqlite3TreeViewLine(pView, "First FROM table rowid");
30993 }else{
30994 sqlite3TreeViewLine(pView, "First FROM table column %d",
30995 pExpr->iColumn-1);
30996 }
30997 break;
30998 }
30999 default: {
31000 sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
31001 break;
31002 }
31003 }
31004 if( zBinOp ){
31005 sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
31006 sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
31007 sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
31008 }else if( zUniOp ){
31009 sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
31010 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
31011 }
31012 sqlite3TreeViewPop(pView);
31013}
31014
31015
31016/*
31017** Generate a human-readable explanation of an expression list.
31018*/
31019SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
31020 TreeView *pView,
31021 const ExprList *pList,
31022 const char *zLabel
31023){
31024 if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
31025 if( pList==0 ){
31026 sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
31027 }else{
31028 int i;
31029 sqlite3TreeViewLine(pView, "%s", zLabel);
31030 for(i=0; i<pList->nExpr; i++){
31031 int j = pList->a[i].u.x.iOrderByCol;
31032 char *zName = pList->a[i].zEName;
31033 int moreToFollow = i<pList->nExpr - 1;
31034 if( pList->a[i].eEName!=ENAME_NAME ) zName = 0;
31035 if( j || zName ){
31036 sqlite3TreeViewPush(pView, moreToFollow);
31037 moreToFollow = 0;
31038 sqlite3TreeViewLine(pView, 0);
31039 if( zName ){
31040 fprintf(stdout, "AS %s ", zName);
31041 }
31042 if( j ){
31043 fprintf(stdout, "iOrderByCol=%d", j);
31044 }
31045 fprintf(stdout, "\n");
31046 fflush(stdout);
31047 }
31048 sqlite3TreeViewExpr(pView, pList->a[i].pExpr, moreToFollow);
31049 if( j || zName ){
31050 sqlite3TreeViewPop(pView);
31051 }
31052 }
31053 }
31054}
31055SQLITE_PRIVATE void sqlite3TreeViewExprList(
31056 TreeView *pView,
31057 const ExprList *pList,
31058 u8 moreToFollow,
31059 const char *zLabel
31060){
31061 pView = sqlite3TreeViewPush(pView, moreToFollow);
31062 sqlite3TreeViewBareExprList(pView, pList, zLabel);
31063 sqlite3TreeViewPop(pView);
31064}
31065
31066#endif /* SQLITE_DEBUG */
31067
31068/************** End of treeview.c ********************************************/
31069/************** Begin file random.c ******************************************/
31070/*
31071** 2001 September 15
31072**
31073** The author disclaims copyright to this source code. In place of
31074** a legal notice, here is a blessing:
31075**
31076** May you do good and not evil.
31077** May you find forgiveness for yourself and forgive others.
31078** May you share freely, never taking more than you give.
31079**
31080*************************************************************************
31081** This file contains code to implement a pseudo-random number
31082** generator (PRNG) for SQLite.
31083**
31084** Random numbers are used by some of the database backends in order
31085** to generate random integer keys for tables or random filenames.
31086*/
31087/* #include "sqliteInt.h" */
31088
31089
31090/* All threads share a single random number generator.
31091** This structure is the current state of the generator.
31092*/
31093static SQLITE_WSD struct sqlite3PrngType {
31094 unsigned char isInit; /* True if initialized */
31095 unsigned char i, j; /* State variables */
31096 unsigned char s[256]; /* State variables */
31097} sqlite3Prng;
31098
31099/*
31100** Return N random bytes.
31101*/
31102SQLITE_API void sqlite3_randomness(int N, void *pBuf){
31103 unsigned char t;
31104 unsigned char *zBuf = pBuf;
31105
31106 /* The "wsdPrng" macro will resolve to the pseudo-random number generator
31107 ** state vector. If writable static data is unsupported on the target,
31108 ** we have to locate the state vector at run-time. In the more common
31109 ** case where writable static data is supported, wsdPrng can refer directly
31110 ** to the "sqlite3Prng" state vector declared above.
31111 */
31112#ifdef SQLITE_OMIT_WSD
31113 struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
31114# define wsdPrng p[0]
31115#else
31116# define wsdPrng sqlite3Prng
31117#endif
31118
31119#if SQLITE_THREADSAFE
31120 sqlite3_mutex *mutex;
31121#endif
31122
31123#ifndef SQLITE_OMIT_AUTOINIT
31124 if( sqlite3_initialize() ) return;
31125#endif
31126
31127#if SQLITE_THREADSAFE
31128 mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
31129#endif
31130
31131 sqlite3_mutex_enter(p: mutex);
31132 if( N<=0 || pBuf==0 ){
31133 wsdPrng.isInit = 0;
31134 sqlite3_mutex_leave(p: mutex);
31135 return;
31136 }
31137
31138 /* Initialize the state of the random number generator once,
31139 ** the first time this routine is called. The seed value does
31140 ** not need to contain a lot of randomness since we are not
31141 ** trying to do secure encryption or anything like that...
31142 **
31143 ** Nothing in this file or anywhere else in SQLite does any kind of
31144 ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
31145 ** number generator) not as an encryption device.
31146 */
31147 if( !wsdPrng.isInit ){
31148 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs: 0);
31149 int i;
31150 char k[256];
31151 wsdPrng.j = 0;
31152 wsdPrng.i = 0;
31153 if( NEVER(pVfs==0) ){
31154 memset(s: k, c: 0, n: sizeof(k));
31155 }else{
31156 sqlite3OsRandomness(pVfs, nByte: 256, zBufOut: k);
31157 }
31158 for(i=0; i<256; i++){
31159 wsdPrng.s[i] = (u8)i;
31160 }
31161 for(i=0; i<256; i++){
31162 wsdPrng.j += wsdPrng.s[i] + k[i];
31163 t = wsdPrng.s[wsdPrng.j];
31164 wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
31165 wsdPrng.s[i] = t;
31166 }
31167 wsdPrng.isInit = 1;
31168 }
31169
31170 assert( N>0 );
31171 do{
31172 wsdPrng.i++;
31173 t = wsdPrng.s[wsdPrng.i];
31174 wsdPrng.j += t;
31175 wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
31176 wsdPrng.s[wsdPrng.j] = t;
31177 t += wsdPrng.s[wsdPrng.i];
31178 *(zBuf++) = wsdPrng.s[t];
31179 }while( --N );
31180 sqlite3_mutex_leave(p: mutex);
31181}
31182
31183#ifndef SQLITE_UNTESTABLE
31184/*
31185** For testing purposes, we sometimes want to preserve the state of
31186** PRNG and restore the PRNG to its saved state at a later time, or
31187** to reset the PRNG to its initial state. These routines accomplish
31188** those tasks.
31189**
31190** The sqlite3_test_control() interface calls these routines to
31191** control the PRNG.
31192*/
31193static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
31194SQLITE_PRIVATE void sqlite3PrngSaveState(void){
31195 memcpy(
31196 dest: &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
31197 src: &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
31198 n: sizeof(sqlite3Prng)
31199 );
31200}
31201SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
31202 memcpy(
31203 dest: &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
31204 src: &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
31205 n: sizeof(sqlite3Prng)
31206 );
31207}
31208#endif /* SQLITE_UNTESTABLE */
31209
31210/************** End of random.c **********************************************/
31211/************** Begin file threads.c *****************************************/
31212/*
31213** 2012 July 21
31214**
31215** The author disclaims copyright to this source code. In place of
31216** a legal notice, here is a blessing:
31217**
31218** May you do good and not evil.
31219** May you find forgiveness for yourself and forgive others.
31220** May you share freely, never taking more than you give.
31221**
31222******************************************************************************
31223**
31224** This file presents a simple cross-platform threading interface for
31225** use internally by SQLite.
31226**
31227** A "thread" can be created using sqlite3ThreadCreate(). This thread
31228** runs independently of its creator until it is joined using
31229** sqlite3ThreadJoin(), at which point it terminates.
31230**
31231** Threads do not have to be real. It could be that the work of the
31232** "thread" is done by the main thread at either the sqlite3ThreadCreate()
31233** or sqlite3ThreadJoin() call. This is, in fact, what happens in
31234** single threaded systems. Nothing in SQLite requires multiple threads.
31235** This interface exists so that applications that want to take advantage
31236** of multiple cores can do so, while also allowing applications to stay
31237** single-threaded if desired.
31238*/
31239/* #include "sqliteInt.h" */
31240#if SQLITE_OS_WIN
31241/* # include "os_win.h" */
31242#endif
31243
31244#if SQLITE_MAX_WORKER_THREADS>0
31245
31246/********************************* Unix Pthreads ****************************/
31247#if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
31248
31249#define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
31250/* #include <pthread.h> */
31251
31252/* A running thread */
31253struct SQLiteThread {
31254 pthread_t tid; /* Thread ID */
31255 int done; /* Set to true when thread finishes */
31256 void *pOut; /* Result returned by the thread */
31257 void *(*xTask)(void*); /* The thread routine */
31258 void *pIn; /* Argument to the thread */
31259};
31260
31261/* Create a new thread */
31262SQLITE_PRIVATE int sqlite3ThreadCreate(
31263 SQLiteThread **ppThread, /* OUT: Write the thread object here */
31264 void *(*xTask)(void*), /* Routine to run in a separate thread */
31265 void *pIn /* Argument passed into xTask() */
31266){
31267 SQLiteThread *p;
31268 int rc;
31269
31270 assert( ppThread!=0 );
31271 assert( xTask!=0 );
31272 /* This routine is never used in single-threaded mode */
31273 assert( sqlite3GlobalConfig.bCoreMutex!=0 );
31274
31275 *ppThread = 0;
31276 p = sqlite3Malloc(n: sizeof(*p));
31277 if( p==0 ) return SQLITE_NOMEM_BKPT;
31278 memset(s: p, c: 0, n: sizeof(*p));
31279 p->xTask = xTask;
31280 p->pIn = pIn;
31281 /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
31282 ** function that returns SQLITE_ERROR when passed the argument 200, that
31283 ** forces worker threads to run sequentially and deterministically
31284 ** for testing purposes. */
31285 if( sqlite3FaultSim(200) ){
31286 rc = 1;
31287 }else{
31288 rc = pthread_create(newthread: &p->tid, attr: 0, start_routine: xTask, arg: pIn);
31289 }
31290 if( rc ){
31291 p->done = 1;
31292 p->pOut = xTask(pIn);
31293 }
31294 *ppThread = p;
31295 return SQLITE_OK;
31296}
31297
31298/* Get the results of the thread */
31299SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
31300 int rc;
31301
31302 assert( ppOut!=0 );
31303 if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
31304 if( p->done ){
31305 *ppOut = p->pOut;
31306 rc = SQLITE_OK;
31307 }else{
31308 rc = pthread_join(th: p->tid, thread_return: ppOut) ? SQLITE_ERROR : SQLITE_OK;
31309 }
31310 sqlite3_free(p);
31311 return rc;
31312}
31313
31314#endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
31315/******************************** End Unix Pthreads *************************/
31316
31317
31318/********************************* Win32 Threads ****************************/
31319#if SQLITE_OS_WIN_THREADS
31320
31321#define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
31322#include <process.h>
31323
31324/* A running thread */
31325struct SQLiteThread {
31326 void *tid; /* The thread handle */
31327 unsigned id; /* The thread identifier */
31328 void *(*xTask)(void*); /* The routine to run as a thread */
31329 void *pIn; /* Argument to xTask */
31330 void *pResult; /* Result of xTask */
31331};
31332
31333/* Thread procedure Win32 compatibility shim */
31334static unsigned __stdcall sqlite3ThreadProc(
31335 void *pArg /* IN: Pointer to the SQLiteThread structure */
31336){
31337 SQLiteThread *p = (SQLiteThread *)pArg;
31338
31339 assert( p!=0 );
31340#if 0
31341 /*
31342 ** This assert appears to trigger spuriously on certain
31343 ** versions of Windows, possibly due to _beginthreadex()
31344 ** and/or CreateThread() not fully setting their thread
31345 ** ID parameter before starting the thread.
31346 */
31347 assert( p->id==GetCurrentThreadId() );
31348#endif
31349 assert( p->xTask!=0 );
31350 p->pResult = p->xTask(p->pIn);
31351
31352 _endthreadex(0);
31353 return 0; /* NOT REACHED */
31354}
31355
31356/* Create a new thread */
31357SQLITE_PRIVATE int sqlite3ThreadCreate(
31358 SQLiteThread **ppThread, /* OUT: Write the thread object here */
31359 void *(*xTask)(void*), /* Routine to run in a separate thread */
31360 void *pIn /* Argument passed into xTask() */
31361){
31362 SQLiteThread *p;
31363
31364 assert( ppThread!=0 );
31365 assert( xTask!=0 );
31366 *ppThread = 0;
31367 p = sqlite3Malloc(sizeof(*p));
31368 if( p==0 ) return SQLITE_NOMEM_BKPT;
31369 /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
31370 ** function that returns SQLITE_ERROR when passed the argument 200, that
31371 ** forces worker threads to run sequentially and deterministically
31372 ** (via the sqlite3FaultSim() term of the conditional) for testing
31373 ** purposes. */
31374 if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
31375 memset(p, 0, sizeof(*p));
31376 }else{
31377 p->xTask = xTask;
31378 p->pIn = pIn;
31379 p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
31380 if( p->tid==0 ){
31381 memset(p, 0, sizeof(*p));
31382 }
31383 }
31384 if( p->xTask==0 ){
31385 p->id = GetCurrentThreadId();
31386 p->pResult = xTask(pIn);
31387 }
31388 *ppThread = p;
31389 return SQLITE_OK;
31390}
31391
31392SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
31393
31394/* Get the results of the thread */
31395SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
31396 DWORD rc;
31397 BOOL bRc;
31398
31399 assert( ppOut!=0 );
31400 if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
31401 if( p->xTask==0 ){
31402 /* assert( p->id==GetCurrentThreadId() ); */
31403 rc = WAIT_OBJECT_0;
31404 assert( p->tid==0 );
31405 }else{
31406 assert( p->id!=0 && p->id!=GetCurrentThreadId() );
31407 rc = sqlite3Win32Wait((HANDLE)p->tid);
31408 assert( rc!=WAIT_IO_COMPLETION );
31409 bRc = CloseHandle((HANDLE)p->tid);
31410 assert( bRc );
31411 }
31412 if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
31413 sqlite3_free(p);
31414 return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
31415}
31416
31417#endif /* SQLITE_OS_WIN_THREADS */
31418/******************************** End Win32 Threads *************************/
31419
31420
31421/********************************* Single-Threaded **************************/
31422#ifndef SQLITE_THREADS_IMPLEMENTED
31423/*
31424** This implementation does not actually create a new thread. It does the
31425** work of the thread in the main thread, when either the thread is created
31426** or when it is joined
31427*/
31428
31429/* A running thread */
31430struct SQLiteThread {
31431 void *(*xTask)(void*); /* The routine to run as a thread */
31432 void *pIn; /* Argument to xTask */
31433 void *pResult; /* Result of xTask */
31434};
31435
31436/* Create a new thread */
31437SQLITE_PRIVATE int sqlite3ThreadCreate(
31438 SQLiteThread **ppThread, /* OUT: Write the thread object here */
31439 void *(*xTask)(void*), /* Routine to run in a separate thread */
31440 void *pIn /* Argument passed into xTask() */
31441){
31442 SQLiteThread *p;
31443
31444 assert( ppThread!=0 );
31445 assert( xTask!=0 );
31446 *ppThread = 0;
31447 p = sqlite3Malloc(sizeof(*p));
31448 if( p==0 ) return SQLITE_NOMEM_BKPT;
31449 if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
31450 p->xTask = xTask;
31451 p->pIn = pIn;
31452 }else{
31453 p->xTask = 0;
31454 p->pResult = xTask(pIn);
31455 }
31456 *ppThread = p;
31457 return SQLITE_OK;
31458}
31459
31460/* Get the results of the thread */
31461SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
31462
31463 assert( ppOut!=0 );
31464 if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
31465 if( p->xTask ){
31466 *ppOut = p->xTask(p->pIn);
31467 }else{
31468 *ppOut = p->pResult;
31469 }
31470 sqlite3_free(p);
31471
31472#if defined(SQLITE_TEST)
31473 {
31474 void *pTstAlloc = sqlite3Malloc(10);
31475 if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
31476 sqlite3_free(pTstAlloc);
31477 }
31478#endif
31479
31480 return SQLITE_OK;
31481}
31482
31483#endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
31484/****************************** End Single-Threaded *************************/
31485#endif /* SQLITE_MAX_WORKER_THREADS>0 */
31486
31487/************** End of threads.c *********************************************/
31488/************** Begin file utf.c *********************************************/
31489/*
31490** 2004 April 13
31491**
31492** The author disclaims copyright to this source code. In place of
31493** a legal notice, here is a blessing:
31494**
31495** May you do good and not evil.
31496** May you find forgiveness for yourself and forgive others.
31497** May you share freely, never taking more than you give.
31498**
31499*************************************************************************
31500** This file contains routines used to translate between UTF-8,
31501** UTF-16, UTF-16BE, and UTF-16LE.
31502**
31503** Notes on UTF-8:
31504**
31505** Byte-0 Byte-1 Byte-2 Byte-3 Value
31506** 0xxxxxxx 00000000 00000000 0xxxxxxx
31507** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
31508** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
31509** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
31510**
31511**
31512** Notes on UTF-16: (with wwww+1==uuuuu)
31513**
31514** Word-0 Word-1 Value
31515** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
31516** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
31517**
31518**
31519** BOM or Byte Order Mark:
31520** 0xff 0xfe little-endian utf-16 follows
31521** 0xfe 0xff big-endian utf-16 follows
31522**
31523*/
31524/* #include "sqliteInt.h" */
31525/* #include <assert.h> */
31526/* #include "vdbeInt.h" */
31527
31528#if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
31529/*
31530** The following constant value is used by the SQLITE_BIGENDIAN and
31531** SQLITE_LITTLEENDIAN macros.
31532*/
31533SQLITE_PRIVATE const int sqlite3one = 1;
31534#endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
31535
31536/*
31537** This lookup table is used to help decode the first byte of
31538** a multi-byte UTF8 character.
31539*/
31540static const unsigned char sqlite3Utf8Trans1[] = {
31541 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
31542 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
31543 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
31544 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
31545 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
31546 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
31547 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
31548 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
31549};
31550
31551
31552#define WRITE_UTF8(zOut, c) { \
31553 if( c<0x00080 ){ \
31554 *zOut++ = (u8)(c&0xFF); \
31555 } \
31556 else if( c<0x00800 ){ \
31557 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
31558 *zOut++ = 0x80 + (u8)(c & 0x3F); \
31559 } \
31560 else if( c<0x10000 ){ \
31561 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
31562 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
31563 *zOut++ = 0x80 + (u8)(c & 0x3F); \
31564 }else{ \
31565 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
31566 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
31567 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
31568 *zOut++ = 0x80 + (u8)(c & 0x3F); \
31569 } \
31570}
31571
31572#define WRITE_UTF16LE(zOut, c) { \
31573 if( c<=0xFFFF ){ \
31574 *zOut++ = (u8)(c&0x00FF); \
31575 *zOut++ = (u8)((c>>8)&0x00FF); \
31576 }else{ \
31577 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
31578 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
31579 *zOut++ = (u8)(c&0x00FF); \
31580 *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
31581 } \
31582}
31583
31584#define WRITE_UTF16BE(zOut, c) { \
31585 if( c<=0xFFFF ){ \
31586 *zOut++ = (u8)((c>>8)&0x00FF); \
31587 *zOut++ = (u8)(c&0x00FF); \
31588 }else{ \
31589 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
31590 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
31591 *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
31592 *zOut++ = (u8)(c&0x00FF); \
31593 } \
31594}
31595
31596/*
31597** Translate a single UTF-8 character. Return the unicode value.
31598**
31599** During translation, assume that the byte that zTerm points
31600** is a 0x00.
31601**
31602** Write a pointer to the next unread byte back into *pzNext.
31603**
31604** Notes On Invalid UTF-8:
31605**
31606** * This routine never allows a 7-bit character (0x00 through 0x7f) to
31607** be encoded as a multi-byte character. Any multi-byte character that
31608** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
31609**
31610** * This routine never allows a UTF16 surrogate value to be encoded.
31611** If a multi-byte character attempts to encode a value between
31612** 0xd800 and 0xe000 then it is rendered as 0xfffd.
31613**
31614** * Bytes in the range of 0x80 through 0xbf which occur as the first
31615** byte of a character are interpreted as single-byte characters
31616** and rendered as themselves even though they are technically
31617** invalid characters.
31618**
31619** * This routine accepts over-length UTF8 encodings
31620** for unicode values 0x80 and greater. It does not change over-length
31621** encodings to 0xfffd as some systems recommend.
31622*/
31623#define READ_UTF8(zIn, zTerm, c) \
31624 c = *(zIn++); \
31625 if( c>=0xc0 ){ \
31626 c = sqlite3Utf8Trans1[c-0xc0]; \
31627 while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
31628 c = (c<<6) + (0x3f & *(zIn++)); \
31629 } \
31630 if( c<0x80 \
31631 || (c&0xFFFFF800)==0xD800 \
31632 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
31633 }
31634SQLITE_PRIVATE u32 sqlite3Utf8Read(
31635 const unsigned char **pz /* Pointer to string from which to read char */
31636){
31637 unsigned int c;
31638
31639 /* Same as READ_UTF8() above but without the zTerm parameter.
31640 ** For this routine, we assume the UTF8 string is always zero-terminated.
31641 */
31642 c = *((*pz)++);
31643 if( c>=0xc0 ){
31644 c = sqlite3Utf8Trans1[c-0xc0];
31645 while( (*(*pz) & 0xc0)==0x80 ){
31646 c = (c<<6) + (0x3f & *((*pz)++));
31647 }
31648 if( c<0x80
31649 || (c&0xFFFFF800)==0xD800
31650 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
31651 }
31652 return c;
31653}
31654
31655
31656
31657
31658/*
31659** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
31660** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
31661*/
31662/* #define TRANSLATE_TRACE 1 */
31663
31664#ifndef SQLITE_OMIT_UTF16
31665/*
31666** This routine transforms the internal text encoding used by pMem to
31667** desiredEnc. It is an error if the string is already of the desired
31668** encoding, or if *pMem does not contain a string value.
31669*/
31670SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
31671 sqlite3_int64 len; /* Maximum length of output string in bytes */
31672 unsigned char *zOut; /* Output buffer */
31673 unsigned char *zIn; /* Input iterator */
31674 unsigned char *zTerm; /* End of input */
31675 unsigned char *z; /* Output iterator */
31676 unsigned int c;
31677
31678 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
31679 assert( pMem->flags&MEM_Str );
31680 assert( pMem->enc!=desiredEnc );
31681 assert( pMem->enc!=0 );
31682 assert( pMem->n>=0 );
31683
31684#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
31685 {
31686 StrAccum acc;
31687 char zBuf[1000];
31688 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
31689 sqlite3VdbeMemPrettyPrint(pMem, &acc);
31690 fprintf(stderr, "INPUT: %s\n", sqlite3StrAccumFinish(&acc));
31691 }
31692#endif
31693
31694 /* If the translation is between UTF-16 little and big endian, then
31695 ** all that is required is to swap the byte order. This case is handled
31696 ** differently from the others.
31697 */
31698 if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
31699 u8 temp;
31700 int rc;
31701 rc = sqlite3VdbeMemMakeWriteable(pMem);
31702 if( rc!=SQLITE_OK ){
31703 assert( rc==SQLITE_NOMEM );
31704 return SQLITE_NOMEM_BKPT;
31705 }
31706 zIn = (u8*)pMem->z;
31707 zTerm = &zIn[pMem->n&~1];
31708 while( zIn<zTerm ){
31709 temp = *zIn;
31710 *zIn = *(zIn+1);
31711 zIn++;
31712 *zIn++ = temp;
31713 }
31714 pMem->enc = desiredEnc;
31715 goto translate_out;
31716 }
31717
31718 /* Set len to the maximum number of bytes required in the output buffer. */
31719 if( desiredEnc==SQLITE_UTF8 ){
31720 /* When converting from UTF-16, the maximum growth results from
31721 ** translating a 2-byte character to a 4-byte UTF-8 character.
31722 ** A single byte is required for the output string
31723 ** nul-terminator.
31724 */
31725 pMem->n &= ~1;
31726 len = 2 * (sqlite3_int64)pMem->n + 1;
31727 }else{
31728 /* When converting from UTF-8 to UTF-16 the maximum growth is caused
31729 ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
31730 ** character. Two bytes are required in the output buffer for the
31731 ** nul-terminator.
31732 */
31733 len = 2 * (sqlite3_int64)pMem->n + 2;
31734 }
31735
31736 /* Set zIn to point at the start of the input buffer and zTerm to point 1
31737 ** byte past the end.
31738 **
31739 ** Variable zOut is set to point at the output buffer, space obtained
31740 ** from sqlite3_malloc().
31741 */
31742 zIn = (u8*)pMem->z;
31743 zTerm = &zIn[pMem->n];
31744 zOut = sqlite3DbMallocRaw(db: pMem->db, n: len);
31745 if( !zOut ){
31746 return SQLITE_NOMEM_BKPT;
31747 }
31748 z = zOut;
31749
31750 if( pMem->enc==SQLITE_UTF8 ){
31751 if( desiredEnc==SQLITE_UTF16LE ){
31752 /* UTF-8 -> UTF-16 Little-endian */
31753 while( zIn<zTerm ){
31754 READ_UTF8(zIn, zTerm, c);
31755 WRITE_UTF16LE(z, c);
31756 }
31757 }else{
31758 assert( desiredEnc==SQLITE_UTF16BE );
31759 /* UTF-8 -> UTF-16 Big-endian */
31760 while( zIn<zTerm ){
31761 READ_UTF8(zIn, zTerm, c);
31762 WRITE_UTF16BE(z, c);
31763 }
31764 }
31765 pMem->n = (int)(z - zOut);
31766 *z++ = 0;
31767 }else{
31768 assert( desiredEnc==SQLITE_UTF8 );
31769 if( pMem->enc==SQLITE_UTF16LE ){
31770 /* UTF-16 Little-endian -> UTF-8 */
31771 while( zIn<zTerm ){
31772 c = *(zIn++);
31773 c += (*(zIn++))<<8;
31774 if( c>=0xd800 && c<0xe000 ){
31775#ifdef SQLITE_REPLACE_INVALID_UTF
31776 if( c>=0xdc00 || zIn>=zTerm ){
31777 c = 0xfffd;
31778 }else{
31779 int c2 = *(zIn++);
31780 c2 += (*(zIn++))<<8;
31781 if( c2<0xdc00 || c2>=0xe000 ){
31782 zIn -= 2;
31783 c = 0xfffd;
31784 }else{
31785 c = ((c&0x3ff)<<10) + (c2&0x3ff) + 0x10000;
31786 }
31787 }
31788#else
31789 if( zIn<zTerm ){
31790 int c2 = (*zIn++);
31791 c2 += ((*zIn++)<<8);
31792 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);
31793 }
31794#endif
31795 }
31796 WRITE_UTF8(z, c);
31797 }
31798 }else{
31799 /* UTF-16 Big-endian -> UTF-8 */
31800 while( zIn<zTerm ){
31801 c = (*(zIn++))<<8;
31802 c += *(zIn++);
31803 if( c>=0xd800 && c<0xe000 ){
31804#ifdef SQLITE_REPLACE_INVALID_UTF
31805 if( c>=0xdc00 || zIn>=zTerm ){
31806 c = 0xfffd;
31807 }else{
31808 int c2 = (*(zIn++))<<8;
31809 c2 += *(zIn++);
31810 if( c2<0xdc00 || c2>=0xe000 ){
31811 zIn -= 2;
31812 c = 0xfffd;
31813 }else{
31814 c = ((c&0x3ff)<<10) + (c2&0x3ff) + 0x10000;
31815 }
31816 }
31817#else
31818 if( zIn<zTerm ){
31819 int c2 = ((*zIn++)<<8);
31820 c2 += (*zIn++);
31821 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);
31822 }
31823#endif
31824 }
31825 WRITE_UTF8(z, c);
31826 }
31827 }
31828 pMem->n = (int)(z - zOut);
31829 }
31830 *z = 0;
31831 assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
31832
31833 c = MEM_Str|MEM_Term|(pMem->flags&(MEM_AffMask|MEM_Subtype));
31834 sqlite3VdbeMemRelease(p: pMem);
31835 pMem->flags = c;
31836 pMem->enc = desiredEnc;
31837 pMem->z = (char*)zOut;
31838 pMem->zMalloc = pMem->z;
31839 pMem->szMalloc = sqlite3DbMallocSize(db: pMem->db, p: pMem->z);
31840
31841translate_out:
31842#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
31843 {
31844 StrAccum acc;
31845 char zBuf[1000];
31846 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
31847 sqlite3VdbeMemPrettyPrint(pMem, &acc);
31848 fprintf(stderr, "OUTPUT: %s\n", sqlite3StrAccumFinish(&acc));
31849 }
31850#endif
31851 return SQLITE_OK;
31852}
31853#endif /* SQLITE_OMIT_UTF16 */
31854
31855#ifndef SQLITE_OMIT_UTF16
31856/*
31857** This routine checks for a byte-order mark at the beginning of the
31858** UTF-16 string stored in *pMem. If one is present, it is removed and
31859** the encoding of the Mem adjusted. This routine does not do any
31860** byte-swapping, it just sets Mem.enc appropriately.
31861**
31862** The allocation (static, dynamic etc.) and encoding of the Mem may be
31863** changed by this function.
31864*/
31865SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
31866 int rc = SQLITE_OK;
31867 u8 bom = 0;
31868
31869 assert( pMem->n>=0 );
31870 if( pMem->n>1 ){
31871 u8 b1 = *(u8 *)pMem->z;
31872 u8 b2 = *(((u8 *)pMem->z) + 1);
31873 if( b1==0xFE && b2==0xFF ){
31874 bom = SQLITE_UTF16BE;
31875 }
31876 if( b1==0xFF && b2==0xFE ){
31877 bom = SQLITE_UTF16LE;
31878 }
31879 }
31880
31881 if( bom ){
31882 rc = sqlite3VdbeMemMakeWriteable(pMem);
31883 if( rc==SQLITE_OK ){
31884 pMem->n -= 2;
31885 memmove(dest: pMem->z, src: &pMem->z[2], n: pMem->n);
31886 pMem->z[pMem->n] = '\0';
31887 pMem->z[pMem->n+1] = '\0';
31888 pMem->flags |= MEM_Term;
31889 pMem->enc = bom;
31890 }
31891 }
31892 return rc;
31893}
31894#endif /* SQLITE_OMIT_UTF16 */
31895
31896/*
31897** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
31898** return the number of unicode characters in pZ up to (but not including)
31899** the first 0x00 byte. If nByte is not less than zero, return the
31900** number of unicode characters in the first nByte of pZ (or up to
31901** the first 0x00, whichever comes first).
31902*/
31903SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
31904 int r = 0;
31905 const u8 *z = (const u8*)zIn;
31906 const u8 *zTerm;
31907 if( nByte>=0 ){
31908 zTerm = &z[nByte];
31909 }else{
31910 zTerm = (const u8*)(-1);
31911 }
31912 assert( z<=zTerm );
31913 while( *z!=0 && z<zTerm ){
31914 SQLITE_SKIP_UTF8(z);
31915 r++;
31916 }
31917 return r;
31918}
31919
31920/* This test function is not currently used by the automated test-suite.
31921** Hence it is only available in debug builds.
31922*/
31923#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
31924/*
31925** Translate UTF-8 to UTF-8.
31926**
31927** This has the effect of making sure that the string is well-formed
31928** UTF-8. Miscoded characters are removed.
31929**
31930** The translation is done in-place and aborted if the output
31931** overruns the input.
31932*/
31933SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
31934 unsigned char *zOut = zIn;
31935 unsigned char *zStart = zIn;
31936 u32 c;
31937
31938 while( zIn[0] && zOut<=zIn ){
31939 c = sqlite3Utf8Read((const u8**)&zIn);
31940 if( c!=0xfffd ){
31941 WRITE_UTF8(zOut, c);
31942 }
31943 }
31944 *zOut = 0;
31945 return (int)(zOut - zStart);
31946}
31947#endif
31948
31949#ifndef SQLITE_OMIT_UTF16
31950/*
31951** Convert a UTF-16 string in the native encoding into a UTF-8 string.
31952** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
31953** be freed by the calling function.
31954**
31955** NULL is returned if there is an allocation error.
31956*/
31957SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
31958 Mem m;
31959 memset(s: &m, c: 0, n: sizeof(m));
31960 m.db = db;
31961 sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
31962 sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
31963 if( db->mallocFailed ){
31964 sqlite3VdbeMemRelease(p: &m);
31965 m.z = 0;
31966 }
31967 assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
31968 assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
31969 assert( m.z || db->mallocFailed );
31970 return m.z;
31971}
31972
31973/*
31974** zIn is a UTF-16 encoded unicode string at least nChar characters long.
31975** Return the number of bytes in the first nChar unicode characters
31976** in pZ. nChar must be non-negative.
31977*/
31978SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
31979 int c;
31980 unsigned char const *z = zIn;
31981 int n = 0;
31982
31983 if( SQLITE_UTF16NATIVE==SQLITE_UTF16LE ) z++;
31984 while( n<nChar ){
31985 c = z[0];
31986 z += 2;
31987 if( c>=0xd8 && c<0xdc && z[0]>=0xdc && z[0]<0xe0 ) z += 2;
31988 n++;
31989 }
31990 return (int)(z-(unsigned char const *)zIn)
31991 - (SQLITE_UTF16NATIVE==SQLITE_UTF16LE);
31992}
31993
31994#if defined(SQLITE_TEST)
31995/*
31996** This routine is called from the TCL test function "translate_selftest".
31997** It checks that the primitives for serializing and deserializing
31998** characters in each encoding are inverses of each other.
31999*/
32000SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
32001 unsigned int i, t;
32002 unsigned char zBuf[20];
32003 unsigned char *z;
32004 int n;
32005 unsigned int c;
32006
32007 for(i=0; i<0x00110000; i++){
32008 z = zBuf;
32009 WRITE_UTF8(z, i);
32010 n = (int)(z-zBuf);
32011 assert( n>0 && n<=4 );
32012 z[0] = 0;
32013 z = zBuf;
32014 c = sqlite3Utf8Read((const u8**)&z);
32015 t = i;
32016 if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
32017 if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
32018 assert( c==t );
32019 assert( (z-zBuf)==n );
32020 }
32021}
32022#endif /* SQLITE_TEST */
32023#endif /* SQLITE_OMIT_UTF16 */
32024
32025/************** End of utf.c *************************************************/
32026/************** Begin file util.c ********************************************/
32027/*
32028** 2001 September 15
32029**
32030** The author disclaims copyright to this source code. In place of
32031** a legal notice, here is a blessing:
32032**
32033** May you do good and not evil.
32034** May you find forgiveness for yourself and forgive others.
32035** May you share freely, never taking more than you give.
32036**
32037*************************************************************************
32038** Utility functions used throughout sqlite.
32039**
32040** This file contains functions for allocating memory, comparing
32041** strings, and stuff like that.
32042**
32043*/
32044/* #include "sqliteInt.h" */
32045/* #include <stdarg.h> */
32046#ifndef SQLITE_OMIT_FLOATING_POINT
32047#include <math.h>
32048#endif
32049
32050/*
32051** Calls to sqlite3FaultSim() are used to simulate a failure during testing,
32052** or to bypass normal error detection during testing in order to let
32053** execute proceed futher downstream.
32054**
32055** In deployment, sqlite3FaultSim() *always* return SQLITE_OK (0). The
32056** sqlite3FaultSim() function only returns non-zero during testing.
32057**
32058** During testing, if the test harness has set a fault-sim callback using
32059** a call to sqlite3_test_control(SQLITE_TESTCTRL_FAULT_INSTALL), then
32060** each call to sqlite3FaultSim() is relayed to that application-supplied
32061** callback and the integer return value form the application-supplied
32062** callback is returned by sqlite3FaultSim().
32063**
32064** The integer argument to sqlite3FaultSim() is a code to identify which
32065** sqlite3FaultSim() instance is being invoked. Each call to sqlite3FaultSim()
32066** should have a unique code. To prevent legacy testing applications from
32067** breaking, the codes should not be changed or reused.
32068*/
32069#ifndef SQLITE_UNTESTABLE
32070SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
32071 int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
32072 return xCallback ? xCallback(iTest) : SQLITE_OK;
32073}
32074#endif
32075
32076#ifndef SQLITE_OMIT_FLOATING_POINT
32077/*
32078** Return true if the floating point value is Not a Number (NaN).
32079**
32080** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
32081** Otherwise, we have our own implementation that works on most systems.
32082*/
32083SQLITE_PRIVATE int sqlite3IsNaN(double x){
32084 int rc; /* The value return */
32085#if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
32086 u64 y;
32087 memcpy(dest: &y,src: &x,n: sizeof(y));
32088 rc = IsNaN(y);
32089#else
32090 rc = isnan(x);
32091#endif /* HAVE_ISNAN */
32092 testcase( rc );
32093 return rc;
32094}
32095#endif /* SQLITE_OMIT_FLOATING_POINT */
32096
32097/*
32098** Compute a string length that is limited to what can be stored in
32099** lower 30 bits of a 32-bit signed integer.
32100**
32101** The value returned will never be negative. Nor will it ever be greater
32102** than the actual length of the string. For very long strings (greater
32103** than 1GiB) the value returned might be less than the true string length.
32104*/
32105SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
32106 if( z==0 ) return 0;
32107 return 0x3fffffff & (int)strlen(s: z);
32108}
32109
32110/*
32111** Return the declared type of a column. Or return zDflt if the column
32112** has no declared type.
32113**
32114** The column type is an extra string stored after the zero-terminator on
32115** the column name if and only if the COLFLAG_HASTYPE flag is set.
32116*/
32117SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
32118 if( pCol->colFlags & COLFLAG_HASTYPE ){
32119 return pCol->zCnName + strlen(s: pCol->zCnName) + 1;
32120 }else if( pCol->eCType ){
32121 assert( pCol->eCType<=SQLITE_N_STDTYPE );
32122 return (char*)sqlite3StdType[pCol->eCType-1];
32123 }else{
32124 return zDflt;
32125 }
32126}
32127
32128/*
32129** Helper function for sqlite3Error() - called rarely. Broken out into
32130** a separate routine to avoid unnecessary register saves on entry to
32131** sqlite3Error().
32132*/
32133static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){
32134 if( db->pErr ) sqlite3ValueSetNull(db->pErr);
32135 sqlite3SystemError(db, err_code);
32136}
32137
32138/*
32139** Set the current error code to err_code and clear any prior error message.
32140** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
32141** that would be appropriate.
32142*/
32143SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
32144 assert( db!=0 );
32145 db->errCode = err_code;
32146 if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
32147}
32148
32149/*
32150** The equivalent of sqlite3Error(db, SQLITE_OK). Clear the error state
32151** and error message.
32152*/
32153SQLITE_PRIVATE void sqlite3ErrorClear(sqlite3 *db){
32154 assert( db!=0 );
32155 db->errCode = SQLITE_OK;
32156 if( db->pErr ) sqlite3ValueSetNull(db->pErr);
32157}
32158
32159/*
32160** Load the sqlite3.iSysErrno field if that is an appropriate thing
32161** to do based on the SQLite error code in rc.
32162*/
32163SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
32164 if( rc==SQLITE_IOERR_NOMEM ) return;
32165 rc &= 0xff;
32166 if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
32167 db->iSysErrno = sqlite3OsGetLastError(pVfs: db->pVfs);
32168 }
32169}
32170
32171/*
32172** Set the most recent error code and error string for the sqlite
32173** handle "db". The error code is set to "err_code".
32174**
32175** If it is not NULL, string zFormat specifies the format of the
32176** error string in the style of the printf functions: The following
32177** format characters are allowed:
32178**
32179** %s Insert a string
32180** %z A string that should be freed after use
32181** %d Insert an integer
32182** %T Insert a token
32183** %S Insert the first element of a SrcList
32184**
32185** zFormat and any string tokens that follow it are assumed to be
32186** encoded in UTF-8.
32187**
32188** To clear the most recent error for sqlite handle "db", sqlite3Error
32189** should be called with err_code set to SQLITE_OK and zFormat set
32190** to NULL.
32191*/
32192SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
32193 assert( db!=0 );
32194 db->errCode = err_code;
32195 sqlite3SystemError(db, rc: err_code);
32196 if( zFormat==0 ){
32197 sqlite3Error(db, err_code);
32198 }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
32199 char *z;
32200 va_list ap;
32201 va_start(ap, zFormat);
32202 z = sqlite3VMPrintf(db, zFormat, ap);
32203 va_end(ap);
32204 sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
32205 }
32206}
32207
32208/*
32209** Add an error message to pParse->zErrMsg and increment pParse->nErr.
32210** The following formatting characters are allowed:
32211**
32212** %s Insert a string
32213** %z A string that should be freed after use
32214** %d Insert an integer
32215** %T Insert a token
32216** %S Insert the first element of a SrcList
32217**
32218** This function should be used to report any error that occurs while
32219** compiling an SQL statement (i.e. within sqlite3_prepare()). The
32220** last thing the sqlite3_prepare() function does is copy the error
32221** stored by this function into the database handle using sqlite3Error().
32222** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
32223** during statement execution (sqlite3_step() etc.).
32224*/
32225SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
32226 char *zMsg;
32227 va_list ap;
32228 sqlite3 *db = pParse->db;
32229 va_start(ap, zFormat);
32230 zMsg = sqlite3VMPrintf(db, zFormat, ap);
32231 va_end(ap);
32232 if( db->suppressErr ){
32233 sqlite3DbFree(db, p: zMsg);
32234 }else{
32235 pParse->nErr++;
32236 sqlite3DbFree(db, p: pParse->zErrMsg);
32237 pParse->zErrMsg = zMsg;
32238 pParse->rc = SQLITE_ERROR;
32239 pParse->pWith = 0;
32240 }
32241}
32242
32243/*
32244** If database connection db is currently parsing SQL, then transfer
32245** error code errCode to that parser if the parser has not already
32246** encountered some other kind of error.
32247*/
32248SQLITE_PRIVATE int sqlite3ErrorToParser(sqlite3 *db, int errCode){
32249 Parse *pParse;
32250 if( db==0 || (pParse = db->pParse)==0 ) return errCode;
32251 pParse->rc = errCode;
32252 pParse->nErr++;
32253 return errCode;
32254}
32255
32256/*
32257** Convert an SQL-style quoted string into a normal string by removing
32258** the quote characters. The conversion is done in-place. If the
32259** input does not begin with a quote character, then this routine
32260** is a no-op.
32261**
32262** The input string must be zero-terminated. A new zero-terminator
32263** is added to the dequoted string.
32264**
32265** The return value is -1 if no dequoting occurs or the length of the
32266** dequoted string, exclusive of the zero terminator, if dequoting does
32267** occur.
32268**
32269** 2002-02-14: This routine is extended to remove MS-Access style
32270** brackets from around identifiers. For example: "[a-b-c]" becomes
32271** "a-b-c".
32272*/
32273SQLITE_PRIVATE void sqlite3Dequote(char *z){
32274 char quote;
32275 int i, j;
32276 if( z==0 ) return;
32277 quote = z[0];
32278 if( !sqlite3Isquote(quote) ) return;
32279 if( quote=='[' ) quote = ']';
32280 for(i=1, j=0;; i++){
32281 assert( z[i] );
32282 if( z[i]==quote ){
32283 if( z[i+1]==quote ){
32284 z[j++] = quote;
32285 i++;
32286 }else{
32287 break;
32288 }
32289 }else{
32290 z[j++] = z[i];
32291 }
32292 }
32293 z[j] = 0;
32294}
32295SQLITE_PRIVATE void sqlite3DequoteExpr(Expr *p){
32296 assert( !ExprHasProperty(p, EP_IntValue) );
32297 assert( sqlite3Isquote(p->u.zToken[0]) );
32298 p->flags |= p->u.zToken[0]=='"' ? EP_Quoted|EP_DblQuoted : EP_Quoted;
32299 sqlite3Dequote(z: p->u.zToken);
32300}
32301
32302/*
32303** If the input token p is quoted, try to adjust the token to remove
32304** the quotes. This is not always possible:
32305**
32306** "abc" -> abc
32307** "ab""cd" -> (not possible because of the interior "")
32308**
32309** Remove the quotes if possible. This is a optimization. The overall
32310** system should still return the correct answer even if this routine
32311** is always a no-op.
32312*/
32313SQLITE_PRIVATE void sqlite3DequoteToken(Token *p){
32314 unsigned int i;
32315 if( p->n<2 ) return;
32316 if( !sqlite3Isquote(p->z[0]) ) return;
32317 for(i=1; i<p->n-1; i++){
32318 if( sqlite3Isquote(p->z[i]) ) return;
32319 }
32320 p->n -= 2;
32321 p->z++;
32322}
32323
32324/*
32325** Generate a Token object from a string
32326*/
32327SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
32328 p->z = z;
32329 p->n = sqlite3Strlen30(z);
32330}
32331
32332/* Convenient short-hand */
32333#define UpperToLower sqlite3UpperToLower
32334
32335/*
32336** Some systems have stricmp(). Others have strcasecmp(). Because
32337** there is no consistency, we will define our own.
32338**
32339** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
32340** sqlite3_strnicmp() APIs allow applications and extensions to compare
32341** the contents of two buffers containing UTF-8 strings in a
32342** case-independent fashion, using the same definition of "case
32343** independence" that SQLite uses internally when comparing identifiers.
32344*/
32345SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
32346 if( zLeft==0 ){
32347 return zRight ? -1 : 0;
32348 }else if( zRight==0 ){
32349 return 1;
32350 }
32351 return sqlite3StrICmp(zLeft, zRight);
32352}
32353SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
32354 unsigned char *a, *b;
32355 int c, x;
32356 a = (unsigned char *)zLeft;
32357 b = (unsigned char *)zRight;
32358 for(;;){
32359 c = *a;
32360 x = *b;
32361 if( c==x ){
32362 if( c==0 ) break;
32363 }else{
32364 c = (int)UpperToLower[c] - (int)UpperToLower[x];
32365 if( c ) break;
32366 }
32367 a++;
32368 b++;
32369 }
32370 return c;
32371}
32372SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
32373 register unsigned char *a, *b;
32374 if( zLeft==0 ){
32375 return zRight ? -1 : 0;
32376 }else if( zRight==0 ){
32377 return 1;
32378 }
32379 a = (unsigned char *)zLeft;
32380 b = (unsigned char *)zRight;
32381 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
32382 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
32383}
32384
32385/*
32386** Compute an 8-bit hash on a string that is insensitive to case differences
32387*/
32388SQLITE_PRIVATE u8 sqlite3StrIHash(const char *z){
32389 u8 h = 0;
32390 if( z==0 ) return 0;
32391 while( z[0] ){
32392 h += UpperToLower[(unsigned char)z[0]];
32393 z++;
32394 }
32395 return h;
32396}
32397
32398/*
32399** Compute 10 to the E-th power. Examples: E==1 results in 10.
32400** E==2 results in 100. E==50 results in 1.0e50.
32401**
32402** This routine only works for values of E between 1 and 341.
32403*/
32404static LONGDOUBLE_TYPE sqlite3Pow10(int E){
32405#if defined(_MSC_VER)
32406 static const LONGDOUBLE_TYPE x[] = {
32407 1.0e+001L,
32408 1.0e+002L,
32409 1.0e+004L,
32410 1.0e+008L,
32411 1.0e+016L,
32412 1.0e+032L,
32413 1.0e+064L,
32414 1.0e+128L,
32415 1.0e+256L
32416 };
32417 LONGDOUBLE_TYPE r = 1.0;
32418 int i;
32419 assert( E>=0 && E<=307 );
32420 for(i=0; E!=0; i++, E >>=1){
32421 if( E & 1 ) r *= x[i];
32422 }
32423 return r;
32424#else
32425 LONGDOUBLE_TYPE x = 10.0;
32426 LONGDOUBLE_TYPE r = 1.0;
32427 while(1){
32428 if( E & 1 ) r *= x;
32429 E >>= 1;
32430 if( E==0 ) break;
32431 x *= x;
32432 }
32433 return r;
32434#endif
32435}
32436
32437/*
32438** The string z[] is an text representation of a real number.
32439** Convert this string to a double and write it into *pResult.
32440**
32441** The string z[] is length bytes in length (bytes, not characters) and
32442** uses the encoding enc. The string is not necessarily zero-terminated.
32443**
32444** Return TRUE if the result is a valid real number (or integer) and FALSE
32445** if the string is empty or contains extraneous text. More specifically
32446** return
32447** 1 => The input string is a pure integer
32448** 2 or more => The input has a decimal point or eNNN clause
32449** 0 or less => The input string is not a valid number
32450** -1 => Not a valid number, but has a valid prefix which
32451** includes a decimal point and/or an eNNN clause
32452**
32453** Valid numbers are in one of these formats:
32454**
32455** [+-]digits[E[+-]digits]
32456** [+-]digits.[digits][E[+-]digits]
32457** [+-].digits[E[+-]digits]
32458**
32459** Leading and trailing whitespace is ignored for the purpose of determining
32460** validity.
32461**
32462** If some prefix of the input string is a valid number, this routine
32463** returns FALSE but it still converts the prefix and writes the result
32464** into *pResult.
32465*/
32466#if defined(_MSC_VER)
32467#pragma warning(disable : 4756)
32468#endif
32469SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
32470#ifndef SQLITE_OMIT_FLOATING_POINT
32471 int incr;
32472 const char *zEnd;
32473 /* sign * significand * (10 ^ (esign * exponent)) */
32474 int sign = 1; /* sign of significand */
32475 i64 s = 0; /* significand */
32476 int d = 0; /* adjust exponent for shifting decimal point */
32477 int esign = 1; /* sign of exponent */
32478 int e = 0; /* exponent */
32479 int eValid = 1; /* True exponent is either not used or is well-formed */
32480 double result;
32481 int nDigit = 0; /* Number of digits processed */
32482 int eType = 1; /* 1: pure integer, 2+: fractional -1 or less: bad UTF16 */
32483
32484 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
32485 *pResult = 0.0; /* Default return value, in case of an error */
32486 if( length==0 ) return 0;
32487
32488 if( enc==SQLITE_UTF8 ){
32489 incr = 1;
32490 zEnd = z + length;
32491 }else{
32492 int i;
32493 incr = 2;
32494 length &= ~1;
32495 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
32496 testcase( enc==SQLITE_UTF16LE );
32497 testcase( enc==SQLITE_UTF16BE );
32498 for(i=3-enc; i<length && z[i]==0; i+=2){}
32499 if( i<length ) eType = -100;
32500 zEnd = &z[i^1];
32501 z += (enc&1);
32502 }
32503
32504 /* skip leading spaces */
32505 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
32506 if( z>=zEnd ) return 0;
32507
32508 /* get sign of significand */
32509 if( *z=='-' ){
32510 sign = -1;
32511 z+=incr;
32512 }else if( *z=='+' ){
32513 z+=incr;
32514 }
32515
32516 /* copy max significant digits to significand */
32517 while( z<zEnd && sqlite3Isdigit(*z) ){
32518 s = s*10 + (*z - '0');
32519 z+=incr; nDigit++;
32520 if( s>=((LARGEST_INT64-9)/10) ){
32521 /* skip non-significant significand digits
32522 ** (increase exponent by d to shift decimal left) */
32523 while( z<zEnd && sqlite3Isdigit(*z) ){ z+=incr; d++; }
32524 }
32525 }
32526 if( z>=zEnd ) goto do_atof_calc;
32527
32528 /* if decimal point is present */
32529 if( *z=='.' ){
32530 z+=incr;
32531 eType++;
32532 /* copy digits from after decimal to significand
32533 ** (decrease exponent by d to shift decimal right) */
32534 while( z<zEnd && sqlite3Isdigit(*z) ){
32535 if( s<((LARGEST_INT64-9)/10) ){
32536 s = s*10 + (*z - '0');
32537 d--;
32538 nDigit++;
32539 }
32540 z+=incr;
32541 }
32542 }
32543 if( z>=zEnd ) goto do_atof_calc;
32544
32545 /* if exponent is present */
32546 if( *z=='e' || *z=='E' ){
32547 z+=incr;
32548 eValid = 0;
32549 eType++;
32550
32551 /* This branch is needed to avoid a (harmless) buffer overread. The
32552 ** special comment alerts the mutation tester that the correct answer
32553 ** is obtained even if the branch is omitted */
32554 if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
32555
32556 /* get sign of exponent */
32557 if( *z=='-' ){
32558 esign = -1;
32559 z+=incr;
32560 }else if( *z=='+' ){
32561 z+=incr;
32562 }
32563 /* copy digits to exponent */
32564 while( z<zEnd && sqlite3Isdigit(*z) ){
32565 e = e<10000 ? (e*10 + (*z - '0')) : 10000;
32566 z+=incr;
32567 eValid = 1;
32568 }
32569 }
32570
32571 /* skip trailing spaces */
32572 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
32573
32574do_atof_calc:
32575 /* adjust exponent by d, and update sign */
32576 e = (e*esign) + d;
32577 if( e<0 ) {
32578 esign = -1;
32579 e *= -1;
32580 } else {
32581 esign = 1;
32582 }
32583
32584 if( s==0 ) {
32585 /* In the IEEE 754 standard, zero is signed. */
32586 result = sign<0 ? -(double)0 : (double)0;
32587 } else {
32588 /* Attempt to reduce exponent.
32589 **
32590 ** Branches that are not required for the correct answer but which only
32591 ** help to obtain the correct answer faster are marked with special
32592 ** comments, as a hint to the mutation tester.
32593 */
32594 while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
32595 if( esign>0 ){
32596 if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
32597 s *= 10;
32598 }else{
32599 if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
32600 s /= 10;
32601 }
32602 e--;
32603 }
32604
32605 /* adjust the sign of significand */
32606 s = sign<0 ? -s : s;
32607
32608 if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
32609 result = (double)s;
32610 }else{
32611 /* attempt to handle extremely small/large numbers better */
32612 if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
32613 if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
32614 LONGDOUBLE_TYPE scale = sqlite3Pow10(E: e-308);
32615 if( esign<0 ){
32616 result = s / scale;
32617 result /= 1.0e+308;
32618 }else{
32619 result = s * scale;
32620 result *= 1.0e+308;
32621 }
32622 }else{ assert( e>=342 );
32623 if( esign<0 ){
32624 result = 0.0*s;
32625 }else{
32626#ifdef INFINITY
32627 result = INFINITY*s;
32628#else
32629 result = 1e308*1e308*s; /* Infinity */
32630#endif
32631 }
32632 }
32633 }else{
32634 LONGDOUBLE_TYPE scale = sqlite3Pow10(E: e);
32635 if( esign<0 ){
32636 result = s / scale;
32637 }else{
32638 result = s * scale;
32639 }
32640 }
32641 }
32642 }
32643
32644 /* store the result */
32645 *pResult = result;
32646
32647 /* return true if number and no extra non-whitespace chracters after */
32648 if( z==zEnd && nDigit>0 && eValid && eType>0 ){
32649 return eType;
32650 }else if( eType>=2 && (eType==3 || eValid) && nDigit>0 ){
32651 return -1;
32652 }else{
32653 return 0;
32654 }
32655#else
32656 return !sqlite3Atoi64(z, pResult, length, enc);
32657#endif /* SQLITE_OMIT_FLOATING_POINT */
32658}
32659#if defined(_MSC_VER)
32660#pragma warning(default : 4756)
32661#endif
32662
32663/*
32664** Render an signed 64-bit integer as text. Store the result in zOut[].
32665**
32666** The caller must ensure that zOut[] is at least 21 bytes in size.
32667*/
32668SQLITE_PRIVATE void sqlite3Int64ToText(i64 v, char *zOut){
32669 int i;
32670 u64 x;
32671 char zTemp[22];
32672 if( v<0 ){
32673 x = (v==SMALLEST_INT64) ? ((u64)1)<<63 : (u64)-v;
32674 }else{
32675 x = v;
32676 }
32677 i = sizeof(zTemp)-2;
32678 zTemp[sizeof(zTemp)-1] = 0;
32679 do{
32680 zTemp[i--] = (x%10) + '0';
32681 x = x/10;
32682 }while( x );
32683 if( v<0 ) zTemp[i--] = '-';
32684 memcpy(dest: zOut, src: &zTemp[i+1], n: sizeof(zTemp)-1-i);
32685}
32686
32687/*
32688** Compare the 19-character string zNum against the text representation
32689** value 2^63: 9223372036854775808. Return negative, zero, or positive
32690** if zNum is less than, equal to, or greater than the string.
32691** Note that zNum must contain exactly 19 characters.
32692**
32693** Unlike memcmp() this routine is guaranteed to return the difference
32694** in the values of the last digit if the only difference is in the
32695** last digit. So, for example,
32696**
32697** compare2pow63("9223372036854775800", 1)
32698**
32699** will return -8.
32700*/
32701static int compare2pow63(const char *zNum, int incr){
32702 int c = 0;
32703 int i;
32704 /* 012345678901234567 */
32705 const char *pow63 = "922337203685477580";
32706 for(i=0; c==0 && i<18; i++){
32707 c = (zNum[i*incr]-pow63[i])*10;
32708 }
32709 if( c==0 ){
32710 c = zNum[18*incr] - '8';
32711 testcase( c==(-1) );
32712 testcase( c==0 );
32713 testcase( c==(+1) );
32714 }
32715 return c;
32716}
32717
32718/*
32719** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
32720** routine does *not* accept hexadecimal notation.
32721**
32722** Returns:
32723**
32724** -1 Not even a prefix of the input text looks like an integer
32725** 0 Successful transformation. Fits in a 64-bit signed integer.
32726** 1 Excess non-space text after the integer value
32727** 2 Integer too large for a 64-bit signed integer or is malformed
32728** 3 Special case of 9223372036854775808
32729**
32730** length is the number of bytes in the string (bytes, not characters).
32731** The string is not necessarily zero-terminated. The encoding is
32732** given by enc.
32733*/
32734SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
32735 int incr;
32736 u64 u = 0;
32737 int neg = 0; /* assume positive */
32738 int i;
32739 int c = 0;
32740 int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
32741 int rc; /* Baseline return code */
32742 const char *zStart;
32743 const char *zEnd = zNum + length;
32744 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
32745 if( enc==SQLITE_UTF8 ){
32746 incr = 1;
32747 }else{
32748 incr = 2;
32749 length &= ~1;
32750 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
32751 for(i=3-enc; i<length && zNum[i]==0; i+=2){}
32752 nonNum = i<length;
32753 zEnd = &zNum[i^1];
32754 zNum += (enc&1);
32755 }
32756 while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
32757 if( zNum<zEnd ){
32758 if( *zNum=='-' ){
32759 neg = 1;
32760 zNum+=incr;
32761 }else if( *zNum=='+' ){
32762 zNum+=incr;
32763 }
32764 }
32765 zStart = zNum;
32766 while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
32767 for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
32768 u = u*10 + c - '0';
32769 }
32770 testcase( i==18*incr );
32771 testcase( i==19*incr );
32772 testcase( i==20*incr );
32773 if( u>LARGEST_INT64 ){
32774 /* This test and assignment is needed only to suppress UB warnings
32775 ** from clang and -fsanitize=undefined. This test and assignment make
32776 ** the code a little larger and slower, and no harm comes from omitting
32777 ** them, but we must appaise the undefined-behavior pharisees. */
32778 *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
32779 }else if( neg ){
32780 *pNum = -(i64)u;
32781 }else{
32782 *pNum = (i64)u;
32783 }
32784 rc = 0;
32785 if( i==0 && zStart==zNum ){ /* No digits */
32786 rc = -1;
32787 }else if( nonNum ){ /* UTF16 with high-order bytes non-zero */
32788 rc = 1;
32789 }else if( &zNum[i]<zEnd ){ /* Extra bytes at the end */
32790 int jj = i;
32791 do{
32792 if( !sqlite3Isspace(zNum[jj]) ){
32793 rc = 1; /* Extra non-space text after the integer */
32794 break;
32795 }
32796 jj += incr;
32797 }while( &zNum[jj]<zEnd );
32798 }
32799 if( i<19*incr ){
32800 /* Less than 19 digits, so we know that it fits in 64 bits */
32801 assert( u<=LARGEST_INT64 );
32802 return rc;
32803 }else{
32804 /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
32805 c = i>19*incr ? 1 : compare2pow63(zNum, incr);
32806 if( c<0 ){
32807 /* zNum is less than 9223372036854775808 so it fits */
32808 assert( u<=LARGEST_INT64 );
32809 return rc;
32810 }else{
32811 *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
32812 if( c>0 ){
32813 /* zNum is greater than 9223372036854775808 so it overflows */
32814 return 2;
32815 }else{
32816 /* zNum is exactly 9223372036854775808. Fits if negative. The
32817 ** special case 2 overflow if positive */
32818 assert( u-1==LARGEST_INT64 );
32819 return neg ? rc : 3;
32820 }
32821 }
32822 }
32823}
32824
32825/*
32826** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
32827** into a 64-bit signed integer. This routine accepts hexadecimal literals,
32828** whereas sqlite3Atoi64() does not.
32829**
32830** Returns:
32831**
32832** 0 Successful transformation. Fits in a 64-bit signed integer.
32833** 1 Excess text after the integer value
32834** 2 Integer too large for a 64-bit signed integer or is malformed
32835** 3 Special case of 9223372036854775808
32836*/
32837SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
32838#ifndef SQLITE_OMIT_HEX_INTEGER
32839 if( z[0]=='0'
32840 && (z[1]=='x' || z[1]=='X')
32841 ){
32842 u64 u = 0;
32843 int i, k;
32844 for(i=2; z[i]=='0'; i++){}
32845 for(k=i; sqlite3Isxdigit(z[k]); k++){
32846 u = u*16 + sqlite3HexToInt(h: z[k]);
32847 }
32848 memcpy(dest: pOut, src: &u, n: 8);
32849 return (z[k]==0 && k-i<=16) ? 0 : 2;
32850 }else
32851#endif /* SQLITE_OMIT_HEX_INTEGER */
32852 {
32853 return sqlite3Atoi64(zNum: z, pNum: pOut, length: sqlite3Strlen30(z), SQLITE_UTF8);
32854 }
32855}
32856
32857/*
32858** If zNum represents an integer that will fit in 32-bits, then set
32859** *pValue to that integer and return true. Otherwise return false.
32860**
32861** This routine accepts both decimal and hexadecimal notation for integers.
32862**
32863** Any non-numeric characters that following zNum are ignored.
32864** This is different from sqlite3Atoi64() which requires the
32865** input number to be zero-terminated.
32866*/
32867SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
32868 sqlite_int64 v = 0;
32869 int i, c;
32870 int neg = 0;
32871 if( zNum[0]=='-' ){
32872 neg = 1;
32873 zNum++;
32874 }else if( zNum[0]=='+' ){
32875 zNum++;
32876 }
32877#ifndef SQLITE_OMIT_HEX_INTEGER
32878 else if( zNum[0]=='0'
32879 && (zNum[1]=='x' || zNum[1]=='X')
32880 && sqlite3Isxdigit(zNum[2])
32881 ){
32882 u32 u = 0;
32883 zNum += 2;
32884 while( zNum[0]=='0' ) zNum++;
32885 for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
32886 u = u*16 + sqlite3HexToInt(h: zNum[i]);
32887 }
32888 if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
32889 memcpy(dest: pValue, src: &u, n: 4);
32890 return 1;
32891 }else{
32892 return 0;
32893 }
32894 }
32895#endif
32896 if( !sqlite3Isdigit(zNum[0]) ) return 0;
32897 while( zNum[0]=='0' ) zNum++;
32898 for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
32899 v = v*10 + c;
32900 }
32901
32902 /* The longest decimal representation of a 32 bit integer is 10 digits:
32903 **
32904 ** 1234567890
32905 ** 2^31 -> 2147483648
32906 */
32907 testcase( i==10 );
32908 if( i>10 ){
32909 return 0;
32910 }
32911 testcase( v-neg==2147483647 );
32912 if( v-neg>2147483647 ){
32913 return 0;
32914 }
32915 if( neg ){
32916 v = -v;
32917 }
32918 *pValue = (int)v;
32919 return 1;
32920}
32921
32922/*
32923** Return a 32-bit integer value extracted from a string. If the
32924** string is not an integer, just return 0.
32925*/
32926SQLITE_PRIVATE int sqlite3Atoi(const char *z){
32927 int x = 0;
32928 sqlite3GetInt32(zNum: z, pValue: &x);
32929 return x;
32930}
32931
32932/*
32933** Try to convert z into an unsigned 32-bit integer. Return true on
32934** success and false if there is an error.
32935**
32936** Only decimal notation is accepted.
32937*/
32938SQLITE_PRIVATE int sqlite3GetUInt32(const char *z, u32 *pI){
32939 u64 v = 0;
32940 int i;
32941 for(i=0; sqlite3Isdigit(z[i]); i++){
32942 v = v*10 + z[i] - '0';
32943 if( v>4294967296LL ){ *pI = 0; return 0; }
32944 }
32945 if( i==0 || z[i]!=0 ){ *pI = 0; return 0; }
32946 *pI = (u32)v;
32947 return 1;
32948}
32949
32950/*
32951** The variable-length integer encoding is as follows:
32952**
32953** KEY:
32954** A = 0xxxxxxx 7 bits of data and one flag bit
32955** B = 1xxxxxxx 7 bits of data and one flag bit
32956** C = xxxxxxxx 8 bits of data
32957**
32958** 7 bits - A
32959** 14 bits - BA
32960** 21 bits - BBA
32961** 28 bits - BBBA
32962** 35 bits - BBBBA
32963** 42 bits - BBBBBA
32964** 49 bits - BBBBBBA
32965** 56 bits - BBBBBBBA
32966** 64 bits - BBBBBBBBC
32967*/
32968
32969/*
32970** Write a 64-bit variable-length integer to memory starting at p[0].
32971** The length of data write will be between 1 and 9 bytes. The number
32972** of bytes written is returned.
32973**
32974** A variable-length integer consists of the lower 7 bits of each byte
32975** for all bytes that have the 8th bit set and one byte with the 8th
32976** bit clear. Except, if we get to the 9th byte, it stores the full
32977** 8 bits and is the last byte.
32978*/
32979static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
32980 int i, j, n;
32981 u8 buf[10];
32982 if( v & (((u64)0xff000000)<<32) ){
32983 p[8] = (u8)v;
32984 v >>= 8;
32985 for(i=7; i>=0; i--){
32986 p[i] = (u8)((v & 0x7f) | 0x80);
32987 v >>= 7;
32988 }
32989 return 9;
32990 }
32991 n = 0;
32992 do{
32993 buf[n++] = (u8)((v & 0x7f) | 0x80);
32994 v >>= 7;
32995 }while( v!=0 );
32996 buf[0] &= 0x7f;
32997 assert( n<=9 );
32998 for(i=0, j=n-1; j>=0; j--, i++){
32999 p[i] = buf[j];
33000 }
33001 return n;
33002}
33003SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
33004 if( v<=0x7f ){
33005 p[0] = v&0x7f;
33006 return 1;
33007 }
33008 if( v<=0x3fff ){
33009 p[0] = ((v>>7)&0x7f)|0x80;
33010 p[1] = v&0x7f;
33011 return 2;
33012 }
33013 return putVarint64(p,v);
33014}
33015
33016/*
33017** Bitmasks used by sqlite3GetVarint(). These precomputed constants
33018** are defined here rather than simply putting the constant expressions
33019** inline in order to work around bugs in the RVT compiler.
33020**
33021** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
33022**
33023** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
33024*/
33025#define SLOT_2_0 0x001fc07f
33026#define SLOT_4_2_0 0xf01fc07f
33027
33028
33029/*
33030** Read a 64-bit variable-length integer from memory starting at p[0].
33031** Return the number of bytes read. The value is stored in *v.
33032*/
33033SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
33034 u32 a,b,s;
33035
33036 if( ((signed char*)p)[0]>=0 ){
33037 *v = *p;
33038 return 1;
33039 }
33040 if( ((signed char*)p)[1]>=0 ){
33041 *v = ((u32)(p[0]&0x7f)<<7) | p[1];
33042 return 2;
33043 }
33044
33045 /* Verify that constants are precomputed correctly */
33046 assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
33047 assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
33048
33049 a = ((u32)p[0])<<14;
33050 b = p[1];
33051 p += 2;
33052 a |= *p;
33053 /* a: p0<<14 | p2 (unmasked) */
33054 if (!(a&0x80))
33055 {
33056 a &= SLOT_2_0;
33057 b &= 0x7f;
33058 b = b<<7;
33059 a |= b;
33060 *v = a;
33061 return 3;
33062 }
33063
33064 /* CSE1 from below */
33065 a &= SLOT_2_0;
33066 p++;
33067 b = b<<14;
33068 b |= *p;
33069 /* b: p1<<14 | p3 (unmasked) */
33070 if (!(b&0x80))
33071 {
33072 b &= SLOT_2_0;
33073 /* moved CSE1 up */
33074 /* a &= (0x7f<<14)|(0x7f); */
33075 a = a<<7;
33076 a |= b;
33077 *v = a;
33078 return 4;
33079 }
33080
33081 /* a: p0<<14 | p2 (masked) */
33082 /* b: p1<<14 | p3 (unmasked) */
33083 /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
33084 /* moved CSE1 up */
33085 /* a &= (0x7f<<14)|(0x7f); */
33086 b &= SLOT_2_0;
33087 s = a;
33088 /* s: p0<<14 | p2 (masked) */
33089
33090 p++;
33091 a = a<<14;
33092 a |= *p;
33093 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
33094 if (!(a&0x80))
33095 {
33096 /* we can skip these cause they were (effectively) done above
33097 ** while calculating s */
33098 /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
33099 /* b &= (0x7f<<14)|(0x7f); */
33100 b = b<<7;
33101 a |= b;
33102 s = s>>18;
33103 *v = ((u64)s)<<32 | a;
33104 return 5;
33105 }
33106
33107 /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
33108 s = s<<7;
33109 s |= b;
33110 /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
33111
33112 p++;
33113 b = b<<14;
33114 b |= *p;
33115 /* b: p1<<28 | p3<<14 | p5 (unmasked) */
33116 if (!(b&0x80))
33117 {
33118 /* we can skip this cause it was (effectively) done above in calc'ing s */
33119 /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
33120 a &= SLOT_2_0;
33121 a = a<<7;
33122 a |= b;
33123 s = s>>18;
33124 *v = ((u64)s)<<32 | a;
33125 return 6;
33126 }
33127
33128 p++;
33129 a = a<<14;
33130 a |= *p;
33131 /* a: p2<<28 | p4<<14 | p6 (unmasked) */
33132 if (!(a&0x80))
33133 {
33134 a &= SLOT_4_2_0;
33135 b &= SLOT_2_0;
33136 b = b<<7;
33137 a |= b;
33138 s = s>>11;
33139 *v = ((u64)s)<<32 | a;
33140 return 7;
33141 }
33142
33143 /* CSE2 from below */
33144 a &= SLOT_2_0;
33145 p++;
33146 b = b<<14;
33147 b |= *p;
33148 /* b: p3<<28 | p5<<14 | p7 (unmasked) */
33149 if (!(b&0x80))
33150 {
33151 b &= SLOT_4_2_0;
33152 /* moved CSE2 up */
33153 /* a &= (0x7f<<14)|(0x7f); */
33154 a = a<<7;
33155 a |= b;
33156 s = s>>4;
33157 *v = ((u64)s)<<32 | a;
33158 return 8;
33159 }
33160
33161 p++;
33162 a = a<<15;
33163 a |= *p;
33164 /* a: p4<<29 | p6<<15 | p8 (unmasked) */
33165
33166 /* moved CSE2 up */
33167 /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
33168 b &= SLOT_2_0;
33169 b = b<<8;
33170 a |= b;
33171
33172 s = s<<4;
33173 b = p[-4];
33174 b &= 0x7f;
33175 b = b>>3;
33176 s |= b;
33177
33178 *v = ((u64)s)<<32 | a;
33179
33180 return 9;
33181}
33182
33183/*
33184** Read a 32-bit variable-length integer from memory starting at p[0].
33185** Return the number of bytes read. The value is stored in *v.
33186**
33187** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
33188** integer, then set *v to 0xffffffff.
33189**
33190** A MACRO version, getVarint32, is provided which inlines the
33191** single-byte case. All code should use the MACRO version as
33192** this function assumes the single-byte case has already been handled.
33193*/
33194SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
33195 u32 a,b;
33196
33197 /* The 1-byte case. Overwhelmingly the most common. Handled inline
33198 ** by the getVarin32() macro */
33199 a = *p;
33200 /* a: p0 (unmasked) */
33201#ifndef getVarint32
33202 if (!(a&0x80))
33203 {
33204 /* Values between 0 and 127 */
33205 *v = a;
33206 return 1;
33207 }
33208#endif
33209
33210 /* The 2-byte case */
33211 p++;
33212 b = *p;
33213 /* b: p1 (unmasked) */
33214 if (!(b&0x80))
33215 {
33216 /* Values between 128 and 16383 */
33217 a &= 0x7f;
33218 a = a<<7;
33219 *v = a | b;
33220 return 2;
33221 }
33222
33223 /* The 3-byte case */
33224 p++;
33225 a = a<<14;
33226 a |= *p;
33227 /* a: p0<<14 | p2 (unmasked) */
33228 if (!(a&0x80))
33229 {
33230 /* Values between 16384 and 2097151 */
33231 a &= (0x7f<<14)|(0x7f);
33232 b &= 0x7f;
33233 b = b<<7;
33234 *v = a | b;
33235 return 3;
33236 }
33237
33238 /* A 32-bit varint is used to store size information in btrees.
33239 ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
33240 ** A 3-byte varint is sufficient, for example, to record the size
33241 ** of a 1048569-byte BLOB or string.
33242 **
33243 ** We only unroll the first 1-, 2-, and 3- byte cases. The very
33244 ** rare larger cases can be handled by the slower 64-bit varint
33245 ** routine.
33246 */
33247#if 1
33248 {
33249 u64 v64;
33250 u8 n;
33251
33252 n = sqlite3GetVarint(p: p-2, v: &v64);
33253 assert( n>3 && n<=9 );
33254 if( (v64 & SQLITE_MAX_U32)!=v64 ){
33255 *v = 0xffffffff;
33256 }else{
33257 *v = (u32)v64;
33258 }
33259 return n;
33260 }
33261
33262#else
33263 /* For following code (kept for historical record only) shows an
33264 ** unrolling for the 3- and 4-byte varint cases. This code is
33265 ** slightly faster, but it is also larger and much harder to test.
33266 */
33267 p++;
33268 b = b<<14;
33269 b |= *p;
33270 /* b: p1<<14 | p3 (unmasked) */
33271 if (!(b&0x80))
33272 {
33273 /* Values between 2097152 and 268435455 */
33274 b &= (0x7f<<14)|(0x7f);
33275 a &= (0x7f<<14)|(0x7f);
33276 a = a<<7;
33277 *v = a | b;
33278 return 4;
33279 }
33280
33281 p++;
33282 a = a<<14;
33283 a |= *p;
33284 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
33285 if (!(a&0x80))
33286 {
33287 /* Values between 268435456 and 34359738367 */
33288 a &= SLOT_4_2_0;
33289 b &= SLOT_4_2_0;
33290 b = b<<7;
33291 *v = a | b;
33292 return 5;
33293 }
33294
33295 /* We can only reach this point when reading a corrupt database
33296 ** file. In that case we are not in any hurry. Use the (relatively
33297 ** slow) general-purpose sqlite3GetVarint() routine to extract the
33298 ** value. */
33299 {
33300 u64 v64;
33301 u8 n;
33302
33303 p -= 4;
33304 n = sqlite3GetVarint(p, &v64);
33305 assert( n>5 && n<=9 );
33306 *v = (u32)v64;
33307 return n;
33308 }
33309#endif
33310}
33311
33312/*
33313** Return the number of bytes that will be needed to store the given
33314** 64-bit integer.
33315*/
33316SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
33317 int i;
33318 for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
33319 return i;
33320}
33321
33322
33323/*
33324** Read or write a four-byte big-endian integer value.
33325*/
33326SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
33327#if SQLITE_BYTEORDER==4321
33328 u32 x;
33329 memcpy(&x,p,4);
33330 return x;
33331#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
33332 u32 x;
33333 memcpy(&x,p,4);
33334 return __builtin_bswap32(x);
33335#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
33336 u32 x;
33337 memcpy(&x,p,4);
33338 return _byteswap_ulong(x);
33339#else
33340 testcase( p[0]&0x80 );
33341 return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
33342#endif
33343}
33344SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
33345#if SQLITE_BYTEORDER==4321
33346 memcpy(p,&v,4);
33347#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
33348 u32 x = __builtin_bswap32(v);
33349 memcpy(p,&x,4);
33350#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
33351 u32 x = _byteswap_ulong(v);
33352 memcpy(p,&x,4);
33353#else
33354 p[0] = (u8)(v>>24);
33355 p[1] = (u8)(v>>16);
33356 p[2] = (u8)(v>>8);
33357 p[3] = (u8)v;
33358#endif
33359}
33360
33361
33362
33363/*
33364** Translate a single byte of Hex into an integer.
33365** This routine only works if h really is a valid hexadecimal
33366** character: 0..9a..fA..F
33367*/
33368SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
33369 assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
33370#ifdef SQLITE_ASCII
33371 h += 9*(1&(h>>6));
33372#endif
33373#ifdef SQLITE_EBCDIC
33374 h += 9*(1&~(h>>4));
33375#endif
33376 return (u8)(h & 0xf);
33377}
33378
33379#if !defined(SQLITE_OMIT_BLOB_LITERAL)
33380/*
33381** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
33382** value. Return a pointer to its binary value. Space to hold the
33383** binary value has been obtained from malloc and must be freed by
33384** the calling routine.
33385*/
33386SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
33387 char *zBlob;
33388 int i;
33389
33390 zBlob = (char *)sqlite3DbMallocRawNN(db, n: n/2 + 1);
33391 n--;
33392 if( zBlob ){
33393 for(i=0; i<n; i+=2){
33394 zBlob[i/2] = (sqlite3HexToInt(h: z[i])<<4) | sqlite3HexToInt(h: z[i+1]);
33395 }
33396 zBlob[i/2] = 0;
33397 }
33398 return zBlob;
33399}
33400#endif /* !SQLITE_OMIT_BLOB_LITERAL */
33401
33402/*
33403** Log an error that is an API call on a connection pointer that should
33404** not have been used. The "type" of connection pointer is given as the
33405** argument. The zType is a word like "NULL" or "closed" or "invalid".
33406*/
33407static void logBadConnection(const char *zType){
33408 sqlite3_log(SQLITE_MISUSE,
33409 zFormat: "API call with %s database connection pointer",
33410 zType
33411 );
33412}
33413
33414/*
33415** Check to make sure we have a valid db pointer. This test is not
33416** foolproof but it does provide some measure of protection against
33417** misuse of the interface such as passing in db pointers that are
33418** NULL or which have been previously closed. If this routine returns
33419** 1 it means that the db pointer is valid and 0 if it should not be
33420** dereferenced for any reason. The calling function should invoke
33421** SQLITE_MISUSE immediately.
33422**
33423** sqlite3SafetyCheckOk() requires that the db pointer be valid for
33424** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
33425** open properly and is not fit for general use but which can be
33426** used as an argument to sqlite3_errmsg() or sqlite3_close().
33427*/
33428SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
33429 u8 eOpenState;
33430 if( db==0 ){
33431 logBadConnection(zType: "NULL");
33432 return 0;
33433 }
33434 eOpenState = db->eOpenState;
33435 if( eOpenState!=SQLITE_STATE_OPEN ){
33436 if( sqlite3SafetyCheckSickOrOk(db) ){
33437 testcase( sqlite3GlobalConfig.xLog!=0 );
33438 logBadConnection(zType: "unopened");
33439 }
33440 return 0;
33441 }else{
33442 return 1;
33443 }
33444}
33445SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
33446 u8 eOpenState;
33447 eOpenState = db->eOpenState;
33448 if( eOpenState!=SQLITE_STATE_SICK &&
33449 eOpenState!=SQLITE_STATE_OPEN &&
33450 eOpenState!=SQLITE_STATE_BUSY ){
33451 testcase( sqlite3GlobalConfig.xLog!=0 );
33452 logBadConnection(zType: "invalid");
33453 return 0;
33454 }else{
33455 return 1;
33456 }
33457}
33458
33459/*
33460** Attempt to add, substract, or multiply the 64-bit signed value iB against
33461** the other 64-bit signed integer at *pA and store the result in *pA.
33462** Return 0 on success. Or if the operation would have resulted in an
33463** overflow, leave *pA unchanged and return 1.
33464*/
33465SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
33466#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
33467 return __builtin_add_overflow(*pA, iB, pA);
33468#else
33469 i64 iA = *pA;
33470 testcase( iA==0 ); testcase( iA==1 );
33471 testcase( iB==-1 ); testcase( iB==0 );
33472 if( iB>=0 ){
33473 testcase( iA>0 && LARGEST_INT64 - iA == iB );
33474 testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
33475 if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
33476 }else{
33477 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
33478 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
33479 if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
33480 }
33481 *pA += iB;
33482 return 0;
33483#endif
33484}
33485SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
33486#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
33487 return __builtin_sub_overflow(*pA, iB, pA);
33488#else
33489 testcase( iB==SMALLEST_INT64+1 );
33490 if( iB==SMALLEST_INT64 ){
33491 testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
33492 if( (*pA)>=0 ) return 1;
33493 *pA -= iB;
33494 return 0;
33495 }else{
33496 return sqlite3AddInt64(pA, iB: -iB);
33497 }
33498#endif
33499}
33500SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
33501#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
33502 return __builtin_mul_overflow(*pA, iB, pA);
33503#else
33504 i64 iA = *pA;
33505 if( iB>0 ){
33506 if( iA>LARGEST_INT64/iB ) return 1;
33507 if( iA<SMALLEST_INT64/iB ) return 1;
33508 }else if( iB<0 ){
33509 if( iA>0 ){
33510 if( iB<SMALLEST_INT64/iA ) return 1;
33511 }else if( iA<0 ){
33512 if( iB==SMALLEST_INT64 ) return 1;
33513 if( iA==SMALLEST_INT64 ) return 1;
33514 if( -iA>LARGEST_INT64/-iB ) return 1;
33515 }
33516 }
33517 *pA = iA*iB;
33518 return 0;
33519#endif
33520}
33521
33522/*
33523** Compute the absolute value of a 32-bit signed integer, of possible. Or
33524** if the integer has a value of -2147483648, return +2147483647
33525*/
33526SQLITE_PRIVATE int sqlite3AbsInt32(int x){
33527 if( x>=0 ) return x;
33528 if( x==(int)0x80000000 ) return 0x7fffffff;
33529 return -x;
33530}
33531
33532#ifdef SQLITE_ENABLE_8_3_NAMES
33533/*
33534** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
33535** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
33536** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
33537** three characters, then shorten the suffix on z[] to be the last three
33538** characters of the original suffix.
33539**
33540** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
33541** do the suffix shortening regardless of URI parameter.
33542**
33543** Examples:
33544**
33545** test.db-journal => test.nal
33546** test.db-wal => test.wal
33547** test.db-shm => test.shm
33548** test.db-mj7f3319fa => test.9fa
33549*/
33550SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
33551#if SQLITE_ENABLE_8_3_NAMES<2
33552 if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
33553#endif
33554 {
33555 int i, sz;
33556 sz = sqlite3Strlen30(z);
33557 for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
33558 if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
33559 }
33560}
33561#endif
33562
33563/*
33564** Find (an approximate) sum of two LogEst values. This computation is
33565** not a simple "+" operator because LogEst is stored as a logarithmic
33566** value.
33567**
33568*/
33569SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
33570 static const unsigned char x[] = {
33571 10, 10, /* 0,1 */
33572 9, 9, /* 2,3 */
33573 8, 8, /* 4,5 */
33574 7, 7, 7, /* 6,7,8 */
33575 6, 6, 6, /* 9,10,11 */
33576 5, 5, 5, /* 12-14 */
33577 4, 4, 4, 4, /* 15-18 */
33578 3, 3, 3, 3, 3, 3, /* 19-24 */
33579 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
33580 };
33581 if( a>=b ){
33582 if( a>b+49 ) return a;
33583 if( a>b+31 ) return a+1;
33584 return a+x[a-b];
33585 }else{
33586 if( b>a+49 ) return b;
33587 if( b>a+31 ) return b+1;
33588 return b+x[b-a];
33589 }
33590}
33591
33592/*
33593** Convert an integer into a LogEst. In other words, compute an
33594** approximation for 10*log2(x).
33595*/
33596SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
33597 static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
33598 LogEst y = 40;
33599 if( x<8 ){
33600 if( x<2 ) return 0;
33601 while( x<8 ){ y -= 10; x <<= 1; }
33602 }else{
33603#if GCC_VERSION>=5004000
33604 int i = 60 - __builtin_clzll(x);
33605 y += i*10;
33606 x >>= i;
33607#else
33608 while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
33609 while( x>15 ){ y += 10; x >>= 1; }
33610#endif
33611 }
33612 return a[x&7] + y - 10;
33613}
33614
33615#ifndef SQLITE_OMIT_VIRTUALTABLE
33616/*
33617** Convert a double into a LogEst
33618** In other words, compute an approximation for 10*log2(x).
33619*/
33620SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
33621 u64 a;
33622 LogEst e;
33623 assert( sizeof(x)==8 && sizeof(a)==8 );
33624 if( x<=1 ) return 0;
33625 if( x<=2000000000 ) return sqlite3LogEst(x: (u64)x);
33626 memcpy(dest: &a, src: &x, n: 8);
33627 e = (a>>52) - 1022;
33628 return e*10;
33629}
33630#endif /* SQLITE_OMIT_VIRTUALTABLE */
33631
33632#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
33633 defined(SQLITE_ENABLE_STAT4) || \
33634 defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
33635/*
33636** Convert a LogEst into an integer.
33637**
33638** Note that this routine is only used when one or more of various
33639** non-standard compile-time options is enabled.
33640*/
33641SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
33642 u64 n;
33643 n = x%10;
33644 x /= 10;
33645 if( n>=5 ) n -= 2;
33646 else if( n>=1 ) n -= 1;
33647#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
33648 defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
33649 if( x>60 ) return (u64)LARGEST_INT64;
33650#else
33651 /* If only SQLITE_ENABLE_STAT4 is on, then the largest input
33652 ** possible to this routine is 310, resulting in a maximum x of 31 */
33653 assert( x<=60 );
33654#endif
33655 return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
33656}
33657#endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
33658
33659/*
33660** Add a new name/number pair to a VList. This might require that the
33661** VList object be reallocated, so return the new VList. If an OOM
33662** error occurs, the original VList returned and the
33663** db->mallocFailed flag is set.
33664**
33665** A VList is really just an array of integers. To destroy a VList,
33666** simply pass it to sqlite3DbFree().
33667**
33668** The first integer is the number of integers allocated for the whole
33669** VList. The second integer is the number of integers actually used.
33670** Each name/number pair is encoded by subsequent groups of 3 or more
33671** integers.
33672**
33673** Each name/number pair starts with two integers which are the numeric
33674** value for the pair and the size of the name/number pair, respectively.
33675** The text name overlays one or more following integers. The text name
33676** is always zero-terminated.
33677**
33678** Conceptually:
33679**
33680** struct VList {
33681** int nAlloc; // Number of allocated slots
33682** int nUsed; // Number of used slots
33683** struct VListEntry {
33684** int iValue; // Value for this entry
33685** int nSlot; // Slots used by this entry
33686** // ... variable name goes here
33687** } a[0];
33688** }
33689**
33690** During code generation, pointers to the variable names within the
33691** VList are taken. When that happens, nAlloc is set to zero as an
33692** indication that the VList may never again be enlarged, since the
33693** accompanying realloc() would invalidate the pointers.
33694*/
33695SQLITE_PRIVATE VList *sqlite3VListAdd(
33696 sqlite3 *db, /* The database connection used for malloc() */
33697 VList *pIn, /* The input VList. Might be NULL */
33698 const char *zName, /* Name of symbol to add */
33699 int nName, /* Bytes of text in zName */
33700 int iVal /* Value to associate with zName */
33701){
33702 int nInt; /* number of sizeof(int) objects needed for zName */
33703 char *z; /* Pointer to where zName will be stored */
33704 int i; /* Index in pIn[] where zName is stored */
33705
33706 nInt = nName/4 + 3;
33707 assert( pIn==0 || pIn[0]>=3 ); /* Verify ok to add new elements */
33708 if( pIn==0 || pIn[1]+nInt > pIn[0] ){
33709 /* Enlarge the allocation */
33710 sqlite3_int64 nAlloc = (pIn ? 2*(sqlite3_int64)pIn[0] : 10) + nInt;
33711 VList *pOut = sqlite3DbRealloc(db, p: pIn, n: nAlloc*sizeof(int));
33712 if( pOut==0 ) return pIn;
33713 if( pIn==0 ) pOut[1] = 2;
33714 pIn = pOut;
33715 pIn[0] = nAlloc;
33716 }
33717 i = pIn[1];
33718 pIn[i] = iVal;
33719 pIn[i+1] = nInt;
33720 z = (char*)&pIn[i+2];
33721 pIn[1] = i+nInt;
33722 assert( pIn[1]<=pIn[0] );
33723 memcpy(dest: z, src: zName, n: nName);
33724 z[nName] = 0;
33725 return pIn;
33726}
33727
33728/*
33729** Return a pointer to the name of a variable in the given VList that
33730** has the value iVal. Or return a NULL if there is no such variable in
33731** the list
33732*/
33733SQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){
33734 int i, mx;
33735 if( pIn==0 ) return 0;
33736 mx = pIn[1];
33737 i = 2;
33738 do{
33739 if( pIn[i]==iVal ) return (char*)&pIn[i+2];
33740 i += pIn[i+1];
33741 }while( i<mx );
33742 return 0;
33743}
33744
33745/*
33746** Return the number of the variable named zName, if it is in VList.
33747** or return 0 if there is no such variable.
33748*/
33749SQLITE_PRIVATE int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
33750 int i, mx;
33751 if( pIn==0 ) return 0;
33752 mx = pIn[1];
33753 i = 2;
33754 do{
33755 const char *z = (const char*)&pIn[i+2];
33756 if( strncmp(s1: z,s2: zName,n: nName)==0 && z[nName]==0 ) return pIn[i];
33757 i += pIn[i+1];
33758 }while( i<mx );
33759 return 0;
33760}
33761
33762/************** End of util.c ************************************************/
33763/************** Begin file hash.c ********************************************/
33764/*
33765** 2001 September 22
33766**
33767** The author disclaims copyright to this source code. In place of
33768** a legal notice, here is a blessing:
33769**
33770** May you do good and not evil.
33771** May you find forgiveness for yourself and forgive others.
33772** May you share freely, never taking more than you give.
33773**
33774*************************************************************************
33775** This is the implementation of generic hash-tables
33776** used in SQLite.
33777*/
33778/* #include "sqliteInt.h" */
33779/* #include <assert.h> */
33780
33781/* Turn bulk memory into a hash table object by initializing the
33782** fields of the Hash structure.
33783**
33784** "pNew" is a pointer to the hash table that is to be initialized.
33785*/
33786SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
33787 assert( pNew!=0 );
33788 pNew->first = 0;
33789 pNew->count = 0;
33790 pNew->htsize = 0;
33791 pNew->ht = 0;
33792}
33793
33794/* Remove all entries from a hash table. Reclaim all memory.
33795** Call this routine to delete a hash table or to reset a hash table
33796** to the empty state.
33797*/
33798SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
33799 HashElem *elem; /* For looping over all elements of the table */
33800
33801 assert( pH!=0 );
33802 elem = pH->first;
33803 pH->first = 0;
33804 sqlite3_free(p: pH->ht);
33805 pH->ht = 0;
33806 pH->htsize = 0;
33807 while( elem ){
33808 HashElem *next_elem = elem->next;
33809 sqlite3_free(p: elem);
33810 elem = next_elem;
33811 }
33812 pH->count = 0;
33813}
33814
33815/*
33816** The hashing function.
33817*/
33818static unsigned int strHash(const char *z){
33819 unsigned int h = 0;
33820 unsigned char c;
33821 while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
33822 /* Knuth multiplicative hashing. (Sorting & Searching, p. 510).
33823 ** 0x9e3779b1 is 2654435761 which is the closest prime number to
33824 ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
33825 h += sqlite3UpperToLower[c];
33826 h *= 0x9e3779b1;
33827 }
33828 return h;
33829}
33830
33831
33832/* Link pNew element into the hash table pH. If pEntry!=0 then also
33833** insert pNew into the pEntry hash bucket.
33834*/
33835static void insertElement(
33836 Hash *pH, /* The complete hash table */
33837 struct _ht *pEntry, /* The entry into which pNew is inserted */
33838 HashElem *pNew /* The element to be inserted */
33839){
33840 HashElem *pHead; /* First element already in pEntry */
33841 if( pEntry ){
33842 pHead = pEntry->count ? pEntry->chain : 0;
33843 pEntry->count++;
33844 pEntry->chain = pNew;
33845 }else{
33846 pHead = 0;
33847 }
33848 if( pHead ){
33849 pNew->next = pHead;
33850 pNew->prev = pHead->prev;
33851 if( pHead->prev ){ pHead->prev->next = pNew; }
33852 else { pH->first = pNew; }
33853 pHead->prev = pNew;
33854 }else{
33855 pNew->next = pH->first;
33856 if( pH->first ){ pH->first->prev = pNew; }
33857 pNew->prev = 0;
33858 pH->first = pNew;
33859 }
33860}
33861
33862
33863/* Resize the hash table so that it cantains "new_size" buckets.
33864**
33865** The hash table might fail to resize if sqlite3_malloc() fails or
33866** if the new size is the same as the prior size.
33867** Return TRUE if the resize occurs and false if not.
33868*/
33869static int rehash(Hash *pH, unsigned int new_size){
33870 struct _ht *new_ht; /* The new hash table */
33871 HashElem *elem, *next_elem; /* For looping over existing elements */
33872
33873#if SQLITE_MALLOC_SOFT_LIMIT>0
33874 if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
33875 new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
33876 }
33877 if( new_size==pH->htsize ) return 0;
33878#endif
33879
33880 /* The inability to allocates space for a larger hash table is
33881 ** a performance hit but it is not a fatal error. So mark the
33882 ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
33883 ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
33884 ** only zeroes the requested number of bytes whereas this module will
33885 ** use the actual amount of space allocated for the hash table (which
33886 ** may be larger than the requested amount).
33887 */
33888 sqlite3BeginBenignMalloc();
33889 new_ht = (struct _ht *)sqlite3Malloc( n: new_size*sizeof(struct _ht) );
33890 sqlite3EndBenignMalloc();
33891
33892 if( new_ht==0 ) return 0;
33893 sqlite3_free(p: pH->ht);
33894 pH->ht = new_ht;
33895 pH->htsize = new_size = sqlite3MallocSize(p: new_ht)/sizeof(struct _ht);
33896 memset(s: new_ht, c: 0, n: new_size*sizeof(struct _ht));
33897 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
33898 unsigned int h = strHash(z: elem->pKey) % new_size;
33899 next_elem = elem->next;
33900 insertElement(pH, pEntry: &new_ht[h], pNew: elem);
33901 }
33902 return 1;
33903}
33904
33905/* This function (for internal use only) locates an element in an
33906** hash table that matches the given key. If no element is found,
33907** a pointer to a static null element with HashElem.data==0 is returned.
33908** If pH is not NULL, then the hash for this key is written to *pH.
33909*/
33910static HashElem *findElementWithHash(
33911 const Hash *pH, /* The pH to be searched */
33912 const char *pKey, /* The key we are searching for */
33913 unsigned int *pHash /* Write the hash value here */
33914){
33915 HashElem *elem; /* Used to loop thru the element list */
33916 unsigned int count; /* Number of elements left to test */
33917 unsigned int h; /* The computed hash */
33918 static HashElem nullElement = { 0, 0, 0, 0 };
33919
33920 if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
33921 struct _ht *pEntry;
33922 h = strHash(z: pKey) % pH->htsize;
33923 pEntry = &pH->ht[h];
33924 elem = pEntry->chain;
33925 count = pEntry->count;
33926 }else{
33927 h = 0;
33928 elem = pH->first;
33929 count = pH->count;
33930 }
33931 if( pHash ) *pHash = h;
33932 while( count-- ){
33933 assert( elem!=0 );
33934 if( sqlite3StrICmp(zLeft: elem->pKey,zRight: pKey)==0 ){
33935 return elem;
33936 }
33937 elem = elem->next;
33938 }
33939 return &nullElement;
33940}
33941
33942/* Remove a single entry from the hash table given a pointer to that
33943** element and a hash on the element's key.
33944*/
33945static void removeElementGivenHash(
33946 Hash *pH, /* The pH containing "elem" */
33947 HashElem* elem, /* The element to be removed from the pH */
33948 unsigned int h /* Hash value for the element */
33949){
33950 struct _ht *pEntry;
33951 if( elem->prev ){
33952 elem->prev->next = elem->next;
33953 }else{
33954 pH->first = elem->next;
33955 }
33956 if( elem->next ){
33957 elem->next->prev = elem->prev;
33958 }
33959 if( pH->ht ){
33960 pEntry = &pH->ht[h];
33961 if( pEntry->chain==elem ){
33962 pEntry->chain = elem->next;
33963 }
33964 assert( pEntry->count>0 );
33965 pEntry->count--;
33966 }
33967 sqlite3_free( p: elem );
33968 pH->count--;
33969 if( pH->count==0 ){
33970 assert( pH->first==0 );
33971 assert( pH->count==0 );
33972 sqlite3HashClear(pH);
33973 }
33974}
33975
33976/* Attempt to locate an element of the hash table pH with a key
33977** that matches pKey. Return the data for this element if it is
33978** found, or NULL if there is no match.
33979*/
33980SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
33981 assert( pH!=0 );
33982 assert( pKey!=0 );
33983 return findElementWithHash(pH, pKey, pHash: 0)->data;
33984}
33985
33986/* Insert an element into the hash table pH. The key is pKey
33987** and the data is "data".
33988**
33989** If no element exists with a matching key, then a new
33990** element is created and NULL is returned.
33991**
33992** If another element already exists with the same key, then the
33993** new data replaces the old data and the old data is returned.
33994** The key is not copied in this instance. If a malloc fails, then
33995** the new data is returned and the hash table is unchanged.
33996**
33997** If the "data" parameter to this function is NULL, then the
33998** element corresponding to "key" is removed from the hash table.
33999*/
34000SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
34001 unsigned int h; /* the hash of the key modulo hash table size */
34002 HashElem *elem; /* Used to loop thru the element list */
34003 HashElem *new_elem; /* New element added to the pH */
34004
34005 assert( pH!=0 );
34006 assert( pKey!=0 );
34007 elem = findElementWithHash(pH,pKey,pHash: &h);
34008 if( elem->data ){
34009 void *old_data = elem->data;
34010 if( data==0 ){
34011 removeElementGivenHash(pH,elem,h);
34012 }else{
34013 elem->data = data;
34014 elem->pKey = pKey;
34015 }
34016 return old_data;
34017 }
34018 if( data==0 ) return 0;
34019 new_elem = (HashElem*)sqlite3Malloc( n: sizeof(HashElem) );
34020 if( new_elem==0 ) return data;
34021 new_elem->pKey = pKey;
34022 new_elem->data = data;
34023 pH->count++;
34024 if( pH->count>=10 && pH->count > 2*pH->htsize ){
34025 if( rehash(pH, new_size: pH->count*2) ){
34026 assert( pH->htsize>0 );
34027 h = strHash(z: pKey) % pH->htsize;
34028 }
34029 }
34030 insertElement(pH, pEntry: pH->ht ? &pH->ht[h] : 0, pNew: new_elem);
34031 return 0;
34032}
34033
34034/************** End of hash.c ************************************************/
34035/************** Begin file opcodes.c *****************************************/
34036/* Automatically generated. Do not edit */
34037/* See the tool/mkopcodec.tcl script for details. */
34038#if !defined(SQLITE_OMIT_EXPLAIN) \
34039 || defined(VDBE_PROFILE) \
34040 || defined(SQLITE_DEBUG)
34041#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
34042# define OpHelp(X) "\0" X
34043#else
34044# define OpHelp(X)
34045#endif
34046SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
34047 static const char *const azName[] = {
34048 /* 0 */ "Savepoint" OpHelp(""),
34049 /* 1 */ "AutoCommit" OpHelp(""),
34050 /* 2 */ "Transaction" OpHelp(""),
34051 /* 3 */ "SorterNext" OpHelp(""),
34052 /* 4 */ "Prev" OpHelp(""),
34053 /* 5 */ "Next" OpHelp(""),
34054 /* 6 */ "Checkpoint" OpHelp(""),
34055 /* 7 */ "JournalMode" OpHelp(""),
34056 /* 8 */ "Vacuum" OpHelp(""),
34057 /* 9 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
34058 /* 10 */ "VUpdate" OpHelp("data=r[P3@P2]"),
34059 /* 11 */ "Goto" OpHelp(""),
34060 /* 12 */ "Gosub" OpHelp(""),
34061 /* 13 */ "InitCoroutine" OpHelp(""),
34062 /* 14 */ "Yield" OpHelp(""),
34063 /* 15 */ "MustBeInt" OpHelp(""),
34064 /* 16 */ "Jump" OpHelp(""),
34065 /* 17 */ "Once" OpHelp(""),
34066 /* 18 */ "If" OpHelp(""),
34067 /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
34068 /* 20 */ "IfNot" OpHelp(""),
34069 /* 21 */ "IsNullOrType" OpHelp("if typeof(r[P1]) IN (P3,5) goto P2"),
34070 /* 22 */ "IfNullRow" OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"),
34071 /* 23 */ "SeekLT" OpHelp("key=r[P3@P4]"),
34072 /* 24 */ "SeekLE" OpHelp("key=r[P3@P4]"),
34073 /* 25 */ "SeekGE" OpHelp("key=r[P3@P4]"),
34074 /* 26 */ "SeekGT" OpHelp("key=r[P3@P4]"),
34075 /* 27 */ "IfNotOpen" OpHelp("if( !csr[P1] ) goto P2"),
34076 /* 28 */ "IfNoHope" OpHelp("key=r[P3@P4]"),
34077 /* 29 */ "NoConflict" OpHelp("key=r[P3@P4]"),
34078 /* 30 */ "NotFound" OpHelp("key=r[P3@P4]"),
34079 /* 31 */ "Found" OpHelp("key=r[P3@P4]"),
34080 /* 32 */ "SeekRowid" OpHelp("intkey=r[P3]"),
34081 /* 33 */ "NotExists" OpHelp("intkey=r[P3]"),
34082 /* 34 */ "Last" OpHelp(""),
34083 /* 35 */ "IfSmaller" OpHelp(""),
34084 /* 36 */ "SorterSort" OpHelp(""),
34085 /* 37 */ "Sort" OpHelp(""),
34086 /* 38 */ "Rewind" OpHelp(""),
34087 /* 39 */ "IdxLE" OpHelp("key=r[P3@P4]"),
34088 /* 40 */ "IdxGT" OpHelp("key=r[P3@P4]"),
34089 /* 41 */ "IdxLT" OpHelp("key=r[P3@P4]"),
34090 /* 42 */ "IdxGE" OpHelp("key=r[P3@P4]"),
34091 /* 43 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
34092 /* 44 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
34093 /* 45 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
34094 /* 46 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
34095 /* 47 */ "Program" OpHelp(""),
34096 /* 48 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
34097 /* 49 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
34098 /* 50 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
34099 /* 51 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
34100 /* 52 */ "Ne" OpHelp("IF r[P3]!=r[P1]"),
34101 /* 53 */ "Eq" OpHelp("IF r[P3]==r[P1]"),
34102 /* 54 */ "Gt" OpHelp("IF r[P3]>r[P1]"),
34103 /* 55 */ "Le" OpHelp("IF r[P3]<=r[P1]"),
34104 /* 56 */ "Lt" OpHelp("IF r[P3]<r[P1]"),
34105 /* 57 */ "Ge" OpHelp("IF r[P3]>=r[P1]"),
34106 /* 58 */ "ElseEq" OpHelp(""),
34107 /* 59 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
34108 /* 60 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
34109 /* 61 */ "IncrVacuum" OpHelp(""),
34110 /* 62 */ "VNext" OpHelp(""),
34111 /* 63 */ "Init" OpHelp("Start at P2"),
34112 /* 64 */ "PureFunc" OpHelp("r[P3]=func(r[P2@NP])"),
34113 /* 65 */ "Function" OpHelp("r[P3]=func(r[P2@NP])"),
34114 /* 66 */ "Return" OpHelp(""),
34115 /* 67 */ "EndCoroutine" OpHelp(""),
34116 /* 68 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
34117 /* 69 */ "Halt" OpHelp(""),
34118 /* 70 */ "Integer" OpHelp("r[P2]=P1"),
34119 /* 71 */ "Int64" OpHelp("r[P2]=P4"),
34120 /* 72 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
34121 /* 73 */ "Null" OpHelp("r[P2..P3]=NULL"),
34122 /* 74 */ "SoftNull" OpHelp("r[P1]=NULL"),
34123 /* 75 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
34124 /* 76 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
34125 /* 77 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
34126 /* 78 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
34127 /* 79 */ "SCopy" OpHelp("r[P2]=r[P1]"),
34128 /* 80 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
34129 /* 81 */ "ChngCntRow" OpHelp("output=r[P1]"),
34130 /* 82 */ "ResultRow" OpHelp("output=r[P1@P2]"),
34131 /* 83 */ "CollSeq" OpHelp(""),
34132 /* 84 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
34133 /* 85 */ "RealAffinity" OpHelp(""),
34134 /* 86 */ "Cast" OpHelp("affinity(r[P1])"),
34135 /* 87 */ "Permutation" OpHelp(""),
34136 /* 88 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
34137 /* 89 */ "IsTrue" OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"),
34138 /* 90 */ "ZeroOrNull" OpHelp("r[P2] = 0 OR NULL"),
34139 /* 91 */ "Offset" OpHelp("r[P3] = sqlite_offset(P1)"),
34140 /* 92 */ "Column" OpHelp("r[P3]=PX"),
34141 /* 93 */ "TypeCheck" OpHelp("typecheck(r[P1@P2])"),
34142 /* 94 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
34143 /* 95 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
34144 /* 96 */ "Count" OpHelp("r[P2]=count()"),
34145 /* 97 */ "ReadCookie" OpHelp(""),
34146 /* 98 */ "SetCookie" OpHelp(""),
34147 /* 99 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
34148 /* 100 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
34149 /* 101 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
34150 /* 102 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
34151 /* 103 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
34152 /* 104 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
34153 /* 105 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
34154 /* 106 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
34155 /* 107 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
34156 /* 108 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
34157 /* 109 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
34158 /* 110 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
34159 /* 111 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
34160 /* 112 */ "OpenDup" OpHelp(""),
34161 /* 113 */ "BitNot" OpHelp("r[P2]= ~r[P1]"),
34162 /* 114 */ "OpenAutoindex" OpHelp("nColumn=P2"),
34163 /* 115 */ "OpenEphemeral" OpHelp("nColumn=P2"),
34164 /* 116 */ "String8" OpHelp("r[P2]='P4'"),
34165 /* 117 */ "SorterOpen" OpHelp(""),
34166 /* 118 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
34167 /* 119 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
34168 /* 120 */ "Close" OpHelp(""),
34169 /* 121 */ "ColumnsUsed" OpHelp(""),
34170 /* 122 */ "SeekScan" OpHelp("Scan-ahead up to P1 rows"),
34171 /* 123 */ "SeekHit" OpHelp("set P2<=seekHit<=P3"),
34172 /* 124 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
34173 /* 125 */ "NewRowid" OpHelp("r[P2]=rowid"),
34174 /* 126 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
34175 /* 127 */ "RowCell" OpHelp(""),
34176 /* 128 */ "Delete" OpHelp(""),
34177 /* 129 */ "ResetCount" OpHelp(""),
34178 /* 130 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
34179 /* 131 */ "SorterData" OpHelp("r[P2]=data"),
34180 /* 132 */ "RowData" OpHelp("r[P2]=data"),
34181 /* 133 */ "Rowid" OpHelp("r[P2]=rowid"),
34182 /* 134 */ "NullRow" OpHelp(""),
34183 /* 135 */ "SeekEnd" OpHelp(""),
34184 /* 136 */ "IdxInsert" OpHelp("key=r[P2]"),
34185 /* 137 */ "SorterInsert" OpHelp("key=r[P2]"),
34186 /* 138 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
34187 /* 139 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"),
34188 /* 140 */ "IdxRowid" OpHelp("r[P2]=rowid"),
34189 /* 141 */ "FinishSeek" OpHelp(""),
34190 /* 142 */ "Destroy" OpHelp(""),
34191 /* 143 */ "Clear" OpHelp(""),
34192 /* 144 */ "ResetSorter" OpHelp(""),
34193 /* 145 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"),
34194 /* 146 */ "SqlExec" OpHelp(""),
34195 /* 147 */ "ParseSchema" OpHelp(""),
34196 /* 148 */ "LoadAnalysis" OpHelp(""),
34197 /* 149 */ "DropTable" OpHelp(""),
34198 /* 150 */ "DropIndex" OpHelp(""),
34199 /* 151 */ "DropTrigger" OpHelp(""),
34200 /* 152 */ "Real" OpHelp("r[P2]=P4"),
34201 /* 153 */ "IntegrityCk" OpHelp(""),
34202 /* 154 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
34203 /* 155 */ "Param" OpHelp(""),
34204 /* 156 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
34205 /* 157 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
34206 /* 158 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
34207 /* 159 */ "AggInverse" OpHelp("accum=r[P3] inverse(r[P2@P5])"),
34208 /* 160 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
34209 /* 161 */ "AggStep1" OpHelp("accum=r[P3] step(r[P2@P5])"),
34210 /* 162 */ "AggValue" OpHelp("r[P3]=value N=P2"),
34211 /* 163 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
34212 /* 164 */ "Expire" OpHelp(""),
34213 /* 165 */ "CursorLock" OpHelp(""),
34214 /* 166 */ "CursorUnlock" OpHelp(""),
34215 /* 167 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
34216 /* 168 */ "VBegin" OpHelp(""),
34217 /* 169 */ "VCreate" OpHelp(""),
34218 /* 170 */ "VDestroy" OpHelp(""),
34219 /* 171 */ "VOpen" OpHelp(""),
34220 /* 172 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
34221 /* 173 */ "VRename" OpHelp(""),
34222 /* 174 */ "Pagecount" OpHelp(""),
34223 /* 175 */ "MaxPgcnt" OpHelp(""),
34224 /* 176 */ "Trace" OpHelp(""),
34225 /* 177 */ "CursorHint" OpHelp(""),
34226 /* 178 */ "ReleaseReg" OpHelp("release r[P1@P2] mask P3"),
34227 /* 179 */ "Noop" OpHelp(""),
34228 /* 180 */ "Explain" OpHelp(""),
34229 /* 181 */ "Abortable" OpHelp(""),
34230 };
34231 return azName[i];
34232}
34233#endif
34234
34235/************** End of opcodes.c *********************************************/
34236/************** Begin file os_unix.c *****************************************/
34237/*
34238** 2004 May 22
34239**
34240** The author disclaims copyright to this source code. In place of
34241** a legal notice, here is a blessing:
34242**
34243** May you do good and not evil.
34244** May you find forgiveness for yourself and forgive others.
34245** May you share freely, never taking more than you give.
34246**
34247******************************************************************************
34248**
34249** This file contains the VFS implementation for unix-like operating systems
34250** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
34251**
34252** There are actually several different VFS implementations in this file.
34253** The differences are in the way that file locking is done. The default
34254** implementation uses Posix Advisory Locks. Alternative implementations
34255** use flock(), dot-files, various proprietary locking schemas, or simply
34256** skip locking all together.
34257**
34258** This source file is organized into divisions where the logic for various
34259** subfunctions is contained within the appropriate division. PLEASE
34260** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
34261** in the correct division and should be clearly labeled.
34262**
34263** The layout of divisions is as follows:
34264**
34265** * General-purpose declarations and utility functions.
34266** * Unique file ID logic used by VxWorks.
34267** * Various locking primitive implementations (all except proxy locking):
34268** + for Posix Advisory Locks
34269** + for no-op locks
34270** + for dot-file locks
34271** + for flock() locking
34272** + for named semaphore locks (VxWorks only)
34273** + for AFP filesystem locks (MacOSX only)
34274** * sqlite3_file methods not associated with locking.
34275** * Definitions of sqlite3_io_methods objects for all locking
34276** methods plus "finder" functions for each locking method.
34277** * sqlite3_vfs method implementations.
34278** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
34279** * Definitions of sqlite3_vfs objects for all locking methods
34280** plus implementations of sqlite3_os_init() and sqlite3_os_end().
34281*/
34282/* #include "sqliteInt.h" */
34283#if SQLITE_OS_UNIX /* This file is used on unix only */
34284
34285/*
34286** There are various methods for file locking used for concurrency
34287** control:
34288**
34289** 1. POSIX locking (the default),
34290** 2. No locking,
34291** 3. Dot-file locking,
34292** 4. flock() locking,
34293** 5. AFP locking (OSX only),
34294** 6. Named POSIX semaphores (VXWorks only),
34295** 7. proxy locking. (OSX only)
34296**
34297** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
34298** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
34299** selection of the appropriate locking style based on the filesystem
34300** where the database is located.
34301*/
34302#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
34303# if defined(__APPLE__)
34304# define SQLITE_ENABLE_LOCKING_STYLE 1
34305# else
34306# define SQLITE_ENABLE_LOCKING_STYLE 0
34307# endif
34308#endif
34309
34310/* Use pread() and pwrite() if they are available */
34311#if defined(__APPLE__)
34312# define HAVE_PREAD 1
34313# define HAVE_PWRITE 1
34314#endif
34315#if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
34316# undef USE_PREAD
34317# define USE_PREAD64 1
34318#elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
34319# undef USE_PREAD64
34320# define USE_PREAD 1
34321#endif
34322
34323/*
34324** standard include files.
34325*/
34326#include <sys/types.h>
34327#include <sys/stat.h>
34328#include <fcntl.h>
34329#include <sys/ioctl.h>
34330#include <unistd.h>
34331/* #include <time.h> */
34332#include <sys/time.h>
34333#include <errno.h>
34334#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
34335# include <sys/mman.h>
34336#endif
34337
34338#if SQLITE_ENABLE_LOCKING_STYLE
34339/* # include <sys/ioctl.h> */
34340# include <sys/file.h>
34341# include <sys/param.h>
34342#endif /* SQLITE_ENABLE_LOCKING_STYLE */
34343
34344/*
34345** Try to determine if gethostuuid() is available based on standard
34346** macros. This might sometimes compute the wrong value for some
34347** obscure platforms. For those cases, simply compile with one of
34348** the following:
34349**
34350** -DHAVE_GETHOSTUUID=0
34351** -DHAVE_GETHOSTUUID=1
34352**
34353** None if this matters except when building on Apple products with
34354** -DSQLITE_ENABLE_LOCKING_STYLE.
34355*/
34356#ifndef HAVE_GETHOSTUUID
34357# define HAVE_GETHOSTUUID 0
34358# if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
34359 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
34360# if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
34361 && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))\
34362 && (!defined(TARGET_OS_MACCATALYST) || (TARGET_OS_MACCATALYST==0))
34363# undef HAVE_GETHOSTUUID
34364# define HAVE_GETHOSTUUID 1
34365# else
34366# warning "gethostuuid() is disabled."
34367# endif
34368# endif
34369#endif
34370
34371
34372#if OS_VXWORKS
34373/* # include <sys/ioctl.h> */
34374# include <semaphore.h>
34375# include <limits.h>
34376#endif /* OS_VXWORKS */
34377
34378#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
34379# include <sys/mount.h>
34380#endif
34381
34382#ifdef HAVE_UTIME
34383# include <utime.h>
34384#endif
34385
34386/*
34387** Allowed values of unixFile.fsFlags
34388*/
34389#define SQLITE_FSFLAGS_IS_MSDOS 0x1
34390
34391/*
34392** If we are to be thread-safe, include the pthreads header.
34393*/
34394#if SQLITE_THREADSAFE
34395/* # include <pthread.h> */
34396#endif
34397
34398/*
34399** Default permissions when creating a new file
34400*/
34401#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
34402# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
34403#endif
34404
34405/*
34406** Default permissions when creating auto proxy dir
34407*/
34408#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
34409# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
34410#endif
34411
34412/*
34413** Maximum supported path-length.
34414*/
34415#define MAX_PATHNAME 512
34416
34417/*
34418** Maximum supported symbolic links
34419*/
34420#define SQLITE_MAX_SYMLINKS 100
34421
34422/* Always cast the getpid() return type for compatibility with
34423** kernel modules in VxWorks. */
34424#define osGetpid(X) (pid_t)getpid()
34425
34426/*
34427** Only set the lastErrno if the error code is a real error and not
34428** a normal expected return code of SQLITE_BUSY or SQLITE_OK
34429*/
34430#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
34431
34432/* Forward references */
34433typedef struct unixShm unixShm; /* Connection shared memory */
34434typedef struct unixShmNode unixShmNode; /* Shared memory instance */
34435typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
34436typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
34437
34438/*
34439** Sometimes, after a file handle is closed by SQLite, the file descriptor
34440** cannot be closed immediately. In these cases, instances of the following
34441** structure are used to store the file descriptor while waiting for an
34442** opportunity to either close or reuse it.
34443*/
34444struct UnixUnusedFd {
34445 int fd; /* File descriptor to close */
34446 int flags; /* Flags this file descriptor was opened with */
34447 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
34448};
34449
34450/*
34451** The unixFile structure is subclass of sqlite3_file specific to the unix
34452** VFS implementations.
34453*/
34454typedef struct unixFile unixFile;
34455struct unixFile {
34456 sqlite3_io_methods const *pMethod; /* Always the first entry */
34457 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
34458 unixInodeInfo *pInode; /* Info about locks on this inode */
34459 int h; /* The file descriptor */
34460 unsigned char eFileLock; /* The type of lock held on this fd */
34461 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
34462 int lastErrno; /* The unix errno from last I/O error */
34463 void *lockingContext; /* Locking style specific state */
34464 UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
34465 const char *zPath; /* Name of the file */
34466 unixShm *pShm; /* Shared memory segment information */
34467 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
34468#if SQLITE_MAX_MMAP_SIZE>0
34469 int nFetchOut; /* Number of outstanding xFetch refs */
34470 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
34471 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
34472 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
34473 void *pMapRegion; /* Memory mapped region */
34474#endif
34475 int sectorSize; /* Device sector size */
34476 int deviceCharacteristics; /* Precomputed device characteristics */
34477#if SQLITE_ENABLE_LOCKING_STYLE
34478 int openFlags; /* The flags specified at open() */
34479#endif
34480#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
34481 unsigned fsFlags; /* cached details from statfs() */
34482#endif
34483#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
34484 unsigned iBusyTimeout; /* Wait this many millisec on locks */
34485#endif
34486#if OS_VXWORKS
34487 struct vxworksFileId *pId; /* Unique file ID */
34488#endif
34489#ifdef SQLITE_DEBUG
34490 /* The next group of variables are used to track whether or not the
34491 ** transaction counter in bytes 24-27 of database files are updated
34492 ** whenever any part of the database changes. An assertion fault will
34493 ** occur if a file is updated without also updating the transaction
34494 ** counter. This test is made to avoid new problems similar to the
34495 ** one described by ticket #3584.
34496 */
34497 unsigned char transCntrChng; /* True if the transaction counter changed */
34498 unsigned char dbUpdate; /* True if any part of database file changed */
34499 unsigned char inNormalWrite; /* True if in a normal write operation */
34500
34501#endif
34502
34503#ifdef SQLITE_TEST
34504 /* In test mode, increase the size of this structure a bit so that
34505 ** it is larger than the struct CrashFile defined in test6.c.
34506 */
34507 char aPadding[32];
34508#endif
34509};
34510
34511/* This variable holds the process id (pid) from when the xRandomness()
34512** method was called. If xOpen() is called from a different process id,
34513** indicating that a fork() has occurred, the PRNG will be reset.
34514*/
34515static pid_t randomnessPid = 0;
34516
34517/*
34518** Allowed values for the unixFile.ctrlFlags bitmask:
34519*/
34520#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
34521#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
34522#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
34523#ifndef SQLITE_DISABLE_DIRSYNC
34524# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
34525#else
34526# define UNIXFILE_DIRSYNC 0x00
34527#endif
34528#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
34529#define UNIXFILE_DELETE 0x20 /* Delete on close */
34530#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
34531#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
34532
34533/*
34534** Include code that is common to all os_*.c files
34535*/
34536/* #include "os_common.h" */
34537
34538/*
34539** Define various macros that are missing from some systems.
34540*/
34541#ifndef O_LARGEFILE
34542# define O_LARGEFILE 0
34543#endif
34544#ifdef SQLITE_DISABLE_LFS
34545# undef O_LARGEFILE
34546# define O_LARGEFILE 0
34547#endif
34548#ifndef O_NOFOLLOW
34549# define O_NOFOLLOW 0
34550#endif
34551#ifndef O_BINARY
34552# define O_BINARY 0
34553#endif
34554
34555/*
34556** The threadid macro resolves to the thread-id or to 0. Used for
34557** testing and debugging only.
34558*/
34559#if SQLITE_THREADSAFE
34560#define threadid pthread_self()
34561#else
34562#define threadid 0
34563#endif
34564
34565/*
34566** HAVE_MREMAP defaults to true on Linux and false everywhere else.
34567*/
34568#if !defined(HAVE_MREMAP)
34569# if defined(__linux__) && defined(_GNU_SOURCE)
34570# define HAVE_MREMAP 1
34571# else
34572# define HAVE_MREMAP 0
34573# endif
34574#endif
34575
34576/*
34577** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
34578** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
34579*/
34580#ifdef __ANDROID__
34581# define lseek lseek64
34582#endif
34583
34584#ifdef __linux__
34585/*
34586** Linux-specific IOCTL magic numbers used for controlling F2FS
34587*/
34588#define F2FS_IOCTL_MAGIC 0xf5
34589#define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
34590#define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
34591#define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
34592#define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
34593#define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
34594#define F2FS_FEATURE_ATOMIC_WRITE 0x0004
34595#endif /* __linux__ */
34596
34597
34598/*
34599** Different Unix systems declare open() in different ways. Same use
34600** open(const char*,int,mode_t). Others use open(const char*,int,...).
34601** The difference is important when using a pointer to the function.
34602**
34603** The safest way to deal with the problem is to always use this wrapper
34604** which always has the same well-defined interface.
34605*/
34606static int posixOpen(const char *zFile, int flags, int mode){
34607 return open(file: zFile, oflag: flags, mode);
34608}
34609
34610/* Forward reference */
34611static int openDirectory(const char*, int*);
34612static int unixGetpagesize(void);
34613
34614/*
34615** Many system calls are accessed through pointer-to-functions so that
34616** they may be overridden at runtime to facilitate fault injection during
34617** testing and sandboxing. The following array holds the names and pointers
34618** to all overrideable system calls.
34619*/
34620static struct unix_syscall {
34621 const char *zName; /* Name of the system call */
34622 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
34623 sqlite3_syscall_ptr pDefault; /* Default value */
34624} aSyscall[] = {
34625 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
34626#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
34627
34628 { "close", (sqlite3_syscall_ptr)close, 0 },
34629#define osClose ((int(*)(int))aSyscall[1].pCurrent)
34630
34631 { "access", (sqlite3_syscall_ptr)access, 0 },
34632#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
34633
34634 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
34635#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
34636
34637 { "stat", (sqlite3_syscall_ptr)stat, 0 },
34638#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
34639
34640/*
34641** The DJGPP compiler environment looks mostly like Unix, but it
34642** lacks the fcntl() system call. So redefine fcntl() to be something
34643** that always succeeds. This means that locking does not occur under
34644** DJGPP. But it is DOS - what did you expect?
34645*/
34646#ifdef __DJGPP__
34647 { "fstat", 0, 0 },
34648#define osFstat(a,b,c) 0
34649#else
34650 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
34651#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
34652#endif
34653
34654 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
34655#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
34656
34657 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
34658#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
34659
34660 { "read", (sqlite3_syscall_ptr)read, 0 },
34661#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
34662
34663#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
34664 { "pread", (sqlite3_syscall_ptr)pread, 0 },
34665#else
34666 { "pread", (sqlite3_syscall_ptr)0, 0 },
34667#endif
34668#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
34669
34670#if defined(USE_PREAD64)
34671 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
34672#else
34673 { "pread64", (sqlite3_syscall_ptr)0, 0 },
34674#endif
34675#define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
34676
34677 { "write", (sqlite3_syscall_ptr)write, 0 },
34678#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
34679
34680#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
34681 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
34682#else
34683 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
34684#endif
34685#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
34686 aSyscall[12].pCurrent)
34687
34688#if defined(USE_PREAD64)
34689 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
34690#else
34691 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
34692#endif
34693#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
34694 aSyscall[13].pCurrent)
34695
34696 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
34697#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
34698
34699#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
34700 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
34701#else
34702 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
34703#endif
34704#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
34705
34706 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
34707#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
34708
34709 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
34710#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
34711
34712 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
34713#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
34714
34715 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
34716#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
34717
34718#if defined(HAVE_FCHOWN)
34719 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
34720#else
34721 { "fchown", (sqlite3_syscall_ptr)0, 0 },
34722#endif
34723#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
34724
34725#if defined(HAVE_FCHOWN)
34726 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
34727#else
34728 { "geteuid", (sqlite3_syscall_ptr)0, 0 },
34729#endif
34730#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
34731
34732#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
34733 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
34734#else
34735 { "mmap", (sqlite3_syscall_ptr)0, 0 },
34736#endif
34737#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
34738
34739#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
34740 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
34741#else
34742 { "munmap", (sqlite3_syscall_ptr)0, 0 },
34743#endif
34744#define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
34745
34746#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
34747 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
34748#else
34749 { "mremap", (sqlite3_syscall_ptr)0, 0 },
34750#endif
34751#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
34752
34753#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
34754 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
34755#else
34756 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
34757#endif
34758#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
34759
34760#if defined(HAVE_READLINK)
34761 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
34762#else
34763 { "readlink", (sqlite3_syscall_ptr)0, 0 },
34764#endif
34765#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
34766
34767#if defined(HAVE_LSTAT)
34768 { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
34769#else
34770 { "lstat", (sqlite3_syscall_ptr)0, 0 },
34771#endif
34772#define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
34773
34774#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
34775# ifdef __ANDROID__
34776 { "ioctl", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 },
34777#define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
34778# else
34779 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
34780#define osIoctl ((int(*)(int,unsigned long,...))aSyscall[28].pCurrent)
34781# endif
34782#else
34783 { "ioctl", (sqlite3_syscall_ptr)0, 0 },
34784#endif
34785
34786}; /* End of the overrideable system calls */
34787
34788
34789/*
34790** On some systems, calls to fchown() will trigger a message in a security
34791** log if they come from non-root processes. So avoid calling fchown() if
34792** we are not running as root.
34793*/
34794static int robustFchown(int fd, uid_t uid, gid_t gid){
34795#if defined(HAVE_FCHOWN)
34796 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
34797#else
34798 return 0;
34799#endif
34800}
34801
34802/*
34803** This is the xSetSystemCall() method of sqlite3_vfs for all of the
34804** "unix" VFSes. Return SQLITE_OK opon successfully updating the
34805** system call pointer, or SQLITE_NOTFOUND if there is no configurable
34806** system call named zName.
34807*/
34808static int unixSetSystemCall(
34809 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
34810 const char *zName, /* Name of system call to override */
34811 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
34812){
34813 unsigned int i;
34814 int rc = SQLITE_NOTFOUND;
34815
34816 UNUSED_PARAMETER(pNotUsed);
34817 if( zName==0 ){
34818 /* If no zName is given, restore all system calls to their default
34819 ** settings and return NULL
34820 */
34821 rc = SQLITE_OK;
34822 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
34823 if( aSyscall[i].pDefault ){
34824 aSyscall[i].pCurrent = aSyscall[i].pDefault;
34825 }
34826 }
34827 }else{
34828 /* If zName is specified, operate on only the one system call
34829 ** specified.
34830 */
34831 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
34832 if( strcmp(s1: zName, s2: aSyscall[i].zName)==0 ){
34833 if( aSyscall[i].pDefault==0 ){
34834 aSyscall[i].pDefault = aSyscall[i].pCurrent;
34835 }
34836 rc = SQLITE_OK;
34837 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
34838 aSyscall[i].pCurrent = pNewFunc;
34839 break;
34840 }
34841 }
34842 }
34843 return rc;
34844}
34845
34846/*
34847** Return the value of a system call. Return NULL if zName is not a
34848** recognized system call name. NULL is also returned if the system call
34849** is currently undefined.
34850*/
34851static sqlite3_syscall_ptr unixGetSystemCall(
34852 sqlite3_vfs *pNotUsed,
34853 const char *zName
34854){
34855 unsigned int i;
34856
34857 UNUSED_PARAMETER(pNotUsed);
34858 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
34859 if( strcmp(s1: zName, s2: aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
34860 }
34861 return 0;
34862}
34863
34864/*
34865** Return the name of the first system call after zName. If zName==NULL
34866** then return the name of the first system call. Return NULL if zName
34867** is the last system call or if zName is not the name of a valid
34868** system call.
34869*/
34870static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
34871 int i = -1;
34872
34873 UNUSED_PARAMETER(p);
34874 if( zName ){
34875 for(i=0; i<ArraySize(aSyscall)-1; i++){
34876 if( strcmp(s1: zName, s2: aSyscall[i].zName)==0 ) break;
34877 }
34878 }
34879 for(i++; i<ArraySize(aSyscall); i++){
34880 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
34881 }
34882 return 0;
34883}
34884
34885/*
34886** Do not accept any file descriptor less than this value, in order to avoid
34887** opening database file using file descriptors that are commonly used for
34888** standard input, output, and error.
34889*/
34890#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
34891# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
34892#endif
34893
34894/*
34895** Invoke open(). Do so multiple times, until it either succeeds or
34896** fails for some reason other than EINTR.
34897**
34898** If the file creation mode "m" is 0 then set it to the default for
34899** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
34900** 0644) as modified by the system umask. If m is not 0, then
34901** make the file creation mode be exactly m ignoring the umask.
34902**
34903** The m parameter will be non-zero only when creating -wal, -journal,
34904** and -shm files. We want those files to have *exactly* the same
34905** permissions as their original database, unadulterated by the umask.
34906** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
34907** transaction crashes and leaves behind hot journals, then any
34908** process that is able to write to the database will also be able to
34909** recover the hot journals.
34910*/
34911static int robust_open(const char *z, int f, mode_t m){
34912 int fd;
34913 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
34914 while(1){
34915#if defined(O_CLOEXEC)
34916 fd = osOpen(z,f|O_CLOEXEC,m2);
34917#else
34918 fd = osOpen(z,f,m2);
34919#endif
34920 if( fd<0 ){
34921 if( errno==EINTR ) continue;
34922 break;
34923 }
34924 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
34925 osClose(fd);
34926 sqlite3_log(SQLITE_WARNING,
34927 zFormat: "attempt to open \"%s\" as file descriptor %d", z, fd);
34928 fd = -1;
34929 if( osOpen("/dev/null", O_RDONLY, m)<0 ) break;
34930 }
34931 if( fd>=0 ){
34932 if( m!=0 ){
34933 struct stat statbuf;
34934 if( osFstat(fd, &statbuf)==0
34935 && statbuf.st_size==0
34936 && (statbuf.st_mode&0777)!=m
34937 ){
34938 osFchmod(fd, m);
34939 }
34940 }
34941#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
34942 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
34943#endif
34944 }
34945 return fd;
34946}
34947
34948/*
34949** Helper functions to obtain and relinquish the global mutex. The
34950** global mutex is used to protect the unixInodeInfo and
34951** vxworksFileId objects used by this file, all of which may be
34952** shared by multiple threads.
34953**
34954** Function unixMutexHeld() is used to assert() that the global mutex
34955** is held when required. This function is only used as part of assert()
34956** statements. e.g.
34957**
34958** unixEnterMutex()
34959** assert( unixMutexHeld() );
34960** unixEnterLeave()
34961**
34962** To prevent deadlock, the global unixBigLock must must be acquired
34963** before the unixInodeInfo.pLockMutex mutex, if both are held. It is
34964** OK to get the pLockMutex without holding unixBigLock first, but if
34965** that happens, the unixBigLock mutex must not be acquired until after
34966** pLockMutex is released.
34967**
34968** OK: enter(unixBigLock), enter(pLockInfo)
34969** OK: enter(unixBigLock)
34970** OK: enter(pLockInfo)
34971** ERROR: enter(pLockInfo), enter(unixBigLock)
34972*/
34973static sqlite3_mutex *unixBigLock = 0;
34974static void unixEnterMutex(void){
34975 assert( sqlite3_mutex_notheld(unixBigLock) ); /* Not a recursive mutex */
34976 sqlite3_mutex_enter(p: unixBigLock);
34977}
34978static void unixLeaveMutex(void){
34979 assert( sqlite3_mutex_held(unixBigLock) );
34980 sqlite3_mutex_leave(p: unixBigLock);
34981}
34982#ifdef SQLITE_DEBUG
34983static int unixMutexHeld(void) {
34984 return sqlite3_mutex_held(unixBigLock);
34985}
34986#endif
34987
34988
34989#ifdef SQLITE_HAVE_OS_TRACE
34990/*
34991** Helper function for printing out trace information from debugging
34992** binaries. This returns the string representation of the supplied
34993** integer lock-type.
34994*/
34995static const char *azFileLock(int eFileLock){
34996 switch( eFileLock ){
34997 case NO_LOCK: return "NONE";
34998 case SHARED_LOCK: return "SHARED";
34999 case RESERVED_LOCK: return "RESERVED";
35000 case PENDING_LOCK: return "PENDING";
35001 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
35002 }
35003 return "ERROR";
35004}
35005#endif
35006
35007#ifdef SQLITE_LOCK_TRACE
35008/*
35009** Print out information about all locking operations.
35010**
35011** This routine is used for troubleshooting locks on multithreaded
35012** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
35013** command-line option on the compiler. This code is normally
35014** turned off.
35015*/
35016static int lockTrace(int fd, int op, struct flock *p){
35017 char *zOpName, *zType;
35018 int s;
35019 int savedErrno;
35020 if( op==F_GETLK ){
35021 zOpName = "GETLK";
35022 }else if( op==F_SETLK ){
35023 zOpName = "SETLK";
35024 }else{
35025 s = osFcntl(fd, op, p);
35026 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
35027 return s;
35028 }
35029 if( p->l_type==F_RDLCK ){
35030 zType = "RDLCK";
35031 }else if( p->l_type==F_WRLCK ){
35032 zType = "WRLCK";
35033 }else if( p->l_type==F_UNLCK ){
35034 zType = "UNLCK";
35035 }else{
35036 assert( 0 );
35037 }
35038 assert( p->l_whence==SEEK_SET );
35039 s = osFcntl(fd, op, p);
35040 savedErrno = errno;
35041 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
35042 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
35043 (int)p->l_pid, s);
35044 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
35045 struct flock l2;
35046 l2 = *p;
35047 osFcntl(fd, F_GETLK, &l2);
35048 if( l2.l_type==F_RDLCK ){
35049 zType = "RDLCK";
35050 }else if( l2.l_type==F_WRLCK ){
35051 zType = "WRLCK";
35052 }else if( l2.l_type==F_UNLCK ){
35053 zType = "UNLCK";
35054 }else{
35055 assert( 0 );
35056 }
35057 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
35058 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
35059 }
35060 errno = savedErrno;
35061 return s;
35062}
35063#undef osFcntl
35064#define osFcntl lockTrace
35065#endif /* SQLITE_LOCK_TRACE */
35066
35067/*
35068** Retry ftruncate() calls that fail due to EINTR
35069**
35070** All calls to ftruncate() within this file should be made through
35071** this wrapper. On the Android platform, bypassing the logic below
35072** could lead to a corrupt database.
35073*/
35074static int robust_ftruncate(int h, sqlite3_int64 sz){
35075 int rc;
35076#ifdef __ANDROID__
35077 /* On Android, ftruncate() always uses 32-bit offsets, even if
35078 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
35079 ** truncate a file to any size larger than 2GiB. Silently ignore any
35080 ** such attempts. */
35081 if( sz>(sqlite3_int64)0x7FFFFFFF ){
35082 rc = SQLITE_OK;
35083 }else
35084#endif
35085 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
35086 return rc;
35087}
35088
35089/*
35090** This routine translates a standard POSIX errno code into something
35091** useful to the clients of the sqlite3 functions. Specifically, it is
35092** intended to translate a variety of "try again" errors into SQLITE_BUSY
35093** and a variety of "please close the file descriptor NOW" errors into
35094** SQLITE_IOERR
35095**
35096** Errors during initialization of locks, or file system support for locks,
35097** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
35098*/
35099static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
35100 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
35101 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
35102 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
35103 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
35104 switch (posixError) {
35105 case EACCES:
35106 case EAGAIN:
35107 case ETIMEDOUT:
35108 case EBUSY:
35109 case EINTR:
35110 case ENOLCK:
35111 /* random NFS retry error, unless during file system support
35112 * introspection, in which it actually means what it says */
35113 return SQLITE_BUSY;
35114
35115 case EPERM:
35116 return SQLITE_PERM;
35117
35118 default:
35119 return sqliteIOErr;
35120 }
35121}
35122
35123
35124/******************************************************************************
35125****************** Begin Unique File ID Utility Used By VxWorks ***************
35126**
35127** On most versions of unix, we can get a unique ID for a file by concatenating
35128** the device number and the inode number. But this does not work on VxWorks.
35129** On VxWorks, a unique file id must be based on the canonical filename.
35130**
35131** A pointer to an instance of the following structure can be used as a
35132** unique file ID in VxWorks. Each instance of this structure contains
35133** a copy of the canonical filename. There is also a reference count.
35134** The structure is reclaimed when the number of pointers to it drops to
35135** zero.
35136**
35137** There are never very many files open at one time and lookups are not
35138** a performance-critical path, so it is sufficient to put these
35139** structures on a linked list.
35140*/
35141struct vxworksFileId {
35142 struct vxworksFileId *pNext; /* Next in a list of them all */
35143 int nRef; /* Number of references to this one */
35144 int nName; /* Length of the zCanonicalName[] string */
35145 char *zCanonicalName; /* Canonical filename */
35146};
35147
35148#if OS_VXWORKS
35149/*
35150** All unique filenames are held on a linked list headed by this
35151** variable:
35152*/
35153static struct vxworksFileId *vxworksFileList = 0;
35154
35155/*
35156** Simplify a filename into its canonical form
35157** by making the following changes:
35158**
35159** * removing any trailing and duplicate /
35160** * convert /./ into just /
35161** * convert /A/../ where A is any simple name into just /
35162**
35163** Changes are made in-place. Return the new name length.
35164**
35165** The original filename is in z[0..n-1]. Return the number of
35166** characters in the simplified name.
35167*/
35168static int vxworksSimplifyName(char *z, int n){
35169 int i, j;
35170 while( n>1 && z[n-1]=='/' ){ n--; }
35171 for(i=j=0; i<n; i++){
35172 if( z[i]=='/' ){
35173 if( z[i+1]=='/' ) continue;
35174 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
35175 i += 1;
35176 continue;
35177 }
35178 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
35179 while( j>0 && z[j-1]!='/' ){ j--; }
35180 if( j>0 ){ j--; }
35181 i += 2;
35182 continue;
35183 }
35184 }
35185 z[j++] = z[i];
35186 }
35187 z[j] = 0;
35188 return j;
35189}
35190
35191/*
35192** Find a unique file ID for the given absolute pathname. Return
35193** a pointer to the vxworksFileId object. This pointer is the unique
35194** file ID.
35195**
35196** The nRef field of the vxworksFileId object is incremented before
35197** the object is returned. A new vxworksFileId object is created
35198** and added to the global list if necessary.
35199**
35200** If a memory allocation error occurs, return NULL.
35201*/
35202static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
35203 struct vxworksFileId *pNew; /* search key and new file ID */
35204 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
35205 int n; /* Length of zAbsoluteName string */
35206
35207 assert( zAbsoluteName[0]=='/' );
35208 n = (int)strlen(zAbsoluteName);
35209 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
35210 if( pNew==0 ) return 0;
35211 pNew->zCanonicalName = (char*)&pNew[1];
35212 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
35213 n = vxworksSimplifyName(pNew->zCanonicalName, n);
35214
35215 /* Search for an existing entry that matching the canonical name.
35216 ** If found, increment the reference count and return a pointer to
35217 ** the existing file ID.
35218 */
35219 unixEnterMutex();
35220 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
35221 if( pCandidate->nName==n
35222 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
35223 ){
35224 sqlite3_free(pNew);
35225 pCandidate->nRef++;
35226 unixLeaveMutex();
35227 return pCandidate;
35228 }
35229 }
35230
35231 /* No match was found. We will make a new file ID */
35232 pNew->nRef = 1;
35233 pNew->nName = n;
35234 pNew->pNext = vxworksFileList;
35235 vxworksFileList = pNew;
35236 unixLeaveMutex();
35237 return pNew;
35238}
35239
35240/*
35241** Decrement the reference count on a vxworksFileId object. Free
35242** the object when the reference count reaches zero.
35243*/
35244static void vxworksReleaseFileId(struct vxworksFileId *pId){
35245 unixEnterMutex();
35246 assert( pId->nRef>0 );
35247 pId->nRef--;
35248 if( pId->nRef==0 ){
35249 struct vxworksFileId **pp;
35250 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
35251 assert( *pp==pId );
35252 *pp = pId->pNext;
35253 sqlite3_free(pId);
35254 }
35255 unixLeaveMutex();
35256}
35257#endif /* OS_VXWORKS */
35258/*************** End of Unique File ID Utility Used By VxWorks ****************
35259******************************************************************************/
35260
35261
35262/******************************************************************************
35263*************************** Posix Advisory Locking ****************************
35264**
35265** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
35266** section 6.5.2.2 lines 483 through 490 specify that when a process
35267** sets or clears a lock, that operation overrides any prior locks set
35268** by the same process. It does not explicitly say so, but this implies
35269** that it overrides locks set by the same process using a different
35270** file descriptor. Consider this test case:
35271**
35272** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
35273** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
35274**
35275** Suppose ./file1 and ./file2 are really the same file (because
35276** one is a hard or symbolic link to the other) then if you set
35277** an exclusive lock on fd1, then try to get an exclusive lock
35278** on fd2, it works. I would have expected the second lock to
35279** fail since there was already a lock on the file due to fd1.
35280** But not so. Since both locks came from the same process, the
35281** second overrides the first, even though they were on different
35282** file descriptors opened on different file names.
35283**
35284** This means that we cannot use POSIX locks to synchronize file access
35285** among competing threads of the same process. POSIX locks will work fine
35286** to synchronize access for threads in separate processes, but not
35287** threads within the same process.
35288**
35289** To work around the problem, SQLite has to manage file locks internally
35290** on its own. Whenever a new database is opened, we have to find the
35291** specific inode of the database file (the inode is determined by the
35292** st_dev and st_ino fields of the stat structure that fstat() fills in)
35293** and check for locks already existing on that inode. When locks are
35294** created or removed, we have to look at our own internal record of the
35295** locks to see if another thread has previously set a lock on that same
35296** inode.
35297**
35298** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
35299** For VxWorks, we have to use the alternative unique ID system based on
35300** canonical filename and implemented in the previous division.)
35301**
35302** The sqlite3_file structure for POSIX is no longer just an integer file
35303** descriptor. It is now a structure that holds the integer file
35304** descriptor and a pointer to a structure that describes the internal
35305** locks on the corresponding inode. There is one locking structure
35306** per inode, so if the same inode is opened twice, both unixFile structures
35307** point to the same locking structure. The locking structure keeps
35308** a reference count (so we will know when to delete it) and a "cnt"
35309** field that tells us its internal lock status. cnt==0 means the
35310** file is unlocked. cnt==-1 means the file has an exclusive lock.
35311** cnt>0 means there are cnt shared locks on the file.
35312**
35313** Any attempt to lock or unlock a file first checks the locking
35314** structure. The fcntl() system call is only invoked to set a
35315** POSIX lock if the internal lock structure transitions between
35316** a locked and an unlocked state.
35317**
35318** But wait: there are yet more problems with POSIX advisory locks.
35319**
35320** If you close a file descriptor that points to a file that has locks,
35321** all locks on that file that are owned by the current process are
35322** released. To work around this problem, each unixInodeInfo object
35323** maintains a count of the number of pending locks on tha inode.
35324** When an attempt is made to close an unixFile, if there are
35325** other unixFile open on the same inode that are holding locks, the call
35326** to close() the file descriptor is deferred until all of the locks clear.
35327** The unixInodeInfo structure keeps a list of file descriptors that need to
35328** be closed and that list is walked (and cleared) when the last lock
35329** clears.
35330**
35331** Yet another problem: LinuxThreads do not play well with posix locks.
35332**
35333** Many older versions of linux use the LinuxThreads library which is
35334** not posix compliant. Under LinuxThreads, a lock created by thread
35335** A cannot be modified or overridden by a different thread B.
35336** Only thread A can modify the lock. Locking behavior is correct
35337** if the appliation uses the newer Native Posix Thread Library (NPTL)
35338** on linux - with NPTL a lock created by thread A can override locks
35339** in thread B. But there is no way to know at compile-time which
35340** threading library is being used. So there is no way to know at
35341** compile-time whether or not thread A can override locks on thread B.
35342** One has to do a run-time check to discover the behavior of the
35343** current process.
35344**
35345** SQLite used to support LinuxThreads. But support for LinuxThreads
35346** was dropped beginning with version 3.7.0. SQLite will still work with
35347** LinuxThreads provided that (1) there is no more than one connection
35348** per database file in the same process and (2) database connections
35349** do not move across threads.
35350*/
35351
35352/*
35353** An instance of the following structure serves as the key used
35354** to locate a particular unixInodeInfo object.
35355*/
35356struct unixFileId {
35357 dev_t dev; /* Device number */
35358#if OS_VXWORKS
35359 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
35360#else
35361 /* We are told that some versions of Android contain a bug that
35362 ** sizes ino_t at only 32-bits instead of 64-bits. (See
35363 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
35364 ** To work around this, always allocate 64-bits for the inode number.
35365 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
35366 ** but that should not be a big deal. */
35367 /* WAS: ino_t ino; */
35368 u64 ino; /* Inode number */
35369#endif
35370};
35371
35372/*
35373** An instance of the following structure is allocated for each open
35374** inode.
35375**
35376** A single inode can have multiple file descriptors, so each unixFile
35377** structure contains a pointer to an instance of this object and this
35378** object keeps a count of the number of unixFile pointing to it.
35379**
35380** Mutex rules:
35381**
35382** (1) Only the pLockMutex mutex must be held in order to read or write
35383** any of the locking fields:
35384** nShared, nLock, eFileLock, bProcessLock, pUnused
35385**
35386** (2) When nRef>0, then the following fields are unchanging and can
35387** be read (but not written) without holding any mutex:
35388** fileId, pLockMutex
35389**
35390** (3) With the exceptions above, all the fields may only be read
35391** or written while holding the global unixBigLock mutex.
35392**
35393** Deadlock prevention: The global unixBigLock mutex may not
35394** be acquired while holding the pLockMutex mutex. If both unixBigLock
35395** and pLockMutex are needed, then unixBigLock must be acquired first.
35396*/
35397struct unixInodeInfo {
35398 struct unixFileId fileId; /* The lookup key */
35399 sqlite3_mutex *pLockMutex; /* Hold this mutex for... */
35400 int nShared; /* Number of SHARED locks held */
35401 int nLock; /* Number of outstanding file locks */
35402 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
35403 unsigned char bProcessLock; /* An exclusive process lock is held */
35404 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
35405 int nRef; /* Number of pointers to this structure */
35406 unixShmNode *pShmNode; /* Shared memory associated with this inode */
35407 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
35408 unixInodeInfo *pPrev; /* .... doubly linked */
35409#if SQLITE_ENABLE_LOCKING_STYLE
35410 unsigned long long sharedByte; /* for AFP simulated shared lock */
35411#endif
35412#if OS_VXWORKS
35413 sem_t *pSem; /* Named POSIX semaphore */
35414 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
35415#endif
35416};
35417
35418/*
35419** A lists of all unixInodeInfo objects.
35420**
35421** Must hold unixBigLock in order to read or write this variable.
35422*/
35423static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
35424
35425#ifdef SQLITE_DEBUG
35426/*
35427** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not.
35428** This routine is used only within assert() to help verify correct mutex
35429** usage.
35430*/
35431int unixFileMutexHeld(unixFile *pFile){
35432 assert( pFile->pInode );
35433 return sqlite3_mutex_held(pFile->pInode->pLockMutex);
35434}
35435int unixFileMutexNotheld(unixFile *pFile){
35436 assert( pFile->pInode );
35437 return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);
35438}
35439#endif
35440
35441/*
35442**
35443** This function - unixLogErrorAtLine(), is only ever called via the macro
35444** unixLogError().
35445**
35446** It is invoked after an error occurs in an OS function and errno has been
35447** set. It logs a message using sqlite3_log() containing the current value of
35448** errno and, if possible, the human-readable equivalent from strerror() or
35449** strerror_r().
35450**
35451** The first argument passed to the macro should be the error code that
35452** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
35453** The two s