Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(82)

Side by Side Diff: third_party/sqlite/amalgamation/sqlite3.00.c

Issue 1636873003: Try for backport (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@zzsql_import3_10_2_websql_backport
Patch Set: Created 4 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « third_party/sqlite/BUILD.gn ('k') | third_party/sqlite/amalgamation/sqlite3.01.c » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.10.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 /*
44 ** Include the header file used to customize the compiler options for MSVC.
45 ** This should be done first so that it can successfully prevent spurious
46 ** compiler warnings due to subsequent content in this file and other files
47 ** that are included by this file.
48 */
49 /************** Include msvc.h in the middle of sqliteInt.h ******************/
50 /************** Begin file msvc.h ********************************************/
51 /*
52 ** 2015 January 12
53 **
54 ** The author disclaims copyright to this source code. In place of
55 ** a legal notice, here is a blessing:
56 **
57 ** May you do good and not evil.
58 ** May you find forgiveness for yourself and forgive others.
59 ** May you share freely, never taking more than you give.
60 **
61 ******************************************************************************
62 **
63 ** This file contains code that is specific to MSVC.
64 */
65 #ifndef _MSVC_H_
66 #define _MSVC_H_
67
68 #if defined(_MSC_VER)
69 #pragma warning(disable : 4054)
70 #pragma warning(disable : 4055)
71 #pragma warning(disable : 4100)
72 #pragma warning(disable : 4127)
73 #pragma warning(disable : 4130)
74 #pragma warning(disable : 4152)
75 #pragma warning(disable : 4189)
76 #pragma warning(disable : 4206)
77 #pragma warning(disable : 4210)
78 #pragma warning(disable : 4232)
79 #pragma warning(disable : 4244)
80 #pragma warning(disable : 4305)
81 #pragma warning(disable : 4306)
82 #pragma warning(disable : 4702)
83 #pragma warning(disable : 4706)
84 #endif /* defined(_MSC_VER) */
85
86 #endif /* _MSVC_H_ */
87
88 /************** End of msvc.h ************************************************/
89 /************** Continuing where we left off in sqliteInt.h ******************/
90
91 /*
92 ** Special setup for VxWorks
93 */
94 /************** Include vxworks.h in the middle of sqliteInt.h ***************/
95 /************** Begin file vxworks.h *****************************************/
96 /*
97 ** 2015-03-02
98 **
99 ** The author disclaims copyright to this source code. In place of
100 ** a legal notice, here is a blessing:
101 **
102 ** May you do good and not evil.
103 ** May you find forgiveness for yourself and forgive others.
104 ** May you share freely, never taking more than you give.
105 **
106 ******************************************************************************
107 **
108 ** This file contains code that is specific to Wind River's VxWorks
109 */
110 #if defined(__RTP__) || defined(_WRS_KERNEL)
111 /* This is VxWorks. Set up things specially for that OS
112 */
113 #include <vxWorks.h>
114 #include <pthread.h> /* amalgamator: dontcache */
115 #define OS_VXWORKS 1
116 #define SQLITE_OS_OTHER 0
117 #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
118 #define SQLITE_OMIT_LOAD_EXTENSION 1
119 #define SQLITE_ENABLE_LOCKING_STYLE 0
120 #define HAVE_UTIME 1
121 #else
122 /* This is not VxWorks. */
123 #define OS_VXWORKS 0
124 #endif /* defined(_WRS_KERNEL) */
125
126 /************** End of vxworks.h *********************************************/
127 /************** Continuing where we left off in sqliteInt.h ******************/
128
129 /*
130 ** These #defines should enable >2GB file support on POSIX if the
131 ** underlying operating system supports it. If the OS lacks
132 ** large file support, or if the OS is windows, these should be no-ops.
133 **
134 ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
135 ** system #includes. Hence, this block of code must be the very first
136 ** code in all source files.
137 **
138 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
139 ** on the compiler command line. This is necessary if you are compiling
140 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
141 ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
142 ** without this option, LFS is enable. But LFS does not exist in the kernel
143 ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
144 ** portability you should omit LFS.
145 **
146 ** The previous paragraph was written in 2005. (This paragraph is written
147 ** on 2008-11-28.) These days, all Linux kernels support large files, so
148 ** you should probably leave LFS enabled. But some embedded platforms might
149 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
150 **
151 ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
152 */
153 #ifndef SQLITE_DISABLE_LFS
154 # define _LARGE_FILE 1
155 # ifndef _FILE_OFFSET_BITS
156 # define _FILE_OFFSET_BITS 64
157 # endif
158 # define _LARGEFILE_SOURCE 1
159 #endif
160
161 /* What version of GCC is being used. 0 means GCC is not being used */
162 #ifdef __GNUC__
163 # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
164 #else
165 # define GCC_VERSION 0
166 #endif
167
168 /* Needed for various definitions... */
169 #if defined(__GNUC__) && !defined(_GNU_SOURCE)
170 # define _GNU_SOURCE
171 #endif
172
173 #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
174 # define _BSD_SOURCE
175 #endif
176
177 /*
178 ** For MinGW, check to see if we can include the header file containing its
179 ** version information, among other things. Normally, this internal MinGW
180 ** header file would [only] be included automatically by other MinGW header
181 ** files; however, the contained version information is now required by this
182 ** header file to work around binary compatibility issues (see below) and
183 ** this is the only known way to reliably obtain it. This entire #if block
184 ** would be completely unnecessary if there was any other way of detecting
185 ** MinGW via their preprocessor (e.g. if they customized their GCC to define
186 ** some MinGW-specific macros). When compiling for MinGW, either the
187 ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
188 ** defined; otherwise, detection of conditions specific to MinGW will be
189 ** disabled.
190 */
191 #if defined(_HAVE_MINGW_H)
192 # include "mingw.h"
193 #elif defined(_HAVE__MINGW_H)
194 # include "_mingw.h"
195 #endif
196
197 /*
198 ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
199 ** define is required to maintain binary compatibility with the MSVC runtime
200 ** library in use (e.g. for Windows XP).
201 */
202 #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
203 defined(_WIN32) && !defined(_WIN64) && \
204 defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
205 defined(__MSVCRT__)
206 # define _USE_32BIT_TIME_T
207 #endif
208
209 /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
210 ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
211 ** MinGW.
212 */
213 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
214 /************** Begin file sqlite3.h *****************************************/
215 /*
216 ** 2001 September 15
217 **
218 ** The author disclaims copyright to this source code. In place of
219 ** a legal notice, here is a blessing:
220 **
221 ** May you do good and not evil.
222 ** May you find forgiveness for yourself and forgive others.
223 ** May you share freely, never taking more than you give.
224 **
225 *************************************************************************
226 ** This header file defines the interface that the SQLite library
227 ** presents to client programs. If a C-function, structure, datatype,
228 ** or constant definition does not appear in this file, then it is
229 ** not a published API of SQLite, is subject to change without
230 ** notice, and should not be referenced by programs that use SQLite.
231 **
232 ** Some of the definitions that are in this file are marked as
233 ** "experimental". Experimental interfaces are normally new
234 ** features recently added to SQLite. We do not anticipate changes
235 ** to experimental interfaces but reserve the right to make minor changes
236 ** if experience from use "in the wild" suggest such changes are prudent.
237 **
238 ** The official C-language API documentation for SQLite is derived
239 ** from comments in this file. This file is the authoritative source
240 ** on how SQLite interfaces are supposed to operate.
241 **
242 ** The name of this file under configuration management is "sqlite.h.in".
243 ** The makefile makes some minor changes to this file (such as inserting
244 ** the version number) and changes its name to "sqlite3.h" as
245 ** part of the build process.
246 */
247 #ifndef _SQLITE3_H_
248 #define _SQLITE3_H_
249 #include <stdarg.h> /* Needed for the definition of va_list */
250
251 /*
252 ** Make sure we can call this stuff from C++.
253 */
254 #if 0
255 extern "C" {
256 #endif
257
258
259 /*
260 ** Provide the ability to override linkage features of the interface.
261 */
262 #ifndef SQLITE_EXTERN
263 # define SQLITE_EXTERN extern
264 #endif
265 #ifndef SQLITE_API
266 # define SQLITE_API
267 #endif
268 #ifndef SQLITE_CDECL
269 # define SQLITE_CDECL
270 #endif
271 #ifndef SQLITE_STDCALL
272 # define SQLITE_STDCALL
273 #endif
274
275 /*
276 ** These no-op macros are used in front of interfaces to mark those
277 ** interfaces as either deprecated or experimental. New applications
278 ** should not use deprecated interfaces - they are supported for backwards
279 ** compatibility only. Application writers should be aware that
280 ** experimental interfaces are subject to change in point releases.
281 **
282 ** These macros used to resolve to various kinds of compiler magic that
283 ** would generate warning messages when they were used. But that
284 ** compiler magic ended up generating such a flurry of bug reports
285 ** that we have taken it all out and gone back to using simple
286 ** noop macros.
287 */
288 #define SQLITE_DEPRECATED
289 #define SQLITE_EXPERIMENTAL
290
291 /*
292 ** Ensure these symbols were not defined by some previous header file.
293 */
294 #ifdef SQLITE_VERSION
295 # undef SQLITE_VERSION
296 #endif
297 #ifdef SQLITE_VERSION_NUMBER
298 # undef SQLITE_VERSION_NUMBER
299 #endif
300
301 /*
302 ** CAPI3REF: Compile-Time Library Version Numbers
303 **
304 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
305 ** evaluates to a string literal that is the SQLite version in the
306 ** format "X.Y.Z" where X is the major version number (always 3 for
307 ** SQLite3) and Y is the minor version number and Z is the release number.)^
308 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
309 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
310 ** numbers used in [SQLITE_VERSION].)^
311 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
312 ** be larger than the release from which it is derived. Either Y will
313 ** be held constant and Z will be incremented or else Y will be incremented
314 ** and Z will be reset to zero.
315 **
316 ** Since version 3.6.18, SQLite source code has been stored in the
317 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
318 ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
319 ** a string which identifies a particular check-in of SQLite
320 ** within its configuration management system. ^The SQLITE_SOURCE_ID
321 ** string contains the date and time of the check-in (UTC) and an SHA1
322 ** hash of the entire source tree.
323 **
324 ** See also: [sqlite3_libversion()],
325 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
326 ** [sqlite_version()] and [sqlite_source_id()].
327 */
328 #define SQLITE_VERSION "3.10.2"
329 #define SQLITE_VERSION_NUMBER 3010002
330 #define SQLITE_SOURCE_ID "2016-01-20 15:27:19 17efb4209f97fb4971656086b1385 99a91a75ff9"
331
332 /*
333 ** CAPI3REF: Run-Time Library Version Numbers
334 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
335 **
336 ** These interfaces provide the same information as the [SQLITE_VERSION],
337 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
338 ** but are associated with the library instead of the header file. ^(Cautious
339 ** programmers might include assert() statements in their application to
340 ** verify that values returned by these interfaces match the macros in
341 ** the header, and thus ensure that the application is
342 ** compiled with matching library and header files.
343 **
344 ** <blockquote><pre>
345 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
346 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
347 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
348 ** </pre></blockquote>)^
349 **
350 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
351 ** macro. ^The sqlite3_libversion() function returns a pointer to the
352 ** to the sqlite3_version[] string constant. The sqlite3_libversion()
353 ** function is provided for use in DLLs since DLL users usually do not have
354 ** direct access to string constants within the DLL. ^The
355 ** sqlite3_libversion_number() function returns an integer equal to
356 ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
357 ** a pointer to a string constant whose value is the same as the
358 ** [SQLITE_SOURCE_ID] C preprocessor macro.
359 **
360 ** See also: [sqlite_version()] and [sqlite_source_id()].
361 */
362 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
363 SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void);
364 SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void);
365 SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void);
366
367 /*
368 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
369 **
370 ** ^The sqlite3_compileoption_used() function returns 0 or 1
371 ** indicating whether the specified option was defined at
372 ** compile time. ^The SQLITE_ prefix may be omitted from the
373 ** option name passed to sqlite3_compileoption_used().
374 **
375 ** ^The sqlite3_compileoption_get() function allows iterating
376 ** over the list of options that were defined at compile time by
377 ** returning the N-th compile time option string. ^If N is out of range,
378 ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
379 ** prefix is omitted from any strings returned by
380 ** sqlite3_compileoption_get().
381 **
382 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
383 ** and sqlite3_compileoption_get() may be omitted by specifying the
384 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
385 **
386 ** See also: SQL functions [sqlite_compileoption_used()] and
387 ** [sqlite_compileoption_get()] and the [compile_options pragma].
388 */
389 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
390 SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName);
391 SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N);
392 #endif
393
394 /*
395 ** CAPI3REF: Test To See If The Library Is Threadsafe
396 **
397 ** ^The sqlite3_threadsafe() function returns zero if and only if
398 ** SQLite was compiled with mutexing code omitted due to the
399 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
400 **
401 ** SQLite can be compiled with or without mutexes. When
402 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
403 ** are enabled and SQLite is threadsafe. When the
404 ** [SQLITE_THREADSAFE] macro is 0,
405 ** the mutexes are omitted. Without the mutexes, it is not safe
406 ** to use SQLite concurrently from more than one thread.
407 **
408 ** Enabling mutexes incurs a measurable performance penalty.
409 ** So if speed is of utmost importance, it makes sense to disable
410 ** the mutexes. But for maximum safety, mutexes should be enabled.
411 ** ^The default behavior is for mutexes to be enabled.
412 **
413 ** This interface can be used by an application to make sure that the
414 ** version of SQLite that it is linking against was compiled with
415 ** the desired setting of the [SQLITE_THREADSAFE] macro.
416 **
417 ** This interface only reports on the compile-time mutex setting
418 ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
419 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
420 ** can be fully or partially disabled using a call to [sqlite3_config()]
421 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
422 ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
423 ** sqlite3_threadsafe() function shows only the compile-time setting of
424 ** thread safety, not any run-time changes to that setting made by
425 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
426 ** is unchanged by calls to sqlite3_config().)^
427 **
428 ** See the [threading mode] documentation for additional information.
429 */
430 SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void);
431
432 /*
433 ** CAPI3REF: Database Connection Handle
434 ** KEYWORDS: {database connection} {database connections}
435 **
436 ** Each open SQLite database is represented by a pointer to an instance of
437 ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
438 ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
439 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
440 ** and [sqlite3_close_v2()] are its destructors. There are many other
441 ** interfaces (such as
442 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
443 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
444 ** sqlite3 object.
445 */
446 typedef struct sqlite3 sqlite3;
447
448 /*
449 ** CAPI3REF: 64-Bit Integer Types
450 ** KEYWORDS: sqlite_int64 sqlite_uint64
451 **
452 ** Because there is no cross-platform way to specify 64-bit integer types
453 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
454 **
455 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
456 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
457 ** compatibility only.
458 **
459 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
460 ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
461 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
462 ** between 0 and +18446744073709551615 inclusive.
463 */
464 #ifdef SQLITE_INT64_TYPE
465 typedef SQLITE_INT64_TYPE sqlite_int64;
466 typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
467 #elif defined(_MSC_VER) || defined(__BORLANDC__)
468 typedef __int64 sqlite_int64;
469 typedef unsigned __int64 sqlite_uint64;
470 #else
471 typedef long long int sqlite_int64;
472 typedef unsigned long long int sqlite_uint64;
473 #endif
474 typedef sqlite_int64 sqlite3_int64;
475 typedef sqlite_uint64 sqlite3_uint64;
476
477 /*
478 ** If compiling for a processor that lacks floating point support,
479 ** substitute integer for floating-point.
480 */
481 #ifdef SQLITE_OMIT_FLOATING_POINT
482 # define double sqlite3_int64
483 #endif
484
485 /*
486 ** CAPI3REF: Closing A Database Connection
487 ** DESTRUCTOR: sqlite3
488 **
489 ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
490 ** for the [sqlite3] object.
491 ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
492 ** the [sqlite3] object is successfully destroyed and all associated
493 ** resources are deallocated.
494 **
495 ** ^If the database connection is associated with unfinalized prepared
496 ** statements or unfinished sqlite3_backup objects then sqlite3_close()
497 ** will leave the database connection open and return [SQLITE_BUSY].
498 ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
499 ** and/or unfinished sqlite3_backups, then the database connection becomes
500 ** an unusable "zombie" which will automatically be deallocated when the
501 ** last prepared statement is finalized or the last sqlite3_backup is
502 ** finished. The sqlite3_close_v2() interface is intended for use with
503 ** host languages that are garbage collected, and where the order in which
504 ** destructors are called is arbitrary.
505 **
506 ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
507 ** [sqlite3_blob_close | close] all [BLOB handles], and
508 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
509 ** with the [sqlite3] object prior to attempting to close the object. ^If
510 ** sqlite3_close_v2() is called on a [database connection] that still has
511 ** outstanding [prepared statements], [BLOB handles], and/or
512 ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
513 ** of resources is deferred until all [prepared statements], [BLOB handles],
514 ** and [sqlite3_backup] objects are also destroyed.
515 **
516 ** ^If an [sqlite3] object is destroyed while a transaction is open,
517 ** the transaction is automatically rolled back.
518 **
519 ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
520 ** must be either a NULL
521 ** pointer or an [sqlite3] object pointer obtained
522 ** from [sqlite3_open()], [sqlite3_open16()], or
523 ** [sqlite3_open_v2()], and not previously closed.
524 ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
525 ** argument is a harmless no-op.
526 */
527 SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3*);
528 SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3*);
529
530 /*
531 ** The type for a callback function.
532 ** This is legacy and deprecated. It is included for historical
533 ** compatibility and is not documented.
534 */
535 typedef int (*sqlite3_callback)(void*,int,char**, char**);
536
537 /*
538 ** CAPI3REF: One-Step Query Execution Interface
539 ** METHOD: sqlite3
540 **
541 ** The sqlite3_exec() interface is a convenience wrapper around
542 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
543 ** that allows an application to run multiple statements of SQL
544 ** without having to use a lot of C code.
545 **
546 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
547 ** semicolon-separate SQL statements passed into its 2nd argument,
548 ** in the context of the [database connection] passed in as its 1st
549 ** argument. ^If the callback function of the 3rd argument to
550 ** sqlite3_exec() is not NULL, then it is invoked for each result row
551 ** coming out of the evaluated SQL statements. ^The 4th argument to
552 ** sqlite3_exec() is relayed through to the 1st argument of each
553 ** callback invocation. ^If the callback pointer to sqlite3_exec()
554 ** is NULL, then no callback is ever invoked and result rows are
555 ** ignored.
556 **
557 ** ^If an error occurs while evaluating the SQL statements passed into
558 ** sqlite3_exec(), then execution of the current statement stops and
559 ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
560 ** is not NULL then any error message is written into memory obtained
561 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
562 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
563 ** on error message strings returned through the 5th parameter of
564 ** of sqlite3_exec() after the error message string is no longer needed.
565 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
566 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
567 ** NULL before returning.
568 **
569 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
570 ** routine returns SQLITE_ABORT without invoking the callback again and
571 ** without running any subsequent SQL statements.
572 **
573 ** ^The 2nd argument to the sqlite3_exec() callback function is the
574 ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
575 ** callback is an array of pointers to strings obtained as if from
576 ** [sqlite3_column_text()], one for each column. ^If an element of a
577 ** result row is NULL then the corresponding string pointer for the
578 ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
579 ** sqlite3_exec() callback is an array of pointers to strings where each
580 ** entry represents the name of corresponding result column as obtained
581 ** from [sqlite3_column_name()].
582 **
583 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
584 ** to an empty string, or a pointer that contains only whitespace and/or
585 ** SQL comments, then no SQL statements are evaluated and the database
586 ** is not changed.
587 **
588 ** Restrictions:
589 **
590 ** <ul>
591 ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
592 ** is a valid and open [database connection].
593 ** <li> The application must not close the [database connection] specified by
594 ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
595 ** <li> The application must not modify the SQL statement text passed into
596 ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
597 ** </ul>
598 */
599 SQLITE_API int SQLITE_STDCALL sqlite3_exec(
600 sqlite3*, /* An open database */
601 const char *sql, /* SQL to be evaluated */
602 int (*callback)(void*,int,char**,char**), /* Callback function */
603 void *, /* 1st argument to callback */
604 char **errmsg /* Error msg written here */
605 );
606
607 /*
608 ** CAPI3REF: Result Codes
609 ** KEYWORDS: {result code definitions}
610 **
611 ** Many SQLite functions return an integer result code from the set shown
612 ** here in order to indicate success or failure.
613 **
614 ** New error codes may be added in future versions of SQLite.
615 **
616 ** See also: [extended result code definitions]
617 */
618 #define SQLITE_OK 0 /* Successful result */
619 /* beginning-of-error-codes */
620 #define SQLITE_ERROR 1 /* SQL error or missing database */
621 #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
622 #define SQLITE_PERM 3 /* Access permission denied */
623 #define SQLITE_ABORT 4 /* Callback routine requested an abort */
624 #define SQLITE_BUSY 5 /* The database file is locked */
625 #define SQLITE_LOCKED 6 /* A table in the database is locked */
626 #define SQLITE_NOMEM 7 /* A malloc() failed */
627 #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
628 #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
629 #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
630 #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
631 #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
632 #define SQLITE_FULL 13 /* Insertion failed because database is full */
633 #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
634 #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
635 #define SQLITE_EMPTY 16 /* Database is empty */
636 #define SQLITE_SCHEMA 17 /* The database schema changed */
637 #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
638 #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
639 #define SQLITE_MISMATCH 20 /* Data type mismatch */
640 #define SQLITE_MISUSE 21 /* Library used incorrectly */
641 #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
642 #define SQLITE_AUTH 23 /* Authorization denied */
643 #define SQLITE_FORMAT 24 /* Auxiliary database format error */
644 #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
645 #define SQLITE_NOTADB 26 /* File opened that is not a database file */
646 #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
647 #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
648 #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
649 #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
650 /* end-of-error-codes */
651
652 /*
653 ** CAPI3REF: Extended Result Codes
654 ** KEYWORDS: {extended result code definitions}
655 **
656 ** In its default configuration, SQLite API routines return one of 30 integer
657 ** [result codes]. However, experience has shown that many of
658 ** these result codes are too coarse-grained. They do not provide as
659 ** much information about problems as programmers might like. In an effort to
660 ** address this, newer versions of SQLite (version 3.3.8 and later) include
661 ** support for additional result codes that provide more detailed information
662 ** about errors. These [extended result codes] are enabled or disabled
663 ** on a per database connection basis using the
664 ** [sqlite3_extended_result_codes()] API. Or, the extended code for
665 ** the most recent error can be obtained using
666 ** [sqlite3_extended_errcode()].
667 */
668 #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
669 #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
670 #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
671 #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
672 #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
673 #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
674 #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
675 #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
676 #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
677 #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
678 #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
679 #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
680 #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
681 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
682 #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
683 #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
684 #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
685 #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
686 #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
687 #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
688 #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
689 #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
690 #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
691 #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
692 #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
693 #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
694 #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
695 #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
696 #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
697 #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
698 #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
699 #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
700 #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
701 #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
702 #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
703 #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
704 #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
705 #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
706 #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
707 #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
708 #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
709 #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
710 #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
711 #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
712 #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
713 #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
714 #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
715 #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
716 #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
717 #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
718 #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
719 #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
720 #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
721 #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
722 #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
723
724 /*
725 ** CAPI3REF: Flags For File Open Operations
726 **
727 ** These bit values are intended for use in the
728 ** 3rd parameter to the [sqlite3_open_v2()] interface and
729 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
730 */
731 #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
732 #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
733 #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
734 #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
735 #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
736 #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
737 #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
738 #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
739 #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
740 #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
741 #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
742 #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
743 #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
744 #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
745 #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
746 #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
747 #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
748 #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
749 #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
750 #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
751
752 /* Reserved: 0x00F00000 */
753
754 /*
755 ** CAPI3REF: Device Characteristics
756 **
757 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
758 ** object returns an integer which is a vector of these
759 ** bit values expressing I/O characteristics of the mass storage
760 ** device that holds the file that the [sqlite3_io_methods]
761 ** refers to.
762 **
763 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
764 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
765 ** mean that writes of blocks that are nnn bytes in size and
766 ** are aligned to an address which is an integer multiple of
767 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
768 ** that when data is appended to a file, the data is appended
769 ** first then the size of the file is extended, never the other
770 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
771 ** information is written to disk in the same order as calls
772 ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
773 ** after reboot following a crash or power loss, the only bytes in a
774 ** file that were written at the application level might have changed
775 ** and that adjacent bytes, even bytes within the same sector are
776 ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
777 ** flag indicate that a file cannot be deleted when open. The
778 ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
779 ** read-only media and cannot be changed even by processes with
780 ** elevated privileges.
781 */
782 #define SQLITE_IOCAP_ATOMIC 0x00000001
783 #define SQLITE_IOCAP_ATOMIC512 0x00000002
784 #define SQLITE_IOCAP_ATOMIC1K 0x00000004
785 #define SQLITE_IOCAP_ATOMIC2K 0x00000008
786 #define SQLITE_IOCAP_ATOMIC4K 0x00000010
787 #define SQLITE_IOCAP_ATOMIC8K 0x00000020
788 #define SQLITE_IOCAP_ATOMIC16K 0x00000040
789 #define SQLITE_IOCAP_ATOMIC32K 0x00000080
790 #define SQLITE_IOCAP_ATOMIC64K 0x00000100
791 #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
792 #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
793 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
794 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
795 #define SQLITE_IOCAP_IMMUTABLE 0x00002000
796
797 /*
798 ** CAPI3REF: File Locking Levels
799 **
800 ** SQLite uses one of these integer values as the second
801 ** argument to calls it makes to the xLock() and xUnlock() methods
802 ** of an [sqlite3_io_methods] object.
803 */
804 #define SQLITE_LOCK_NONE 0
805 #define SQLITE_LOCK_SHARED 1
806 #define SQLITE_LOCK_RESERVED 2
807 #define SQLITE_LOCK_PENDING 3
808 #define SQLITE_LOCK_EXCLUSIVE 4
809
810 /*
811 ** CAPI3REF: Synchronization Type Flags
812 **
813 ** When SQLite invokes the xSync() method of an
814 ** [sqlite3_io_methods] object it uses a combination of
815 ** these integer values as the second argument.
816 **
817 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
818 ** sync operation only needs to flush data to mass storage. Inode
819 ** information need not be flushed. If the lower four bits of the flag
820 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
821 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
822 ** to use Mac OS X style fullsync instead of fsync().
823 **
824 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
825 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
826 ** settings. The [synchronous pragma] determines when calls to the
827 ** xSync VFS method occur and applies uniformly across all platforms.
828 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
829 ** energetic or rigorous or forceful the sync operations are and
830 ** only make a difference on Mac OSX for the default SQLite code.
831 ** (Third-party VFS implementations might also make the distinction
832 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
833 ** operating systems natively supported by SQLite, only Mac OSX
834 ** cares about the difference.)
835 */
836 #define SQLITE_SYNC_NORMAL 0x00002
837 #define SQLITE_SYNC_FULL 0x00003
838 #define SQLITE_SYNC_DATAONLY 0x00010
839
840 /*
841 ** CAPI3REF: OS Interface Open File Handle
842 **
843 ** An [sqlite3_file] object represents an open file in the
844 ** [sqlite3_vfs | OS interface layer]. Individual OS interface
845 ** implementations will
846 ** want to subclass this object by appending additional fields
847 ** for their own use. The pMethods entry is a pointer to an
848 ** [sqlite3_io_methods] object that defines methods for performing
849 ** I/O operations on the open file.
850 */
851 typedef struct sqlite3_file sqlite3_file;
852 struct sqlite3_file {
853 const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
854 };
855
856 /*
857 ** CAPI3REF: OS Interface File Virtual Methods Object
858 **
859 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
860 ** [sqlite3_file] object (or, more commonly, a subclass of the
861 ** [sqlite3_file] object) with a pointer to an instance of this object.
862 ** This object defines the methods used to perform various operations
863 ** against the open file represented by the [sqlite3_file] object.
864 **
865 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
866 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
867 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
868 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
869 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
870 ** to NULL.
871 **
872 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
873 ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
874 ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
875 ** flag may be ORed in to indicate that only the data of the file
876 ** and not its inode needs to be synced.
877 **
878 ** The integer values to xLock() and xUnlock() are one of
879 ** <ul>
880 ** <li> [SQLITE_LOCK_NONE],
881 ** <li> [SQLITE_LOCK_SHARED],
882 ** <li> [SQLITE_LOCK_RESERVED],
883 ** <li> [SQLITE_LOCK_PENDING], or
884 ** <li> [SQLITE_LOCK_EXCLUSIVE].
885 ** </ul>
886 ** xLock() increases the lock. xUnlock() decreases the lock.
887 ** The xCheckReservedLock() method checks whether any database connection,
888 ** either in this process or in some other process, is holding a RESERVED,
889 ** PENDING, or EXCLUSIVE lock on the file. It returns true
890 ** if such a lock exists and false otherwise.
891 **
892 ** The xFileControl() method is a generic interface that allows custom
893 ** VFS implementations to directly control an open file using the
894 ** [sqlite3_file_control()] interface. The second "op" argument is an
895 ** integer opcode. The third argument is a generic pointer intended to
896 ** point to a structure that may contain arguments or space in which to
897 ** write return values. Potential uses for xFileControl() might be
898 ** functions to enable blocking locks with timeouts, to change the
899 ** locking strategy (for example to use dot-file locks), to inquire
900 ** about the status of a lock, or to break stale locks. The SQLite
901 ** core reserves all opcodes less than 100 for its own use.
902 ** A [file control opcodes | list of opcodes] less than 100 is available.
903 ** Applications that define a custom xFileControl method should use opcodes
904 ** greater than 100 to avoid conflicts. VFS implementations should
905 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
906 ** recognize.
907 **
908 ** The xSectorSize() method returns the sector size of the
909 ** device that underlies the file. The sector size is the
910 ** minimum write that can be performed without disturbing
911 ** other bytes in the file. The xDeviceCharacteristics()
912 ** method returns a bit vector describing behaviors of the
913 ** underlying device:
914 **
915 ** <ul>
916 ** <li> [SQLITE_IOCAP_ATOMIC]
917 ** <li> [SQLITE_IOCAP_ATOMIC512]
918 ** <li> [SQLITE_IOCAP_ATOMIC1K]
919 ** <li> [SQLITE_IOCAP_ATOMIC2K]
920 ** <li> [SQLITE_IOCAP_ATOMIC4K]
921 ** <li> [SQLITE_IOCAP_ATOMIC8K]
922 ** <li> [SQLITE_IOCAP_ATOMIC16K]
923 ** <li> [SQLITE_IOCAP_ATOMIC32K]
924 ** <li> [SQLITE_IOCAP_ATOMIC64K]
925 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
926 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
927 ** </ul>
928 **
929 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
930 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
931 ** mean that writes of blocks that are nnn bytes in size and
932 ** are aligned to an address which is an integer multiple of
933 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
934 ** that when data is appended to a file, the data is appended
935 ** first then the size of the file is extended, never the other
936 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
937 ** information is written to disk in the same order as calls
938 ** to xWrite().
939 **
940 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
941 ** in the unread portions of the buffer with zeros. A VFS that
942 ** fails to zero-fill short reads might seem to work. However,
943 ** failure to zero-fill short reads will eventually lead to
944 ** database corruption.
945 */
946 typedef struct sqlite3_io_methods sqlite3_io_methods;
947 struct sqlite3_io_methods {
948 int iVersion;
949 int (*xClose)(sqlite3_file*);
950 int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
951 int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
952 int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
953 int (*xSync)(sqlite3_file*, int flags);
954 int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
955 int (*xLock)(sqlite3_file*, int);
956 int (*xUnlock)(sqlite3_file*, int);
957 int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
958 int (*xFileControl)(sqlite3_file*, int op, void *pArg);
959 int (*xSectorSize)(sqlite3_file*);
960 int (*xDeviceCharacteristics)(sqlite3_file*);
961 /* Methods above are valid for version 1 */
962 int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
963 int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
964 void (*xShmBarrier)(sqlite3_file*);
965 int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
966 /* Methods above are valid for version 2 */
967 int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
968 int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
969 /* Methods above are valid for version 3 */
970 /* Additional methods may be added in future releases */
971 };
972
973 /*
974 ** CAPI3REF: Standard File Control Opcodes
975 ** KEYWORDS: {file control opcodes} {file control opcode}
976 **
977 ** These integer constants are opcodes for the xFileControl method
978 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
979 ** interface.
980 **
981 ** <ul>
982 ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
983 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
984 ** opcode causes the xFileControl method to write the current state of
985 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
986 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
987 ** into an integer that the pArg argument points to. This capability
988 ** is used during testing and is only available when the SQLITE_TEST
989 ** compile-time option is used.
990 **
991 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
992 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
993 ** layer a hint of how large the database file will grow to be during the
994 ** current transaction. This hint is not guaranteed to be accurate but it
995 ** is often close. The underlying VFS might choose to preallocate database
996 ** file space based on this hint in order to help writes to the database
997 ** file run faster.
998 **
999 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1000 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1001 ** extends and truncates the database file in chunks of a size specified
1002 ** by the user. The fourth argument to [sqlite3_file_control()] should
1003 ** point to an integer (type int) containing the new chunk-size to use
1004 ** for the nominated database. Allocating database file space in large
1005 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1006 ** improve performance on some systems.
1007 **
1008 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1009 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1010 ** to the [sqlite3_file] object associated with a particular database
1011 ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
1012 **
1013 ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
1014 ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
1015 ** to the [sqlite3_file] object associated with the journal file (either
1016 ** the [rollback journal] or the [write-ahead log]) for a particular database
1017 ** connection. See also [SQLITE_FCNTL_FILE_POINTER].
1018 **
1019 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1020 ** No longer in use.
1021 **
1022 ** <li>[[SQLITE_FCNTL_SYNC]]
1023 ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
1024 ** sent to the VFS immediately before the xSync method is invoked on a
1025 ** database file descriptor. Or, if the xSync method is not invoked
1026 ** because the user has configured SQLite with
1027 ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
1028 ** of the xSync method. In most cases, the pointer argument passed with
1029 ** this file-control is NULL. However, if the database file is being synced
1030 ** as part of a multi-database commit, the argument points to a nul-terminated
1031 ** string containing the transactions master-journal file name. VFSes that
1032 ** do not need this signal should silently ignore this opcode. Applications
1033 ** should not call [sqlite3_file_control()] with this opcode as doing so may
1034 ** disrupt the operation of the specialized VFSes that do require it.
1035 **
1036 ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
1037 ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
1038 ** and sent to the VFS after a transaction has been committed immediately
1039 ** but before the database is unlocked. VFSes that do not need this signal
1040 ** should silently ignore this opcode. Applications should not call
1041 ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
1042 ** operation of the specialized VFSes that do require it.
1043 **
1044 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1045 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1046 ** retry counts and intervals for certain disk I/O operations for the
1047 ** windows [VFS] in order to provide robustness in the presence of
1048 ** anti-virus programs. By default, the windows VFS will retry file read,
1049 ** file write, and file delete operations up to 10 times, with a delay
1050 ** of 25 milliseconds before the first retry and with the delay increasing
1051 ** by an additional 25 milliseconds with each subsequent retry. This
1052 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
1053 ** to be adjusted. The values are changed for all database connections
1054 ** within the same process. The argument is a pointer to an array of two
1055 ** integers where the first integer i the new retry count and the second
1056 ** integer is the delay. If either integer is negative, then the setting
1057 ** is not changed but instead the prior value of that setting is written
1058 ** into the array entry, allowing the current retry settings to be
1059 ** interrogated. The zDbName parameter is ignored.
1060 **
1061 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1062 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1063 ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
1064 ** write ahead log and shared memory files used for transaction control
1065 ** are automatically deleted when the latest connection to the database
1066 ** closes. Setting persistent WAL mode causes those files to persist after
1067 ** close. Persisting the files is useful when other processes that do not
1068 ** have write permission on the directory containing the database file want
1069 ** to read the database file, as the WAL and shared memory files must exist
1070 ** in order for the database to be readable. The fourth parameter to
1071 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1072 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1073 ** WAL mode. If the integer is -1, then it is overwritten with the current
1074 ** WAL persistence setting.
1075 **
1076 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1077 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1078 ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
1079 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1080 ** xDeviceCharacteristics methods. The fourth parameter to
1081 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1082 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1083 ** mode. If the integer is -1, then it is overwritten with the current
1084 ** zero-damage mode setting.
1085 **
1086 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
1087 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1088 ** a write transaction to indicate that, unless it is rolled back for some
1089 ** reason, the entire database file will be overwritten by the current
1090 ** transaction. This is used by VACUUM operations.
1091 **
1092 ** <li>[[SQLITE_FCNTL_VFSNAME]]
1093 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1094 ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
1095 ** final bottom-level VFS are written into memory obtained from
1096 ** [sqlite3_malloc()] and the result is stored in the char* variable
1097 ** that the fourth parameter of [sqlite3_file_control()] points to.
1098 ** The caller is responsible for freeing the memory when done. As with
1099 ** all file-control actions, there is no guarantee that this will actually
1100 ** do anything. Callers should initialize the char* variable to a NULL
1101 ** pointer in case this file-control is not implemented. This file-control
1102 ** is intended for diagnostic use only.
1103 **
1104 ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
1105 ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
1106 ** [VFSes] currently in use. ^(The argument X in
1107 ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
1108 ** of type "[sqlite3_vfs] **". This opcodes will set *X
1109 ** to a pointer to the top-level VFS.)^
1110 ** ^When there are multiple VFS shims in the stack, this opcode finds the
1111 ** upper-most shim only.
1112 **
1113 ** <li>[[SQLITE_FCNTL_PRAGMA]]
1114 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1115 ** file control is sent to the open [sqlite3_file] object corresponding
1116 ** to the database file to which the pragma statement refers. ^The argument
1117 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1118 ** pointers to strings (char**) in which the second element of the array
1119 ** is the name of the pragma and the third element is the argument to the
1120 ** pragma or NULL if the pragma has no argument. ^The handler for an
1121 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1122 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1123 ** or the equivalent and that string will become the result of the pragma or
1124 ** the error message if the pragma fails. ^If the
1125 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1126 ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
1127 ** file control returns [SQLITE_OK], then the parser assumes that the
1128 ** VFS has handled the PRAGMA itself and the parser generates a no-op
1129 ** prepared statement if result string is NULL, or that returns a copy
1130 ** of the result string if the string is non-NULL.
1131 ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1132 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1133 ** that the VFS encountered an error while handling the [PRAGMA] and the
1134 ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
1135 ** file control occurs at the beginning of pragma statement analysis and so
1136 ** it is able to override built-in [PRAGMA] statements.
1137 **
1138 ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1139 ** ^The [SQLITE_FCNTL_BUSYHANDLER]
1140 ** file-control may be invoked by SQLite on the database file handle
1141 ** shortly after it is opened in order to provide a custom VFS with access
1142 ** to the connections busy-handler callback. The argument is of type (void **)
1143 ** - an array of two (void *) values. The first (void *) actually points
1144 ** to a function of type (int (*)(void *)). In order to invoke the connections
1145 ** busy-handler, this function should be invoked with the second (void *) in
1146 ** the array as the only argument. If it returns non-zero, then the operation
1147 ** should be retried. If it returns zero, the custom VFS should abandon the
1148 ** current operation.
1149 **
1150 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1151 ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1152 ** to have SQLite generate a
1153 ** temporary filename using the same algorithm that is followed to generate
1154 ** temporary filenames for TEMP tables and other internal uses. The
1155 ** argument should be a char** which will be filled with the filename
1156 ** written into memory obtained from [sqlite3_malloc()]. The caller should
1157 ** invoke [sqlite3_free()] on the result to avoid a memory leak.
1158 **
1159 ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1160 ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1161 ** maximum number of bytes that will be used for memory-mapped I/O.
1162 ** The argument is a pointer to a value of type sqlite3_int64 that
1163 ** is an advisory maximum number of bytes in the file to memory map. The
1164 ** pointer is overwritten with the old value. The limit is not changed if
1165 ** the value originally pointed to is negative, and so the current limit
1166 ** can be queried by passing in a pointer to a negative number. This
1167 ** file-control is used internally to implement [PRAGMA mmap_size].
1168 **
1169 ** <li>[[SQLITE_FCNTL_TRACE]]
1170 ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
1171 ** to the VFS about what the higher layers of the SQLite stack are doing.
1172 ** This file control is used by some VFS activity tracing [shims].
1173 ** The argument is a zero-terminated string. Higher layers in the
1174 ** SQLite stack may generate instances of this file control if
1175 ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
1176 **
1177 ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
1178 ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
1179 ** pointer to an integer and it writes a boolean into that integer depending
1180 ** on whether or not the file has been renamed, moved, or deleted since it
1181 ** was first opened.
1182 **
1183 ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
1184 ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
1185 ** opcode causes the xFileControl method to swap the file handle with the one
1186 ** pointed to by the pArg argument. This capability is used during testing
1187 ** and only needs to be supported when SQLITE_TEST is defined.
1188 **
1189 ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
1190 ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
1191 ** be advantageous to block on the next WAL lock if the lock is not immediately
1192 ** available. The WAL subsystem issues this signal during rare
1193 ** circumstances in order to fix a problem with priority inversion.
1194 ** Applications should <em>not</em> use this file-control.
1195 **
1196 ** <li>[[SQLITE_FCNTL_ZIPVFS]]
1197 ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
1198 ** VFS should return SQLITE_NOTFOUND for this opcode.
1199 **
1200 ** <li>[[SQLITE_FCNTL_RBU]]
1201 ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
1202 ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
1203 ** this opcode.
1204 ** </ul>
1205 */
1206 #define SQLITE_FCNTL_LOCKSTATE 1
1207 #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
1208 #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
1209 #define SQLITE_FCNTL_LAST_ERRNO 4
1210 #define SQLITE_FCNTL_SIZE_HINT 5
1211 #define SQLITE_FCNTL_CHUNK_SIZE 6
1212 #define SQLITE_FCNTL_FILE_POINTER 7
1213 #define SQLITE_FCNTL_SYNC_OMITTED 8
1214 #define SQLITE_FCNTL_WIN32_AV_RETRY 9
1215 #define SQLITE_FCNTL_PERSIST_WAL 10
1216 #define SQLITE_FCNTL_OVERWRITE 11
1217 #define SQLITE_FCNTL_VFSNAME 12
1218 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
1219 #define SQLITE_FCNTL_PRAGMA 14
1220 #define SQLITE_FCNTL_BUSYHANDLER 15
1221 #define SQLITE_FCNTL_TEMPFILENAME 16
1222 #define SQLITE_FCNTL_MMAP_SIZE 18
1223 #define SQLITE_FCNTL_TRACE 19
1224 #define SQLITE_FCNTL_HAS_MOVED 20
1225 #define SQLITE_FCNTL_SYNC 21
1226 #define SQLITE_FCNTL_COMMIT_PHASETWO 22
1227 #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
1228 #define SQLITE_FCNTL_WAL_BLOCK 24
1229 #define SQLITE_FCNTL_ZIPVFS 25
1230 #define SQLITE_FCNTL_RBU 26
1231 #define SQLITE_FCNTL_VFS_POINTER 27
1232 #define SQLITE_FCNTL_JOURNAL_POINTER 28
1233
1234 /* deprecated names */
1235 #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
1236 #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
1237 #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
1238
1239
1240 /*
1241 ** CAPI3REF: Mutex Handle
1242 **
1243 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1244 ** abstract type for a mutex object. The SQLite core never looks
1245 ** at the internal representation of an [sqlite3_mutex]. It only
1246 ** deals with pointers to the [sqlite3_mutex] object.
1247 **
1248 ** Mutexes are created using [sqlite3_mutex_alloc()].
1249 */
1250 typedef struct sqlite3_mutex sqlite3_mutex;
1251
1252 /*
1253 ** CAPI3REF: OS Interface Object
1254 **
1255 ** An instance of the sqlite3_vfs object defines the interface between
1256 ** the SQLite core and the underlying operating system. The "vfs"
1257 ** in the name of the object stands for "virtual file system". See
1258 ** the [VFS | VFS documentation] for further information.
1259 **
1260 ** The value of the iVersion field is initially 1 but may be larger in
1261 ** future versions of SQLite. Additional fields may be appended to this
1262 ** object when the iVersion value is increased. Note that the structure
1263 ** of the sqlite3_vfs object changes in the transaction between
1264 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1265 ** modified.
1266 **
1267 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1268 ** structure used by this VFS. mxPathname is the maximum length of
1269 ** a pathname in this VFS.
1270 **
1271 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1272 ** the pNext pointer. The [sqlite3_vfs_register()]
1273 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1274 ** in a thread-safe way. The [sqlite3_vfs_find()] interface
1275 ** searches the list. Neither the application code nor the VFS
1276 ** implementation should use the pNext pointer.
1277 **
1278 ** The pNext field is the only field in the sqlite3_vfs
1279 ** structure that SQLite will ever modify. SQLite will only access
1280 ** or modify this field while holding a particular static mutex.
1281 ** The application should never modify anything within the sqlite3_vfs
1282 ** object once the object has been registered.
1283 **
1284 ** The zName field holds the name of the VFS module. The name must
1285 ** be unique across all VFS modules.
1286 **
1287 ** [[sqlite3_vfs.xOpen]]
1288 ** ^SQLite guarantees that the zFilename parameter to xOpen
1289 ** is either a NULL pointer or string obtained
1290 ** from xFullPathname() with an optional suffix added.
1291 ** ^If a suffix is added to the zFilename parameter, it will
1292 ** consist of a single "-" character followed by no more than
1293 ** 11 alphanumeric and/or "-" characters.
1294 ** ^SQLite further guarantees that
1295 ** the string will be valid and unchanged until xClose() is
1296 ** called. Because of the previous sentence,
1297 ** the [sqlite3_file] can safely store a pointer to the
1298 ** filename if it needs to remember the filename for some reason.
1299 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1300 ** must invent its own temporary name for the file. ^Whenever the
1301 ** xFilename parameter is NULL it will also be the case that the
1302 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1303 **
1304 ** The flags argument to xOpen() includes all bits set in
1305 ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
1306 ** or [sqlite3_open16()] is used, then flags includes at least
1307 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1308 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1309 ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
1310 **
1311 ** ^(SQLite will also add one of the following flags to the xOpen()
1312 ** call, depending on the object being opened:
1313 **
1314 ** <ul>
1315 ** <li> [SQLITE_OPEN_MAIN_DB]
1316 ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
1317 ** <li> [SQLITE_OPEN_TEMP_DB]
1318 ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
1319 ** <li> [SQLITE_OPEN_TRANSIENT_DB]
1320 ** <li> [SQLITE_OPEN_SUBJOURNAL]
1321 ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
1322 ** <li> [SQLITE_OPEN_WAL]
1323 ** </ul>)^
1324 **
1325 ** The file I/O implementation can use the object type flags to
1326 ** change the way it deals with files. For example, an application
1327 ** that does not care about crash recovery or rollback might make
1328 ** the open of a journal file a no-op. Writes to this journal would
1329 ** also be no-ops, and any attempt to read the journal would return
1330 ** SQLITE_IOERR. Or the implementation might recognize that a database
1331 ** file will be doing page-aligned sector reads and writes in a random
1332 ** order and set up its I/O subsystem accordingly.
1333 **
1334 ** SQLite might also add one of the following flags to the xOpen method:
1335 **
1336 ** <ul>
1337 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1338 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1339 ** </ul>
1340 **
1341 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1342 ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
1343 ** will be set for TEMP databases and their journals, transient
1344 ** databases, and subjournals.
1345 **
1346 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1347 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1348 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1349 ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1350 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1351 ** be created, and that it is an error if it already exists.
1352 ** It is <i>not</i> used to indicate the file should be opened
1353 ** for exclusive access.
1354 **
1355 ** ^At least szOsFile bytes of memory are allocated by SQLite
1356 ** to hold the [sqlite3_file] structure passed as the third
1357 ** argument to xOpen. The xOpen method does not have to
1358 ** allocate the structure; it should just fill it in. Note that
1359 ** the xOpen method must set the sqlite3_file.pMethods to either
1360 ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
1361 ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
1362 ** element will be valid after xOpen returns regardless of the success
1363 ** or failure of the xOpen call.
1364 **
1365 ** [[sqlite3_vfs.xAccess]]
1366 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1367 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1368 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1369 ** to test whether a file is at least readable. The file can be a
1370 ** directory.
1371 **
1372 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1373 ** output buffer xFullPathname. The exact size of the output buffer
1374 ** is also passed as a parameter to both methods. If the output buffer
1375 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1376 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1377 ** to prevent this by setting mxPathname to a sufficiently large value.
1378 **
1379 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1380 ** interfaces are not strictly a part of the filesystem, but they are
1381 ** included in the VFS structure for completeness.
1382 ** The xRandomness() function attempts to return nBytes bytes
1383 ** of good-quality randomness into zOut. The return value is
1384 ** the actual number of bytes of randomness obtained.
1385 ** The xSleep() method causes the calling thread to sleep for at
1386 ** least the number of microseconds given. ^The xCurrentTime()
1387 ** method returns a Julian Day Number for the current date and time as
1388 ** a floating point value.
1389 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1390 ** Day Number multiplied by 86400000 (the number of milliseconds in
1391 ** a 24-hour day).
1392 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1393 ** date and time if that method is available (if iVersion is 2 or
1394 ** greater and the function pointer is not NULL) and will fall back
1395 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1396 **
1397 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1398 ** are not used by the SQLite core. These optional interfaces are provided
1399 ** by some VFSes to facilitate testing of the VFS code. By overriding
1400 ** system calls with functions under its control, a test program can
1401 ** simulate faults and error conditions that would otherwise be difficult
1402 ** or impossible to induce. The set of system calls that can be overridden
1403 ** varies from one VFS to another, and from one version of the same VFS to the
1404 ** next. Applications that use these interfaces must be prepared for any
1405 ** or all of these interfaces to be NULL or for their behavior to change
1406 ** from one release to the next. Applications must not attempt to access
1407 ** any of these methods if the iVersion of the VFS is less than 3.
1408 */
1409 typedef struct sqlite3_vfs sqlite3_vfs;
1410 typedef void (*sqlite3_syscall_ptr)(void);
1411 struct sqlite3_vfs {
1412 int iVersion; /* Structure version number (currently 3) */
1413 int szOsFile; /* Size of subclassed sqlite3_file */
1414 int mxPathname; /* Maximum file pathname length */
1415 sqlite3_vfs *pNext; /* Next registered VFS */
1416 const char *zName; /* Name of this virtual file system */
1417 void *pAppData; /* Pointer to application-specific data */
1418 int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1419 int flags, int *pOutFlags);
1420 int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1421 int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1422 int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1423 void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1424 void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1425 void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1426 void (*xDlClose)(sqlite3_vfs*, void*);
1427 int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1428 int (*xSleep)(sqlite3_vfs*, int microseconds);
1429 int (*xCurrentTime)(sqlite3_vfs*, double*);
1430 int (*xGetLastError)(sqlite3_vfs*, int, char *);
1431 /*
1432 ** The methods above are in version 1 of the sqlite_vfs object
1433 ** definition. Those that follow are added in version 2 or later
1434 */
1435 int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1436 /*
1437 ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1438 ** Those below are for version 3 and greater.
1439 */
1440 int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1441 sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1442 const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1443 /*
1444 ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1445 ** New fields may be appended in figure versions. The iVersion
1446 ** value will increment whenever this happens.
1447 */
1448 };
1449
1450 /*
1451 ** CAPI3REF: Flags for the xAccess VFS method
1452 **
1453 ** These integer constants can be used as the third parameter to
1454 ** the xAccess method of an [sqlite3_vfs] object. They determine
1455 ** what kind of permissions the xAccess method is looking for.
1456 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1457 ** simply checks whether the file exists.
1458 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1459 ** checks whether the named directory is both readable and writable
1460 ** (in other words, if files can be added, removed, and renamed within
1461 ** the directory).
1462 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1463 ** [temp_store_directory pragma], though this could change in a future
1464 ** release of SQLite.
1465 ** With SQLITE_ACCESS_READ, the xAccess method
1466 ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
1467 ** currently unused, though it might be used in a future release of
1468 ** SQLite.
1469 */
1470 #define SQLITE_ACCESS_EXISTS 0
1471 #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
1472 #define SQLITE_ACCESS_READ 2 /* Unused */
1473
1474 /*
1475 ** CAPI3REF: Flags for the xShmLock VFS method
1476 **
1477 ** These integer constants define the various locking operations
1478 ** allowed by the xShmLock method of [sqlite3_io_methods]. The
1479 ** following are the only legal combinations of flags to the
1480 ** xShmLock method:
1481 **
1482 ** <ul>
1483 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1484 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1485 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1486 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1487 ** </ul>
1488 **
1489 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1490 ** was given on the corresponding lock.
1491 **
1492 ** The xShmLock method can transition between unlocked and SHARED or
1493 ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
1494 ** and EXCLUSIVE.
1495 */
1496 #define SQLITE_SHM_UNLOCK 1
1497 #define SQLITE_SHM_LOCK 2
1498 #define SQLITE_SHM_SHARED 4
1499 #define SQLITE_SHM_EXCLUSIVE 8
1500
1501 /*
1502 ** CAPI3REF: Maximum xShmLock index
1503 **
1504 ** The xShmLock method on [sqlite3_io_methods] may use values
1505 ** between 0 and this upper bound as its "offset" argument.
1506 ** The SQLite core will never attempt to acquire or release a
1507 ** lock outside of this range
1508 */
1509 #define SQLITE_SHM_NLOCK 8
1510
1511
1512 /*
1513 ** CAPI3REF: Initialize The SQLite Library
1514 **
1515 ** ^The sqlite3_initialize() routine initializes the
1516 ** SQLite library. ^The sqlite3_shutdown() routine
1517 ** deallocates any resources that were allocated by sqlite3_initialize().
1518 ** These routines are designed to aid in process initialization and
1519 ** shutdown on embedded systems. Workstation applications using
1520 ** SQLite normally do not need to invoke either of these routines.
1521 **
1522 ** A call to sqlite3_initialize() is an "effective" call if it is
1523 ** the first time sqlite3_initialize() is invoked during the lifetime of
1524 ** the process, or if it is the first time sqlite3_initialize() is invoked
1525 ** following a call to sqlite3_shutdown(). ^(Only an effective call
1526 ** of sqlite3_initialize() does any initialization. All other calls
1527 ** are harmless no-ops.)^
1528 **
1529 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1530 ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
1531 ** an effective call to sqlite3_shutdown() does any deinitialization.
1532 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1533 **
1534 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1535 ** is not. The sqlite3_shutdown() interface must only be called from a
1536 ** single thread. All open [database connections] must be closed and all
1537 ** other SQLite resources must be deallocated prior to invoking
1538 ** sqlite3_shutdown().
1539 **
1540 ** Among other things, ^sqlite3_initialize() will invoke
1541 ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
1542 ** will invoke sqlite3_os_end().
1543 **
1544 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1545 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1546 ** the library (perhaps it is unable to allocate a needed resource such
1547 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1548 **
1549 ** ^The sqlite3_initialize() routine is called internally by many other
1550 ** SQLite interfaces so that an application usually does not need to
1551 ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
1552 ** calls sqlite3_initialize() so the SQLite library will be automatically
1553 ** initialized when [sqlite3_open()] is called if it has not be initialized
1554 ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1555 ** compile-time option, then the automatic calls to sqlite3_initialize()
1556 ** are omitted and the application must call sqlite3_initialize() directly
1557 ** prior to using any other SQLite interface. For maximum portability,
1558 ** it is recommended that applications always invoke sqlite3_initialize()
1559 ** directly prior to using any other SQLite interface. Future releases
1560 ** of SQLite may require this. In other words, the behavior exhibited
1561 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1562 ** default behavior in some future release of SQLite.
1563 **
1564 ** The sqlite3_os_init() routine does operating-system specific
1565 ** initialization of the SQLite library. The sqlite3_os_end()
1566 ** routine undoes the effect of sqlite3_os_init(). Typical tasks
1567 ** performed by these routines include allocation or deallocation
1568 ** of static resources, initialization of global variables,
1569 ** setting up a default [sqlite3_vfs] module, or setting up
1570 ** a default configuration using [sqlite3_config()].
1571 **
1572 ** The application should never invoke either sqlite3_os_init()
1573 ** or sqlite3_os_end() directly. The application should only invoke
1574 ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
1575 ** interface is called automatically by sqlite3_initialize() and
1576 ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
1577 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1578 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1579 ** When [custom builds | built for other platforms]
1580 ** (using the [SQLITE_OS_OTHER=1] compile-time
1581 ** option) the application must supply a suitable implementation for
1582 ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
1583 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1584 ** must return [SQLITE_OK] on success and some other [error code] upon
1585 ** failure.
1586 */
1587 SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void);
1588 SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void);
1589 SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void);
1590 SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void);
1591
1592 /*
1593 ** CAPI3REF: Configuring The SQLite Library
1594 **
1595 ** The sqlite3_config() interface is used to make global configuration
1596 ** changes to SQLite in order to tune SQLite to the specific needs of
1597 ** the application. The default configuration is recommended for most
1598 ** applications and so this routine is usually not necessary. It is
1599 ** provided to support rare applications with unusual needs.
1600 **
1601 ** <b>The sqlite3_config() interface is not threadsafe. The application
1602 ** must ensure that no other SQLite interfaces are invoked by other
1603 ** threads while sqlite3_config() is running.</b>
1604 **
1605 ** The sqlite3_config() interface
1606 ** may only be invoked prior to library initialization using
1607 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1608 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1609 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1610 ** Note, however, that ^sqlite3_config() can be called as part of the
1611 ** implementation of an application-defined [sqlite3_os_init()].
1612 **
1613 ** The first argument to sqlite3_config() is an integer
1614 ** [configuration option] that determines
1615 ** what property of SQLite is to be configured. Subsequent arguments
1616 ** vary depending on the [configuration option]
1617 ** in the first argument.
1618 **
1619 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1620 ** ^If the option is unknown or SQLite is unable to set the option
1621 ** then this routine returns a non-zero [error code].
1622 */
1623 SQLITE_API int SQLITE_CDECL sqlite3_config(int, ...);
1624
1625 /*
1626 ** CAPI3REF: Configure database connections
1627 ** METHOD: sqlite3
1628 **
1629 ** The sqlite3_db_config() interface is used to make configuration
1630 ** changes to a [database connection]. The interface is similar to
1631 ** [sqlite3_config()] except that the changes apply to a single
1632 ** [database connection] (specified in the first argument).
1633 **
1634 ** The second argument to sqlite3_db_config(D,V,...) is the
1635 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1636 ** that indicates what aspect of the [database connection] is being configured.
1637 ** Subsequent arguments vary depending on the configuration verb.
1638 **
1639 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1640 ** the call is considered successful.
1641 */
1642 SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3*, int op, ...);
1643
1644 /*
1645 ** CAPI3REF: Memory Allocation Routines
1646 **
1647 ** An instance of this object defines the interface between SQLite
1648 ** and low-level memory allocation routines.
1649 **
1650 ** This object is used in only one place in the SQLite interface.
1651 ** A pointer to an instance of this object is the argument to
1652 ** [sqlite3_config()] when the configuration option is
1653 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1654 ** By creating an instance of this object
1655 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1656 ** during configuration, an application can specify an alternative
1657 ** memory allocation subsystem for SQLite to use for all of its
1658 ** dynamic memory needs.
1659 **
1660 ** Note that SQLite comes with several [built-in memory allocators]
1661 ** that are perfectly adequate for the overwhelming majority of applications
1662 ** and that this object is only useful to a tiny minority of applications
1663 ** with specialized memory allocation requirements. This object is
1664 ** also used during testing of SQLite in order to specify an alternative
1665 ** memory allocator that simulates memory out-of-memory conditions in
1666 ** order to verify that SQLite recovers gracefully from such
1667 ** conditions.
1668 **
1669 ** The xMalloc, xRealloc, and xFree methods must work like the
1670 ** malloc(), realloc() and free() functions from the standard C library.
1671 ** ^SQLite guarantees that the second argument to
1672 ** xRealloc is always a value returned by a prior call to xRoundup.
1673 **
1674 ** xSize should return the allocated size of a memory allocation
1675 ** previously obtained from xMalloc or xRealloc. The allocated size
1676 ** is always at least as big as the requested size but may be larger.
1677 **
1678 ** The xRoundup method returns what would be the allocated size of
1679 ** a memory allocation given a particular requested size. Most memory
1680 ** allocators round up memory allocations at least to the next multiple
1681 ** of 8. Some allocators round up to a larger multiple or to a power of 2.
1682 ** Every memory allocation request coming in through [sqlite3_malloc()]
1683 ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
1684 ** that causes the corresponding memory allocation to fail.
1685 **
1686 ** The xInit method initializes the memory allocator. For example,
1687 ** it might allocate any require mutexes or initialize internal data
1688 ** structures. The xShutdown method is invoked (indirectly) by
1689 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1690 ** by xInit. The pAppData pointer is used as the only parameter to
1691 ** xInit and xShutdown.
1692 **
1693 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1694 ** the xInit method, so the xInit method need not be threadsafe. The
1695 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1696 ** not need to be threadsafe either. For all other methods, SQLite
1697 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1698 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1699 ** it is by default) and so the methods are automatically serialized.
1700 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1701 ** methods must be threadsafe or else make their own arrangements for
1702 ** serialization.
1703 **
1704 ** SQLite will never invoke xInit() more than once without an intervening
1705 ** call to xShutdown().
1706 */
1707 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1708 struct sqlite3_mem_methods {
1709 void *(*xMalloc)(int); /* Memory allocation function */
1710 void (*xFree)(void*); /* Free a prior allocation */
1711 void *(*xRealloc)(void*,int); /* Resize an allocation */
1712 int (*xSize)(void*); /* Return the size of an allocation */
1713 int (*xRoundup)(int); /* Round up request size to allocation size */
1714 int (*xInit)(void*); /* Initialize the memory allocator */
1715 void (*xShutdown)(void*); /* Deinitialize the memory allocator */
1716 void *pAppData; /* Argument to xInit() and xShutdown() */
1717 };
1718
1719 /*
1720 ** CAPI3REF: Configuration Options
1721 ** KEYWORDS: {configuration option}
1722 **
1723 ** These constants are the available integer configuration options that
1724 ** can be passed as the first argument to the [sqlite3_config()] interface.
1725 **
1726 ** New configuration options may be added in future releases of SQLite.
1727 ** Existing configuration options might be discontinued. Applications
1728 ** should check the return code from [sqlite3_config()] to make sure that
1729 ** the call worked. The [sqlite3_config()] interface will return a
1730 ** non-zero [error code] if a discontinued or unsupported configuration option
1731 ** is invoked.
1732 **
1733 ** <dl>
1734 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1735 ** <dd>There are no arguments to this option. ^This option sets the
1736 ** [threading mode] to Single-thread. In other words, it disables
1737 ** all mutexing and puts SQLite into a mode where it can only be used
1738 ** by a single thread. ^If SQLite is compiled with
1739 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1740 ** it is not possible to change the [threading mode] from its default
1741 ** value of Single-thread and so [sqlite3_config()] will return
1742 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1743 ** configuration option.</dd>
1744 **
1745 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1746 ** <dd>There are no arguments to this option. ^This option sets the
1747 ** [threading mode] to Multi-thread. In other words, it disables
1748 ** mutexing on [database connection] and [prepared statement] objects.
1749 ** The application is responsible for serializing access to
1750 ** [database connections] and [prepared statements]. But other mutexes
1751 ** are enabled so that SQLite will be safe to use in a multi-threaded
1752 ** environment as long as no two threads attempt to use the same
1753 ** [database connection] at the same time. ^If SQLite is compiled with
1754 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1755 ** it is not possible to set the Multi-thread [threading mode] and
1756 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1757 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1758 **
1759 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1760 ** <dd>There are no arguments to this option. ^This option sets the
1761 ** [threading mode] to Serialized. In other words, this option enables
1762 ** all mutexes including the recursive
1763 ** mutexes on [database connection] and [prepared statement] objects.
1764 ** In this mode (which is the default when SQLite is compiled with
1765 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1766 ** to [database connections] and [prepared statements] so that the
1767 ** application is free to use the same [database connection] or the
1768 ** same [prepared statement] in different threads at the same time.
1769 ** ^If SQLite is compiled with
1770 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1771 ** it is not possible to set the Serialized [threading mode] and
1772 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1773 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1774 **
1775 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1776 ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
1777 ** a pointer to an instance of the [sqlite3_mem_methods] structure.
1778 ** The argument specifies
1779 ** alternative low-level memory allocation routines to be used in place of
1780 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1781 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1782 ** before the [sqlite3_config()] call returns.</dd>
1783 **
1784 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1785 ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
1786 ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
1787 ** The [sqlite3_mem_methods]
1788 ** structure is filled with the currently defined memory allocation routines.)^
1789 ** This option can be used to overload the default memory allocation
1790 ** routines with a wrapper that simulations memory allocation failure or
1791 ** tracks memory usage, for example. </dd>
1792 **
1793 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1794 ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
1795 ** interpreted as a boolean, which enables or disables the collection of
1796 ** memory allocation statistics. ^(When memory allocation statistics are
1797 ** disabled, the following SQLite interfaces become non-operational:
1798 ** <ul>
1799 ** <li> [sqlite3_memory_used()]
1800 ** <li> [sqlite3_memory_highwater()]
1801 ** <li> [sqlite3_soft_heap_limit64()]
1802 ** <li> [sqlite3_status64()]
1803 ** </ul>)^
1804 ** ^Memory allocation statistics are enabled by default unless SQLite is
1805 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1806 ** allocation statistics are disabled by default.
1807 ** </dd>
1808 **
1809 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
1810 ** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer
1811 ** that SQLite can use for scratch memory. ^(There are three arguments
1812 ** to SQLITE_CONFIG_SCRATCH: A pointer an 8-byte
1813 ** aligned memory buffer from which the scratch allocations will be
1814 ** drawn, the size of each scratch allocation (sz),
1815 ** and the maximum number of scratch allocations (N).)^
1816 ** The first argument must be a pointer to an 8-byte aligned buffer
1817 ** of at least sz*N bytes of memory.
1818 ** ^SQLite will not use more than one scratch buffers per thread.
1819 ** ^SQLite will never request a scratch buffer that is more than 6
1820 ** times the database page size.
1821 ** ^If SQLite needs needs additional
1822 ** scratch memory beyond what is provided by this configuration option, then
1823 ** [sqlite3_malloc()] will be used to obtain the memory needed.<p>
1824 ** ^When the application provides any amount of scratch memory using
1825 ** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large
1826 ** [sqlite3_malloc|heap allocations].
1827 ** This can help [Robson proof|prevent memory allocation failures] due to heap
1828 ** fragmentation in low-memory embedded systems.
1829 ** </dd>
1830 **
1831 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
1832 ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
1833 ** that SQLite can use for the database page cache with the default page
1834 ** cache implementation.
1835 ** This configuration option is a no-op if an application-define page
1836 ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
1837 ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
1838 ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
1839 ** and the number of cache lines (N).
1840 ** The sz argument should be the size of the largest database page
1841 ** (a power of two between 512 and 65536) plus some extra bytes for each
1842 ** page header. ^The number of extra bytes needed by the page header
1843 ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
1844 ** ^It is harmless, apart from the wasted memory,
1845 ** for the sz parameter to be larger than necessary. The pMem
1846 ** argument must be either a NULL pointer or a pointer to an 8-byte
1847 ** aligned block of memory of at least sz*N bytes, otherwise
1848 ** subsequent behavior is undefined.
1849 ** ^When pMem is not NULL, SQLite will strive to use the memory provided
1850 ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
1851 ** a page cache line is larger than sz bytes or if all of the pMem buffer
1852 ** is exhausted.
1853 ** ^If pMem is NULL and N is non-zero, then each database connection
1854 ** does an initial bulk allocation for page cache memory
1855 ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
1856 ** of -1024*N bytes if N is negative, . ^If additional
1857 ** page cache memory is needed beyond what is provided by the initial
1858 ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
1859 ** additional cache line. </dd>
1860 **
1861 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
1862 ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
1863 ** that SQLite will use for all of its dynamic memory allocation needs
1864 ** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and
1865 ** [SQLITE_CONFIG_PAGECACHE].
1866 ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
1867 ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
1868 ** [SQLITE_ERROR] if invoked otherwise.
1869 ** ^There are three arguments to SQLITE_CONFIG_HEAP:
1870 ** An 8-byte aligned pointer to the memory,
1871 ** the number of bytes in the memory buffer, and the minimum allocation size.
1872 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1873 ** to using its default memory allocator (the system malloc() implementation),
1874 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
1875 ** memory pointer is not NULL then the alternative memory
1876 ** allocator is engaged to handle all of SQLites memory allocation needs.
1877 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1878 ** boundary or subsequent behavior of SQLite will be undefined.
1879 ** The minimum allocation size is capped at 2**12. Reasonable values
1880 ** for the minimum allocation size are 2**5 through 2**8.</dd>
1881 **
1882 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
1883 ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
1884 ** pointer to an instance of the [sqlite3_mutex_methods] structure.
1885 ** The argument specifies alternative low-level mutex routines to be used
1886 ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
1887 ** the content of the [sqlite3_mutex_methods] structure before the call to
1888 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1889 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1890 ** the entire mutexing subsystem is omitted from the build and hence calls to
1891 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1892 ** return [SQLITE_ERROR].</dd>
1893 **
1894 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
1895 ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
1896 ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
1897 ** [sqlite3_mutex_methods]
1898 ** structure is filled with the currently defined mutex routines.)^
1899 ** This option can be used to overload the default mutex allocation
1900 ** routines with a wrapper used to track mutex usage for performance
1901 ** profiling or testing, for example. ^If SQLite is compiled with
1902 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1903 ** the entire mutexing subsystem is omitted from the build and hence calls to
1904 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1905 ** return [SQLITE_ERROR].</dd>
1906 **
1907 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1908 ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
1909 ** the default size of lookaside memory on each [database connection].
1910 ** The first argument is the
1911 ** size of each lookaside buffer slot and the second is the number of
1912 ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
1913 ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1914 ** option to [sqlite3_db_config()] can be used to change the lookaside
1915 ** configuration on individual connections.)^ </dd>
1916 **
1917 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
1918 ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
1919 ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
1920 ** the interface to a custom page cache implementation.)^
1921 ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
1922 **
1923 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
1924 ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
1925 ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
1926 ** the current page cache implementation into that object.)^ </dd>
1927 **
1928 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
1929 ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
1930 ** global [error log].
1931 ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1932 ** function with a call signature of void(*)(void*,int,const char*),
1933 ** and a pointer to void. ^If the function pointer is not NULL, it is
1934 ** invoked by [sqlite3_log()] to process each logging event. ^If the
1935 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1936 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1937 ** passed through as the first parameter to the application-defined logger
1938 ** function whenever that function is invoked. ^The second parameter to
1939 ** the logger function is a copy of the first parameter to the corresponding
1940 ** [sqlite3_log()] call and is intended to be a [result code] or an
1941 ** [extended result code]. ^The third parameter passed to the logger is
1942 ** log message after formatting via [sqlite3_snprintf()].
1943 ** The SQLite logging interface is not reentrant; the logger function
1944 ** supplied by the application must not invoke any SQLite interface.
1945 ** In a multi-threaded application, the application-defined logger
1946 ** function must be threadsafe. </dd>
1947 **
1948 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
1949 ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
1950 ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
1951 ** then URI handling is globally disabled.)^ ^If URI handling is globally
1952 ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
1953 ** [sqlite3_open16()] or
1954 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
1955 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
1956 ** connection is opened. ^If it is globally disabled, filenames are
1957 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
1958 ** database connection is opened. ^(By default, URI handling is globally
1959 ** disabled. The default value may be changed by compiling with the
1960 ** [SQLITE_USE_URI] symbol defined.)^
1961 **
1962 ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
1963 ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
1964 ** argument which is interpreted as a boolean in order to enable or disable
1965 ** the use of covering indices for full table scans in the query optimizer.
1966 ** ^The default setting is determined
1967 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
1968 ** if that compile-time option is omitted.
1969 ** The ability to disable the use of covering indices for full table scans
1970 ** is because some incorrectly coded legacy applications might malfunction
1971 ** when the optimization is enabled. Providing the ability to
1972 ** disable the optimization allows the older, buggy application code to work
1973 ** without change even with newer versions of SQLite.
1974 **
1975 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
1976 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
1977 ** <dd> These options are obsolete and should not be used by new code.
1978 ** They are retained for backwards compatibility but are now no-ops.
1979 ** </dd>
1980 **
1981 ** [[SQLITE_CONFIG_SQLLOG]]
1982 ** <dt>SQLITE_CONFIG_SQLLOG
1983 ** <dd>This option is only available if sqlite is compiled with the
1984 ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
1985 ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
1986 ** The second should be of type (void*). The callback is invoked by the library
1987 ** in three separate circumstances, identified by the value passed as the
1988 ** fourth parameter. If the fourth parameter is 0, then the database connection
1989 ** passed as the second argument has just been opened. The third argument
1990 ** points to a buffer containing the name of the main database file. If the
1991 ** fourth parameter is 1, then the SQL statement that the third parameter
1992 ** points to has just been executed. Or, if the fourth parameter is 2, then
1993 ** the connection being passed as the second parameter is being closed. The
1994 ** third parameter is passed NULL In this case. An example of using this
1995 ** configuration option can be seen in the "test_sqllog.c" source file in
1996 ** the canonical SQLite source tree.</dd>
1997 **
1998 ** [[SQLITE_CONFIG_MMAP_SIZE]]
1999 ** <dt>SQLITE_CONFIG_MMAP_SIZE
2000 ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
2001 ** that are the default mmap size limit (the default setting for
2002 ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
2003 ** ^The default setting can be overridden by each database connection using
2004 ** either the [PRAGMA mmap_size] command, or by using the
2005 ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
2006 ** will be silently truncated if necessary so that it does not exceed the
2007 ** compile-time maximum mmap size set by the
2008 ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
2009 ** ^If either argument to this option is negative, then that argument is
2010 ** changed to its compile-time default.
2011 **
2012 ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
2013 ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
2014 ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
2015 ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
2016 ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
2017 ** that specifies the maximum size of the created heap.
2018 **
2019 ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
2020 ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
2021 ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
2022 ** is a pointer to an integer and writes into that integer the number of extra
2023 ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
2024 ** The amount of extra space required can change depending on the compiler,
2025 ** target platform, and SQLite version.
2026 **
2027 ** [[SQLITE_CONFIG_PMASZ]]
2028 ** <dt>SQLITE_CONFIG_PMASZ
2029 ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
2030 ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
2031 ** sorter to that integer. The default minimum PMA Size is set by the
2032 ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
2033 ** to help with sort operations when multithreaded sorting
2034 ** is enabled (using the [PRAGMA threads] command) and the amount of content
2035 ** to be sorted exceeds the page size times the minimum of the
2036 ** [PRAGMA cache_size] setting and this value.
2037 ** </dl>
2038 */
2039 #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
2040 #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
2041 #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
2042 #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
2043 #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
2044 #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
2045 #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
2046 #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
2047 #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
2048 #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
2049 #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
2050 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2051 #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
2052 #define SQLITE_CONFIG_PCACHE 14 /* no-op */
2053 #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
2054 #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
2055 #define SQLITE_CONFIG_URI 17 /* int */
2056 #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
2057 #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
2058 #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
2059 #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
2060 #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
2061 #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
2062 #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
2063 #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
2064
2065 /*
2066 ** CAPI3REF: Database Connection Configuration Options
2067 **
2068 ** These constants are the available integer configuration options that
2069 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
2070 **
2071 ** New configuration options may be added in future releases of SQLite.
2072 ** Existing configuration options might be discontinued. Applications
2073 ** should check the return code from [sqlite3_db_config()] to make sure that
2074 ** the call worked. ^The [sqlite3_db_config()] interface will return a
2075 ** non-zero [error code] if a discontinued or unsupported configuration option
2076 ** is invoked.
2077 **
2078 ** <dl>
2079 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2080 ** <dd> ^This option takes three additional arguments that determine the
2081 ** [lookaside memory allocator] configuration for the [database connection].
2082 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2083 ** pointer to a memory buffer to use for lookaside memory.
2084 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2085 ** may be NULL in which case SQLite will allocate the
2086 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2087 ** size of each lookaside buffer slot. ^The third argument is the number of
2088 ** slots. The size of the buffer in the first argument must be greater than
2089 ** or equal to the product of the second and third arguments. The buffer
2090 ** must be aligned to an 8-byte boundary. ^If the second argument to
2091 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2092 ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
2093 ** configuration for a database connection can only be changed when that
2094 ** connection is not currently using lookaside memory, or in other words
2095 ** when the "current value" returned by
2096 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2097 ** Any attempt to change the lookaside memory configuration when lookaside
2098 ** memory is in use leaves the configuration unchanged and returns
2099 ** [SQLITE_BUSY].)^</dd>
2100 **
2101 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2102 ** <dd> ^This option is used to enable or disable the enforcement of
2103 ** [foreign key constraints]. There should be two additional arguments.
2104 ** The first argument is an integer which is 0 to disable FK enforcement,
2105 ** positive to enable FK enforcement or negative to leave FK enforcement
2106 ** unchanged. The second parameter is a pointer to an integer into which
2107 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2108 ** following this call. The second parameter may be a NULL pointer, in
2109 ** which case the FK enforcement setting is not reported back. </dd>
2110 **
2111 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2112 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2113 ** There should be two additional arguments.
2114 ** The first argument is an integer which is 0 to disable triggers,
2115 ** positive to enable triggers or negative to leave the setting unchanged.
2116 ** The second parameter is a pointer to an integer into which
2117 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2118 ** following this call. The second parameter may be a NULL pointer, in
2119 ** which case the trigger setting is not reported back. </dd>
2120 **
2121 ** </dl>
2122 */
2123 #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
2124 #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
2125 #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
2126
2127
2128 /*
2129 ** CAPI3REF: Enable Or Disable Extended Result Codes
2130 ** METHOD: sqlite3
2131 **
2132 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2133 ** [extended result codes] feature of SQLite. ^The extended result
2134 ** codes are disabled by default for historical compatibility.
2135 */
2136 SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3*, int onoff) ;
2137
2138 /*
2139 ** CAPI3REF: Last Insert Rowid
2140 ** METHOD: sqlite3
2141 **
2142 ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
2143 ** has a unique 64-bit signed
2144 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2145 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2146 ** names are not also used by explicitly declared columns. ^If
2147 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2148 ** is another alias for the rowid.
2149 **
2150 ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the
2151 ** most recent successful [INSERT] into a rowid table or [virtual table]
2152 ** on database connection D.
2153 ** ^Inserts into [WITHOUT ROWID] tables are not recorded.
2154 ** ^If no successful [INSERT]s into rowid tables
2155 ** have ever occurred on the database connection D,
2156 ** then sqlite3_last_insert_rowid(D) returns zero.
2157 **
2158 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2159 ** method, then this routine will return the [rowid] of the inserted
2160 ** row as long as the trigger or virtual table method is running.
2161 ** But once the trigger or virtual table method ends, the value returned
2162 ** by this routine reverts to what it was before the trigger or virtual
2163 ** table method began.)^
2164 **
2165 ** ^An [INSERT] that fails due to a constraint violation is not a
2166 ** successful [INSERT] and does not change the value returned by this
2167 ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2168 ** and INSERT OR ABORT make no changes to the return value of this
2169 ** routine when their insertion fails. ^(When INSERT OR REPLACE
2170 ** encounters a constraint violation, it does not fail. The
2171 ** INSERT continues to completion after deleting rows that caused
2172 ** the constraint problem so INSERT OR REPLACE will always change
2173 ** the return value of this interface.)^
2174 **
2175 ** ^For the purposes of this routine, an [INSERT] is considered to
2176 ** be successful even if it is subsequently rolled back.
2177 **
2178 ** This function is accessible to SQL statements via the
2179 ** [last_insert_rowid() SQL function].
2180 **
2181 ** If a separate thread performs a new [INSERT] on the same
2182 ** database connection while the [sqlite3_last_insert_rowid()]
2183 ** function is running and thus changes the last insert [rowid],
2184 ** then the value returned by [sqlite3_last_insert_rowid()] is
2185 ** unpredictable and might not equal either the old or the new
2186 ** last insert [rowid].
2187 */
2188 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3*);
2189
2190 /*
2191 ** CAPI3REF: Count The Number Of Rows Modified
2192 ** METHOD: sqlite3
2193 **
2194 ** ^This function returns the number of rows modified, inserted or
2195 ** deleted by the most recently completed INSERT, UPDATE or DELETE
2196 ** statement on the database connection specified by the only parameter.
2197 ** ^Executing any other type of SQL statement does not modify the value
2198 ** returned by this function.
2199 **
2200 ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
2201 ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
2202 ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
2203 **
2204 ** Changes to a view that are intercepted by
2205 ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
2206 ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
2207 ** DELETE statement run on a view is always zero. Only changes made to real
2208 ** tables are counted.
2209 **
2210 ** Things are more complicated if the sqlite3_changes() function is
2211 ** executed while a trigger program is running. This may happen if the
2212 ** program uses the [changes() SQL function], or if some other callback
2213 ** function invokes sqlite3_changes() directly. Essentially:
2214 **
2215 ** <ul>
2216 ** <li> ^(Before entering a trigger program the value returned by
2217 ** sqlite3_changes() function is saved. After the trigger program
2218 ** has finished, the original value is restored.)^
2219 **
2220 ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
2221 ** statement sets the value returned by sqlite3_changes()
2222 ** upon completion as normal. Of course, this value will not include
2223 ** any changes performed by sub-triggers, as the sqlite3_changes()
2224 ** value will be saved and restored after each sub-trigger has run.)^
2225 ** </ul>
2226 **
2227 ** ^This means that if the changes() SQL function (or similar) is used
2228 ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
2229 ** returns the value as set when the calling statement began executing.
2230 ** ^If it is used by the second or subsequent such statement within a trigger
2231 ** program, the value returned reflects the number of rows modified by the
2232 ** previous INSERT, UPDATE or DELETE statement within the same trigger.
2233 **
2234 ** See also the [sqlite3_total_changes()] interface, the
2235 ** [count_changes pragma], and the [changes() SQL function].
2236 **
2237 ** If a separate thread makes changes on the same database connection
2238 ** while [sqlite3_changes()] is running then the value returned
2239 ** is unpredictable and not meaningful.
2240 */
2241 SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3*);
2242
2243 /*
2244 ** CAPI3REF: Total Number Of Rows Modified
2245 ** METHOD: sqlite3
2246 **
2247 ** ^This function returns the total number of rows inserted, modified or
2248 ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
2249 ** since the database connection was opened, including those executed as
2250 ** part of trigger programs. ^Executing any other type of SQL statement
2251 ** does not affect the value returned by sqlite3_total_changes().
2252 **
2253 ** ^Changes made as part of [foreign key actions] are included in the
2254 ** count, but those made as part of REPLACE constraint resolution are
2255 ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
2256 ** are not counted.
2257 **
2258 ** See also the [sqlite3_changes()] interface, the
2259 ** [count_changes pragma], and the [total_changes() SQL function].
2260 **
2261 ** If a separate thread makes changes on the same database connection
2262 ** while [sqlite3_total_changes()] is running then the value
2263 ** returned is unpredictable and not meaningful.
2264 */
2265 SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3*);
2266
2267 /*
2268 ** CAPI3REF: Interrupt A Long-Running Query
2269 ** METHOD: sqlite3
2270 **
2271 ** ^This function causes any pending database operation to abort and
2272 ** return at its earliest opportunity. This routine is typically
2273 ** called in response to a user action such as pressing "Cancel"
2274 ** or Ctrl-C where the user wants a long query operation to halt
2275 ** immediately.
2276 **
2277 ** ^It is safe to call this routine from a thread different from the
2278 ** thread that is currently running the database operation. But it
2279 ** is not safe to call this routine with a [database connection] that
2280 ** is closed or might close before sqlite3_interrupt() returns.
2281 **
2282 ** ^If an SQL operation is very nearly finished at the time when
2283 ** sqlite3_interrupt() is called, then it might not have an opportunity
2284 ** to be interrupted and might continue to completion.
2285 **
2286 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2287 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2288 ** that is inside an explicit transaction, then the entire transaction
2289 ** will be rolled back automatically.
2290 **
2291 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2292 ** SQL statements on [database connection] D complete. ^Any new SQL statements
2293 ** that are started after the sqlite3_interrupt() call and before the
2294 ** running statements reaches zero are interrupted as if they had been
2295 ** running prior to the sqlite3_interrupt() call. ^New SQL statements
2296 ** that are started after the running statement count reaches zero are
2297 ** not effected by the sqlite3_interrupt().
2298 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2299 ** SQL statements is a no-op and has no effect on SQL statements
2300 ** that are started after the sqlite3_interrupt() call returns.
2301 **
2302 ** If the database connection closes while [sqlite3_interrupt()]
2303 ** is running then bad things will likely happen.
2304 */
2305 SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3*);
2306
2307 /*
2308 ** CAPI3REF: Determine If An SQL Statement Is Complete
2309 **
2310 ** These routines are useful during command-line input to determine if the
2311 ** currently entered text seems to form a complete SQL statement or
2312 ** if additional input is needed before sending the text into
2313 ** SQLite for parsing. ^These routines return 1 if the input string
2314 ** appears to be a complete SQL statement. ^A statement is judged to be
2315 ** complete if it ends with a semicolon token and is not a prefix of a
2316 ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
2317 ** string literals or quoted identifier names or comments are not
2318 ** independent tokens (they are part of the token in which they are
2319 ** embedded) and thus do not count as a statement terminator. ^Whitespace
2320 ** and comments that follow the final semicolon are ignored.
2321 **
2322 ** ^These routines return 0 if the statement is incomplete. ^If a
2323 ** memory allocation fails, then SQLITE_NOMEM is returned.
2324 **
2325 ** ^These routines do not parse the SQL statements thus
2326 ** will not detect syntactically incorrect SQL.
2327 **
2328 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2329 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2330 ** automatically by sqlite3_complete16(). If that initialization fails,
2331 ** then the return value from sqlite3_complete16() will be non-zero
2332 ** regardless of whether or not the input SQL is complete.)^
2333 **
2334 ** The input to [sqlite3_complete()] must be a zero-terminated
2335 ** UTF-8 string.
2336 **
2337 ** The input to [sqlite3_complete16()] must be a zero-terminated
2338 ** UTF-16 string in native byte order.
2339 */
2340 SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *sql);
2341 SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *sql);
2342
2343 /*
2344 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2345 ** KEYWORDS: {busy-handler callback} {busy handler}
2346 ** METHOD: sqlite3
2347 **
2348 ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
2349 ** that might be invoked with argument P whenever
2350 ** an attempt is made to access a database table associated with
2351 ** [database connection] D when another thread
2352 ** or process has the table locked.
2353 ** The sqlite3_busy_handler() interface is used to implement
2354 ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
2355 **
2356 ** ^If the busy callback is NULL, then [SQLITE_BUSY]
2357 ** is returned immediately upon encountering the lock. ^If the busy callback
2358 ** is not NULL, then the callback might be invoked with two arguments.
2359 **
2360 ** ^The first argument to the busy handler is a copy of the void* pointer which
2361 ** is the third argument to sqlite3_busy_handler(). ^The second argument to
2362 ** the busy handler callback is the number of times that the busy handler has
2363 ** been invoked previously for the same locking event. ^If the
2364 ** busy callback returns 0, then no additional attempts are made to
2365 ** access the database and [SQLITE_BUSY] is returned
2366 ** to the application.
2367 ** ^If the callback returns non-zero, then another attempt
2368 ** is made to access the database and the cycle repeats.
2369 **
2370 ** The presence of a busy handler does not guarantee that it will be invoked
2371 ** when there is lock contention. ^If SQLite determines that invoking the busy
2372 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2373 ** to the application instead of invoking the
2374 ** busy handler.
2375 ** Consider a scenario where one process is holding a read lock that
2376 ** it is trying to promote to a reserved lock and
2377 ** a second process is holding a reserved lock that it is trying
2378 ** to promote to an exclusive lock. The first process cannot proceed
2379 ** because it is blocked by the second and the second process cannot
2380 ** proceed because it is blocked by the first. If both processes
2381 ** invoke the busy handlers, neither will make any progress. Therefore,
2382 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2383 ** will induce the first process to release its read lock and allow
2384 ** the second process to proceed.
2385 **
2386 ** ^The default busy callback is NULL.
2387 **
2388 ** ^(There can only be a single busy handler defined for each
2389 ** [database connection]. Setting a new busy handler clears any
2390 ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
2391 ** or evaluating [PRAGMA busy_timeout=N] will change the
2392 ** busy handler and thus clear any previously set busy handler.
2393 **
2394 ** The busy callback should not take any actions which modify the
2395 ** database connection that invoked the busy handler. In other words,
2396 ** the busy handler is not reentrant. Any such actions
2397 ** result in undefined behavior.
2398 **
2399 ** A busy handler must not close the database connection
2400 ** or [prepared statement] that invoked the busy handler.
2401 */
2402 SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2403
2404 /*
2405 ** CAPI3REF: Set A Busy Timeout
2406 ** METHOD: sqlite3
2407 **
2408 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2409 ** for a specified amount of time when a table is locked. ^The handler
2410 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2411 ** have accumulated. ^After at least "ms" milliseconds of sleeping,
2412 ** the handler returns 0 which causes [sqlite3_step()] to return
2413 ** [SQLITE_BUSY].
2414 **
2415 ** ^Calling this routine with an argument less than or equal to zero
2416 ** turns off all busy handlers.
2417 **
2418 ** ^(There can only be a single busy handler for a particular
2419 ** [database connection] at any given moment. If another busy handler
2420 ** was defined (using [sqlite3_busy_handler()]) prior to calling
2421 ** this routine, that other busy handler is cleared.)^
2422 **
2423 ** See also: [PRAGMA busy_timeout]
2424 */
2425 SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3*, int ms);
2426
2427 /*
2428 ** CAPI3REF: Convenience Routines For Running Queries
2429 ** METHOD: sqlite3
2430 **
2431 ** This is a legacy interface that is preserved for backwards compatibility.
2432 ** Use of this interface is not recommended.
2433 **
2434 ** Definition: A <b>result table</b> is memory data structure created by the
2435 ** [sqlite3_get_table()] interface. A result table records the
2436 ** complete query results from one or more queries.
2437 **
2438 ** The table conceptually has a number of rows and columns. But
2439 ** these numbers are not part of the result table itself. These
2440 ** numbers are obtained separately. Let N be the number of rows
2441 ** and M be the number of columns.
2442 **
2443 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2444 ** There are (N+1)*M elements in the array. The first M pointers point
2445 ** to zero-terminated strings that contain the names of the columns.
2446 ** The remaining entries all point to query results. NULL values result
2447 ** in NULL pointers. All other values are in their UTF-8 zero-terminated
2448 ** string representation as returned by [sqlite3_column_text()].
2449 **
2450 ** A result table might consist of one or more memory allocations.
2451 ** It is not safe to pass a result table directly to [sqlite3_free()].
2452 ** A result table should be deallocated using [sqlite3_free_table()].
2453 **
2454 ** ^(As an example of the result table format, suppose a query result
2455 ** is as follows:
2456 **
2457 ** <blockquote><pre>
2458 ** Name | Age
2459 ** -----------------------
2460 ** Alice | 43
2461 ** Bob | 28
2462 ** Cindy | 21
2463 ** </pre></blockquote>
2464 **
2465 ** There are two column (M==2) and three rows (N==3). Thus the
2466 ** result table has 8 entries. Suppose the result table is stored
2467 ** in an array names azResult. Then azResult holds this content:
2468 **
2469 ** <blockquote><pre>
2470 ** azResult&#91;0] = "Name";
2471 ** azResult&#91;1] = "Age";
2472 ** azResult&#91;2] = "Alice";
2473 ** azResult&#91;3] = "43";
2474 ** azResult&#91;4] = "Bob";
2475 ** azResult&#91;5] = "28";
2476 ** azResult&#91;6] = "Cindy";
2477 ** azResult&#91;7] = "21";
2478 ** </pre></blockquote>)^
2479 **
2480 ** ^The sqlite3_get_table() function evaluates one or more
2481 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2482 ** string of its 2nd parameter and returns a result table to the
2483 ** pointer given in its 3rd parameter.
2484 **
2485 ** After the application has finished with the result from sqlite3_get_table(),
2486 ** it must pass the result table pointer to sqlite3_free_table() in order to
2487 ** release the memory that was malloced. Because of the way the
2488 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2489 ** function must not try to call [sqlite3_free()] directly. Only
2490 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2491 **
2492 ** The sqlite3_get_table() interface is implemented as a wrapper around
2493 ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
2494 ** to any internal data structures of SQLite. It uses only the public
2495 ** interface defined here. As a consequence, errors that occur in the
2496 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2497 ** reflected in subsequent calls to [sqlite3_errcode()] or
2498 ** [sqlite3_errmsg()].
2499 */
2500 SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
2501 sqlite3 *db, /* An open database */
2502 const char *zSql, /* SQL to be evaluated */
2503 char ***pazResult, /* Results of the query */
2504 int *pnRow, /* Number of result rows written here */
2505 int *pnColumn, /* Number of result columns written here */
2506 char **pzErrmsg /* Error msg written here */
2507 );
2508 SQLITE_API void SQLITE_STDCALL sqlite3_free_table(char **result);
2509
2510 /*
2511 ** CAPI3REF: Formatted String Printing Functions
2512 **
2513 ** These routines are work-alikes of the "printf()" family of functions
2514 ** from the standard C library.
2515 ** These routines understand most of the common K&R formatting options,
2516 ** plus some additional non-standard formats, detailed below.
2517 ** Note that some of the more obscure formatting options from recent
2518 ** C-library standards are omitted from this implementation.
2519 **
2520 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2521 ** results into memory obtained from [sqlite3_malloc()].
2522 ** The strings returned by these two routines should be
2523 ** released by [sqlite3_free()]. ^Both routines return a
2524 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2525 ** memory to hold the resulting string.
2526 **
2527 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2528 ** the standard C library. The result is written into the
2529 ** buffer supplied as the second parameter whose size is given by
2530 ** the first parameter. Note that the order of the
2531 ** first two parameters is reversed from snprintf().)^ This is an
2532 ** historical accident that cannot be fixed without breaking
2533 ** backwards compatibility. ^(Note also that sqlite3_snprintf()
2534 ** returns a pointer to its buffer instead of the number of
2535 ** characters actually written into the buffer.)^ We admit that
2536 ** the number of characters written would be a more useful return
2537 ** value but we cannot change the implementation of sqlite3_snprintf()
2538 ** now without breaking compatibility.
2539 **
2540 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2541 ** guarantees that the buffer is always zero-terminated. ^The first
2542 ** parameter "n" is the total size of the buffer, including space for
2543 ** the zero terminator. So the longest string that can be completely
2544 ** written will be n-1 characters.
2545 **
2546 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2547 **
2548 ** These routines all implement some additional formatting
2549 ** options that are useful for constructing SQL statements.
2550 ** All of the usual printf() formatting options apply. In addition, there
2551 ** is are "%q", "%Q", "%w" and "%z" options.
2552 **
2553 ** ^(The %q option works like %s in that it substitutes a nul-terminated
2554 ** string from the argument list. But %q also doubles every '\'' character.
2555 ** %q is designed for use inside a string literal.)^ By doubling each '\''
2556 ** character it escapes that character and allows it to be inserted into
2557 ** the string.
2558 **
2559 ** For example, assume the string variable zText contains text as follows:
2560 **
2561 ** <blockquote><pre>
2562 ** char *zText = "It's a happy day!";
2563 ** </pre></blockquote>
2564 **
2565 ** One can use this text in an SQL statement as follows:
2566 **
2567 ** <blockquote><pre>
2568 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2569 ** sqlite3_exec(db, zSQL, 0, 0, 0);
2570 ** sqlite3_free(zSQL);
2571 ** </pre></blockquote>
2572 **
2573 ** Because the %q format string is used, the '\'' character in zText
2574 ** is escaped and the SQL generated is as follows:
2575 **
2576 ** <blockquote><pre>
2577 ** INSERT INTO table1 VALUES('It''s a happy day!')
2578 ** </pre></blockquote>
2579 **
2580 ** This is correct. Had we used %s instead of %q, the generated SQL
2581 ** would have looked like this:
2582 **
2583 ** <blockquote><pre>
2584 ** INSERT INTO table1 VALUES('It's a happy day!');
2585 ** </pre></blockquote>
2586 **
2587 ** This second example is an SQL syntax error. As a general rule you should
2588 ** always use %q instead of %s when inserting text into a string literal.
2589 **
2590 ** ^(The %Q option works like %q except it also adds single quotes around
2591 ** the outside of the total string. Additionally, if the parameter in the
2592 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2593 ** single quotes).)^ So, for example, one could say:
2594 **
2595 ** <blockquote><pre>
2596 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2597 ** sqlite3_exec(db, zSQL, 0, 0, 0);
2598 ** sqlite3_free(zSQL);
2599 ** </pre></blockquote>
2600 **
2601 ** The code above will render a correct SQL statement in the zSQL
2602 ** variable even if the zText variable is a NULL pointer.
2603 **
2604 ** ^(The "%w" formatting option is like "%q" except that it expects to
2605 ** be contained within double-quotes instead of single quotes, and it
2606 ** escapes the double-quote character instead of the single-quote
2607 ** character.)^ The "%w" formatting option is intended for safely inserting
2608 ** table and column names into a constructed SQL statement.
2609 **
2610 ** ^(The "%z" formatting option works like "%s" but with the
2611 ** addition that after the string has been read and copied into
2612 ** the result, [sqlite3_free()] is called on the input string.)^
2613 */
2614 SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char*,...);
2615 SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char*, va_list);
2616 SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int,char*,const char*, ...);
2617 SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int,char*,const char*, va_list );
2618
2619 /*
2620 ** CAPI3REF: Memory Allocation Subsystem
2621 **
2622 ** The SQLite core uses these three routines for all of its own
2623 ** internal memory allocation needs. "Core" in the previous sentence
2624 ** does not include operating-system specific VFS implementation. The
2625 ** Windows VFS uses native malloc() and free() for some operations.
2626 **
2627 ** ^The sqlite3_malloc() routine returns a pointer to a block
2628 ** of memory at least N bytes in length, where N is the parameter.
2629 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2630 ** memory, it returns a NULL pointer. ^If the parameter N to
2631 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2632 ** a NULL pointer.
2633 **
2634 ** ^The sqlite3_malloc64(N) routine works just like
2635 ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
2636 ** of a signed 32-bit integer.
2637 **
2638 ** ^Calling sqlite3_free() with a pointer previously returned
2639 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2640 ** that it might be reused. ^The sqlite3_free() routine is
2641 ** a no-op if is called with a NULL pointer. Passing a NULL pointer
2642 ** to sqlite3_free() is harmless. After being freed, memory
2643 ** should neither be read nor written. Even reading previously freed
2644 ** memory might result in a segmentation fault or other severe error.
2645 ** Memory corruption, a segmentation fault, or other severe error
2646 ** might result if sqlite3_free() is called with a non-NULL pointer that
2647 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2648 **
2649 ** ^The sqlite3_realloc(X,N) interface attempts to resize a
2650 ** prior memory allocation X to be at least N bytes.
2651 ** ^If the X parameter to sqlite3_realloc(X,N)
2652 ** is a NULL pointer then its behavior is identical to calling
2653 ** sqlite3_malloc(N).
2654 ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
2655 ** negative then the behavior is exactly the same as calling
2656 ** sqlite3_free(X).
2657 ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
2658 ** of at least N bytes in size or NULL if insufficient memory is available.
2659 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2660 ** of the prior allocation are copied into the beginning of buffer returned
2661 ** by sqlite3_realloc(X,N) and the prior allocation is freed.
2662 ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
2663 ** prior allocation is not freed.
2664 **
2665 ** ^The sqlite3_realloc64(X,N) interfaces works the same as
2666 ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
2667 ** of a 32-bit signed integer.
2668 **
2669 ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
2670 ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
2671 ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
2672 ** ^The value returned by sqlite3_msize(X) might be larger than the number
2673 ** of bytes requested when X was allocated. ^If X is a NULL pointer then
2674 ** sqlite3_msize(X) returns zero. If X points to something that is not
2675 ** the beginning of memory allocation, or if it points to a formerly
2676 ** valid memory allocation that has now been freed, then the behavior
2677 ** of sqlite3_msize(X) is undefined and possibly harmful.
2678 **
2679 ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
2680 ** sqlite3_malloc64(), and sqlite3_realloc64()
2681 ** is always aligned to at least an 8 byte boundary, or to a
2682 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2683 ** option is used.
2684 **
2685 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2686 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2687 ** implementation of these routines to be omitted. That capability
2688 ** is no longer provided. Only built-in memory allocators can be used.
2689 **
2690 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2691 ** the system malloc() and free() directly when converting
2692 ** filenames between the UTF-8 encoding used by SQLite
2693 ** and whatever filename encoding is used by the particular Windows
2694 ** installation. Memory allocation errors were detected, but
2695 ** they were reported back as [SQLITE_CANTOPEN] or
2696 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2697 **
2698 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2699 ** must be either NULL or else pointers obtained from a prior
2700 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2701 ** not yet been released.
2702 **
2703 ** The application must not read or write any part of
2704 ** a block of memory after it has been released using
2705 ** [sqlite3_free()] or [sqlite3_realloc()].
2706 */
2707 SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int);
2708 SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64);
2709 SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void*, int);
2710 SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void*, sqlite3_uint64);
2711 SQLITE_API void SQLITE_STDCALL sqlite3_free(void*);
2712 SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void*);
2713
2714 /*
2715 ** CAPI3REF: Memory Allocator Statistics
2716 **
2717 ** SQLite provides these two interfaces for reporting on the status
2718 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2719 ** routines, which form the built-in memory allocation subsystem.
2720 **
2721 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2722 ** of memory currently outstanding (malloced but not freed).
2723 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2724 ** value of [sqlite3_memory_used()] since the high-water mark
2725 ** was last reset. ^The values returned by [sqlite3_memory_used()] and
2726 ** [sqlite3_memory_highwater()] include any overhead
2727 ** added by SQLite in its implementation of [sqlite3_malloc()],
2728 ** but not overhead added by the any underlying system library
2729 ** routines that [sqlite3_malloc()] may call.
2730 **
2731 ** ^The memory high-water mark is reset to the current value of
2732 ** [sqlite3_memory_used()] if and only if the parameter to
2733 ** [sqlite3_memory_highwater()] is true. ^The value returned
2734 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2735 ** prior to the reset.
2736 */
2737 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void);
2738 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag);
2739
2740 /*
2741 ** CAPI3REF: Pseudo-Random Number Generator
2742 **
2743 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2744 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2745 ** already uses the largest possible [ROWID]. The PRNG is also used for
2746 ** the build-in random() and randomblob() SQL functions. This interface allows
2747 ** applications to access the same PRNG for other purposes.
2748 **
2749 ** ^A call to this routine stores N bytes of randomness into buffer P.
2750 ** ^The P parameter can be a NULL pointer.
2751 **
2752 ** ^If this routine has not been previously called or if the previous
2753 ** call had N less than one or a NULL pointer for P, then the PRNG is
2754 ** seeded using randomness obtained from the xRandomness method of
2755 ** the default [sqlite3_vfs] object.
2756 ** ^If the previous call to this routine had an N of 1 or more and a
2757 ** non-NULL P then the pseudo-randomness is generated
2758 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2759 ** method.
2760 */
2761 SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *P);
2762
2763 /*
2764 ** CAPI3REF: Compile-Time Authorization Callbacks
2765 ** METHOD: sqlite3
2766 **
2767 ** ^This routine registers an authorizer callback with a particular
2768 ** [database connection], supplied in the first argument.
2769 ** ^The authorizer callback is invoked as SQL statements are being compiled
2770 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2771 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
2772 ** points during the compilation process, as logic is being created
2773 ** to perform various actions, the authorizer callback is invoked to
2774 ** see if those actions are allowed. ^The authorizer callback should
2775 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2776 ** specific action but allow the SQL statement to continue to be
2777 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2778 ** rejected with an error. ^If the authorizer callback returns
2779 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2780 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2781 ** the authorizer will fail with an error message.
2782 **
2783 ** When the callback returns [SQLITE_OK], that means the operation
2784 ** requested is ok. ^When the callback returns [SQLITE_DENY], the
2785 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2786 ** authorizer will fail with an error message explaining that
2787 ** access is denied.
2788 **
2789 ** ^The first parameter to the authorizer callback is a copy of the third
2790 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2791 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2792 ** the particular action to be authorized. ^The third through sixth parameters
2793 ** to the callback are zero-terminated strings that contain additional
2794 ** details about the action to be authorized.
2795 **
2796 ** ^If the action code is [SQLITE_READ]
2797 ** and the callback returns [SQLITE_IGNORE] then the
2798 ** [prepared statement] statement is constructed to substitute
2799 ** a NULL value in place of the table column that would have
2800 ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
2801 ** return can be used to deny an untrusted user access to individual
2802 ** columns of a table.
2803 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2804 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2805 ** [truncate optimization] is disabled and all rows are deleted individually.
2806 **
2807 ** An authorizer is used when [sqlite3_prepare | preparing]
2808 ** SQL statements from an untrusted source, to ensure that the SQL statements
2809 ** do not try to access data they are not allowed to see, or that they do not
2810 ** try to execute malicious statements that damage the database. For
2811 ** example, an application may allow a user to enter arbitrary
2812 ** SQL queries for evaluation by a database. But the application does
2813 ** not want the user to be able to make arbitrary changes to the
2814 ** database. An authorizer could then be put in place while the
2815 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2816 ** disallows everything except [SELECT] statements.
2817 **
2818 ** Applications that need to process SQL from untrusted sources
2819 ** might also consider lowering resource limits using [sqlite3_limit()]
2820 ** and limiting database size using the [max_page_count] [PRAGMA]
2821 ** in addition to using an authorizer.
2822 **
2823 ** ^(Only a single authorizer can be in place on a database connection
2824 ** at a time. Each call to sqlite3_set_authorizer overrides the
2825 ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
2826 ** The authorizer is disabled by default.
2827 **
2828 ** The authorizer callback must not do anything that will modify
2829 ** the database connection that invoked the authorizer callback.
2830 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2831 ** database connections for the meaning of "modify" in this paragraph.
2832 **
2833 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2834 ** statement might be re-prepared during [sqlite3_step()] due to a
2835 ** schema change. Hence, the application should ensure that the
2836 ** correct authorizer callback remains in place during the [sqlite3_step()].
2837 **
2838 ** ^Note that the authorizer callback is invoked only during
2839 ** [sqlite3_prepare()] or its variants. Authorization is not
2840 ** performed during statement evaluation in [sqlite3_step()], unless
2841 ** as stated in the previous paragraph, sqlite3_step() invokes
2842 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2843 */
2844 SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
2845 sqlite3*,
2846 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2847 void *pUserData
2848 );
2849
2850 /*
2851 ** CAPI3REF: Authorizer Return Codes
2852 **
2853 ** The [sqlite3_set_authorizer | authorizer callback function] must
2854 ** return either [SQLITE_OK] or one of these two constants in order
2855 ** to signal SQLite whether or not the action is permitted. See the
2856 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2857 ** information.
2858 **
2859 ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
2860 ** returned from the [sqlite3_vtab_on_conflict()] interface.
2861 */
2862 #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
2863 #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
2864
2865 /*
2866 ** CAPI3REF: Authorizer Action Codes
2867 **
2868 ** The [sqlite3_set_authorizer()] interface registers a callback function
2869 ** that is invoked to authorize certain SQL statement actions. The
2870 ** second parameter to the callback is an integer code that specifies
2871 ** what action is being authorized. These are the integer action codes that
2872 ** the authorizer callback may be passed.
2873 **
2874 ** These action code values signify what kind of operation is to be
2875 ** authorized. The 3rd and 4th parameters to the authorization
2876 ** callback function will be parameters or NULL depending on which of these
2877 ** codes is used as the second parameter. ^(The 5th parameter to the
2878 ** authorizer callback is the name of the database ("main", "temp",
2879 ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
2880 ** is the name of the inner-most trigger or view that is responsible for
2881 ** the access attempt or NULL if this access attempt is directly from
2882 ** top-level SQL code.
2883 */
2884 /******************************************* 3rd ************ 4th ***********/
2885 #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
2886 #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
2887 #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
2888 #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
2889 #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
2890 #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
2891 #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
2892 #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
2893 #define SQLITE_DELETE 9 /* Table Name NULL */
2894 #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
2895 #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
2896 #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
2897 #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
2898 #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
2899 #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
2900 #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
2901 #define SQLITE_DROP_VIEW 17 /* View Name NULL */
2902 #define SQLITE_INSERT 18 /* Table Name NULL */
2903 #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
2904 #define SQLITE_READ 20 /* Table Name Column Name */
2905 #define SQLITE_SELECT 21 /* NULL NULL */
2906 #define SQLITE_TRANSACTION 22 /* Operation NULL */
2907 #define SQLITE_UPDATE 23 /* Table Name Column Name */
2908 #define SQLITE_ATTACH 24 /* Filename NULL */
2909 #define SQLITE_DETACH 25 /* Database Name NULL */
2910 #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
2911 #define SQLITE_REINDEX 27 /* Index Name NULL */
2912 #define SQLITE_ANALYZE 28 /* Table Name NULL */
2913 #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
2914 #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
2915 #define SQLITE_FUNCTION 31 /* NULL Function Name */
2916 #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
2917 #define SQLITE_COPY 0 /* No longer used */
2918 #define SQLITE_RECURSIVE 33 /* NULL NULL */
2919
2920 /*
2921 ** CAPI3REF: Tracing And Profiling Functions
2922 ** METHOD: sqlite3
2923 **
2924 ** These routines register callback functions that can be used for
2925 ** tracing and profiling the execution of SQL statements.
2926 **
2927 ** ^The callback function registered by sqlite3_trace() is invoked at
2928 ** various times when an SQL statement is being run by [sqlite3_step()].
2929 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2930 ** SQL statement text as the statement first begins executing.
2931 ** ^(Additional sqlite3_trace() callbacks might occur
2932 ** as each triggered subprogram is entered. The callbacks for triggers
2933 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2934 **
2935 ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
2936 ** the length of [bound parameter] expansion in the output of sqlite3_trace().
2937 **
2938 ** ^The callback function registered by sqlite3_profile() is invoked
2939 ** as each SQL statement finishes. ^The profile callback contains
2940 ** the original statement text and an estimate of wall-clock time
2941 ** of how long that statement took to run. ^The profile callback
2942 ** time is in units of nanoseconds, however the current implementation
2943 ** is only capable of millisecond resolution so the six least significant
2944 ** digits in the time are meaningless. Future versions of SQLite
2945 ** might provide greater resolution on the profiler callback. The
2946 ** sqlite3_profile() function is considered experimental and is
2947 ** subject to change in future versions of SQLite.
2948 */
2949 SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3*, void(*xTrace)(void*,cons t char*), void*);
2950 SQLITE_API SQLITE_EXPERIMENTAL void *SQLITE_STDCALL sqlite3_profile(sqlite3*,
2951 void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2952
2953 /*
2954 ** CAPI3REF: Query Progress Callbacks
2955 ** METHOD: sqlite3
2956 **
2957 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2958 ** function X to be invoked periodically during long running calls to
2959 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2960 ** database connection D. An example use for this
2961 ** interface is to keep a GUI updated during a large query.
2962 **
2963 ** ^The parameter P is passed through as the only parameter to the
2964 ** callback function X. ^The parameter N is the approximate number of
2965 ** [virtual machine instructions] that are evaluated between successive
2966 ** invocations of the callback X. ^If N is less than one then the progress
2967 ** handler is disabled.
2968 **
2969 ** ^Only a single progress handler may be defined at one time per
2970 ** [database connection]; setting a new progress handler cancels the
2971 ** old one. ^Setting parameter X to NULL disables the progress handler.
2972 ** ^The progress handler is also disabled by setting N to a value less
2973 ** than 1.
2974 **
2975 ** ^If the progress callback returns non-zero, the operation is
2976 ** interrupted. This feature can be used to implement a
2977 ** "Cancel" button on a GUI progress dialog box.
2978 **
2979 ** The progress handler callback must not do anything that will modify
2980 ** the database connection that invoked the progress handler.
2981 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2982 ** database connections for the meaning of "modify" in this paragraph.
2983 **
2984 */
2985 SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(sqlite3*, int, int(*)(vo id*), void*);
2986
2987 /*
2988 ** CAPI3REF: Opening A New Database Connection
2989 ** CONSTRUCTOR: sqlite3
2990 **
2991 ** ^These routines open an SQLite database file as specified by the
2992 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2993 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2994 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
2995 ** returned in *ppDb, even if an error occurs. The only exception is that
2996 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2997 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2998 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2999 ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
3000 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3001 ** an English language description of the error following a failure of any
3002 ** of the sqlite3_open() routines.
3003 **
3004 ** ^The default encoding will be UTF-8 for databases created using
3005 ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
3006 ** created using sqlite3_open16() will be UTF-16 in the native byte order.
3007 **
3008 ** Whether or not an error occurs when it is opened, resources
3009 ** associated with the [database connection] handle should be released by
3010 ** passing it to [sqlite3_close()] when it is no longer required.
3011 **
3012 ** The sqlite3_open_v2() interface works like sqlite3_open()
3013 ** except that it accepts two additional parameters for additional control
3014 ** over the new database connection. ^(The flags parameter to
3015 ** sqlite3_open_v2() can take one of
3016 ** the following three values, optionally combined with the
3017 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
3018 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
3019 **
3020 ** <dl>
3021 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
3022 ** <dd>The database is opened in read-only mode. If the database does not
3023 ** already exist, an error is returned.</dd>)^
3024 **
3025 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
3026 ** <dd>The database is opened for reading and writing if possible, or reading
3027 ** only if the file is write protected by the operating system. In either
3028 ** case the database must already exist, otherwise an error is returned.</dd>)^
3029 **
3030 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3031 ** <dd>The database is opened for reading and writing, and is created if
3032 ** it does not already exist. This is the behavior that is always used for
3033 ** sqlite3_open() and sqlite3_open16().</dd>)^
3034 ** </dl>
3035 **
3036 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
3037 ** combinations shown above optionally combined with other
3038 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
3039 ** then the behavior is undefined.
3040 **
3041 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3042 ** opens in the multi-thread [threading mode] as long as the single-thread
3043 ** mode has not been set at compile-time or start-time. ^If the
3044 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3045 ** in the serialized [threading mode] unless single-thread was
3046 ** previously selected at compile-time or start-time.
3047 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
3048 ** eligible to use [shared cache mode], regardless of whether or not shared
3049 ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
3050 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
3051 ** participate in [shared cache mode] even if it is enabled.
3052 **
3053 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
3054 ** [sqlite3_vfs] object that defines the operating system interface that
3055 ** the new database connection should use. ^If the fourth parameter is
3056 ** a NULL pointer then the default [sqlite3_vfs] object is used.
3057 **
3058 ** ^If the filename is ":memory:", then a private, temporary in-memory database
3059 ** is created for the connection. ^This in-memory database will vanish when
3060 ** the database connection is closed. Future versions of SQLite might
3061 ** make use of additional special filenames that begin with the ":" character.
3062 ** It is recommended that when a database filename actually does begin with
3063 ** a ":" character you should prefix the filename with a pathname such as
3064 ** "./" to avoid ambiguity.
3065 **
3066 ** ^If the filename is an empty string, then a private, temporary
3067 ** on-disk database will be created. ^This private database will be
3068 ** automatically deleted as soon as the database connection is closed.
3069 **
3070 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3071 **
3072 ** ^If [URI filename] interpretation is enabled, and the filename argument
3073 ** begins with "file:", then the filename is interpreted as a URI. ^URI
3074 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3075 ** set in the fourth argument to sqlite3_open_v2(), or if it has
3076 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3077 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3078 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
3079 ** by default, but future releases of SQLite might enable URI filename
3080 ** interpretation by default. See "[URI filenames]" for additional
3081 ** information.
3082 **
3083 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3084 ** authority, then it must be either an empty string or the string
3085 ** "localhost". ^If the authority is not an empty string or "localhost", an
3086 ** error is returned to the caller. ^The fragment component of a URI, if
3087 ** present, is ignored.
3088 **
3089 ** ^SQLite uses the path component of the URI as the name of the disk file
3090 ** which contains the database. ^If the path begins with a '/' character,
3091 ** then it is interpreted as an absolute path. ^If the path does not begin
3092 ** with a '/' (meaning that the authority section is omitted from the URI)
3093 ** then the path is interpreted as a relative path.
3094 ** ^(On windows, the first component of an absolute path
3095 ** is a drive specification (e.g. "C:").)^
3096 **
3097 ** [[core URI query parameters]]
3098 ** The query component of a URI may contain parameters that are interpreted
3099 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
3100 ** SQLite and its built-in [VFSes] interpret the
3101 ** following query parameters:
3102 **
3103 ** <ul>
3104 ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3105 ** a VFS object that provides the operating system interface that should
3106 ** be used to access the database file on disk. ^If this option is set to
3107 ** an empty string the default VFS object is used. ^Specifying an unknown
3108 ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3109 ** present, then the VFS specified by the option takes precedence over
3110 ** the value passed as the fourth parameter to sqlite3_open_v2().
3111 **
3112 ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
3113 ** "rwc", or "memory". Attempting to set it to any other value is
3114 ** an error)^.
3115 ** ^If "ro" is specified, then the database is opened for read-only
3116 ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
3117 ** third argument to sqlite3_open_v2(). ^If the mode option is set to
3118 ** "rw", then the database is opened for read-write (but not create)
3119 ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
3120 ** been set. ^Value "rwc" is equivalent to setting both
3121 ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
3122 ** set to "memory" then a pure [in-memory database] that never reads
3123 ** or writes from disk is used. ^It is an error to specify a value for
3124 ** the mode parameter that is less restrictive than that specified by
3125 ** the flags passed in the third parameter to sqlite3_open_v2().
3126 **
3127 ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3128 ** "private". ^Setting it to "shared" is equivalent to setting the
3129 ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3130 ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
3131 ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3132 ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3133 ** a URI filename, its value overrides any behavior requested by setting
3134 ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3135 **
3136 ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
3137 ** [powersafe overwrite] property does or does not apply to the
3138 ** storage media on which the database file resides.
3139 **
3140 ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
3141 ** which if set disables file locking in rollback journal modes. This
3142 ** is useful for accessing a database on a filesystem that does not
3143 ** support locking. Caution: Database corruption might result if two
3144 ** or more processes write to the same database and any one of those
3145 ** processes uses nolock=1.
3146 **
3147 ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
3148 ** parameter that indicates that the database file is stored on
3149 ** read-only media. ^When immutable is set, SQLite assumes that the
3150 ** database file cannot be changed, even by a process with higher
3151 ** privilege, and so the database is opened read-only and all locking
3152 ** and change detection is disabled. Caution: Setting the immutable
3153 ** property on a database file that does in fact change can result
3154 ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
3155 ** See also: [SQLITE_IOCAP_IMMUTABLE].
3156 **
3157 ** </ul>
3158 **
3159 ** ^Specifying an unknown parameter in the query component of a URI is not an
3160 ** error. Future versions of SQLite might understand additional query
3161 ** parameters. See "[query parameters with special meaning to SQLite]" for
3162 ** additional information.
3163 **
3164 ** [[URI filename examples]] <h3>URI filename examples</h3>
3165 **
3166 ** <table border="1" align=center cellpadding=5>
3167 ** <tr><th> URI filenames <th> Results
3168 ** <tr><td> file:data.db <td>
3169 ** Open the file "data.db" in the current directory.
3170 ** <tr><td> file:/home/fred/data.db<br>
3171 ** file:///home/fred/data.db <br>
3172 ** file://localhost/home/fred/data.db <br> <td>
3173 ** Open the database file "/home/fred/data.db".
3174 ** <tr><td> file://darkstar/home/fred/data.db <td>
3175 ** An error. "darkstar" is not a recognized authority.
3176 ** <tr><td style="white-space:nowrap">
3177 ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3178 ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
3179 ** C:. Note that the %20 escaping in this example is not strictly
3180 ** necessary - space characters can be used literally
3181 ** in URI filenames.
3182 ** <tr><td> file:data.db?mode=ro&cache=private <td>
3183 ** Open file "data.db" in the current directory for read-only access.
3184 ** Regardless of whether or not shared-cache mode is enabled by
3185 ** default, use a private cache.
3186 ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
3187 ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
3188 ** that uses dot-files in place of posix advisory locking.
3189 ** <tr><td> file:data.db?mode=readonly <td>
3190 ** An error. "readonly" is not a valid option for the "mode" parameter.
3191 ** </table>
3192 **
3193 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3194 ** query components of a URI. A hexadecimal escape sequence consists of a
3195 ** percent sign - "%" - followed by exactly two hexadecimal digits
3196 ** specifying an octet value. ^Before the path or query components of a
3197 ** URI filename are interpreted, they are encoded using UTF-8 and all
3198 ** hexadecimal escape sequences replaced by a single byte containing the
3199 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
3200 ** the results are undefined.
3201 **
3202 ** <b>Note to Windows users:</b> The encoding used for the filename argument
3203 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3204 ** codepage is currently defined. Filenames containing international
3205 ** characters must be converted to UTF-8 prior to passing them into
3206 ** sqlite3_open() or sqlite3_open_v2().
3207 **
3208 ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
3209 ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
3210 ** features that require the use of temporary files may fail.
3211 **
3212 ** See also: [sqlite3_temp_directory]
3213 */
3214 SQLITE_API int SQLITE_STDCALL sqlite3_open(
3215 const char *filename, /* Database filename (UTF-8) */
3216 sqlite3 **ppDb /* OUT: SQLite db handle */
3217 );
3218 SQLITE_API int SQLITE_STDCALL sqlite3_open16(
3219 const void *filename, /* Database filename (UTF-16) */
3220 sqlite3 **ppDb /* OUT: SQLite db handle */
3221 );
3222 SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
3223 const char *filename, /* Database filename (UTF-8) */
3224 sqlite3 **ppDb, /* OUT: SQLite db handle */
3225 int flags, /* Flags */
3226 const char *zVfs /* Name of VFS module to use */
3227 );
3228
3229 /*
3230 ** CAPI3REF: Obtain Values For URI Parameters
3231 **
3232 ** These are utility routines, useful to VFS implementations, that check
3233 ** to see if a database file was a URI that contained a specific query
3234 ** parameter, and if so obtains the value of that query parameter.
3235 **
3236 ** If F is the database filename pointer passed into the xOpen() method of
3237 ** a VFS implementation when the flags parameter to xOpen() has one or
3238 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3239 ** P is the name of the query parameter, then
3240 ** sqlite3_uri_parameter(F,P) returns the value of the P
3241 ** parameter if it exists or a NULL pointer if P does not appear as a
3242 ** query parameter on F. If P is a query parameter of F
3243 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3244 ** a pointer to an empty string.
3245 **
3246 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3247 ** parameter and returns true (1) or false (0) according to the value
3248 ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3249 ** value of query parameter P is one of "yes", "true", or "on" in any
3250 ** case or if the value begins with a non-zero number. The
3251 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3252 ** query parameter P is one of "no", "false", or "off" in any case or
3253 ** if the value begins with a numeric zero. If P is not a query
3254 ** parameter on F or if the value of P is does not match any of the
3255 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3256 **
3257 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3258 ** 64-bit signed integer and returns that integer, or D if P does not
3259 ** exist. If the value of P is something other than an integer, then
3260 ** zero is returned.
3261 **
3262 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3263 ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
3264 ** is not a database file pathname pointer that SQLite passed into the xOpen
3265 ** VFS method, then the behavior of this routine is undefined and probably
3266 ** undesirable.
3267 */
3268 SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilenam e, const char *zParam);
3269 SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3270 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(const char*, const cha r*, sqlite3_int64);
3271
3272
3273 /*
3274 ** CAPI3REF: Error Codes And Messages
3275 ** METHOD: sqlite3
3276 **
3277 ** ^If the most recent sqlite3_* API call associated with
3278 ** [database connection] D failed, then the sqlite3_errcode(D) interface
3279 ** returns the numeric [result code] or [extended result code] for that
3280 ** API call.
3281 ** If the most recent API call was successful,
3282 ** then the return value from sqlite3_errcode() is undefined.
3283 ** ^The sqlite3_extended_errcode()
3284 ** interface is the same except that it always returns the
3285 ** [extended result code] even when extended result codes are
3286 ** disabled.
3287 **
3288 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3289 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3290 ** ^(Memory to hold the error message string is managed internally.
3291 ** The application does not need to worry about freeing the result.
3292 ** However, the error string might be overwritten or deallocated by
3293 ** subsequent calls to other SQLite interface functions.)^
3294 **
3295 ** ^The sqlite3_errstr() interface returns the English-language text
3296 ** that describes the [result code], as UTF-8.
3297 ** ^(Memory to hold the error message string is managed internally
3298 ** and must not be freed by the application)^.
3299 **
3300 ** When the serialized [threading mode] is in use, it might be the
3301 ** case that a second error occurs on a separate thread in between
3302 ** the time of the first error and the call to these interfaces.
3303 ** When that happens, the second error will be reported since these
3304 ** interfaces always report the most recent result. To avoid
3305 ** this, each thread can obtain exclusive use of the [database connection] D
3306 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3307 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3308 ** all calls to the interfaces listed here are completed.
3309 **
3310 ** If an interface fails with SQLITE_MISUSE, that means the interface
3311 ** was invoked incorrectly by the application. In that case, the
3312 ** error code and message may or may not be set.
3313 */
3314 SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db);
3315 SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db);
3316 SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3*);
3317 SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3*);
3318 SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int);
3319
3320 /*
3321 ** CAPI3REF: Prepared Statement Object
3322 ** KEYWORDS: {prepared statement} {prepared statements}
3323 **
3324 ** An instance of this object represents a single SQL statement that
3325 ** has been compiled into binary form and is ready to be evaluated.
3326 **
3327 ** Think of each SQL statement as a separate computer program. The
3328 ** original SQL text is source code. A prepared statement object
3329 ** is the compiled object code. All SQL must be converted into a
3330 ** prepared statement before it can be run.
3331 **
3332 ** The life-cycle of a prepared statement object usually goes like this:
3333 **
3334 ** <ol>
3335 ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
3336 ** <li> Bind values to [parameters] using the sqlite3_bind_*()
3337 ** interfaces.
3338 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3339 ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
3340 ** to step 2. Do this zero or more times.
3341 ** <li> Destroy the object using [sqlite3_finalize()].
3342 ** </ol>
3343 */
3344 typedef struct sqlite3_stmt sqlite3_stmt;
3345
3346 /*
3347 ** CAPI3REF: Run-time Limits
3348 ** METHOD: sqlite3
3349 **
3350 ** ^(This interface allows the size of various constructs to be limited
3351 ** on a connection by connection basis. The first parameter is the
3352 ** [database connection] whose limit is to be set or queried. The
3353 ** second parameter is one of the [limit categories] that define a
3354 ** class of constructs to be size limited. The third parameter is the
3355 ** new limit for that construct.)^
3356 **
3357 ** ^If the new limit is a negative number, the limit is unchanged.
3358 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3359 ** [limits | hard upper bound]
3360 ** set at compile-time by a C preprocessor macro called
3361 ** [limits | SQLITE_MAX_<i>NAME</i>].
3362 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3363 ** ^Attempts to increase a limit above its hard upper bound are
3364 ** silently truncated to the hard upper bound.
3365 **
3366 ** ^Regardless of whether or not the limit was changed, the
3367 ** [sqlite3_limit()] interface returns the prior value of the limit.
3368 ** ^Hence, to find the current value of a limit without changing it,
3369 ** simply invoke this interface with the third parameter set to -1.
3370 **
3371 ** Run-time limits are intended for use in applications that manage
3372 ** both their own internal database and also databases that are controlled
3373 ** by untrusted external sources. An example application might be a
3374 ** web browser that has its own databases for storing history and
3375 ** separate databases controlled by JavaScript applications downloaded
3376 ** off the Internet. The internal databases can be given the
3377 ** large, default limits. Databases managed by external sources can
3378 ** be given much smaller limits designed to prevent a denial of service
3379 ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
3380 ** interface to further control untrusted SQL. The size of the database
3381 ** created by an untrusted script can be contained using the
3382 ** [max_page_count] [PRAGMA].
3383 **
3384 ** New run-time limit categories may be added in future releases.
3385 */
3386 SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3*, int id, int newVal);
3387
3388 /*
3389 ** CAPI3REF: Run-Time Limit Categories
3390 ** KEYWORDS: {limit category} {*limit categories}
3391 **
3392 ** These constants define various performance limits
3393 ** that can be lowered at run-time using [sqlite3_limit()].
3394 ** The synopsis of the meanings of the various limits is shown below.
3395 ** Additional information is available at [limits | Limits in SQLite].
3396 **
3397 ** <dl>
3398 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3399 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3400 **
3401 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3402 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3403 **
3404 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3405 ** <dd>The maximum number of columns in a table definition or in the
3406 ** result set of a [SELECT] or the maximum number of columns in an index
3407 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3408 **
3409 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3410 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3411 **
3412 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3413 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3414 **
3415 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3416 ** <dd>The maximum number of instructions in a virtual machine program
3417 ** used to implement an SQL statement. This limit is not currently
3418 ** enforced, though that might be added in some future release of
3419 ** SQLite.</dd>)^
3420 **
3421 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3422 ** <dd>The maximum number of arguments on a function.</dd>)^
3423 **
3424 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3425 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3426 **
3427 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3428 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3429 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3430 ** [GLOB] operators.</dd>)^
3431 **
3432 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3433 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3434 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3435 **
3436 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3437 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3438 **
3439 ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
3440 ** <dd>The maximum number of auxiliary worker threads that a single
3441 ** [prepared statement] may start.</dd>)^
3442 ** </dl>
3443 */
3444 #define SQLITE_LIMIT_LENGTH 0
3445 #define SQLITE_LIMIT_SQL_LENGTH 1
3446 #define SQLITE_LIMIT_COLUMN 2
3447 #define SQLITE_LIMIT_EXPR_DEPTH 3
3448 #define SQLITE_LIMIT_COMPOUND_SELECT 4
3449 #define SQLITE_LIMIT_VDBE_OP 5
3450 #define SQLITE_LIMIT_FUNCTION_ARG 6
3451 #define SQLITE_LIMIT_ATTACHED 7
3452 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
3453 #define SQLITE_LIMIT_VARIABLE_NUMBER 9
3454 #define SQLITE_LIMIT_TRIGGER_DEPTH 10
3455 #define SQLITE_LIMIT_WORKER_THREADS 11
3456
3457 /*
3458 ** CAPI3REF: Compiling An SQL Statement
3459 ** KEYWORDS: {SQL statement compiler}
3460 ** METHOD: sqlite3
3461 ** CONSTRUCTOR: sqlite3_stmt
3462 **
3463 ** To execute an SQL query, it must first be compiled into a byte-code
3464 ** program using one of these routines.
3465 **
3466 ** The first argument, "db", is a [database connection] obtained from a
3467 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3468 ** [sqlite3_open16()]. The database connection must not have been closed.
3469 **
3470 ** The second argument, "zSql", is the statement to be compiled, encoded
3471 ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
3472 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3473 ** use UTF-16.
3474 **
3475 ** ^If the nByte argument is negative, then zSql is read up to the
3476 ** first zero terminator. ^If nByte is positive, then it is the
3477 ** number of bytes read from zSql. ^If nByte is zero, then no prepared
3478 ** statement is generated.
3479 ** If the caller knows that the supplied string is nul-terminated, then
3480 ** there is a small performance advantage to passing an nByte parameter that
3481 ** is the number of bytes in the input string <i>including</i>
3482 ** the nul-terminator.
3483 **
3484 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3485 ** past the end of the first SQL statement in zSql. These routines only
3486 ** compile the first statement in zSql, so *pzTail is left pointing to
3487 ** what remains uncompiled.
3488 **
3489 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3490 ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
3491 ** to NULL. ^If the input text contains no SQL (if the input is an empty
3492 ** string or a comment) then *ppStmt is set to NULL.
3493 ** The calling procedure is responsible for deleting the compiled
3494 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3495 ** ppStmt may not be NULL.
3496 **
3497 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3498 ** otherwise an [error code] is returned.
3499 **
3500 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3501 ** recommended for all new programs. The two older interfaces are retained
3502 ** for backwards compatibility, but their use is discouraged.
3503 ** ^In the "v2" interfaces, the prepared statement
3504 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3505 ** original SQL text. This causes the [sqlite3_step()] interface to
3506 ** behave differently in three ways:
3507 **
3508 ** <ol>
3509 ** <li>
3510 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3511 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3512 ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
3513 ** retries will occur before sqlite3_step() gives up and returns an error.
3514 ** </li>
3515 **
3516 ** <li>
3517 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3518 ** [error codes] or [extended error codes]. ^The legacy behavior was that
3519 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3520 ** and the application would have to make a second call to [sqlite3_reset()]
3521 ** in order to find the underlying cause of the problem. With the "v2" prepare
3522 ** interfaces, the underlying reason for the error is returned immediately.
3523 ** </li>
3524 **
3525 ** <li>
3526 ** ^If the specific value bound to [parameter | host parameter] in the
3527 ** WHERE clause might influence the choice of query plan for a statement,
3528 ** then the statement will be automatically recompiled, as if there had been
3529 ** a schema change, on the first [sqlite3_step()] call following any change
3530 ** to the [sqlite3_bind_text | bindings] of that [parameter].
3531 ** ^The specific value of WHERE-clause [parameter] might influence the
3532 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3533 ** or [GLOB] operator or if the parameter is compared to an indexed column
3534 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3535 ** </li>
3536 ** </ol>
3537 */
3538 SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
3539 sqlite3 *db, /* Database handle */
3540 const char *zSql, /* SQL statement, UTF-8 encoded */
3541 int nByte, /* Maximum length of zSql in bytes. */
3542 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3543 const char **pzTail /* OUT: Pointer to unused portion of zSql */
3544 );
3545 SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
3546 sqlite3 *db, /* Database handle */
3547 const char *zSql, /* SQL statement, UTF-8 encoded */
3548 int nByte, /* Maximum length of zSql in bytes. */
3549 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3550 const char **pzTail /* OUT: Pointer to unused portion of zSql */
3551 );
3552 SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
3553 sqlite3 *db, /* Database handle */
3554 const void *zSql, /* SQL statement, UTF-16 encoded */
3555 int nByte, /* Maximum length of zSql in bytes. */
3556 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3557 const void **pzTail /* OUT: Pointer to unused portion of zSql */
3558 );
3559 SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
3560 sqlite3 *db, /* Database handle */
3561 const void *zSql, /* SQL statement, UTF-16 encoded */
3562 int nByte, /* Maximum length of zSql in bytes. */
3563 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3564 const void **pzTail /* OUT: Pointer to unused portion of zSql */
3565 );
3566
3567 /*
3568 ** CAPI3REF: Retrieving Statement SQL
3569 ** METHOD: sqlite3_stmt
3570 **
3571 ** ^This interface can be used to retrieve a saved copy of the original
3572 ** SQL text used to create a [prepared statement] if that statement was
3573 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3574 */
3575 SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt);
3576
3577 /*
3578 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3579 ** METHOD: sqlite3_stmt
3580 **
3581 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3582 ** and only if the [prepared statement] X makes no direct changes to
3583 ** the content of the database file.
3584 **
3585 ** Note that [application-defined SQL functions] or
3586 ** [virtual tables] might change the database indirectly as a side effect.
3587 ** ^(For example, if an application defines a function "eval()" that
3588 ** calls [sqlite3_exec()], then the following SQL statement would
3589 ** change the database file through side-effects:
3590 **
3591 ** <blockquote><pre>
3592 ** SELECT eval('DELETE FROM t1') FROM t2;
3593 ** </pre></blockquote>
3594 **
3595 ** But because the [SELECT] statement does not change the database file
3596 ** directly, sqlite3_stmt_readonly() would still return true.)^
3597 **
3598 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3599 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3600 ** since the statements themselves do not actually modify the database but
3601 ** rather they control the timing of when other statements modify the
3602 ** database. ^The [ATTACH] and [DETACH] statements also cause
3603 ** sqlite3_stmt_readonly() to return true since, while those statements
3604 ** change the configuration of a database connection, they do not make
3605 ** changes to the content of the database files on disk.
3606 */
3607 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3608
3609 /*
3610 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3611 ** METHOD: sqlite3_stmt
3612 **
3613 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3614 ** [prepared statement] S has been stepped at least once using
3615 ** [sqlite3_step(S)] but has neither run to completion (returned
3616 ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
3617 ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
3618 ** interface returns false if S is a NULL pointer. If S is not a
3619 ** NULL pointer and is not a pointer to a valid [prepared statement]
3620 ** object, then the behavior is undefined and probably undesirable.
3621 **
3622 ** This interface can be used in combination [sqlite3_next_stmt()]
3623 ** to locate all prepared statements associated with a database
3624 ** connection that are in need of being reset. This can be used,
3625 ** for example, in diagnostic routines to search for prepared
3626 ** statements that are holding a transaction open.
3627 */
3628 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt*);
3629
3630 /*
3631 ** CAPI3REF: Dynamically Typed Value Object
3632 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3633 **
3634 ** SQLite uses the sqlite3_value object to represent all values
3635 ** that can be stored in a database table. SQLite uses dynamic typing
3636 ** for the values it stores. ^Values stored in sqlite3_value objects
3637 ** can be integers, floating point values, strings, BLOBs, or NULL.
3638 **
3639 ** An sqlite3_value object may be either "protected" or "unprotected".
3640 ** Some interfaces require a protected sqlite3_value. Other interfaces
3641 ** will accept either a protected or an unprotected sqlite3_value.
3642 ** Every interface that accepts sqlite3_value arguments specifies
3643 ** whether or not it requires a protected sqlite3_value. The
3644 ** [sqlite3_value_dup()] interface can be used to construct a new
3645 ** protected sqlite3_value from an unprotected sqlite3_value.
3646 **
3647 ** The terms "protected" and "unprotected" refer to whether or not
3648 ** a mutex is held. An internal mutex is held for a protected
3649 ** sqlite3_value object but no mutex is held for an unprotected
3650 ** sqlite3_value object. If SQLite is compiled to be single-threaded
3651 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3652 ** or if SQLite is run in one of reduced mutex modes
3653 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3654 ** then there is no distinction between protected and unprotected
3655 ** sqlite3_value objects and they can be used interchangeably. However,
3656 ** for maximum code portability it is recommended that applications
3657 ** still make the distinction between protected and unprotected
3658 ** sqlite3_value objects even when not strictly required.
3659 **
3660 ** ^The sqlite3_value objects that are passed as parameters into the
3661 ** implementation of [application-defined SQL functions] are protected.
3662 ** ^The sqlite3_value object returned by
3663 ** [sqlite3_column_value()] is unprotected.
3664 ** Unprotected sqlite3_value objects may only be used with
3665 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3666 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3667 ** interfaces require protected sqlite3_value objects.
3668 */
3669 typedef struct Mem sqlite3_value;
3670
3671 /*
3672 ** CAPI3REF: SQL Function Context Object
3673 **
3674 ** The context in which an SQL function executes is stored in an
3675 ** sqlite3_context object. ^A pointer to an sqlite3_context object
3676 ** is always first parameter to [application-defined SQL functions].
3677 ** The application-defined SQL function implementation will pass this
3678 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3679 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3680 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3681 ** and/or [sqlite3_set_auxdata()].
3682 */
3683 typedef struct sqlite3_context sqlite3_context;
3684
3685 /*
3686 ** CAPI3REF: Binding Values To Prepared Statements
3687 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3688 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3689 ** METHOD: sqlite3_stmt
3690 **
3691 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3692 ** literals may be replaced by a [parameter] that matches one of following
3693 ** templates:
3694 **
3695 ** <ul>
3696 ** <li> ?
3697 ** <li> ?NNN
3698 ** <li> :VVV
3699 ** <li> @VVV
3700 ** <li> $VVV
3701 ** </ul>
3702 **
3703 ** In the templates above, NNN represents an integer literal,
3704 ** and VVV represents an alphanumeric identifier.)^ ^The values of these
3705 ** parameters (also called "host parameter names" or "SQL parameters")
3706 ** can be set using the sqlite3_bind_*() routines defined here.
3707 **
3708 ** ^The first argument to the sqlite3_bind_*() routines is always
3709 ** a pointer to the [sqlite3_stmt] object returned from
3710 ** [sqlite3_prepare_v2()] or its variants.
3711 **
3712 ** ^The second argument is the index of the SQL parameter to be set.
3713 ** ^The leftmost SQL parameter has an index of 1. ^When the same named
3714 ** SQL parameter is used more than once, second and subsequent
3715 ** occurrences have the same index as the first occurrence.
3716 ** ^The index for named parameters can be looked up using the
3717 ** [sqlite3_bind_parameter_index()] API if desired. ^The index
3718 ** for "?NNN" parameters is the value of NNN.
3719 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3720 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3721 **
3722 ** ^The third argument is the value to bind to the parameter.
3723 ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3724 ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
3725 ** is ignored and the end result is the same as sqlite3_bind_null().
3726 **
3727 ** ^(In those routines that have a fourth argument, its value is the
3728 ** number of bytes in the parameter. To be clear: the value is the
3729 ** number of <u>bytes</u> in the value, not the number of characters.)^
3730 ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3731 ** is negative, then the length of the string is
3732 ** the number of bytes up to the first zero terminator.
3733 ** If the fourth parameter to sqlite3_bind_blob() is negative, then
3734 ** the behavior is undefined.
3735 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3736 ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
3737 ** that parameter must be the byte offset
3738 ** where the NUL terminator would occur assuming the string were NUL
3739 ** terminated. If any NUL characters occur at byte offsets less than
3740 ** the value of the fourth parameter then the resulting string value will
3741 ** contain embedded NULs. The result of expressions involving strings
3742 ** with embedded NULs is undefined.
3743 **
3744 ** ^The fifth argument to the BLOB and string binding interfaces
3745 ** is a destructor used to dispose of the BLOB or
3746 ** string after SQLite has finished with it. ^The destructor is called
3747 ** to dispose of the BLOB or string even if the call to bind API fails.
3748 ** ^If the fifth argument is
3749 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3750 ** information is in static, unmanaged space and does not need to be freed.
3751 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3752 ** SQLite makes its own private copy of the data immediately, before
3753 ** the sqlite3_bind_*() routine returns.
3754 **
3755 ** ^The sixth argument to sqlite3_bind_text64() must be one of
3756 ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
3757 ** to specify the encoding of the text in the third parameter. If
3758 ** the sixth argument to sqlite3_bind_text64() is not one of the
3759 ** allowed values shown above, or if the text encoding is different
3760 ** from the encoding specified by the sixth parameter, then the behavior
3761 ** is undefined.
3762 **
3763 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3764 ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
3765 ** (just an integer to hold its size) while it is being processed.
3766 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3767 ** content is later written using
3768 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3769 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3770 **
3771 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3772 ** for the [prepared statement] or with a prepared statement for which
3773 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3774 ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
3775 ** routine is passed a [prepared statement] that has been finalized, the
3776 ** result is undefined and probably harmful.
3777 **
3778 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3779 ** ^Unbound parameters are interpreted as NULL.
3780 **
3781 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3782 ** [error code] if anything goes wrong.
3783 ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
3784 ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
3785 ** [SQLITE_MAX_LENGTH].
3786 ** ^[SQLITE_RANGE] is returned if the parameter
3787 ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
3788 **
3789 ** See also: [sqlite3_bind_parameter_count()],
3790 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3791 */
3792 SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3793 SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(sqlite3_stmt*, int, const void *, sqlite3_uint64,
3794 void(*)(void*));
3795 SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt*, int, double);
3796 SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt*, int, int);
3797 SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int 64);
3798 SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt*, int);
3799 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(sqlite3_stmt*,int,const char*,in t,void(*)(void*));
3800 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(sqlite3_stmt*, int, const void *, int, void(*)(void*));
3801 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(sqlite3_stmt*, int, const char *, sqlite3_uint64,
3802 void(*)(void*), unsigned char encoding);
3803 SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt*, int, const sqlit e3_value*);
3804 SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3805 SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite 3_uint64);
3806
3807 /*
3808 ** CAPI3REF: Number Of SQL Parameters
3809 ** METHOD: sqlite3_stmt
3810 **
3811 ** ^This routine can be used to find the number of [SQL parameters]
3812 ** in a [prepared statement]. SQL parameters are tokens of the
3813 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3814 ** placeholders for values that are [sqlite3_bind_blob | bound]
3815 ** to the parameters at a later time.
3816 **
3817 ** ^(This routine actually returns the index of the largest (rightmost)
3818 ** parameter. For all forms except ?NNN, this will correspond to the
3819 ** number of unique parameters. If parameters of the ?NNN form are used,
3820 ** there may be gaps in the list.)^
3821 **
3822 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3823 ** [sqlite3_bind_parameter_name()], and
3824 ** [sqlite3_bind_parameter_index()].
3825 */
3826 SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt*);
3827
3828 /*
3829 ** CAPI3REF: Name Of A Host Parameter
3830 ** METHOD: sqlite3_stmt
3831 **
3832 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3833 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3834 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3835 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3836 ** respectively.
3837 ** In other words, the initial ":" or "$" or "@" or "?"
3838 ** is included as part of the name.)^
3839 ** ^Parameters of the form "?" without a following integer have no name
3840 ** and are referred to as "nameless" or "anonymous parameters".
3841 **
3842 ** ^The first host parameter has an index of 1, not 0.
3843 **
3844 ** ^If the value N is out of range or if the N-th parameter is
3845 ** nameless, then NULL is returned. ^The returned string is
3846 ** always in UTF-8 encoding even if the named parameter was
3847 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3848 ** [sqlite3_prepare16_v2()].
3849 **
3850 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3851 ** [sqlite3_bind_parameter_count()], and
3852 ** [sqlite3_bind_parameter_index()].
3853 */
3854 SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3855
3856 /*
3857 ** CAPI3REF: Index Of A Parameter With A Given Name
3858 ** METHOD: sqlite3_stmt
3859 **
3860 ** ^Return the index of an SQL parameter given its name. ^The
3861 ** index value returned is suitable for use as the second
3862 ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
3863 ** is returned if no matching parameter is found. ^The parameter
3864 ** name must be given in UTF-8 even if the original statement
3865 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3866 **
3867 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3868 ** [sqlite3_bind_parameter_count()], and
3869 ** [sqlite3_bind_parameter_name()].
3870 */
3871 SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3872
3873 /*
3874 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3875 ** METHOD: sqlite3_stmt
3876 **
3877 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3878 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3879 ** ^Use this routine to reset all host parameters to NULL.
3880 */
3881 SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt*);
3882
3883 /*
3884 ** CAPI3REF: Number Of Columns In A Result Set
3885 ** METHOD: sqlite3_stmt
3886 **
3887 ** ^Return the number of columns in the result set returned by the
3888 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3889 ** statement that does not return data (for example an [UPDATE]).
3890 **
3891 ** See also: [sqlite3_data_count()]
3892 */
3893 SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt);
3894
3895 /*
3896 ** CAPI3REF: Column Names In A Result Set
3897 ** METHOD: sqlite3_stmt
3898 **
3899 ** ^These routines return the name assigned to a particular column
3900 ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
3901 ** interface returns a pointer to a zero-terminated UTF-8 string
3902 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3903 ** UTF-16 string. ^The first parameter is the [prepared statement]
3904 ** that implements the [SELECT] statement. ^The second parameter is the
3905 ** column number. ^The leftmost column is number 0.
3906 **
3907 ** ^The returned string pointer is valid until either the [prepared statement]
3908 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3909 ** reprepared by the first call to [sqlite3_step()] for a particular run
3910 ** or until the next call to
3911 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3912 **
3913 ** ^If sqlite3_malloc() fails during the processing of either routine
3914 ** (for example during a conversion from UTF-8 to UTF-16) then a
3915 ** NULL pointer is returned.
3916 **
3917 ** ^The name of a result column is the value of the "AS" clause for
3918 ** that column, if there is an AS clause. If there is no AS clause
3919 ** then the name of the column is unspecified and may change from
3920 ** one release of SQLite to the next.
3921 */
3922 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt*, int N);
3923 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt*, int N );
3924
3925 /*
3926 ** CAPI3REF: Source Of Data In A Query Result
3927 ** METHOD: sqlite3_stmt
3928 **
3929 ** ^These routines provide a means to determine the database, table, and
3930 ** table column that is the origin of a particular result column in
3931 ** [SELECT] statement.
3932 ** ^The name of the database or table or column can be returned as
3933 ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
3934 ** the database name, the _table_ routines return the table name, and
3935 ** the origin_ routines return the column name.
3936 ** ^The returned string is valid until the [prepared statement] is destroyed
3937 ** using [sqlite3_finalize()] or until the statement is automatically
3938 ** reprepared by the first call to [sqlite3_step()] for a particular run
3939 ** or until the same information is requested
3940 ** again in a different encoding.
3941 **
3942 ** ^The names returned are the original un-aliased names of the
3943 ** database, table, and column.
3944 **
3945 ** ^The first argument to these interfaces is a [prepared statement].
3946 ** ^These functions return information about the Nth result column returned by
3947 ** the statement, where N is the second function argument.
3948 ** ^The left-most column is column 0 for these routines.
3949 **
3950 ** ^If the Nth column returned by the statement is an expression or
3951 ** subquery and is not a column value, then all of these functions return
3952 ** NULL. ^These routine might also return NULL if a memory allocation error
3953 ** occurs. ^Otherwise, they return the name of the attached database, table,
3954 ** or column that query result column was extracted from.
3955 **
3956 ** ^As with all other SQLite APIs, those whose names end with "16" return
3957 ** UTF-16 encoded strings and the other functions return UTF-8.
3958 **
3959 ** ^These APIs are only available if the library was compiled with the
3960 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3961 **
3962 ** If two or more threads call one or more of these routines against the same
3963 ** prepared statement and column at the same time then the results are
3964 ** undefined.
3965 **
3966 ** If two or more threads call one or more
3967 ** [sqlite3_column_database_name | column metadata interfaces]
3968 ** for the same [prepared statement] and result column
3969 ** at the same time then the results are undefined.
3970 */
3971 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt* ,int);
3972 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stm t*,int);
3973 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt*,in t);
3974 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt*, int);
3975 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt*,i nt);
3976 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt* ,int);
3977
3978 /*
3979 ** CAPI3REF: Declared Datatype Of A Query Result
3980 ** METHOD: sqlite3_stmt
3981 **
3982 ** ^(The first parameter is a [prepared statement].
3983 ** If this statement is a [SELECT] statement and the Nth column of the
3984 ** returned result set of that [SELECT] is a table column (not an
3985 ** expression or subquery) then the declared type of the table
3986 ** column is returned.)^ ^If the Nth column of the result set is an
3987 ** expression or subquery, then a NULL pointer is returned.
3988 ** ^The returned string is always UTF-8 encoded.
3989 **
3990 ** ^(For example, given the database schema:
3991 **
3992 ** CREATE TABLE t1(c1 VARIANT);
3993 **
3994 ** and the following statement to be compiled:
3995 **
3996 ** SELECT c1 + 1, c1 FROM t1;
3997 **
3998 ** this routine would return the string "VARIANT" for the second result
3999 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
4000 **
4001 ** ^SQLite uses dynamic run-time typing. ^So just because a column
4002 ** is declared to contain a particular type does not mean that the
4003 ** data stored in that column is of the declared type. SQLite is
4004 ** strongly typed, but the typing is dynamic not static. ^Type
4005 ** is associated with individual values, not with the containers
4006 ** used to hold those values.
4007 */
4008 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt*,int) ;
4009 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt*,in t);
4010
4011 /*
4012 ** CAPI3REF: Evaluate An SQL Statement
4013 ** METHOD: sqlite3_stmt
4014 **
4015 ** After a [prepared statement] has been prepared using either
4016 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
4017 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
4018 ** must be called one or more times to evaluate the statement.
4019 **
4020 ** The details of the behavior of the sqlite3_step() interface depend
4021 ** on whether the statement was prepared using the newer "v2" interface
4022 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
4023 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
4024 ** new "v2" interface is recommended for new applications but the legacy
4025 ** interface will continue to be supported.
4026 **
4027 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
4028 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
4029 ** ^With the "v2" interface, any of the other [result codes] or
4030 ** [extended result codes] might be returned as well.
4031 **
4032 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
4033 ** database locks it needs to do its job. ^If the statement is a [COMMIT]
4034 ** or occurs outside of an explicit transaction, then you can retry the
4035 ** statement. If the statement is not a [COMMIT] and occurs within an
4036 ** explicit transaction then you should rollback the transaction before
4037 ** continuing.
4038 **
4039 ** ^[SQLITE_DONE] means that the statement has finished executing
4040 ** successfully. sqlite3_step() should not be called again on this virtual
4041 ** machine without first calling [sqlite3_reset()] to reset the virtual
4042 ** machine back to its initial state.
4043 **
4044 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
4045 ** is returned each time a new row of data is ready for processing by the
4046 ** caller. The values may be accessed using the [column access functions].
4047 ** sqlite3_step() is called again to retrieve the next row of data.
4048 **
4049 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
4050 ** violation) has occurred. sqlite3_step() should not be called again on
4051 ** the VM. More information may be found by calling [sqlite3_errmsg()].
4052 ** ^With the legacy interface, a more specific error code (for example,
4053 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
4054 ** can be obtained by calling [sqlite3_reset()] on the
4055 ** [prepared statement]. ^In the "v2" interface,
4056 ** the more specific error code is returned directly by sqlite3_step().
4057 **
4058 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
4059 ** Perhaps it was called on a [prepared statement] that has
4060 ** already been [sqlite3_finalize | finalized] or on one that had
4061 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
4062 ** be the case that the same database connection is being used by two or
4063 ** more threads at the same moment in time.
4064 **
4065 ** For all versions of SQLite up to and including 3.6.23.1, a call to
4066 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
4067 ** other than [SQLITE_ROW] before any subsequent invocation of
4068 ** sqlite3_step(). Failure to reset the prepared statement using
4069 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
4070 ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
4071 ** calling [sqlite3_reset()] automatically in this circumstance rather
4072 ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
4073 ** break because any application that ever receives an SQLITE_MISUSE error
4074 ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
4075 ** can be used to restore the legacy behavior.
4076 **
4077 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4078 ** API always returns a generic error code, [SQLITE_ERROR], following any
4079 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
4080 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4081 ** specific [error codes] that better describes the error.
4082 ** We admit that this is a goofy design. The problem has been fixed
4083 ** with the "v2" interface. If you prepare all of your SQL statements
4084 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4085 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4086 ** then the more specific [error codes] are returned directly
4087 ** by sqlite3_step(). The use of the "v2" interface is recommended.
4088 */
4089 SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt*);
4090
4091 /*
4092 ** CAPI3REF: Number of columns in a result set
4093 ** METHOD: sqlite3_stmt
4094 **
4095 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
4096 ** current row of the result set of [prepared statement] P.
4097 ** ^If prepared statement P does not have results ready to return
4098 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
4099 ** interfaces) then sqlite3_data_count(P) returns 0.
4100 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
4101 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
4102 ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
4103 ** will return non-zero if previous call to [sqlite3_step](P) returned
4104 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
4105 ** where it always returns zero since each step of that multi-step
4106 ** pragma returns 0 columns of data.
4107 **
4108 ** See also: [sqlite3_column_count()]
4109 */
4110 SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt);
4111
4112 /*
4113 ** CAPI3REF: Fundamental Datatypes
4114 ** KEYWORDS: SQLITE_TEXT
4115 **
4116 ** ^(Every value in SQLite has one of five fundamental datatypes:
4117 **
4118 ** <ul>
4119 ** <li> 64-bit signed integer
4120 ** <li> 64-bit IEEE floating point number
4121 ** <li> string
4122 ** <li> BLOB
4123 ** <li> NULL
4124 ** </ul>)^
4125 **
4126 ** These constants are codes for each of those types.
4127 **
4128 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4129 ** for a completely different meaning. Software that links against both
4130 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4131 ** SQLITE_TEXT.
4132 */
4133 #define SQLITE_INTEGER 1
4134 #define SQLITE_FLOAT 2
4135 #define SQLITE_BLOB 4
4136 #define SQLITE_NULL 5
4137 #ifdef SQLITE_TEXT
4138 # undef SQLITE_TEXT
4139 #else
4140 # define SQLITE_TEXT 3
4141 #endif
4142 #define SQLITE3_TEXT 3
4143
4144 /*
4145 ** CAPI3REF: Result Values From A Query
4146 ** KEYWORDS: {column access functions}
4147 ** METHOD: sqlite3_stmt
4148 **
4149 ** ^These routines return information about a single column of the current
4150 ** result row of a query. ^In every case the first argument is a pointer
4151 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4152 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4153 ** and the second argument is the index of the column for which information
4154 ** should be returned. ^The leftmost column of the result set has the index 0.
4155 ** ^The number of columns in the result can be determined using
4156 ** [sqlite3_column_count()].
4157 **
4158 ** If the SQL statement does not currently point to a valid row, or if the
4159 ** column index is out of range, the result is undefined.
4160 ** These routines may only be called when the most recent call to
4161 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4162 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4163 ** If any of these routines are called after [sqlite3_reset()] or
4164 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4165 ** something other than [SQLITE_ROW], the results are undefined.
4166 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4167 ** are called from a different thread while any of these routines
4168 ** are pending, then the results are undefined.
4169 **
4170 ** ^The sqlite3_column_type() routine returns the
4171 ** [SQLITE_INTEGER | datatype code] for the initial data type
4172 ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
4173 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
4174 ** returned by sqlite3_column_type() is only meaningful if no type
4175 ** conversions have occurred as described below. After a type conversion,
4176 ** the value returned by sqlite3_column_type() is undefined. Future
4177 ** versions of SQLite may change the behavior of sqlite3_column_type()
4178 ** following a type conversion.
4179 **
4180 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4181 ** routine returns the number of bytes in that BLOB or string.
4182 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4183 ** the string to UTF-8 and then returns the number of bytes.
4184 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
4185 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4186 ** the number of bytes in that string.
4187 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4188 **
4189 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4190 ** routine returns the number of bytes in that BLOB or string.
4191 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4192 ** the string to UTF-16 and then returns the number of bytes.
4193 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4194 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4195 ** the number of bytes in that string.
4196 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4197 **
4198 ** ^The values returned by [sqlite3_column_bytes()] and
4199 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4200 ** of the string. ^For clarity: the values returned by
4201 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4202 ** bytes in the string, not the number of characters.
4203 **
4204 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4205 ** even empty strings, are always zero-terminated. ^The return
4206 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4207 **
4208 ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
4209 ** [unprotected sqlite3_value] object. In a multithreaded environment,
4210 ** an unprotected sqlite3_value object may only be used safely with
4211 ** [sqlite3_bind_value()] and [sqlite3_result_value()].
4212 ** If the [unprotected sqlite3_value] object returned by
4213 ** [sqlite3_column_value()] is used in any other way, including calls
4214 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4215 ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
4216 **
4217 ** These routines attempt to convert the value where appropriate. ^For
4218 ** example, if the internal representation is FLOAT and a text result
4219 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4220 ** conversion automatically. ^(The following table details the conversions
4221 ** that are applied:
4222 **
4223 ** <blockquote>
4224 ** <table border="1">
4225 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
4226 **
4227 ** <tr><td> NULL <td> INTEGER <td> Result is 0
4228 ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
4229 ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
4230 ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
4231 ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
4232 ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
4233 ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
4234 ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
4235 ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
4236 ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
4237 ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
4238 ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
4239 ** <tr><td> TEXT <td> BLOB <td> No change
4240 ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
4241 ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
4242 ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
4243 ** </table>
4244 ** </blockquote>)^
4245 **
4246 ** Note that when type conversions occur, pointers returned by prior
4247 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4248 ** sqlite3_column_text16() may be invalidated.
4249 ** Type conversions and pointer invalidations might occur
4250 ** in the following cases:
4251 **
4252 ** <ul>
4253 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4254 ** sqlite3_column_text16() is called. A zero-terminator might
4255 ** need to be added to the string.</li>
4256 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4257 ** sqlite3_column_text16() is called. The content must be converted
4258 ** to UTF-16.</li>
4259 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4260 ** sqlite3_column_text() is called. The content must be converted
4261 ** to UTF-8.</li>
4262 ** </ul>
4263 **
4264 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4265 ** not invalidate a prior pointer, though of course the content of the buffer
4266 ** that the prior pointer references will have been modified. Other kinds
4267 ** of conversion are done in place when it is possible, but sometimes they
4268 ** are not possible and in those cases prior pointers are invalidated.
4269 **
4270 ** The safest policy is to invoke these routines
4271 ** in one of the following ways:
4272 **
4273 ** <ul>
4274 ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4275 ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4276 ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4277 ** </ul>
4278 **
4279 ** In other words, you should call sqlite3_column_text(),
4280 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4281 ** into the desired format, then invoke sqlite3_column_bytes() or
4282 ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
4283 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4284 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4285 ** with calls to sqlite3_column_bytes().
4286 **
4287 ** ^The pointers returned are valid until a type conversion occurs as
4288 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4289 ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
4290 ** and BLOBs is freed automatically. Do <em>not</em> pass the pointers returned
4291 ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4292 ** [sqlite3_free()].
4293 **
4294 ** ^(If a memory allocation error occurs during the evaluation of any
4295 ** of these routines, a default value is returned. The default value
4296 ** is either the integer 0, the floating point number 0.0, or a NULL
4297 ** pointer. Subsequent calls to [sqlite3_errcode()] will return
4298 ** [SQLITE_NOMEM].)^
4299 */
4300 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt*, int iCo l);
4301 SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4302 SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4303 SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt*, int iCol);
4304 SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt*, int iCol);
4305 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt*, int iCol);
4306 SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt* , int iCol);
4307 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt*, int i Col);
4308 SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt*, int iCol);
4309 SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt*, int iCol);
4310
4311 /*
4312 ** CAPI3REF: Destroy A Prepared Statement Object
4313 ** DESTRUCTOR: sqlite3_stmt
4314 **
4315 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4316 ** ^If the most recent evaluation of the statement encountered no errors
4317 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
4318 ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
4319 ** sqlite3_finalize(S) returns the appropriate [error code] or
4320 ** [extended error code].
4321 **
4322 ** ^The sqlite3_finalize(S) routine can be called at any point during
4323 ** the life cycle of [prepared statement] S:
4324 ** before statement S is ever evaluated, after
4325 ** one or more calls to [sqlite3_reset()], or after any call
4326 ** to [sqlite3_step()] regardless of whether or not the statement has
4327 ** completed execution.
4328 **
4329 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4330 **
4331 ** The application must finalize every [prepared statement] in order to avoid
4332 ** resource leaks. It is a grievous error for the application to try to use
4333 ** a prepared statement after it has been finalized. Any use of a prepared
4334 ** statement after it has been finalized can result in undefined and
4335 ** undesirable behavior such as segfaults and heap corruption.
4336 */
4337 SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt);
4338
4339 /*
4340 ** CAPI3REF: Reset A Prepared Statement Object
4341 ** METHOD: sqlite3_stmt
4342 **
4343 ** The sqlite3_reset() function is called to reset a [prepared statement]
4344 ** object back to its initial state, ready to be re-executed.
4345 ** ^Any SQL statement variables that had values bound to them using
4346 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4347 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4348 **
4349 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4350 ** back to the beginning of its program.
4351 **
4352 ** ^If the most recent call to [sqlite3_step(S)] for the
4353 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4354 ** or if [sqlite3_step(S)] has never before been called on S,
4355 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
4356 **
4357 ** ^If the most recent call to [sqlite3_step(S)] for the
4358 ** [prepared statement] S indicated an error, then
4359 ** [sqlite3_reset(S)] returns an appropriate [error code].
4360 **
4361 ** ^The [sqlite3_reset(S)] interface does not change the values
4362 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4363 */
4364 SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt);
4365
4366 /*
4367 ** CAPI3REF: Create Or Redefine SQL Functions
4368 ** KEYWORDS: {function creation routines}
4369 ** KEYWORDS: {application-defined SQL function}
4370 ** KEYWORDS: {application-defined SQL functions}
4371 ** METHOD: sqlite3
4372 **
4373 ** ^These functions (collectively known as "function creation routines")
4374 ** are used to add SQL functions or aggregates or to redefine the behavior
4375 ** of existing SQL functions or aggregates. The only differences between
4376 ** these routines are the text encoding expected for
4377 ** the second parameter (the name of the function being created)
4378 ** and the presence or absence of a destructor callback for
4379 ** the application data pointer.
4380 **
4381 ** ^The first parameter is the [database connection] to which the SQL
4382 ** function is to be added. ^If an application uses more than one database
4383 ** connection then application-defined SQL functions must be added
4384 ** to each database connection separately.
4385 **
4386 ** ^The second parameter is the name of the SQL function to be created or
4387 ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
4388 ** representation, exclusive of the zero-terminator. ^Note that the name
4389 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4390 ** ^Any attempt to create a function with a longer name
4391 ** will result in [SQLITE_MISUSE] being returned.
4392 **
4393 ** ^The third parameter (nArg)
4394 ** is the number of arguments that the SQL function or
4395 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4396 ** aggregate may take any number of arguments between 0 and the limit
4397 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
4398 ** parameter is less than -1 or greater than 127 then the behavior is
4399 ** undefined.
4400 **
4401 ** ^The fourth parameter, eTextRep, specifies what
4402 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4403 ** its parameters. The application should set this parameter to
4404 ** [SQLITE_UTF16LE] if the function implementation invokes
4405 ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
4406 ** implementation invokes [sqlite3_value_text16be()] on an input, or
4407 ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
4408 ** otherwise. ^The same SQL function may be registered multiple times using
4409 ** different preferred text encodings, with different implementations for
4410 ** each encoding.
4411 ** ^When multiple implementations of the same function are available, SQLite
4412 ** will pick the one that involves the least amount of data conversion.
4413 **
4414 ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
4415 ** to signal that the function will always return the same result given
4416 ** the same inputs within a single SQL statement. Most SQL functions are
4417 ** deterministic. The built-in [random()] SQL function is an example of a
4418 ** function that is not deterministic. The SQLite query planner is able to
4419 ** perform additional optimizations on deterministic functions, so use
4420 ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
4421 **
4422 ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
4423 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4424 **
4425 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4426 ** pointers to C-language functions that implement the SQL function or
4427 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4428 ** callback only; NULL pointers must be passed as the xStep and xFinal
4429 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4430 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4431 ** SQL function or aggregate, pass NULL pointers for all three function
4432 ** callbacks.
4433 **
4434 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4435 ** then it is destructor for the application data pointer.
4436 ** The destructor is invoked when the function is deleted, either by being
4437 ** overloaded or when the database connection closes.)^
4438 ** ^The destructor is also invoked if the call to
4439 ** sqlite3_create_function_v2() fails.
4440 ** ^When the destructor callback of the tenth parameter is invoked, it
4441 ** is passed a single argument which is a copy of the application data
4442 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4443 **
4444 ** ^It is permitted to register multiple implementations of the same
4445 ** functions with the same name but with either differing numbers of
4446 ** arguments or differing preferred text encodings. ^SQLite will use
4447 ** the implementation that most closely matches the way in which the
4448 ** SQL function is used. ^A function implementation with a non-negative
4449 ** nArg parameter is a better match than a function implementation with
4450 ** a negative nArg. ^A function where the preferred text encoding
4451 ** matches the database encoding is a better
4452 ** match than a function where the encoding is different.
4453 ** ^A function where the encoding difference is between UTF16le and UTF16be
4454 ** is a closer match than a function where the encoding difference is
4455 ** between UTF8 and UTF16.
4456 **
4457 ** ^Built-in functions may be overloaded by new application-defined functions.
4458 **
4459 ** ^An application-defined function is permitted to call other
4460 ** SQLite interfaces. However, such calls must not
4461 ** close the database connection nor finalize or reset the prepared
4462 ** statement in which the function is running.
4463 */
4464 SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
4465 sqlite3 *db,
4466 const char *zFunctionName,
4467 int nArg,
4468 int eTextRep,
4469 void *pApp,
4470 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4471 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4472 void (*xFinal)(sqlite3_context*)
4473 );
4474 SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
4475 sqlite3 *db,
4476 const void *zFunctionName,
4477 int nArg,
4478 int eTextRep,
4479 void *pApp,
4480 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4481 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4482 void (*xFinal)(sqlite3_context*)
4483 );
4484 SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
4485 sqlite3 *db,
4486 const char *zFunctionName,
4487 int nArg,
4488 int eTextRep,
4489 void *pApp,
4490 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4491 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4492 void (*xFinal)(sqlite3_context*),
4493 void(*xDestroy)(void*)
4494 );
4495
4496 /*
4497 ** CAPI3REF: Text Encodings
4498 **
4499 ** These constant define integer codes that represent the various
4500 ** text encodings supported by SQLite.
4501 */
4502 #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
4503 #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
4504 #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
4505 #define SQLITE_UTF16 4 /* Use native byte order */
4506 #define SQLITE_ANY 5 /* Deprecated */
4507 #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
4508
4509 /*
4510 ** CAPI3REF: Function Flags
4511 **
4512 ** These constants may be ORed together with the
4513 ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
4514 ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
4515 ** [sqlite3_create_function_v2()].
4516 */
4517 #define SQLITE_DETERMINISTIC 0x800
4518
4519 /*
4520 ** CAPI3REF: Deprecated Functions
4521 ** DEPRECATED
4522 **
4523 ** These functions are [deprecated]. In order to maintain
4524 ** backwards compatibility with older code, these functions continue
4525 ** to be supported. However, new applications should avoid
4526 ** the use of these functions. To encourage programmers to avoid
4527 ** these functions, we will not explain what they do.
4528 */
4529 #ifndef SQLITE_OMIT_DEPRECATED
4530 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_ context*);
4531 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt*);
4532 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite 3_stmt*, sqlite3_stmt*);
4533 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_global_recover(void);
4534 SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_thread_cleanup(void);
4535 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_memory_alarm(void(*)(voi d*,sqlite3_int64,int),
4536 void*,sqlite3_int64);
4537 #endif
4538
4539 /*
4540 ** CAPI3REF: Obtaining SQL Values
4541 ** METHOD: sqlite3_value
4542 **
4543 ** The C-language implementation of SQL functions and aggregates uses
4544 ** this set of interface routines to access the parameter values on
4545 ** the function or aggregate.
4546 **
4547 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4548 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4549 ** define callbacks that implement the SQL functions and aggregates.
4550 ** The 3rd parameter to these callbacks is an array of pointers to
4551 ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
4552 ** each parameter to the SQL function. These routines are used to
4553 ** extract values from the [sqlite3_value] objects.
4554 **
4555 ** These routines work only with [protected sqlite3_value] objects.
4556 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4557 ** object results in undefined behavior.
4558 **
4559 ** ^These routines work just like the corresponding [column access functions]
4560 ** except that these routines take a single [protected sqlite3_value] object
4561 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4562 **
4563 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4564 ** in the native byte-order of the host machine. ^The
4565 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4566 ** extract UTF-16 strings as big-endian and little-endian respectively.
4567 **
4568 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4569 ** numeric affinity to the value. This means that an attempt is
4570 ** made to convert the value to an integer or floating point. If
4571 ** such a conversion is possible without loss of information (in other
4572 ** words, if the value is a string that looks like a number)
4573 ** then the conversion is performed. Otherwise no conversion occurs.
4574 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4575 **
4576 ** Please pay particular attention to the fact that the pointer returned
4577 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4578 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4579 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4580 ** or [sqlite3_value_text16()].
4581 **
4582 ** These routines must be called from the same thread as
4583 ** the SQL function that supplied the [sqlite3_value*] parameters.
4584 */
4585 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value*);
4586 SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value*);
4587 SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value*);
4588 SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value*);
4589 SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value*);
4590 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value*);
4591 SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value* );
4592 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value*);
4593 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value*);
4594 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value*);
4595 SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value*);
4596 SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value*);
4597
4598 /*
4599 ** CAPI3REF: Finding The Subtype Of SQL Values
4600 ** METHOD: sqlite3_value
4601 **
4602 ** The sqlite3_value_subtype(V) function returns the subtype for
4603 ** an [application-defined SQL function] argument V. The subtype
4604 ** information can be used to pass a limited amount of context from
4605 ** one SQL function to another. Use the [sqlite3_result_subtype()]
4606 ** routine to set the subtype for the return value of an SQL function.
4607 **
4608 ** SQLite makes no use of subtype itself. It merely passes the subtype
4609 ** from the result of one [application-defined SQL function] into the
4610 ** input of another.
4611 */
4612 SQLITE_API unsigned int SQLITE_STDCALL sqlite3_value_subtype(sqlite3_value*);
4613
4614 /*
4615 ** CAPI3REF: Copy And Free SQL Values
4616 ** METHOD: sqlite3_value
4617 **
4618 ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
4619 ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
4620 ** is a [protected sqlite3_value] object even if the input is not.
4621 ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
4622 ** memory allocation fails.
4623 **
4624 ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
4625 ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
4626 ** then sqlite3_value_free(V) is a harmless no-op.
4627 */
4628 SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_value_dup(const sqlite3_value*) ;
4629 SQLITE_API void SQLITE_STDCALL sqlite3_value_free(sqlite3_value*);
4630
4631 /*
4632 ** CAPI3REF: Obtain Aggregate Function Context
4633 ** METHOD: sqlite3_context
4634 **
4635 ** Implementations of aggregate SQL functions use this
4636 ** routine to allocate memory for storing their state.
4637 **
4638 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4639 ** for a particular aggregate function, SQLite
4640 ** allocates N of memory, zeroes out that memory, and returns a pointer
4641 ** to the new memory. ^On second and subsequent calls to
4642 ** sqlite3_aggregate_context() for the same aggregate function instance,
4643 ** the same buffer is returned. Sqlite3_aggregate_context() is normally
4644 ** called once for each invocation of the xStep callback and then one
4645 ** last time when the xFinal callback is invoked. ^(When no rows match
4646 ** an aggregate query, the xStep() callback of the aggregate function
4647 ** implementation is never called and xFinal() is called exactly once.
4648 ** In those cases, sqlite3_aggregate_context() might be called for the
4649 ** first time from within xFinal().)^
4650 **
4651 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
4652 ** when first called if N is less than or equal to zero or if a memory
4653 ** allocate error occurs.
4654 **
4655 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4656 ** determined by the N parameter on first successful call. Changing the
4657 ** value of N in subsequent call to sqlite3_aggregate_context() within
4658 ** the same aggregate function instance will not resize the memory
4659 ** allocation.)^ Within the xFinal callback, it is customary to set
4660 ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
4661 ** pointless memory allocations occur.
4662 **
4663 ** ^SQLite automatically frees the memory allocated by
4664 ** sqlite3_aggregate_context() when the aggregate query concludes.
4665 **
4666 ** The first parameter must be a copy of the
4667 ** [sqlite3_context | SQL function context] that is the first parameter
4668 ** to the xStep or xFinal callback routine that implements the aggregate
4669 ** function.
4670 **
4671 ** This routine must be called from the same thread in which
4672 ** the aggregate SQL function is running.
4673 */
4674 SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4675
4676 /*
4677 ** CAPI3REF: User Data For Functions
4678 ** METHOD: sqlite3_context
4679 **
4680 ** ^The sqlite3_user_data() interface returns a copy of
4681 ** the pointer that was the pUserData parameter (the 5th parameter)
4682 ** of the [sqlite3_create_function()]
4683 ** and [sqlite3_create_function16()] routines that originally
4684 ** registered the application defined function.
4685 **
4686 ** This routine must be called from the same thread in which
4687 ** the application-defined function is running.
4688 */
4689 SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context*);
4690
4691 /*
4692 ** CAPI3REF: Database Connection For Functions
4693 ** METHOD: sqlite3_context
4694 **
4695 ** ^The sqlite3_context_db_handle() interface returns a copy of
4696 ** the pointer to the [database connection] (the 1st parameter)
4697 ** of the [sqlite3_create_function()]
4698 ** and [sqlite3_create_function16()] routines that originally
4699 ** registered the application defined function.
4700 */
4701 SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context*);
4702
4703 /*
4704 ** CAPI3REF: Function Auxiliary Data
4705 ** METHOD: sqlite3_context
4706 **
4707 ** These functions may be used by (non-aggregate) SQL functions to
4708 ** associate metadata with argument values. If the same value is passed to
4709 ** multiple invocations of the same SQL function during query execution, under
4710 ** some circumstances the associated metadata may be preserved. An example
4711 ** of where this might be useful is in a regular-expression matching
4712 ** function. The compiled version of the regular expression can be stored as
4713 ** metadata associated with the pattern string.
4714 ** Then as long as the pattern string remains the same,
4715 ** the compiled regular expression can be reused on multiple
4716 ** invocations of the same function.
4717 **
4718 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4719 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4720 ** value to the application-defined function. ^If there is no metadata
4721 ** associated with the function argument, this sqlite3_get_auxdata() interface
4722 ** returns a NULL pointer.
4723 **
4724 ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
4725 ** argument of the application-defined function. ^Subsequent
4726 ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
4727 ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
4728 ** NULL if the metadata has been discarded.
4729 ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
4730 ** SQLite will invoke the destructor function X with parameter P exactly
4731 ** once, when the metadata is discarded.
4732 ** SQLite is free to discard the metadata at any time, including: <ul>
4733 ** <li> when the corresponding function parameter changes, or
4734 ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
4735 ** SQL statement, or
4736 ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
4737 ** <li> during the original sqlite3_set_auxdata() call when a memory
4738 ** allocation error occurs. </ul>)^
4739 **
4740 ** Note the last bullet in particular. The destructor X in
4741 ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
4742 ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
4743 ** should be called near the end of the function implementation and the
4744 ** function implementation should not make any use of P after
4745 ** sqlite3_set_auxdata() has been called.
4746 **
4747 ** ^(In practice, metadata is preserved between function calls for
4748 ** function parameters that are compile-time constants, including literal
4749 ** values and [parameters] and expressions composed from the same.)^
4750 **
4751 ** These routines must be called from the same thread in which
4752 ** the SQL function is running.
4753 */
4754 SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context*, int N);
4755 SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(sqlite3_context*, int N, void *, void (*)(void*));
4756
4757
4758 /*
4759 ** CAPI3REF: Constants Defining Special Destructor Behavior
4760 **
4761 ** These are special values for the destructor that is passed in as the
4762 ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
4763 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4764 ** and will never change. It does not need to be destroyed. ^The
4765 ** SQLITE_TRANSIENT value means that the content will likely change in
4766 ** the near future and that SQLite should make its own private copy of
4767 ** the content before returning.
4768 **
4769 ** The typedef is necessary to work around problems in certain
4770 ** C++ compilers.
4771 */
4772 typedef void (*sqlite3_destructor_type)(void*);
4773 #define SQLITE_STATIC ((sqlite3_destructor_type)0)
4774 #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
4775
4776 /*
4777 ** CAPI3REF: Setting The Result Of An SQL Function
4778 ** METHOD: sqlite3_context
4779 **
4780 ** These routines are used by the xFunc or xFinal callbacks that
4781 ** implement SQL functions and aggregates. See
4782 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4783 ** for additional information.
4784 **
4785 ** These functions work very much like the [parameter binding] family of
4786 ** functions used to bind values to host parameters in prepared statements.
4787 ** Refer to the [SQL parameter] documentation for additional information.
4788 **
4789 ** ^The sqlite3_result_blob() interface sets the result from
4790 ** an application-defined function to be the BLOB whose content is pointed
4791 ** to by the second parameter and which is N bytes long where N is the
4792 ** third parameter.
4793 **
4794 ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
4795 ** interfaces set the result of the application-defined function to be
4796 ** a BLOB containing all zero bytes and N bytes in size.
4797 **
4798 ** ^The sqlite3_result_double() interface sets the result from
4799 ** an application-defined function to be a floating point value specified
4800 ** by its 2nd argument.
4801 **
4802 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4803 ** cause the implemented SQL function to throw an exception.
4804 ** ^SQLite uses the string pointed to by the
4805 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4806 ** as the text of an error message. ^SQLite interprets the error
4807 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4808 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4809 ** byte order. ^If the third parameter to sqlite3_result_error()
4810 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4811 ** message all text up through the first zero character.
4812 ** ^If the third parameter to sqlite3_result_error() or
4813 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4814 ** bytes (not characters) from the 2nd parameter as the error message.
4815 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4816 ** routines make a private copy of the error message text before
4817 ** they return. Hence, the calling function can deallocate or
4818 ** modify the text after they return without harm.
4819 ** ^The sqlite3_result_error_code() function changes the error code
4820 ** returned by SQLite as a result of an error in a function. ^By default,
4821 ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
4822 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4823 **
4824 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
4825 ** error indicating that a string or BLOB is too long to represent.
4826 **
4827 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
4828 ** error indicating that a memory allocation failed.
4829 **
4830 ** ^The sqlite3_result_int() interface sets the return value
4831 ** of the application-defined function to be the 32-bit signed integer
4832 ** value given in the 2nd argument.
4833 ** ^The sqlite3_result_int64() interface sets the return value
4834 ** of the application-defined function to be the 64-bit signed integer
4835 ** value given in the 2nd argument.
4836 **
4837 ** ^The sqlite3_result_null() interface sets the return value
4838 ** of the application-defined function to be NULL.
4839 **
4840 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4841 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4842 ** set the return value of the application-defined function to be
4843 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4844 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4845 ** ^The sqlite3_result_text64() interface sets the return value of an
4846 ** application-defined function to be a text string in an encoding
4847 ** specified by the fifth (and last) parameter, which must be one
4848 ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
4849 ** ^SQLite takes the text result from the application from
4850 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4851 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4852 ** is negative, then SQLite takes result text from the 2nd parameter
4853 ** through the first zero character.
4854 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4855 ** is non-negative, then as many bytes (not characters) of the text
4856 ** pointed to by the 2nd parameter are taken as the application-defined
4857 ** function result. If the 3rd parameter is non-negative, then it
4858 ** must be the byte offset into the string where the NUL terminator would
4859 ** appear if the string where NUL terminated. If any NUL characters occur
4860 ** in the string at a byte offset that is less than the value of the 3rd
4861 ** parameter, then the resulting string will contain embedded NULs and the
4862 ** result of expressions operating on strings with embedded NULs is undefined.
4863 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4864 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4865 ** function as the destructor on the text or BLOB result when it has
4866 ** finished using that result.
4867 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4868 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4869 ** assumes that the text or BLOB result is in constant space and does not
4870 ** copy the content of the parameter nor call a destructor on the content
4871 ** when it has finished using that result.
4872 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4873 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4874 ** then SQLite makes a copy of the result into space obtained from
4875 ** from [sqlite3_malloc()] before it returns.
4876 **
4877 ** ^The sqlite3_result_value() interface sets the result of
4878 ** the application-defined function to be a copy of the
4879 ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
4880 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4881 ** so that the [sqlite3_value] specified in the parameter may change or
4882 ** be deallocated after sqlite3_result_value() returns without harm.
4883 ** ^A [protected sqlite3_value] object may always be used where an
4884 ** [unprotected sqlite3_value] object is required, so either
4885 ** kind of [sqlite3_value] object can be used with this interface.
4886 **
4887 ** If these routines are called from within the different thread
4888 ** than the one containing the application-defined function that received
4889 ** the [sqlite3_context] pointer, the results are undefined.
4890 */
4891 SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(sqlite3_context*, const void* , int, void(*)(void*));
4892 SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(sqlite3_context*,const void *,
4893 sqlite3_uint64,void(*)(void*));
4894 SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context*, double);
4895 SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context*, const char *, int);
4896 SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context*, const vo id*, int);
4897 SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context*);
4898 SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context*);
4899 SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context*, int);
4900 SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context*, int);
4901 SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context*, sqlite3_in t64);
4902 SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context*);
4903 SQLITE_API void SQLITE_STDCALL sqlite3_result_text(sqlite3_context*, const char* , int, void(*)(void*));
4904 SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(sqlite3_context*, const cha r*,sqlite3_uint64,
4905 void(*)(void*), unsigned char encoding);
4906 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(sqlite3_context*, const voi d*, int, void(*)(void*));
4907 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(sqlite3_context*, const v oid*, int,void(*)(void*));
4908 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(sqlite3_context*, const v oid*, int,void(*)(void*));
4909 SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context*, sqlite3_va lue*);
4910 SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context*, int n);
4911 SQLITE_API int SQLITE_STDCALL sqlite3_result_zeroblob64(sqlite3_context*, sqlite 3_uint64 n);
4912
4913
4914 /*
4915 ** CAPI3REF: Setting The Subtype Of An SQL Function
4916 ** METHOD: sqlite3_context
4917 **
4918 ** The sqlite3_result_subtype(C,T) function causes the subtype of
4919 ** the result from the [application-defined SQL function] with
4920 ** [sqlite3_context] C to be the value T. Only the lower 8 bits
4921 ** of the subtype T are preserved in current versions of SQLite;
4922 ** higher order bits are discarded.
4923 ** The number of subtype bytes preserved by SQLite might increase
4924 ** in future releases of SQLite.
4925 */
4926 SQLITE_API void SQLITE_STDCALL sqlite3_result_subtype(sqlite3_context*,unsigned int);
4927
4928 /*
4929 ** CAPI3REF: Define New Collating Sequences
4930 ** METHOD: sqlite3
4931 **
4932 ** ^These functions add, remove, or modify a [collation] associated
4933 ** with the [database connection] specified as the first argument.
4934 **
4935 ** ^The name of the collation is a UTF-8 string
4936 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4937 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4938 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4939 ** considered to be the same name.
4940 **
4941 ** ^(The third argument (eTextRep) must be one of the constants:
4942 ** <ul>
4943 ** <li> [SQLITE_UTF8],
4944 ** <li> [SQLITE_UTF16LE],
4945 ** <li> [SQLITE_UTF16BE],
4946 ** <li> [SQLITE_UTF16], or
4947 ** <li> [SQLITE_UTF16_ALIGNED].
4948 ** </ul>)^
4949 ** ^The eTextRep argument determines the encoding of strings passed
4950 ** to the collating function callback, xCallback.
4951 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4952 ** force strings to be UTF16 with native byte order.
4953 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4954 ** on an even byte address.
4955 **
4956 ** ^The fourth argument, pArg, is an application data pointer that is passed
4957 ** through as the first argument to the collating function callback.
4958 **
4959 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4960 ** ^Multiple collating functions can be registered using the same name but
4961 ** with different eTextRep parameters and SQLite will use whichever
4962 ** function requires the least amount of data transformation.
4963 ** ^If the xCallback argument is NULL then the collating function is
4964 ** deleted. ^When all collating functions having the same name are deleted,
4965 ** that collation is no longer usable.
4966 **
4967 ** ^The collating function callback is invoked with a copy of the pArg
4968 ** application data pointer and with two strings in the encoding specified
4969 ** by the eTextRep argument. The collating function must return an
4970 ** integer that is negative, zero, or positive
4971 ** if the first string is less than, equal to, or greater than the second,
4972 ** respectively. A collating function must always return the same answer
4973 ** given the same inputs. If two or more collating functions are registered
4974 ** to the same collation name (using different eTextRep values) then all
4975 ** must give an equivalent answer when invoked with equivalent strings.
4976 ** The collating function must obey the following properties for all
4977 ** strings A, B, and C:
4978 **
4979 ** <ol>
4980 ** <li> If A==B then B==A.
4981 ** <li> If A==B and B==C then A==C.
4982 ** <li> If A&lt;B THEN B&gt;A.
4983 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4984 ** </ol>
4985 **
4986 ** If a collating function fails any of the above constraints and that
4987 ** collating function is registered and used, then the behavior of SQLite
4988 ** is undefined.
4989 **
4990 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4991 ** with the addition that the xDestroy callback is invoked on pArg when
4992 ** the collating function is deleted.
4993 ** ^Collating functions are deleted when they are overridden by later
4994 ** calls to the collation creation functions or when the
4995 ** [database connection] is closed using [sqlite3_close()].
4996 **
4997 ** ^The xDestroy callback is <u>not</u> called if the
4998 ** sqlite3_create_collation_v2() function fails. Applications that invoke
4999 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
5000 ** check the return code and dispose of the application data pointer
5001 ** themselves rather than expecting SQLite to deal with it for them.
5002 ** This is different from every other SQLite interface. The inconsistency
5003 ** is unfortunate but cannot be changed without breaking backwards
5004 ** compatibility.
5005 **
5006 ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
5007 */
5008 SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
5009 sqlite3*,
5010 const char *zName,
5011 int eTextRep,
5012 void *pArg,
5013 int(*xCompare)(void*,int,const void*,int,const void*)
5014 );
5015 SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
5016 sqlite3*,
5017 const char *zName,
5018 int eTextRep,
5019 void *pArg,
5020 int(*xCompare)(void*,int,const void*,int,const void*),
5021 void(*xDestroy)(void*)
5022 );
5023 SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
5024 sqlite3*,
5025 const void *zName,
5026 int eTextRep,
5027 void *pArg,
5028 int(*xCompare)(void*,int,const void*,int,const void*)
5029 );
5030
5031 /*
5032 ** CAPI3REF: Collation Needed Callbacks
5033 ** METHOD: sqlite3
5034 **
5035 ** ^To avoid having to register all collation sequences before a database
5036 ** can be used, a single callback function may be registered with the
5037 ** [database connection] to be invoked whenever an undefined collation
5038 ** sequence is required.
5039 **
5040 ** ^If the function is registered using the sqlite3_collation_needed() API,
5041 ** then it is passed the names of undefined collation sequences as strings
5042 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
5043 ** the names are passed as UTF-16 in machine native byte order.
5044 ** ^A call to either function replaces the existing collation-needed callback.
5045 **
5046 ** ^(When the callback is invoked, the first argument passed is a copy
5047 ** of the second argument to sqlite3_collation_needed() or
5048 ** sqlite3_collation_needed16(). The second argument is the database
5049 ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
5050 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
5051 ** sequence function required. The fourth parameter is the name of the
5052 ** required collation sequence.)^
5053 **
5054 ** The callback function should register the desired collation using
5055 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
5056 ** [sqlite3_create_collation_v2()].
5057 */
5058 SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
5059 sqlite3*,
5060 void*,
5061 void(*)(void*,sqlite3*,int eTextRep,const char*)
5062 );
5063 SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
5064 sqlite3*,
5065 void*,
5066 void(*)(void*,sqlite3*,int eTextRep,const void*)
5067 );
5068
5069 #ifdef SQLITE_HAS_CODEC
5070 /*
5071 ** Specify the key for an encrypted database. This routine should be
5072 ** called right after sqlite3_open().
5073 **
5074 ** The code to implement this API is not available in the public release
5075 ** of SQLite.
5076 */
5077 SQLITE_API int SQLITE_STDCALL sqlite3_key(
5078 sqlite3 *db, /* Database to be rekeyed */
5079 const void *pKey, int nKey /* The key */
5080 );
5081 SQLITE_API int SQLITE_STDCALL sqlite3_key_v2(
5082 sqlite3 *db, /* Database to be rekeyed */
5083 const char *zDbName, /* Name of the database */
5084 const void *pKey, int nKey /* The key */
5085 );
5086
5087 /*
5088 ** Change the key on an open database. If the current database is not
5089 ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
5090 ** database is decrypted.
5091 **
5092 ** The code to implement this API is not available in the public release
5093 ** of SQLite.
5094 */
5095 SQLITE_API int SQLITE_STDCALL sqlite3_rekey(
5096 sqlite3 *db, /* Database to be rekeyed */
5097 const void *pKey, int nKey /* The new key */
5098 );
5099 SQLITE_API int SQLITE_STDCALL sqlite3_rekey_v2(
5100 sqlite3 *db, /* Database to be rekeyed */
5101 const char *zDbName, /* Name of the database */
5102 const void *pKey, int nKey /* The new key */
5103 );
5104
5105 /*
5106 ** Specify the activation key for a SEE database. Unless
5107 ** activated, none of the SEE routines will work.
5108 */
5109 SQLITE_API void SQLITE_STDCALL sqlite3_activate_see(
5110 const char *zPassPhrase /* Activation phrase */
5111 );
5112 #endif
5113
5114 #ifdef SQLITE_ENABLE_CEROD
5115 /*
5116 ** Specify the activation key for a CEROD database. Unless
5117 ** activated, none of the CEROD routines will work.
5118 */
5119 SQLITE_API void SQLITE_STDCALL sqlite3_activate_cerod(
5120 const char *zPassPhrase /* Activation phrase */
5121 );
5122 #endif
5123
5124 /*
5125 ** CAPI3REF: Suspend Execution For A Short Time
5126 **
5127 ** The sqlite3_sleep() function causes the current thread to suspend execution
5128 ** for at least a number of milliseconds specified in its parameter.
5129 **
5130 ** If the operating system does not support sleep requests with
5131 ** millisecond time resolution, then the time will be rounded up to
5132 ** the nearest second. The number of milliseconds of sleep actually
5133 ** requested from the operating system is returned.
5134 **
5135 ** ^SQLite implements this interface by calling the xSleep()
5136 ** method of the default [sqlite3_vfs] object. If the xSleep() method
5137 ** of the default VFS is not implemented correctly, or not implemented at
5138 ** all, then the behavior of sqlite3_sleep() may deviate from the description
5139 ** in the previous paragraphs.
5140 */
5141 SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int);
5142
5143 /*
5144 ** CAPI3REF: Name Of The Folder Holding Temporary Files
5145 **
5146 ** ^(If this global variable is made to point to a string which is
5147 ** the name of a folder (a.k.a. directory), then all temporary files
5148 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
5149 ** will be placed in that directory.)^ ^If this variable
5150 ** is a NULL pointer, then SQLite performs a search for an appropriate
5151 ** temporary file directory.
5152 **
5153 ** Applications are strongly discouraged from using this global variable.
5154 ** It is required to set a temporary folder on Windows Runtime (WinRT).
5155 ** But for all other platforms, it is highly recommended that applications
5156 ** neither read nor write this variable. This global variable is a relic
5157 ** that exists for backwards compatibility of legacy applications and should
5158 ** be avoided in new projects.
5159 **
5160 ** It is not safe to read or modify this variable in more than one
5161 ** thread at a time. It is not safe to read or modify this variable
5162 ** if a [database connection] is being used at the same time in a separate
5163 ** thread.
5164 ** It is intended that this variable be set once
5165 ** as part of process initialization and before any SQLite interface
5166 ** routines have been called and that this variable remain unchanged
5167 ** thereafter.
5168 **
5169 ** ^The [temp_store_directory pragma] may modify this variable and cause
5170 ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
5171 ** the [temp_store_directory pragma] always assumes that any string
5172 ** that this variable points to is held in memory obtained from
5173 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5174 ** using [sqlite3_free].
5175 ** Hence, if this variable is modified directly, either it should be
5176 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5177 ** or else the use of the [temp_store_directory pragma] should be avoided.
5178 ** Except when requested by the [temp_store_directory pragma], SQLite
5179 ** does not free the memory that sqlite3_temp_directory points to. If
5180 ** the application wants that memory to be freed, it must do
5181 ** so itself, taking care to only do so after all [database connection]
5182 ** objects have been destroyed.
5183 **
5184 ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
5185 ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
5186 ** features that require the use of temporary files may fail. Here is an
5187 ** example of how to do this using C++ with the Windows Runtime:
5188 **
5189 ** <blockquote><pre>
5190 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
5191 ** &nbsp; TemporaryFolder->Path->Data();
5192 ** char zPathBuf&#91;MAX_PATH + 1&#93;;
5193 ** memset(zPathBuf, 0, sizeof(zPathBuf));
5194 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
5195 ** &nbsp; NULL, NULL);
5196 ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
5197 ** </pre></blockquote>
5198 */
5199 SQLITE_API char *sqlite3_temp_directory;
5200
5201 /*
5202 ** CAPI3REF: Name Of The Folder Holding Database Files
5203 **
5204 ** ^(If this global variable is made to point to a string which is
5205 ** the name of a folder (a.k.a. directory), then all database files
5206 ** specified with a relative pathname and created or accessed by
5207 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
5208 ** to be relative to that directory.)^ ^If this variable is a NULL
5209 ** pointer, then SQLite assumes that all database files specified
5210 ** with a relative pathname are relative to the current directory
5211 ** for the process. Only the windows VFS makes use of this global
5212 ** variable; it is ignored by the unix VFS.
5213 **
5214 ** Changing the value of this variable while a database connection is
5215 ** open can result in a corrupt database.
5216 **
5217 ** It is not safe to read or modify this variable in more than one
5218 ** thread at a time. It is not safe to read or modify this variable
5219 ** if a [database connection] is being used at the same time in a separate
5220 ** thread.
5221 ** It is intended that this variable be set once
5222 ** as part of process initialization and before any SQLite interface
5223 ** routines have been called and that this variable remain unchanged
5224 ** thereafter.
5225 **
5226 ** ^The [data_store_directory pragma] may modify this variable and cause
5227 ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
5228 ** the [data_store_directory pragma] always assumes that any string
5229 ** that this variable points to is held in memory obtained from
5230 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5231 ** using [sqlite3_free].
5232 ** Hence, if this variable is modified directly, either it should be
5233 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5234 ** or else the use of the [data_store_directory pragma] should be avoided.
5235 */
5236 SQLITE_API char *sqlite3_data_directory;
5237
5238 /*
5239 ** CAPI3REF: Test For Auto-Commit Mode
5240 ** KEYWORDS: {autocommit mode}
5241 ** METHOD: sqlite3
5242 **
5243 ** ^The sqlite3_get_autocommit() interface returns non-zero or
5244 ** zero if the given database connection is or is not in autocommit mode,
5245 ** respectively. ^Autocommit mode is on by default.
5246 ** ^Autocommit mode is disabled by a [BEGIN] statement.
5247 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5248 **
5249 ** If certain kinds of errors occur on a statement within a multi-statement
5250 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5251 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5252 ** transaction might be rolled back automatically. The only way to
5253 ** find out whether SQLite automatically rolled back the transaction after
5254 ** an error is to use this function.
5255 **
5256 ** If another thread changes the autocommit status of the database
5257 ** connection while this routine is running, then the return value
5258 ** is undefined.
5259 */
5260 SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3*);
5261
5262 /*
5263 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
5264 ** METHOD: sqlite3_stmt
5265 **
5266 ** ^The sqlite3_db_handle interface returns the [database connection] handle
5267 ** to which a [prepared statement] belongs. ^The [database connection]
5268 ** returned by sqlite3_db_handle is the same [database connection]
5269 ** that was the first argument
5270 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5271 ** create the statement in the first place.
5272 */
5273 SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt*);
5274
5275 /*
5276 ** CAPI3REF: Return The Filename For A Database Connection
5277 ** METHOD: sqlite3
5278 **
5279 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
5280 ** associated with database N of connection D. ^The main database file
5281 ** has the name "main". If there is no attached database N on the database
5282 ** connection D, or if database N is a temporary or in-memory database, then
5283 ** a NULL pointer is returned.
5284 **
5285 ** ^The filename returned by this function is the output of the
5286 ** xFullPathname method of the [VFS]. ^In other words, the filename
5287 ** will be an absolute pathname, even if the filename used
5288 ** to open the database originally was a URI or relative pathname.
5289 */
5290 SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const cha r *zDbName);
5291
5292 /*
5293 ** CAPI3REF: Determine if a database is read-only
5294 ** METHOD: sqlite3
5295 **
5296 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5297 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5298 ** the name of a database on connection D.
5299 */
5300 SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbNa me);
5301
5302 /*
5303 ** CAPI3REF: Find the next prepared statement
5304 ** METHOD: sqlite3
5305 **
5306 ** ^This interface returns a pointer to the next [prepared statement] after
5307 ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
5308 ** then this interface returns a pointer to the first prepared statement
5309 ** associated with the database connection pDb. ^If no prepared statement
5310 ** satisfies the conditions of this routine, it returns NULL.
5311 **
5312 ** The [database connection] pointer D in a call to
5313 ** [sqlite3_next_stmt(D,S)] must refer to an open database
5314 ** connection and in particular must not be a NULL pointer.
5315 */
5316 SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_ stmt *pStmt);
5317
5318 /*
5319 ** CAPI3REF: Commit And Rollback Notification Callbacks
5320 ** METHOD: sqlite3
5321 **
5322 ** ^The sqlite3_commit_hook() interface registers a callback
5323 ** function to be invoked whenever a transaction is [COMMIT | committed].
5324 ** ^Any callback set by a previous call to sqlite3_commit_hook()
5325 ** for the same database connection is overridden.
5326 ** ^The sqlite3_rollback_hook() interface registers a callback
5327 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5328 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
5329 ** for the same database connection is overridden.
5330 ** ^The pArg argument is passed through to the callback.
5331 ** ^If the callback on a commit hook function returns non-zero,
5332 ** then the commit is converted into a rollback.
5333 **
5334 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5335 ** return the P argument from the previous call of the same function
5336 ** on the same [database connection] D, or NULL for
5337 ** the first call for each function on D.
5338 **
5339 ** The commit and rollback hook callbacks are not reentrant.
5340 ** The callback implementation must not do anything that will modify
5341 ** the database connection that invoked the callback. Any actions
5342 ** to modify the database connection must be deferred until after the
5343 ** completion of the [sqlite3_step()] call that triggered the commit
5344 ** or rollback hook in the first place.
5345 ** Note that running any other SQL statements, including SELECT statements,
5346 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5347 ** the database connections for the meaning of "modify" in this paragraph.
5348 **
5349 ** ^Registering a NULL function disables the callback.
5350 **
5351 ** ^When the commit hook callback routine returns zero, the [COMMIT]
5352 ** operation is allowed to continue normally. ^If the commit hook
5353 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5354 ** ^The rollback hook is invoked on a rollback that results from a commit
5355 ** hook returning non-zero, just as it would be with any other rollback.
5356 **
5357 ** ^For the purposes of this API, a transaction is said to have been
5358 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5359 ** an error or constraint causes an implicit rollback to occur.
5360 ** ^The rollback callback is not invoked if a transaction is
5361 ** automatically rolled back because the database connection is closed.
5362 **
5363 ** See also the [sqlite3_update_hook()] interface.
5364 */
5365 SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(sqlite3*, int(*)(void*), voi d*);
5366 SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5367
5368 /*
5369 ** CAPI3REF: Data Change Notification Callbacks
5370 ** METHOD: sqlite3
5371 **
5372 ** ^The sqlite3_update_hook() interface registers a callback function
5373 ** with the [database connection] identified by the first argument
5374 ** to be invoked whenever a row is updated, inserted or deleted in
5375 ** a rowid table.
5376 ** ^Any callback set by a previous call to this function
5377 ** for the same database connection is overridden.
5378 **
5379 ** ^The second argument is a pointer to the function to invoke when a
5380 ** row is updated, inserted or deleted in a rowid table.
5381 ** ^The first argument to the callback is a copy of the third argument
5382 ** to sqlite3_update_hook().
5383 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5384 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5385 ** to be invoked.
5386 ** ^The third and fourth arguments to the callback contain pointers to the
5387 ** database and table name containing the affected row.
5388 ** ^The final callback parameter is the [rowid] of the row.
5389 ** ^In the case of an update, this is the [rowid] after the update takes place.
5390 **
5391 ** ^(The update hook is not invoked when internal system tables are
5392 ** modified (i.e. sqlite_master and sqlite_sequence).)^
5393 ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
5394 **
5395 ** ^In the current implementation, the update hook
5396 ** is not invoked when duplication rows are deleted because of an
5397 ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
5398 ** invoked when rows are deleted using the [truncate optimization].
5399 ** The exceptions defined in this paragraph might change in a future
5400 ** release of SQLite.
5401 **
5402 ** The update hook implementation must not do anything that will modify
5403 ** the database connection that invoked the update hook. Any actions
5404 ** to modify the database connection must be deferred until after the
5405 ** completion of the [sqlite3_step()] call that triggered the update hook.
5406 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5407 ** database connections for the meaning of "modify" in this paragraph.
5408 **
5409 ** ^The sqlite3_update_hook(D,C,P) function
5410 ** returns the P argument from the previous call
5411 ** on the same [database connection] D, or NULL for
5412 ** the first call on D.
5413 **
5414 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5415 ** interfaces.
5416 */
5417 SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
5418 sqlite3*,
5419 void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5420 void*
5421 );
5422
5423 /*
5424 ** CAPI3REF: Enable Or Disable Shared Pager Cache
5425 **
5426 ** ^(This routine enables or disables the sharing of the database cache
5427 ** and schema data structures between [database connection | connections]
5428 ** to the same database. Sharing is enabled if the argument is true
5429 ** and disabled if the argument is false.)^
5430 **
5431 ** ^Cache sharing is enabled and disabled for an entire process.
5432 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5433 ** sharing was enabled or disabled for each thread separately.
5434 **
5435 ** ^(The cache sharing mode set by this interface effects all subsequent
5436 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5437 ** Existing database connections continue use the sharing mode
5438 ** that was in effect at the time they were opened.)^
5439 **
5440 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5441 ** successfully. An [error code] is returned otherwise.)^
5442 **
5443 ** ^Shared cache is disabled by default. But this might change in
5444 ** future releases of SQLite. Applications that care about shared
5445 ** cache setting should set it explicitly.
5446 **
5447 ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
5448 ** and will always return SQLITE_MISUSE. On those systems,
5449 ** shared cache mode should be enabled per-database connection via
5450 ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
5451 **
5452 ** This interface is threadsafe on processors where writing a
5453 ** 32-bit integer is atomic.
5454 **
5455 ** See Also: [SQLite Shared-Cache Mode]
5456 */
5457 SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int);
5458
5459 /*
5460 ** CAPI3REF: Attempt To Free Heap Memory
5461 **
5462 ** ^The sqlite3_release_memory() interface attempts to free N bytes
5463 ** of heap memory by deallocating non-essential memory allocations
5464 ** held by the database library. Memory used to cache database
5465 ** pages to improve performance is an example of non-essential memory.
5466 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
5467 ** which might be more or less than the amount requested.
5468 ** ^The sqlite3_release_memory() routine is a no-op returning zero
5469 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5470 **
5471 ** See also: [sqlite3_db_release_memory()]
5472 */
5473 SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int);
5474
5475 /*
5476 ** CAPI3REF: Free Memory Used By A Database Connection
5477 ** METHOD: sqlite3
5478 **
5479 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5480 ** memory as possible from database connection D. Unlike the
5481 ** [sqlite3_release_memory()] interface, this interface is in effect even
5482 ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5483 ** omitted.
5484 **
5485 ** See also: [sqlite3_release_memory()]
5486 */
5487 SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3*);
5488
5489 /*
5490 ** CAPI3REF: Impose A Limit On Heap Size
5491 **
5492 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5493 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5494 ** ^SQLite strives to keep heap memory utilization below the soft heap
5495 ** limit by reducing the number of pages held in the page cache
5496 ** as heap memory usages approaches the limit.
5497 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5498 ** below the limit, it will exceed the limit rather than generate
5499 ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
5500 ** is advisory only.
5501 **
5502 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
5503 ** the soft heap limit prior to the call, or negative in the case of an
5504 ** error. ^If the argument N is negative
5505 ** then no change is made to the soft heap limit. Hence, the current
5506 ** size of the soft heap limit can be determined by invoking
5507 ** sqlite3_soft_heap_limit64() with a negative argument.
5508 **
5509 ** ^If the argument N is zero then the soft heap limit is disabled.
5510 **
5511 ** ^(The soft heap limit is not enforced in the current implementation
5512 ** if one or more of following conditions are true:
5513 **
5514 ** <ul>
5515 ** <li> The soft heap limit is set to zero.
5516 ** <li> Memory accounting is disabled using a combination of the
5517 ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5518 ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5519 ** <li> An alternative page cache implementation is specified using
5520 ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5521 ** <li> The page cache allocates from its own memory pool supplied
5522 ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5523 ** from the heap.
5524 ** </ul>)^
5525 **
5526 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5527 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5528 ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5529 ** the soft heap limit is enforced on every memory allocation. Without
5530 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5531 ** when memory is allocated by the page cache. Testing suggests that because
5532 ** the page cache is the predominate memory user in SQLite, most
5533 ** applications will achieve adequate soft heap limit enforcement without
5534 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5535 **
5536 ** The circumstances under which SQLite will enforce the soft heap limit may
5537 ** changes in future releases of SQLite.
5538 */
5539 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 N);
5540
5541 /*
5542 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5543 ** DEPRECATED
5544 **
5545 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5546 ** interface. This routine is provided for historical compatibility
5547 ** only. All new applications should use the
5548 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
5549 */
5550 SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_soft_heap_limit(int N);
5551
5552
5553 /*
5554 ** CAPI3REF: Extract Metadata About A Column Of A Table
5555 ** METHOD: sqlite3
5556 **
5557 ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
5558 ** information about column C of table T in database D
5559 ** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
5560 ** interface returns SQLITE_OK and fills in the non-NULL pointers in
5561 ** the final five arguments with appropriate values if the specified
5562 ** column exists. ^The sqlite3_table_column_metadata() interface returns
5563 ** SQLITE_ERROR and if the specified column does not exist.
5564 ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
5565 ** NULL pointer, then this routine simply checks for the existance of the
5566 ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
5567 ** does not.
5568 **
5569 ** ^The column is identified by the second, third and fourth parameters to
5570 ** this function. ^(The second parameter is either the name of the database
5571 ** (i.e. "main", "temp", or an attached database) containing the specified
5572 ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
5573 ** for the table using the same algorithm used by the database engine to
5574 ** resolve unqualified table references.
5575 **
5576 ** ^The third and fourth parameters to this function are the table and column
5577 ** name of the desired column, respectively.
5578 **
5579 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5580 ** and subsequent parameters to this function. ^Any of these arguments may be
5581 ** NULL, in which case the corresponding element of metadata is omitted.
5582 **
5583 ** ^(<blockquote>
5584 ** <table border="1">
5585 ** <tr><th> Parameter <th> Output<br>Type <th> Description
5586 **
5587 ** <tr><td> 5th <td> const char* <td> Data type
5588 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5589 ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
5590 ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
5591 ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
5592 ** </table>
5593 ** </blockquote>)^
5594 **
5595 ** ^The memory pointed to by the character pointers returned for the
5596 ** declaration type and collation sequence is valid until the next
5597 ** call to any SQLite API function.
5598 **
5599 ** ^If the specified table is actually a view, an [error code] is returned.
5600 **
5601 ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
5602 ** is not a [WITHOUT ROWID] table and an
5603 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5604 ** parameters are set for the explicitly declared column. ^(If there is no
5605 ** [INTEGER PRIMARY KEY] column, then the outputs
5606 ** for the [rowid] are set as follows:
5607 **
5608 ** <pre>
5609 ** data type: "INTEGER"
5610 ** collation sequence: "BINARY"
5611 ** not null: 0
5612 ** primary key: 1
5613 ** auto increment: 0
5614 ** </pre>)^
5615 **
5616 ** ^This function causes all database schemas to be read from disk and
5617 ** parsed, if that has not already been done, and returns an error if
5618 ** any errors are encountered while loading the schema.
5619 */
5620 SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
5621 sqlite3 *db, /* Connection handle */
5622 const char *zDbName, /* Database name or NULL */
5623 const char *zTableName, /* Table name */
5624 const char *zColumnName, /* Column name */
5625 char const **pzDataType, /* OUTPUT: Declared data type */
5626 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
5627 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
5628 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
5629 int *pAutoinc /* OUTPUT: True if column is auto-increment */
5630 );
5631
5632 /*
5633 ** CAPI3REF: Load An Extension
5634 ** METHOD: sqlite3
5635 **
5636 ** ^This interface loads an SQLite extension library from the named file.
5637 **
5638 ** ^The sqlite3_load_extension() interface attempts to load an
5639 ** [SQLite extension] library contained in the file zFile. If
5640 ** the file cannot be loaded directly, attempts are made to load
5641 ** with various operating-system specific extensions added.
5642 ** So for example, if "samplelib" cannot be loaded, then names like
5643 ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
5644 ** be tried also.
5645 **
5646 ** ^The entry point is zProc.
5647 ** ^(zProc may be 0, in which case SQLite will try to come up with an
5648 ** entry point name on its own. It first tries "sqlite3_extension_init".
5649 ** If that does not work, it constructs a name "sqlite3_X_init" where the
5650 ** X is consists of the lower-case equivalent of all ASCII alphabetic
5651 ** characters in the filename from the last "/" to the first following
5652 ** "." and omitting any initial "lib".)^
5653 ** ^The sqlite3_load_extension() interface returns
5654 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5655 ** ^If an error occurs and pzErrMsg is not 0, then the
5656 ** [sqlite3_load_extension()] interface shall attempt to
5657 ** fill *pzErrMsg with error message text stored in memory
5658 ** obtained from [sqlite3_malloc()]. The calling function
5659 ** should free this memory by calling [sqlite3_free()].
5660 **
5661 ** ^Extension loading must be enabled using
5662 ** [sqlite3_enable_load_extension()] prior to calling this API,
5663 ** otherwise an error will be returned.
5664 **
5665 ** See also the [load_extension() SQL function].
5666 */
5667 SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
5668 sqlite3 *db, /* Load the extension into this database connection */
5669 const char *zFile, /* Name of the shared library containing extension */
5670 const char *zProc, /* Entry point. Derived from zFile if 0 */
5671 char **pzErrMsg /* Put error message here if not 0 */
5672 );
5673
5674 /*
5675 ** CAPI3REF: Enable Or Disable Extension Loading
5676 ** METHOD: sqlite3
5677 **
5678 ** ^So as not to open security holes in older applications that are
5679 ** unprepared to deal with [extension loading], and as a means of disabling
5680 ** [extension loading] while evaluating user-entered SQL, the following API
5681 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5682 **
5683 ** ^Extension loading is off by default.
5684 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5685 ** to turn extension loading on and call it with onoff==0 to turn
5686 ** it back off again.
5687 */
5688 SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int ono ff);
5689
5690 /*
5691 ** CAPI3REF: Automatically Load Statically Linked Extensions
5692 **
5693 ** ^This interface causes the xEntryPoint() function to be invoked for
5694 ** each new [database connection] that is created. The idea here is that
5695 ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
5696 ** that is to be automatically loaded into all new database connections.
5697 **
5698 ** ^(Even though the function prototype shows that xEntryPoint() takes
5699 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5700 ** arguments and expects and integer result as if the signature of the
5701 ** entry point where as follows:
5702 **
5703 ** <blockquote><pre>
5704 ** &nbsp; int xEntryPoint(
5705 ** &nbsp; sqlite3 *db,
5706 ** &nbsp; const char **pzErrMsg,
5707 ** &nbsp; const struct sqlite3_api_routines *pThunk
5708 ** &nbsp; );
5709 ** </pre></blockquote>)^
5710 **
5711 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5712 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5713 ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
5714 ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
5715 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
5716 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5717 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5718 **
5719 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5720 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5721 ** will be called more than once for each database connection that is opened.
5722 **
5723 ** See also: [sqlite3_reset_auto_extension()]
5724 ** and [sqlite3_cancel_auto_extension()]
5725 */
5726 SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void (*xEntryPoint)(void));
5727
5728 /*
5729 ** CAPI3REF: Cancel Automatic Extension Loading
5730 **
5731 ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
5732 ** initialization routine X that was registered using a prior call to
5733 ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
5734 ** routine returns 1 if initialization routine X was successfully
5735 ** unregistered and it returns 0 if X was not on the list of initialization
5736 ** routines.
5737 */
5738 SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void (*xEntryPoint)( void));
5739
5740 /*
5741 ** CAPI3REF: Reset Automatic Extension Loading
5742 **
5743 ** ^This interface disables all automatic extensions previously
5744 ** registered using [sqlite3_auto_extension()].
5745 */
5746 SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void);
5747
5748 /*
5749 ** The interface to the virtual-table mechanism is currently considered
5750 ** to be experimental. The interface might change in incompatible ways.
5751 ** If this is a problem for you, do not use the interface at this time.
5752 **
5753 ** When the virtual-table mechanism stabilizes, we will declare the
5754 ** interface fixed, support it indefinitely, and remove this comment.
5755 */
5756
5757 /*
5758 ** Structures used by the virtual table interface
5759 */
5760 typedef struct sqlite3_vtab sqlite3_vtab;
5761 typedef struct sqlite3_index_info sqlite3_index_info;
5762 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5763 typedef struct sqlite3_module sqlite3_module;
5764
5765 /*
5766 ** CAPI3REF: Virtual Table Object
5767 ** KEYWORDS: sqlite3_module {virtual table module}
5768 **
5769 ** This structure, sometimes called a "virtual table module",
5770 ** defines the implementation of a [virtual tables].
5771 ** This structure consists mostly of methods for the module.
5772 **
5773 ** ^A virtual table module is created by filling in a persistent
5774 ** instance of this structure and passing a pointer to that instance
5775 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5776 ** ^The registration remains valid until it is replaced by a different
5777 ** module or until the [database connection] closes. The content
5778 ** of this structure must not change while it is registered with
5779 ** any database connection.
5780 */
5781 struct sqlite3_module {
5782 int iVersion;
5783 int (*xCreate)(sqlite3*, void *pAux,
5784 int argc, const char *const*argv,
5785 sqlite3_vtab **ppVTab, char**);
5786 int (*xConnect)(sqlite3*, void *pAux,
5787 int argc, const char *const*argv,
5788 sqlite3_vtab **ppVTab, char**);
5789 int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5790 int (*xDisconnect)(sqlite3_vtab *pVTab);
5791 int (*xDestroy)(sqlite3_vtab *pVTab);
5792 int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5793 int (*xClose)(sqlite3_vtab_cursor*);
5794 int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5795 int argc, sqlite3_value **argv);
5796 int (*xNext)(sqlite3_vtab_cursor*);
5797 int (*xEof)(sqlite3_vtab_cursor*);
5798 int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5799 int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5800 int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5801 int (*xBegin)(sqlite3_vtab *pVTab);
5802 int (*xSync)(sqlite3_vtab *pVTab);
5803 int (*xCommit)(sqlite3_vtab *pVTab);
5804 int (*xRollback)(sqlite3_vtab *pVTab);
5805 int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5806 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5807 void **ppArg);
5808 int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5809 /* The methods above are in version 1 of the sqlite_module object. Those
5810 ** below are for version 2 and greater. */
5811 int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5812 int (*xRelease)(sqlite3_vtab *pVTab, int);
5813 int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5814 };
5815
5816 /*
5817 ** CAPI3REF: Virtual Table Indexing Information
5818 ** KEYWORDS: sqlite3_index_info
5819 **
5820 ** The sqlite3_index_info structure and its substructures is used as part
5821 ** of the [virtual table] interface to
5822 ** pass information into and receive the reply from the [xBestIndex]
5823 ** method of a [virtual table module]. The fields under **Inputs** are the
5824 ** inputs to xBestIndex and are read-only. xBestIndex inserts its
5825 ** results into the **Outputs** fields.
5826 **
5827 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5828 **
5829 ** <blockquote>column OP expr</blockquote>
5830 **
5831 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
5832 ** stored in aConstraint[].op using one of the
5833 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5834 ** ^(The index of the column is stored in
5835 ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
5836 ** expr on the right-hand side can be evaluated (and thus the constraint
5837 ** is usable) and false if it cannot.)^
5838 **
5839 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5840 ** and makes other simplifications to the WHERE clause in an attempt to
5841 ** get as many WHERE clause terms into the form shown above as possible.
5842 ** ^The aConstraint[] array only reports WHERE clause terms that are
5843 ** relevant to the particular virtual table being queried.
5844 **
5845 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5846 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5847 **
5848 ** The colUsed field indicates which columns of the virtual table may be
5849 ** required by the current scan. Virtual table columns are numbered from
5850 ** zero in the order in which they appear within the CREATE TABLE statement
5851 ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
5852 ** the corresponding bit is set within the colUsed mask if the column may be
5853 ** required by SQLite. If the table has at least 64 columns and any column
5854 ** to the right of the first 63 is required, then bit 63 of colUsed is also
5855 ** set. In other words, column iCol may be required if the expression
5856 ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
5857 ** non-zero.
5858 **
5859 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5860 ** about what parameters to pass to xFilter. ^If argvIndex>0 then
5861 ** the right-hand side of the corresponding aConstraint[] is evaluated
5862 ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
5863 ** is true, then the constraint is assumed to be fully handled by the
5864 ** virtual table and is not checked again by SQLite.)^
5865 **
5866 ** ^The idxNum and idxPtr values are recorded and passed into the
5867 ** [xFilter] method.
5868 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5869 ** needToFreeIdxPtr is true.
5870 **
5871 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5872 ** the correct order to satisfy the ORDER BY clause so that no separate
5873 ** sorting step is required.
5874 **
5875 ** ^The estimatedCost value is an estimate of the cost of a particular
5876 ** strategy. A cost of N indicates that the cost of the strategy is similar
5877 ** to a linear scan of an SQLite table with N rows. A cost of log(N)
5878 ** indicates that the expense of the operation is similar to that of a
5879 ** binary search on a unique indexed field of an SQLite table with N rows.
5880 **
5881 ** ^The estimatedRows value is an estimate of the number of rows that
5882 ** will be returned by the strategy.
5883 **
5884 ** The xBestIndex method may optionally populate the idxFlags field with a
5885 ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
5886 ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
5887 ** assumes that the strategy may visit at most one row.
5888 **
5889 ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
5890 ** SQLite also assumes that if a call to the xUpdate() method is made as
5891 ** part of the same statement to delete or update a virtual table row and the
5892 ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
5893 ** any database changes. In other words, if the xUpdate() returns
5894 ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
5895 ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
5896 ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
5897 ** the xUpdate method are automatically rolled back by SQLite.
5898 **
5899 ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
5900 ** structure for SQLite version 3.8.2. If a virtual table extension is
5901 ** used with an SQLite version earlier than 3.8.2, the results of attempting
5902 ** to read or write the estimatedRows field are undefined (but are likely
5903 ** to included crashing the application). The estimatedRows field should
5904 ** therefore only be used if [sqlite3_libversion_number()] returns a
5905 ** value greater than or equal to 3008002. Similarly, the idxFlags field
5906 ** was added for version 3.9.0. It may therefore only be used if
5907 ** sqlite3_libversion_number() returns a value greater than or equal to
5908 ** 3009000.
5909 */
5910 struct sqlite3_index_info {
5911 /* Inputs */
5912 int nConstraint; /* Number of entries in aConstraint */
5913 struct sqlite3_index_constraint {
5914 int iColumn; /* Column on left-hand side of constraint */
5915 unsigned char op; /* Constraint operator */
5916 unsigned char usable; /* True if this constraint is usable */
5917 int iTermOffset; /* Used internally - xBestIndex should ignore */
5918 } *aConstraint; /* Table of WHERE clause constraints */
5919 int nOrderBy; /* Number of terms in the ORDER BY clause */
5920 struct sqlite3_index_orderby {
5921 int iColumn; /* Column number */
5922 unsigned char desc; /* True for DESC. False for ASC. */
5923 } *aOrderBy; /* The ORDER BY clause */
5924 /* Outputs */
5925 struct sqlite3_index_constraint_usage {
5926 int argvIndex; /* if >0, constraint is part of argv to xFilter */
5927 unsigned char omit; /* Do not code a test for this constraint */
5928 } *aConstraintUsage;
5929 int idxNum; /* Number used to identify the index */
5930 char *idxStr; /* String, possibly obtained from sqlite3_malloc */
5931 int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
5932 int orderByConsumed; /* True if output is already ordered */
5933 double estimatedCost; /* Estimated cost of using this index */
5934 /* Fields below are only available in SQLite 3.8.2 and later */
5935 sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
5936 /* Fields below are only available in SQLite 3.9.0 and later */
5937 int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
5938 /* Fields below are only available in SQLite 3.10.0 and later */
5939 sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
5940 };
5941
5942 /*
5943 ** CAPI3REF: Virtual Table Scan Flags
5944 */
5945 #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
5946
5947 /*
5948 ** CAPI3REF: Virtual Table Constraint Operator Codes
5949 **
5950 ** These macros defined the allowed values for the
5951 ** [sqlite3_index_info].aConstraint[].op field. Each value represents
5952 ** an operator that is part of a constraint term in the wHERE clause of
5953 ** a query that uses a [virtual table].
5954 */
5955 #define SQLITE_INDEX_CONSTRAINT_EQ 2
5956 #define SQLITE_INDEX_CONSTRAINT_GT 4
5957 #define SQLITE_INDEX_CONSTRAINT_LE 8
5958 #define SQLITE_INDEX_CONSTRAINT_LT 16
5959 #define SQLITE_INDEX_CONSTRAINT_GE 32
5960 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5961 #define SQLITE_INDEX_CONSTRAINT_LIKE 65
5962 #define SQLITE_INDEX_CONSTRAINT_GLOB 66
5963 #define SQLITE_INDEX_CONSTRAINT_REGEXP 67
5964
5965 /*
5966 ** CAPI3REF: Register A Virtual Table Implementation
5967 ** METHOD: sqlite3
5968 **
5969 ** ^These routines are used to register a new [virtual table module] name.
5970 ** ^Module names must be registered before
5971 ** creating a new [virtual table] using the module and before using a
5972 ** preexisting [virtual table] for the module.
5973 **
5974 ** ^The module name is registered on the [database connection] specified
5975 ** by the first parameter. ^The name of the module is given by the
5976 ** second parameter. ^The third parameter is a pointer to
5977 ** the implementation of the [virtual table module]. ^The fourth
5978 ** parameter is an arbitrary client data pointer that is passed through
5979 ** into the [xCreate] and [xConnect] methods of the virtual table module
5980 ** when a new virtual table is be being created or reinitialized.
5981 **
5982 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5983 ** is a pointer to a destructor for the pClientData. ^SQLite will
5984 ** invoke the destructor function (if it is not NULL) when SQLite
5985 ** no longer needs the pClientData pointer. ^The destructor will also
5986 ** be invoked if the call to sqlite3_create_module_v2() fails.
5987 ** ^The sqlite3_create_module()
5988 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5989 ** destructor.
5990 */
5991 SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
5992 sqlite3 *db, /* SQLite connection to register module with */
5993 const char *zName, /* Name of the module */
5994 const sqlite3_module *p, /* Methods for the module */
5995 void *pClientData /* Client data for xCreate/xConnect */
5996 );
5997 SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
5998 sqlite3 *db, /* SQLite connection to register module with */
5999 const char *zName, /* Name of the module */
6000 const sqlite3_module *p, /* Methods for the module */
6001 void *pClientData, /* Client data for xCreate/xConnect */
6002 void(*xDestroy)(void*) /* Module destructor function */
6003 );
6004
6005 /*
6006 ** CAPI3REF: Virtual Table Instance Object
6007 ** KEYWORDS: sqlite3_vtab
6008 **
6009 ** Every [virtual table module] implementation uses a subclass
6010 ** of this object to describe a particular instance
6011 ** of the [virtual table]. Each subclass will
6012 ** be tailored to the specific needs of the module implementation.
6013 ** The purpose of this superclass is to define certain fields that are
6014 ** common to all module implementations.
6015 **
6016 ** ^Virtual tables methods can set an error message by assigning a
6017 ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
6018 ** take care that any prior string is freed by a call to [sqlite3_free()]
6019 ** prior to assigning a new string to zErrMsg. ^After the error message
6020 ** is delivered up to the client application, the string will be automatically
6021 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
6022 */
6023 struct sqlite3_vtab {
6024 const sqlite3_module *pModule; /* The module for this virtual table */
6025 int nRef; /* Number of open cursors */
6026 char *zErrMsg; /* Error message from sqlite3_mprintf() */
6027 /* Virtual table implementations will typically add additional fields */
6028 };
6029
6030 /*
6031 ** CAPI3REF: Virtual Table Cursor Object
6032 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
6033 **
6034 ** Every [virtual table module] implementation uses a subclass of the
6035 ** following structure to describe cursors that point into the
6036 ** [virtual table] and are used
6037 ** to loop through the virtual table. Cursors are created using the
6038 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
6039 ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
6040 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
6041 ** of the module. Each module implementation will define
6042 ** the content of a cursor structure to suit its own needs.
6043 **
6044 ** This superclass exists in order to define fields of the cursor that
6045 ** are common to all implementations.
6046 */
6047 struct sqlite3_vtab_cursor {
6048 sqlite3_vtab *pVtab; /* Virtual table of this cursor */
6049 /* Virtual table implementations will typically add additional fields */
6050 };
6051
6052 /*
6053 ** CAPI3REF: Declare The Schema Of A Virtual Table
6054 **
6055 ** ^The [xCreate] and [xConnect] methods of a
6056 ** [virtual table module] call this interface
6057 ** to declare the format (the names and datatypes of the columns) of
6058 ** the virtual tables they implement.
6059 */
6060 SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3*, const char *zSQL);
6061
6062 /*
6063 ** CAPI3REF: Overload A Function For A Virtual Table
6064 ** METHOD: sqlite3
6065 **
6066 ** ^(Virtual tables can provide alternative implementations of functions
6067 ** using the [xFindFunction] method of the [virtual table module].
6068 ** But global versions of those functions
6069 ** must exist in order to be overloaded.)^
6070 **
6071 ** ^(This API makes sure a global version of a function with a particular
6072 ** name and number of parameters exists. If no such function exists
6073 ** before this API is called, a new function is created.)^ ^The implementation
6074 ** of the new function always causes an exception to be thrown. So
6075 ** the new function is not good for anything by itself. Its only
6076 ** purpose is to be a placeholder function that can be overloaded
6077 ** by a [virtual table].
6078 */
6079 SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(sqlite3*, const char *zF uncName, int nArg);
6080
6081 /*
6082 ** The interface to the virtual-table mechanism defined above (back up
6083 ** to a comment remarkably similar to this one) is currently considered
6084 ** to be experimental. The interface might change in incompatible ways.
6085 ** If this is a problem for you, do not use the interface at this time.
6086 **
6087 ** When the virtual-table mechanism stabilizes, we will declare the
6088 ** interface fixed, support it indefinitely, and remove this comment.
6089 */
6090
6091 /*
6092 ** CAPI3REF: A Handle To An Open BLOB
6093 ** KEYWORDS: {BLOB handle} {BLOB handles}
6094 **
6095 ** An instance of this object represents an open BLOB on which
6096 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
6097 ** ^Objects of this type are created by [sqlite3_blob_open()]
6098 ** and destroyed by [sqlite3_blob_close()].
6099 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
6100 ** can be used to read or write small subsections of the BLOB.
6101 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
6102 */
6103 typedef struct sqlite3_blob sqlite3_blob;
6104
6105 /*
6106 ** CAPI3REF: Open A BLOB For Incremental I/O
6107 ** METHOD: sqlite3
6108 ** CONSTRUCTOR: sqlite3_blob
6109 **
6110 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
6111 ** in row iRow, column zColumn, table zTable in database zDb;
6112 ** in other words, the same BLOB that would be selected by:
6113 **
6114 ** <pre>
6115 ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
6116 ** </pre>)^
6117 **
6118 ** ^(Parameter zDb is not the filename that contains the database, but
6119 ** rather the symbolic name of the database. For attached databases, this is
6120 ** the name that appears after the AS keyword in the [ATTACH] statement.
6121 ** For the main database file, the database name is "main". For TEMP
6122 ** tables, the database name is "temp".)^
6123 **
6124 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
6125 ** and write access. ^If the flags parameter is zero, the BLOB is opened for
6126 ** read-only access.
6127 **
6128 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
6129 ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
6130 ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
6131 ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
6132 ** on *ppBlob after this function it returns.
6133 **
6134 ** This function fails with SQLITE_ERROR if any of the following are true:
6135 ** <ul>
6136 ** <li> ^(Database zDb does not exist)^,
6137 ** <li> ^(Table zTable does not exist within database zDb)^,
6138 ** <li> ^(Table zTable is a WITHOUT ROWID table)^,
6139 ** <li> ^(Column zColumn does not exist)^,
6140 ** <li> ^(Row iRow is not present in the table)^,
6141 ** <li> ^(The specified column of row iRow contains a value that is not
6142 ** a TEXT or BLOB value)^,
6143 ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
6144 ** constraint and the blob is being opened for read/write access)^,
6145 ** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
6146 ** column zColumn is part of a [child key] definition and the blob is
6147 ** being opened for read/write access)^.
6148 ** </ul>
6149 **
6150 ** ^Unless it returns SQLITE_MISUSE, this function sets the
6151 ** [database connection] error code and message accessible via
6152 ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
6153 **
6154 **
6155 ** ^(If the row that a BLOB handle points to is modified by an
6156 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
6157 ** then the BLOB handle is marked as "expired".
6158 ** This is true if any column of the row is changed, even a column
6159 ** other than the one the BLOB handle is open on.)^
6160 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
6161 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
6162 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
6163 ** rolled back by the expiration of the BLOB. Such changes will eventually
6164 ** commit if the transaction continues to completion.)^
6165 **
6166 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
6167 ** the opened blob. ^The size of a blob may not be changed by this
6168 ** interface. Use the [UPDATE] SQL command to change the size of a
6169 ** blob.
6170 **
6171 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
6172 ** and the built-in [zeroblob] SQL function may be used to create a
6173 ** zero-filled blob to read or write using the incremental-blob interface.
6174 **
6175 ** To avoid a resource leak, every open [BLOB handle] should eventually
6176 ** be released by a call to [sqlite3_blob_close()].
6177 */
6178 SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
6179 sqlite3*,
6180 const char *zDb,
6181 const char *zTable,
6182 const char *zColumn,
6183 sqlite3_int64 iRow,
6184 int flags,
6185 sqlite3_blob **ppBlob
6186 );
6187
6188 /*
6189 ** CAPI3REF: Move a BLOB Handle to a New Row
6190 ** METHOD: sqlite3_blob
6191 **
6192 ** ^This function is used to move an existing blob handle so that it points
6193 ** to a different row of the same database table. ^The new row is identified
6194 ** by the rowid value passed as the second argument. Only the row can be
6195 ** changed. ^The database, table and column on which the blob handle is open
6196 ** remain the same. Moving an existing blob handle to a new row can be
6197 ** faster than closing the existing handle and opening a new one.
6198 **
6199 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
6200 ** it must exist and there must be either a blob or text value stored in
6201 ** the nominated column.)^ ^If the new row is not present in the table, or if
6202 ** it does not contain a blob or text value, or if another error occurs, an
6203 ** SQLite error code is returned and the blob handle is considered aborted.
6204 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
6205 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
6206 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
6207 ** always returns zero.
6208 **
6209 ** ^This function sets the database handle error code and message.
6210 */
6211 SQLITE_API int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64) ;
6212
6213 /*
6214 ** CAPI3REF: Close A BLOB Handle
6215 ** DESTRUCTOR: sqlite3_blob
6216 **
6217 ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
6218 ** unconditionally. Even if this routine returns an error code, the
6219 ** handle is still closed.)^
6220 **
6221 ** ^If the blob handle being closed was opened for read-write access, and if
6222 ** the database is in auto-commit mode and there are no other open read-write
6223 ** blob handles or active write statements, the current transaction is
6224 ** committed. ^If an error occurs while committing the transaction, an error
6225 ** code is returned and the transaction rolled back.
6226 **
6227 ** Calling this function with an argument that is not a NULL pointer or an
6228 ** open blob handle results in undefined behaviour. ^Calling this routine
6229 ** with a null pointer (such as would be returned by a failed call to
6230 ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
6231 ** is passed a valid open blob handle, the values returned by the
6232 ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
6233 */
6234 SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *);
6235
6236 /*
6237 ** CAPI3REF: Return The Size Of An Open BLOB
6238 ** METHOD: sqlite3_blob
6239 **
6240 ** ^Returns the size in bytes of the BLOB accessible via the
6241 ** successfully opened [BLOB handle] in its only argument. ^The
6242 ** incremental blob I/O routines can only read or overwriting existing
6243 ** blob content; they cannot change the size of a blob.
6244 **
6245 ** This routine only works on a [BLOB handle] which has been created
6246 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6247 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
6248 ** to this routine results in undefined and probably undesirable behavior.
6249 */
6250 SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *);
6251
6252 /*
6253 ** CAPI3REF: Read Data From A BLOB Incrementally
6254 ** METHOD: sqlite3_blob
6255 **
6256 ** ^(This function is used to read data from an open [BLOB handle] into a
6257 ** caller-supplied buffer. N bytes of data are copied into buffer Z
6258 ** from the open BLOB, starting at offset iOffset.)^
6259 **
6260 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6261 ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
6262 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
6263 ** ^The size of the blob (and hence the maximum value of N+iOffset)
6264 ** can be determined using the [sqlite3_blob_bytes()] interface.
6265 **
6266 ** ^An attempt to read from an expired [BLOB handle] fails with an
6267 ** error code of [SQLITE_ABORT].
6268 **
6269 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
6270 ** Otherwise, an [error code] or an [extended error code] is returned.)^
6271 **
6272 ** This routine only works on a [BLOB handle] which has been created
6273 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6274 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
6275 ** to this routine results in undefined and probably undesirable behavior.
6276 **
6277 ** See also: [sqlite3_blob_write()].
6278 */
6279 SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6280
6281 /*
6282 ** CAPI3REF: Write Data Into A BLOB Incrementally
6283 ** METHOD: sqlite3_blob
6284 **
6285 ** ^(This function is used to write data into an open [BLOB handle] from a
6286 ** caller-supplied buffer. N bytes of data are copied from the buffer Z
6287 ** into the open BLOB, starting at offset iOffset.)^
6288 **
6289 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
6290 ** Otherwise, an [error code] or an [extended error code] is returned.)^
6291 ** ^Unless SQLITE_MISUSE is returned, this function sets the
6292 ** [database connection] error code and message accessible via
6293 ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
6294 **
6295 ** ^If the [BLOB handle] passed as the first argument was not opened for
6296 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6297 ** this function returns [SQLITE_READONLY].
6298 **
6299 ** This function may only modify the contents of the BLOB; it is
6300 ** not possible to increase the size of a BLOB using this API.
6301 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6302 ** [SQLITE_ERROR] is returned and no data is written. The size of the
6303 ** BLOB (and hence the maximum value of N+iOffset) can be determined
6304 ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
6305 ** than zero [SQLITE_ERROR] is returned and no data is written.
6306 **
6307 ** ^An attempt to write to an expired [BLOB handle] fails with an
6308 ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
6309 ** before the [BLOB handle] expired are not rolled back by the
6310 ** expiration of the handle, though of course those changes might
6311 ** have been overwritten by the statement that expired the BLOB handle
6312 ** or by other independent statements.
6313 **
6314 ** This routine only works on a [BLOB handle] which has been created
6315 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6316 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
6317 ** to this routine results in undefined and probably undesirable behavior.
6318 **
6319 ** See also: [sqlite3_blob_read()].
6320 */
6321 SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6322
6323 /*
6324 ** CAPI3REF: Virtual File System Objects
6325 **
6326 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6327 ** that SQLite uses to interact
6328 ** with the underlying operating system. Most SQLite builds come with a
6329 ** single default VFS that is appropriate for the host computer.
6330 ** New VFSes can be registered and existing VFSes can be unregistered.
6331 ** The following interfaces are provided.
6332 **
6333 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6334 ** ^Names are case sensitive.
6335 ** ^Names are zero-terminated UTF-8 strings.
6336 ** ^If there is no match, a NULL pointer is returned.
6337 ** ^If zVfsName is NULL then the default VFS is returned.
6338 **
6339 ** ^New VFSes are registered with sqlite3_vfs_register().
6340 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
6341 ** ^The same VFS can be registered multiple times without injury.
6342 ** ^To make an existing VFS into the default VFS, register it again
6343 ** with the makeDflt flag set. If two different VFSes with the
6344 ** same name are registered, the behavior is undefined. If a
6345 ** VFS is registered with a name that is NULL or an empty string,
6346 ** then the behavior is undefined.
6347 **
6348 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
6349 ** ^(If the default VFS is unregistered, another VFS is chosen as
6350 ** the default. The choice for the new VFS is arbitrary.)^
6351 */
6352 SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfsName);
6353 SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6354 SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs*);
6355
6356 /*
6357 ** CAPI3REF: Mutexes
6358 **
6359 ** The SQLite core uses these routines for thread
6360 ** synchronization. Though they are intended for internal
6361 ** use by SQLite, code that links against SQLite is
6362 ** permitted to use any of these routines.
6363 **
6364 ** The SQLite source code contains multiple implementations
6365 ** of these mutex routines. An appropriate implementation
6366 ** is selected automatically at compile-time. The following
6367 ** implementations are available in the SQLite core:
6368 **
6369 ** <ul>
6370 ** <li> SQLITE_MUTEX_PTHREADS
6371 ** <li> SQLITE_MUTEX_W32
6372 ** <li> SQLITE_MUTEX_NOOP
6373 ** </ul>
6374 **
6375 ** The SQLITE_MUTEX_NOOP implementation is a set of routines
6376 ** that does no real locking and is appropriate for use in
6377 ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
6378 ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
6379 ** and Windows.
6380 **
6381 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6382 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6383 ** implementation is included with the library. In this case the
6384 ** application must supply a custom mutex implementation using the
6385 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6386 ** before calling sqlite3_initialize() or any other public sqlite3_
6387 ** function that calls sqlite3_initialize().
6388 **
6389 ** ^The sqlite3_mutex_alloc() routine allocates a new
6390 ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
6391 ** routine returns NULL if it is unable to allocate the requested
6392 ** mutex. The argument to sqlite3_mutex_alloc() must one of these
6393 ** integer constants:
6394 **
6395 ** <ul>
6396 ** <li> SQLITE_MUTEX_FAST
6397 ** <li> SQLITE_MUTEX_RECURSIVE
6398 ** <li> SQLITE_MUTEX_STATIC_MASTER
6399 ** <li> SQLITE_MUTEX_STATIC_MEM
6400 ** <li> SQLITE_MUTEX_STATIC_OPEN
6401 ** <li> SQLITE_MUTEX_STATIC_PRNG
6402 ** <li> SQLITE_MUTEX_STATIC_LRU
6403 ** <li> SQLITE_MUTEX_STATIC_PMEM
6404 ** <li> SQLITE_MUTEX_STATIC_APP1
6405 ** <li> SQLITE_MUTEX_STATIC_APP2
6406 ** <li> SQLITE_MUTEX_STATIC_APP3
6407 ** <li> SQLITE_MUTEX_STATIC_VFS1
6408 ** <li> SQLITE_MUTEX_STATIC_VFS2
6409 ** <li> SQLITE_MUTEX_STATIC_VFS3
6410 ** </ul>
6411 **
6412 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6413 ** cause sqlite3_mutex_alloc() to create
6414 ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6415 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6416 ** The mutex implementation does not need to make a distinction
6417 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6418 ** not want to. SQLite will only request a recursive mutex in
6419 ** cases where it really needs one. If a faster non-recursive mutex
6420 ** implementation is available on the host platform, the mutex subsystem
6421 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6422 **
6423 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6424 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6425 ** a pointer to a static preexisting mutex. ^Nine static mutexes are
6426 ** used by the current version of SQLite. Future versions of SQLite
6427 ** may add additional static mutexes. Static mutexes are for internal
6428 ** use by SQLite only. Applications that use SQLite mutexes should
6429 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6430 ** SQLITE_MUTEX_RECURSIVE.
6431 **
6432 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6433 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6434 ** returns a different mutex on every call. ^For the static
6435 ** mutex types, the same mutex is returned on every call that has
6436 ** the same type number.
6437 **
6438 ** ^The sqlite3_mutex_free() routine deallocates a previously
6439 ** allocated dynamic mutex. Attempting to deallocate a static
6440 ** mutex results in undefined behavior.
6441 **
6442 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6443 ** to enter a mutex. ^If another thread is already within the mutex,
6444 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6445 ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6446 ** upon successful entry. ^(Mutexes created using
6447 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6448 ** In such cases, the
6449 ** mutex must be exited an equal number of times before another thread
6450 ** can enter.)^ If the same thread tries to enter any mutex other
6451 ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
6452 **
6453 ** ^(Some systems (for example, Windows 95) do not support the operation
6454 ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
6455 ** will always return SQLITE_BUSY. The SQLite core only ever uses
6456 ** sqlite3_mutex_try() as an optimization so this is acceptable
6457 ** behavior.)^
6458 **
6459 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
6460 ** previously entered by the same thread. The behavior
6461 ** is undefined if the mutex is not currently entered by the
6462 ** calling thread or is not currently allocated.
6463 **
6464 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6465 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6466 ** behave as no-ops.
6467 **
6468 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6469 */
6470 SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int);
6471 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex*);
6472 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex*);
6473 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex*);
6474 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex*);
6475
6476 /*
6477 ** CAPI3REF: Mutex Methods Object
6478 **
6479 ** An instance of this structure defines the low-level routines
6480 ** used to allocate and use mutexes.
6481 **
6482 ** Usually, the default mutex implementations provided by SQLite are
6483 ** sufficient, however the application has the option of substituting a custom
6484 ** implementation for specialized deployments or systems for which SQLite
6485 ** does not provide a suitable implementation. In this case, the application
6486 ** creates and populates an instance of this structure to pass
6487 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6488 ** Additionally, an instance of this structure can be used as an
6489 ** output variable when querying the system for the current mutex
6490 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6491 **
6492 ** ^The xMutexInit method defined by this structure is invoked as
6493 ** part of system initialization by the sqlite3_initialize() function.
6494 ** ^The xMutexInit routine is called by SQLite exactly once for each
6495 ** effective call to [sqlite3_initialize()].
6496 **
6497 ** ^The xMutexEnd method defined by this structure is invoked as
6498 ** part of system shutdown by the sqlite3_shutdown() function. The
6499 ** implementation of this method is expected to release all outstanding
6500 ** resources obtained by the mutex methods implementation, especially
6501 ** those obtained by the xMutexInit method. ^The xMutexEnd()
6502 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6503 **
6504 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6505 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6506 ** xMutexNotheld) implement the following interfaces (respectively):
6507 **
6508 ** <ul>
6509 ** <li> [sqlite3_mutex_alloc()] </li>
6510 ** <li> [sqlite3_mutex_free()] </li>
6511 ** <li> [sqlite3_mutex_enter()] </li>
6512 ** <li> [sqlite3_mutex_try()] </li>
6513 ** <li> [sqlite3_mutex_leave()] </li>
6514 ** <li> [sqlite3_mutex_held()] </li>
6515 ** <li> [sqlite3_mutex_notheld()] </li>
6516 ** </ul>)^
6517 **
6518 ** The only difference is that the public sqlite3_XXX functions enumerated
6519 ** above silently ignore any invocations that pass a NULL pointer instead
6520 ** of a valid mutex handle. The implementations of the methods defined
6521 ** by this structure are not required to handle this case, the results
6522 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6523 ** (i.e. it is acceptable to provide an implementation that segfaults if
6524 ** it is passed a NULL pointer).
6525 **
6526 ** The xMutexInit() method must be threadsafe. It must be harmless to
6527 ** invoke xMutexInit() multiple times within the same process and without
6528 ** intervening calls to xMutexEnd(). Second and subsequent calls to
6529 ** xMutexInit() must be no-ops.
6530 **
6531 ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6532 ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
6533 ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
6534 ** memory allocation for a fast or recursive mutex.
6535 **
6536 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6537 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6538 ** If xMutexInit fails in any way, it is expected to clean up after itself
6539 ** prior to returning.
6540 */
6541 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6542 struct sqlite3_mutex_methods {
6543 int (*xMutexInit)(void);
6544 int (*xMutexEnd)(void);
6545 sqlite3_mutex *(*xMutexAlloc)(int);
6546 void (*xMutexFree)(sqlite3_mutex *);
6547 void (*xMutexEnter)(sqlite3_mutex *);
6548 int (*xMutexTry)(sqlite3_mutex *);
6549 void (*xMutexLeave)(sqlite3_mutex *);
6550 int (*xMutexHeld)(sqlite3_mutex *);
6551 int (*xMutexNotheld)(sqlite3_mutex *);
6552 };
6553
6554 /*
6555 ** CAPI3REF: Mutex Verification Routines
6556 **
6557 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6558 ** are intended for use inside assert() statements. The SQLite core
6559 ** never uses these routines except inside an assert() and applications
6560 ** are advised to follow the lead of the core. The SQLite core only
6561 ** provides implementations for these routines when it is compiled
6562 ** with the SQLITE_DEBUG flag. External mutex implementations
6563 ** are only required to provide these routines if SQLITE_DEBUG is
6564 ** defined and if NDEBUG is not defined.
6565 **
6566 ** These routines should return true if the mutex in their argument
6567 ** is held or not held, respectively, by the calling thread.
6568 **
6569 ** The implementation is not required to provide versions of these
6570 ** routines that actually work. If the implementation does not provide working
6571 ** versions of these routines, it should at least provide stubs that always
6572 ** return true so that one does not get spurious assertion failures.
6573 **
6574 ** If the argument to sqlite3_mutex_held() is a NULL pointer then
6575 ** the routine should return 1. This seems counter-intuitive since
6576 ** clearly the mutex cannot be held if it does not exist. But
6577 ** the reason the mutex does not exist is because the build is not
6578 ** using mutexes. And we do not want the assert() containing the
6579 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6580 ** the appropriate thing to do. The sqlite3_mutex_notheld()
6581 ** interface should also return 1 when given a NULL pointer.
6582 */
6583 #ifndef NDEBUG
6584 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex*);
6585 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex*);
6586 #endif
6587
6588 /*
6589 ** CAPI3REF: Mutex Types
6590 **
6591 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6592 ** which is one of these integer constants.
6593 **
6594 ** The set of static mutexes may change from one SQLite release to the
6595 ** next. Applications that override the built-in mutex logic must be
6596 ** prepared to accommodate additional static mutexes.
6597 */
6598 #define SQLITE_MUTEX_FAST 0
6599 #define SQLITE_MUTEX_RECURSIVE 1
6600 #define SQLITE_MUTEX_STATIC_MASTER 2
6601 #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
6602 #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
6603 #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
6604 #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
6605 #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
6606 #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
6607 #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
6608 #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
6609 #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
6610 #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
6611 #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
6612 #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
6613 #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
6614
6615 /*
6616 ** CAPI3REF: Retrieve the mutex for a database connection
6617 ** METHOD: sqlite3
6618 **
6619 ** ^This interface returns a pointer the [sqlite3_mutex] object that
6620 ** serializes access to the [database connection] given in the argument
6621 ** when the [threading mode] is Serialized.
6622 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6623 ** routine returns a NULL pointer.
6624 */
6625 SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3*);
6626
6627 /*
6628 ** CAPI3REF: Low-Level Control Of Database Files
6629 ** METHOD: sqlite3
6630 **
6631 ** ^The [sqlite3_file_control()] interface makes a direct call to the
6632 ** xFileControl method for the [sqlite3_io_methods] object associated
6633 ** with a particular database identified by the second argument. ^The
6634 ** name of the database is "main" for the main database or "temp" for the
6635 ** TEMP database, or the name that appears after the AS keyword for
6636 ** databases that are added using the [ATTACH] SQL command.
6637 ** ^A NULL pointer can be used in place of "main" to refer to the
6638 ** main database file.
6639 ** ^The third and fourth parameters to this routine
6640 ** are passed directly through to the second and third parameters of
6641 ** the xFileControl method. ^The return value of the xFileControl
6642 ** method becomes the return value of this routine.
6643 **
6644 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6645 ** a pointer to the underlying [sqlite3_file] object to be written into
6646 ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
6647 ** case is a short-circuit path which does not actually invoke the
6648 ** underlying sqlite3_io_methods.xFileControl method.
6649 **
6650 ** ^If the second parameter (zDbName) does not match the name of any
6651 ** open database file, then SQLITE_ERROR is returned. ^This error
6652 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6653 ** or [sqlite3_errmsg()]. The underlying xFileControl method might
6654 ** also return SQLITE_ERROR. There is no way to distinguish between
6655 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6656 ** xFileControl method.
6657 **
6658 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6659 */
6660 SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3*, const char *zDbName , int op, void*);
6661
6662 /*
6663 ** CAPI3REF: Testing Interface
6664 **
6665 ** ^The sqlite3_test_control() interface is used to read out internal
6666 ** state of SQLite and to inject faults into SQLite for testing
6667 ** purposes. ^The first parameter is an operation code that determines
6668 ** the number, meaning, and operation of all subsequent parameters.
6669 **
6670 ** This interface is not for use by applications. It exists solely
6671 ** for verifying the correct operation of the SQLite library. Depending
6672 ** on how the SQLite library is compiled, this interface might not exist.
6673 **
6674 ** The details of the operation codes, their meanings, the parameters
6675 ** they take, and what they do are all subject to change without notice.
6676 ** Unlike most of the SQLite API, this function is not guaranteed to
6677 ** operate consistently from one release to the next.
6678 */
6679 SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...);
6680
6681 /*
6682 ** CAPI3REF: Testing Interface Operation Codes
6683 **
6684 ** These constants are the valid operation code parameters used
6685 ** as the first argument to [sqlite3_test_control()].
6686 **
6687 ** These parameters and their meanings are subject to change
6688 ** without notice. These values are for testing purposes only.
6689 ** Applications should not use any of these parameters or the
6690 ** [sqlite3_test_control()] interface.
6691 */
6692 #define SQLITE_TESTCTRL_FIRST 5
6693 #define SQLITE_TESTCTRL_PRNG_SAVE 5
6694 #define SQLITE_TESTCTRL_PRNG_RESTORE 6
6695 #define SQLITE_TESTCTRL_PRNG_RESET 7
6696 #define SQLITE_TESTCTRL_BITVEC_TEST 8
6697 #define SQLITE_TESTCTRL_FAULT_INSTALL 9
6698 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
6699 #define SQLITE_TESTCTRL_PENDING_BYTE 11
6700 #define SQLITE_TESTCTRL_ASSERT 12
6701 #define SQLITE_TESTCTRL_ALWAYS 13
6702 #define SQLITE_TESTCTRL_RESERVE 14
6703 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
6704 #define SQLITE_TESTCTRL_ISKEYWORD 16
6705 #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
6706 #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
6707 #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
6708 #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
6709 #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
6710 #define SQLITE_TESTCTRL_BYTEORDER 22
6711 #define SQLITE_TESTCTRL_ISINIT 23
6712 #define SQLITE_TESTCTRL_SORTER_MMAP 24
6713 #define SQLITE_TESTCTRL_IMPOSTER 25
6714 #define SQLITE_TESTCTRL_LAST 25
6715
6716 /*
6717 ** CAPI3REF: SQLite Runtime Status
6718 **
6719 ** ^These interfaces are used to retrieve runtime status information
6720 ** about the performance of SQLite, and optionally to reset various
6721 ** highwater marks. ^The first argument is an integer code for
6722 ** the specific parameter to measure. ^(Recognized integer codes
6723 ** are of the form [status parameters | SQLITE_STATUS_...].)^
6724 ** ^The current value of the parameter is returned into *pCurrent.
6725 ** ^The highest recorded value is returned in *pHighwater. ^If the
6726 ** resetFlag is true, then the highest record value is reset after
6727 ** *pHighwater is written. ^(Some parameters do not record the highest
6728 ** value. For those parameters
6729 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
6730 ** ^(Other parameters record only the highwater mark and not the current
6731 ** value. For these latter parameters nothing is written into *pCurrent.)^
6732 **
6733 ** ^The sqlite3_status() and sqlite3_status64() routines return
6734 ** SQLITE_OK on success and a non-zero [error code] on failure.
6735 **
6736 ** If either the current value or the highwater mark is too large to
6737 ** be represented by a 32-bit integer, then the values returned by
6738 ** sqlite3_status() are undefined.
6739 **
6740 ** See also: [sqlite3_db_status()]
6741 */
6742 SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwa ter, int resetFlag);
6743 SQLITE_API int SQLITE_STDCALL sqlite3_status64(
6744 int op,
6745 sqlite3_int64 *pCurrent,
6746 sqlite3_int64 *pHighwater,
6747 int resetFlag
6748 );
6749
6750
6751 /*
6752 ** CAPI3REF: Status Parameters
6753 ** KEYWORDS: {status parameters}
6754 **
6755 ** These integer constants designate various run-time status parameters
6756 ** that can be returned by [sqlite3_status()].
6757 **
6758 ** <dl>
6759 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6760 ** <dd>This parameter is the current amount of memory checked out
6761 ** using [sqlite3_malloc()], either directly or indirectly. The
6762 ** figure includes calls made to [sqlite3_malloc()] by the application
6763 ** and internal memory usage by the SQLite library. Scratch memory
6764 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6765 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6766 ** this parameter. The amount returned is the sum of the allocation
6767 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6768 **
6769 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6770 ** <dd>This parameter records the largest memory allocation request
6771 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6772 ** internal equivalents). Only the value returned in the
6773 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6774 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6775 **
6776 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6777 ** <dd>This parameter records the number of separate memory allocations
6778 ** currently checked out.</dd>)^
6779 **
6780 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6781 ** <dd>This parameter returns the number of pages used out of the
6782 ** [pagecache memory allocator] that was configured using
6783 ** [SQLITE_CONFIG_PAGECACHE]. The
6784 ** value returned is in pages, not in bytes.</dd>)^
6785 **
6786 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
6787 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6788 ** <dd>This parameter returns the number of bytes of page cache
6789 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6790 ** buffer and where forced to overflow to [sqlite3_malloc()]. The
6791 ** returned value includes allocations that overflowed because they
6792 ** where too large (they were larger than the "sz" parameter to
6793 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6794 ** no space was left in the page cache.</dd>)^
6795 **
6796 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6797 ** <dd>This parameter records the largest memory allocation request
6798 ** handed to [pagecache memory allocator]. Only the value returned in the
6799 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6800 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6801 **
6802 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6803 ** <dd>This parameter returns the number of allocations used out of the
6804 ** [scratch memory allocator] configured using
6805 ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
6806 ** in bytes. Since a single thread may only have one scratch allocation
6807 ** outstanding at time, this parameter also reports the number of threads
6808 ** using scratch memory at the same time.</dd>)^
6809 **
6810 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6811 ** <dd>This parameter returns the number of bytes of scratch memory
6812 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6813 ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
6814 ** returned include overflows because the requested allocation was too
6815 ** larger (that is, because the requested allocation was larger than the
6816 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6817 ** slots were available.
6818 ** </dd>)^
6819 **
6820 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6821 ** <dd>This parameter records the largest memory allocation request
6822 ** handed to [scratch memory allocator]. Only the value returned in the
6823 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6824 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6825 **
6826 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6827 ** <dd>The *pHighwater parameter records the deepest parser stack.
6828 ** The *pCurrent value is undefined. The *pHighwater value is only
6829 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6830 ** </dl>
6831 **
6832 ** New status parameters may be added from time to time.
6833 */
6834 #define SQLITE_STATUS_MEMORY_USED 0
6835 #define SQLITE_STATUS_PAGECACHE_USED 1
6836 #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
6837 #define SQLITE_STATUS_SCRATCH_USED 3
6838 #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
6839 #define SQLITE_STATUS_MALLOC_SIZE 5
6840 #define SQLITE_STATUS_PARSER_STACK 6
6841 #define SQLITE_STATUS_PAGECACHE_SIZE 7
6842 #define SQLITE_STATUS_SCRATCH_SIZE 8
6843 #define SQLITE_STATUS_MALLOC_COUNT 9
6844
6845 /*
6846 ** CAPI3REF: Database Connection Status
6847 ** METHOD: sqlite3
6848 **
6849 ** ^This interface is used to retrieve runtime status information
6850 ** about a single [database connection]. ^The first argument is the
6851 ** database connection object to be interrogated. ^The second argument
6852 ** is an integer constant, taken from the set of
6853 ** [SQLITE_DBSTATUS options], that
6854 ** determines the parameter to interrogate. The set of
6855 ** [SQLITE_DBSTATUS options] is likely
6856 ** to grow in future releases of SQLite.
6857 **
6858 ** ^The current value of the requested parameter is written into *pCur
6859 ** and the highest instantaneous value is written into *pHiwtr. ^If
6860 ** the resetFlg is true, then the highest instantaneous value is
6861 ** reset back down to the current value.
6862 **
6863 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6864 ** non-zero [error code] on failure.
6865 **
6866 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6867 */
6868 SQLITE_API int SQLITE_STDCALL sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6869
6870 /*
6871 ** CAPI3REF: Status Parameters for database connections
6872 ** KEYWORDS: {SQLITE_DBSTATUS options}
6873 **
6874 ** These constants are the available integer "verbs" that can be passed as
6875 ** the second argument to the [sqlite3_db_status()] interface.
6876 **
6877 ** New verbs may be added in future releases of SQLite. Existing verbs
6878 ** might be discontinued. Applications should check the return code from
6879 ** [sqlite3_db_status()] to make sure that the call worked.
6880 ** The [sqlite3_db_status()] interface will return a non-zero error code
6881 ** if a discontinued or unsupported verb is invoked.
6882 **
6883 ** <dl>
6884 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6885 ** <dd>This parameter returns the number of lookaside memory slots currently
6886 ** checked out.</dd>)^
6887 **
6888 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6889 ** <dd>This parameter returns the number malloc attempts that were
6890 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6891 ** the current value is always zero.)^
6892 **
6893 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6894 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6895 ** <dd>This parameter returns the number malloc attempts that might have
6896 ** been satisfied using lookaside memory but failed due to the amount of
6897 ** memory requested being larger than the lookaside slot size.
6898 ** Only the high-water value is meaningful;
6899 ** the current value is always zero.)^
6900 **
6901 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6902 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6903 ** <dd>This parameter returns the number malloc attempts that might have
6904 ** been satisfied using lookaside memory but failed due to all lookaside
6905 ** memory already being in use.
6906 ** Only the high-water value is meaningful;
6907 ** the current value is always zero.)^
6908 **
6909 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6910 ** <dd>This parameter returns the approximate number of bytes of heap
6911 ** memory used by all pager caches associated with the database connection.)^
6912 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6913 **
6914 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6915 ** <dd>This parameter returns the approximate number of bytes of heap
6916 ** memory used to store the schema for all databases associated
6917 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
6918 ** ^The full amount of memory used by the schemas is reported, even if the
6919 ** schema memory is shared with other database connections due to
6920 ** [shared cache mode] being enabled.
6921 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6922 **
6923 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6924 ** <dd>This parameter returns the approximate number of bytes of heap
6925 ** and lookaside memory used by all prepared statements associated with
6926 ** the database connection.)^
6927 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6928 ** </dd>
6929 **
6930 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
6931 ** <dd>This parameter returns the number of pager cache hits that have
6932 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
6933 ** is always 0.
6934 ** </dd>
6935 **
6936 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
6937 ** <dd>This parameter returns the number of pager cache misses that have
6938 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
6939 ** is always 0.
6940 ** </dd>
6941 **
6942 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
6943 ** <dd>This parameter returns the number of dirty cache entries that have
6944 ** been written to disk. Specifically, the number of pages written to the
6945 ** wal file in wal mode databases, or the number of pages written to the
6946 ** database file in rollback mode databases. Any pages written as part of
6947 ** transaction rollback or database recovery operations are not included.
6948 ** If an IO or other error occurs while writing a page to disk, the effect
6949 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
6950 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
6951 ** </dd>
6952 **
6953 ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
6954 ** <dd>This parameter returns zero for the current value if and only if
6955 ** all foreign key constraints (deferred or immediate) have been
6956 ** resolved.)^ ^The highwater mark is always 0.
6957 ** </dd>
6958 ** </dl>
6959 */
6960 #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
6961 #define SQLITE_DBSTATUS_CACHE_USED 1
6962 #define SQLITE_DBSTATUS_SCHEMA_USED 2
6963 #define SQLITE_DBSTATUS_STMT_USED 3
6964 #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
6965 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
6966 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
6967 #define SQLITE_DBSTATUS_CACHE_HIT 7
6968 #define SQLITE_DBSTATUS_CACHE_MISS 8
6969 #define SQLITE_DBSTATUS_CACHE_WRITE 9
6970 #define SQLITE_DBSTATUS_DEFERRED_FKS 10
6971 #define SQLITE_DBSTATUS_MAX 10 /* Largest defined DBSTATUS */
6972
6973
6974 /*
6975 ** CAPI3REF: Prepared Statement Status
6976 ** METHOD: sqlite3_stmt
6977 **
6978 ** ^(Each prepared statement maintains various
6979 ** [SQLITE_STMTSTATUS counters] that measure the number
6980 ** of times it has performed specific operations.)^ These counters can
6981 ** be used to monitor the performance characteristics of the prepared
6982 ** statements. For example, if the number of table steps greatly exceeds
6983 ** the number of table searches or result rows, that would tend to indicate
6984 ** that the prepared statement is using a full table scan rather than
6985 ** an index.
6986 **
6987 ** ^(This interface is used to retrieve and reset counter values from
6988 ** a [prepared statement]. The first argument is the prepared statement
6989 ** object to be interrogated. The second argument
6990 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6991 ** to be interrogated.)^
6992 ** ^The current value of the requested counter is returned.
6993 ** ^If the resetFlg is true, then the counter is reset to zero after this
6994 ** interface call returns.
6995 **
6996 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6997 */
6998 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt*, int op,int rese tFlg);
6999
7000 /*
7001 ** CAPI3REF: Status Parameters for prepared statements
7002 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
7003 **
7004 ** These preprocessor macros define integer codes that name counter
7005 ** values associated with the [sqlite3_stmt_status()] interface.
7006 ** The meanings of the various counters are as follows:
7007 **
7008 ** <dl>
7009 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
7010 ** <dd>^This is the number of times that SQLite has stepped forward in
7011 ** a table as part of a full table scan. Large numbers for this counter
7012 ** may indicate opportunities for performance improvement through
7013 ** careful use of indices.</dd>
7014 **
7015 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
7016 ** <dd>^This is the number of sort operations that have occurred.
7017 ** A non-zero value in this counter may indicate an opportunity to
7018 ** improvement performance through careful use of indices.</dd>
7019 **
7020 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
7021 ** <dd>^This is the number of rows inserted into transient indices that
7022 ** were created automatically in order to help joins run faster.
7023 ** A non-zero value in this counter may indicate an opportunity to
7024 ** improvement performance by adding permanent indices that do not
7025 ** need to be reinitialized each time the statement is run.</dd>
7026 **
7027 ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
7028 ** <dd>^This is the number of virtual machine operations executed
7029 ** by the prepared statement if that number is less than or equal
7030 ** to 2147483647. The number of virtual machine operations can be
7031 ** used as a proxy for the total work done by the prepared statement.
7032 ** If the number of virtual machine operations exceeds 2147483647
7033 ** then the value returned by this statement status code is undefined.
7034 ** </dd>
7035 ** </dl>
7036 */
7037 #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
7038 #define SQLITE_STMTSTATUS_SORT 2
7039 #define SQLITE_STMTSTATUS_AUTOINDEX 3
7040 #define SQLITE_STMTSTATUS_VM_STEP 4
7041
7042 /*
7043 ** CAPI3REF: Custom Page Cache Object
7044 **
7045 ** The sqlite3_pcache type is opaque. It is implemented by
7046 ** the pluggable module. The SQLite core has no knowledge of
7047 ** its size or internal structure and never deals with the
7048 ** sqlite3_pcache object except by holding and passing pointers
7049 ** to the object.
7050 **
7051 ** See [sqlite3_pcache_methods2] for additional information.
7052 */
7053 typedef struct sqlite3_pcache sqlite3_pcache;
7054
7055 /*
7056 ** CAPI3REF: Custom Page Cache Object
7057 **
7058 ** The sqlite3_pcache_page object represents a single page in the
7059 ** page cache. The page cache will allocate instances of this
7060 ** object. Various methods of the page cache use pointers to instances
7061 ** of this object as parameters or as their return value.
7062 **
7063 ** See [sqlite3_pcache_methods2] for additional information.
7064 */
7065 typedef struct sqlite3_pcache_page sqlite3_pcache_page;
7066 struct sqlite3_pcache_page {
7067 void *pBuf; /* The content of the page */
7068 void *pExtra; /* Extra information associated with the page */
7069 };
7070
7071 /*
7072 ** CAPI3REF: Application Defined Page Cache.
7073 ** KEYWORDS: {page cache}
7074 **
7075 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
7076 ** register an alternative page cache implementation by passing in an
7077 ** instance of the sqlite3_pcache_methods2 structure.)^
7078 ** In many applications, most of the heap memory allocated by
7079 ** SQLite is used for the page cache.
7080 ** By implementing a
7081 ** custom page cache using this API, an application can better control
7082 ** the amount of memory consumed by SQLite, the way in which
7083 ** that memory is allocated and released, and the policies used to
7084 ** determine exactly which parts of a database file are cached and for
7085 ** how long.
7086 **
7087 ** The alternative page cache mechanism is an
7088 ** extreme measure that is only needed by the most demanding applications.
7089 ** The built-in page cache is recommended for most uses.
7090 **
7091 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
7092 ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
7093 ** the application may discard the parameter after the call to
7094 ** [sqlite3_config()] returns.)^
7095 **
7096 ** [[the xInit() page cache method]]
7097 ** ^(The xInit() method is called once for each effective
7098 ** call to [sqlite3_initialize()])^
7099 ** (usually only once during the lifetime of the process). ^(The xInit()
7100 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
7101 ** The intent of the xInit() method is to set up global data structures
7102 ** required by the custom page cache implementation.
7103 ** ^(If the xInit() method is NULL, then the
7104 ** built-in default page cache is used instead of the application defined
7105 ** page cache.)^
7106 **
7107 ** [[the xShutdown() page cache method]]
7108 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
7109 ** It can be used to clean up
7110 ** any outstanding resources before process shutdown, if required.
7111 ** ^The xShutdown() method may be NULL.
7112 **
7113 ** ^SQLite automatically serializes calls to the xInit method,
7114 ** so the xInit method need not be threadsafe. ^The
7115 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
7116 ** not need to be threadsafe either. All other methods must be threadsafe
7117 ** in multithreaded applications.
7118 **
7119 ** ^SQLite will never invoke xInit() more than once without an intervening
7120 ** call to xShutdown().
7121 **
7122 ** [[the xCreate() page cache methods]]
7123 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
7124 ** SQLite will typically create one cache instance for each open database file,
7125 ** though this is not guaranteed. ^The
7126 ** first parameter, szPage, is the size in bytes of the pages that must
7127 ** be allocated by the cache. ^szPage will always a power of two. ^The
7128 ** second parameter szExtra is a number of bytes of extra storage
7129 ** associated with each page cache entry. ^The szExtra parameter will
7130 ** a number less than 250. SQLite will use the
7131 ** extra szExtra bytes on each page to store metadata about the underlying
7132 ** database page on disk. The value passed into szExtra depends
7133 ** on the SQLite version, the target platform, and how SQLite was compiled.
7134 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
7135 ** created will be used to cache database pages of a file stored on disk, or
7136 ** false if it is used for an in-memory database. The cache implementation
7137 ** does not have to do anything special based with the value of bPurgeable;
7138 ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
7139 ** never invoke xUnpin() except to deliberately delete a page.
7140 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
7141 ** false will always have the "discard" flag set to true.
7142 ** ^Hence, a cache created with bPurgeable false will
7143 ** never contain any unpinned pages.
7144 **
7145 ** [[the xCachesize() page cache method]]
7146 ** ^(The xCachesize() method may be called at any time by SQLite to set the
7147 ** suggested maximum cache-size (number of pages stored by) the cache
7148 ** instance passed as the first argument. This is the value configured using
7149 ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
7150 ** parameter, the implementation is not required to do anything with this
7151 ** value; it is advisory only.
7152 **
7153 ** [[the xPagecount() page cache methods]]
7154 ** The xPagecount() method must return the number of pages currently
7155 ** stored in the cache, both pinned and unpinned.
7156 **
7157 ** [[the xFetch() page cache methods]]
7158 ** The xFetch() method locates a page in the cache and returns a pointer to
7159 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
7160 ** The pBuf element of the returned sqlite3_pcache_page object will be a
7161 ** pointer to a buffer of szPage bytes used to store the content of a
7162 ** single database page. The pExtra element of sqlite3_pcache_page will be
7163 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
7164 ** for each entry in the page cache.
7165 **
7166 ** The page to be fetched is determined by the key. ^The minimum key value
7167 ** is 1. After it has been retrieved using xFetch, the page is considered
7168 ** to be "pinned".
7169 **
7170 ** If the requested page is already in the page cache, then the page cache
7171 ** implementation must return a pointer to the page buffer with its content
7172 ** intact. If the requested page is not already in the cache, then the
7173 ** cache implementation should use the value of the createFlag
7174 ** parameter to help it determined what action to take:
7175 **
7176 ** <table border=1 width=85% align=center>
7177 ** <tr><th> createFlag <th> Behavior when page is not already in cache
7178 ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
7179 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
7180 ** Otherwise return NULL.
7181 ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
7182 ** NULL if allocating a new page is effectively impossible.
7183 ** </table>
7184 **
7185 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
7186 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
7187 ** failed.)^ In between the to xFetch() calls, SQLite may
7188 ** attempt to unpin one or more cache pages by spilling the content of
7189 ** pinned pages to disk and synching the operating system disk cache.
7190 **
7191 ** [[the xUnpin() page cache method]]
7192 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
7193 ** as its second argument. If the third parameter, discard, is non-zero,
7194 ** then the page must be evicted from the cache.
7195 ** ^If the discard parameter is
7196 ** zero, then the page may be discarded or retained at the discretion of
7197 ** page cache implementation. ^The page cache implementation
7198 ** may choose to evict unpinned pages at any time.
7199 **
7200 ** The cache must not perform any reference counting. A single
7201 ** call to xUnpin() unpins the page regardless of the number of prior calls
7202 ** to xFetch().
7203 **
7204 ** [[the xRekey() page cache methods]]
7205 ** The xRekey() method is used to change the key value associated with the
7206 ** page passed as the second argument. If the cache
7207 ** previously contains an entry associated with newKey, it must be
7208 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
7209 ** to be pinned.
7210 **
7211 ** When SQLite calls the xTruncate() method, the cache must discard all
7212 ** existing cache entries with page numbers (keys) greater than or equal
7213 ** to the value of the iLimit parameter passed to xTruncate(). If any
7214 ** of these pages are pinned, they are implicitly unpinned, meaning that
7215 ** they can be safely discarded.
7216 **
7217 ** [[the xDestroy() page cache method]]
7218 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
7219 ** All resources associated with the specified cache should be freed. ^After
7220 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
7221 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
7222 ** functions.
7223 **
7224 ** [[the xShrink() page cache method]]
7225 ** ^SQLite invokes the xShrink() method when it wants the page cache to
7226 ** free up as much of heap memory as possible. The page cache implementation
7227 ** is not obligated to free any memory, but well-behaved implementations should
7228 ** do their best.
7229 */
7230 typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
7231 struct sqlite3_pcache_methods2 {
7232 int iVersion;
7233 void *pArg;
7234 int (*xInit)(void*);
7235 void (*xShutdown)(void*);
7236 sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
7237 void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7238 int (*xPagecount)(sqlite3_pcache*);
7239 sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7240 void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
7241 void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
7242 unsigned oldKey, unsigned newKey);
7243 void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7244 void (*xDestroy)(sqlite3_pcache*);
7245 void (*xShrink)(sqlite3_pcache*);
7246 };
7247
7248 /*
7249 ** This is the obsolete pcache_methods object that has now been replaced
7250 ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
7251 ** retained in the header file for backwards compatibility only.
7252 */
7253 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
7254 struct sqlite3_pcache_methods {
7255 void *pArg;
7256 int (*xInit)(void*);
7257 void (*xShutdown)(void*);
7258 sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
7259 void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7260 int (*xPagecount)(sqlite3_pcache*);
7261 void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7262 void (*xUnpin)(sqlite3_pcache*, void*, int discard);
7263 void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
7264 void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7265 void (*xDestroy)(sqlite3_pcache*);
7266 };
7267
7268
7269 /*
7270 ** CAPI3REF: Online Backup Object
7271 **
7272 ** The sqlite3_backup object records state information about an ongoing
7273 ** online backup operation. ^The sqlite3_backup object is created by
7274 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
7275 ** [sqlite3_backup_finish()].
7276 **
7277 ** See Also: [Using the SQLite Online Backup API]
7278 */
7279 typedef struct sqlite3_backup sqlite3_backup;
7280
7281 /*
7282 ** CAPI3REF: Online Backup API.
7283 **
7284 ** The backup API copies the content of one database into another.
7285 ** It is useful either for creating backups of databases or
7286 ** for copying in-memory databases to or from persistent files.
7287 **
7288 ** See Also: [Using the SQLite Online Backup API]
7289 **
7290 ** ^SQLite holds a write transaction open on the destination database file
7291 ** for the duration of the backup operation.
7292 ** ^The source database is read-locked only while it is being read;
7293 ** it is not locked continuously for the entire backup operation.
7294 ** ^Thus, the backup may be performed on a live source database without
7295 ** preventing other database connections from
7296 ** reading or writing to the source database while the backup is underway.
7297 **
7298 ** ^(To perform a backup operation:
7299 ** <ol>
7300 ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
7301 ** backup,
7302 ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
7303 ** the data between the two databases, and finally
7304 ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
7305 ** associated with the backup operation.
7306 ** </ol>)^
7307 ** There should be exactly one call to sqlite3_backup_finish() for each
7308 ** successful call to sqlite3_backup_init().
7309 **
7310 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
7311 **
7312 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
7313 ** [database connection] associated with the destination database
7314 ** and the database name, respectively.
7315 ** ^The database name is "main" for the main database, "temp" for the
7316 ** temporary database, or the name specified after the AS keyword in
7317 ** an [ATTACH] statement for an attached database.
7318 ** ^The S and M arguments passed to
7319 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
7320 ** and database name of the source database, respectively.
7321 ** ^The source and destination [database connections] (parameters S and D)
7322 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7323 ** an error.
7324 **
7325 ** ^A call to sqlite3_backup_init() will fail, returning SQLITE_ERROR, if
7326 ** there is already a read or read-write transaction open on the
7327 ** destination database.
7328 **
7329 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7330 ** returned and an error code and error message are stored in the
7331 ** destination [database connection] D.
7332 ** ^The error code and message for the failed call to sqlite3_backup_init()
7333 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
7334 ** [sqlite3_errmsg16()] functions.
7335 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
7336 ** [sqlite3_backup] object.
7337 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
7338 ** sqlite3_backup_finish() functions to perform the specified backup
7339 ** operation.
7340 **
7341 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
7342 **
7343 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
7344 ** the source and destination databases specified by [sqlite3_backup] object B.
7345 ** ^If N is negative, all remaining source pages are copied.
7346 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
7347 ** are still more pages to be copied, then the function returns [SQLITE_OK].
7348 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
7349 ** from source to destination, then it returns [SQLITE_DONE].
7350 ** ^If an error occurs while running sqlite3_backup_step(B,N),
7351 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
7352 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
7353 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
7354 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
7355 **
7356 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
7357 ** <ol>
7358 ** <li> the destination database was opened read-only, or
7359 ** <li> the destination database is using write-ahead-log journaling
7360 ** and the destination and source page sizes differ, or
7361 ** <li> the destination database is an in-memory database and the
7362 ** destination and source page sizes differ.
7363 ** </ol>)^
7364 **
7365 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
7366 ** the [sqlite3_busy_handler | busy-handler function]
7367 ** is invoked (if one is specified). ^If the
7368 ** busy-handler returns non-zero before the lock is available, then
7369 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
7370 ** sqlite3_backup_step() can be retried later. ^If the source
7371 ** [database connection]
7372 ** is being used to write to the source database when sqlite3_backup_step()
7373 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
7374 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
7375 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
7376 ** [SQLITE_READONLY] is returned, then
7377 ** there is no point in retrying the call to sqlite3_backup_step(). These
7378 ** errors are considered fatal.)^ The application must accept
7379 ** that the backup operation has failed and pass the backup operation handle
7380 ** to the sqlite3_backup_finish() to release associated resources.
7381 **
7382 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
7383 ** on the destination file. ^The exclusive lock is not released until either
7384 ** sqlite3_backup_finish() is called or the backup operation is complete
7385 ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
7386 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
7387 ** lasts for the duration of the sqlite3_backup_step() call.
7388 ** ^Because the source database is not locked between calls to
7389 ** sqlite3_backup_step(), the source database may be modified mid-way
7390 ** through the backup process. ^If the source database is modified by an
7391 ** external process or via a database connection other than the one being
7392 ** used by the backup operation, then the backup will be automatically
7393 ** restarted by the next call to sqlite3_backup_step(). ^If the source
7394 ** database is modified by the using the same database connection as is used
7395 ** by the backup operation, then the backup database is automatically
7396 ** updated at the same time.
7397 **
7398 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
7399 **
7400 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
7401 ** application wishes to abandon the backup operation, the application
7402 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
7403 ** ^The sqlite3_backup_finish() interfaces releases all
7404 ** resources associated with the [sqlite3_backup] object.
7405 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
7406 ** active write-transaction on the destination database is rolled back.
7407 ** The [sqlite3_backup] object is invalid
7408 ** and may not be used following a call to sqlite3_backup_finish().
7409 **
7410 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
7411 ** sqlite3_backup_step() errors occurred, regardless or whether or not
7412 ** sqlite3_backup_step() completed.
7413 ** ^If an out-of-memory condition or IO error occurred during any prior
7414 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
7415 ** sqlite3_backup_finish() returns the corresponding [error code].
7416 **
7417 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7418 ** is not a permanent error and does not affect the return value of
7419 ** sqlite3_backup_finish().
7420 **
7421 ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
7422 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7423 **
7424 ** ^The sqlite3_backup_remaining() routine returns the number of pages still
7425 ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
7426 ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
7427 ** in the source database at the conclusion of the most recent
7428 ** sqlite3_backup_step().
7429 ** ^(The values returned by these functions are only updated by
7430 ** sqlite3_backup_step(). If the source database is modified in a way that
7431 ** changes the size of the source database or the number of pages remaining,
7432 ** those changes are not reflected in the output of sqlite3_backup_pagecount()
7433 ** and sqlite3_backup_remaining() until after the next
7434 ** sqlite3_backup_step().)^
7435 **
7436 ** <b>Concurrent Usage of Database Handles</b>
7437 **
7438 ** ^The source [database connection] may be used by the application for other
7439 ** purposes while a backup operation is underway or being initialized.
7440 ** ^If SQLite is compiled and configured to support threadsafe database
7441 ** connections, then the source database connection may be used concurrently
7442 ** from within other threads.
7443 **
7444 ** However, the application must guarantee that the destination
7445 ** [database connection] is not passed to any other API (by any thread) after
7446 ** sqlite3_backup_init() is called and before the corresponding call to
7447 ** sqlite3_backup_finish(). SQLite does not currently check to see
7448 ** if the application incorrectly accesses the destination [database connection]
7449 ** and so no error code is reported, but the operations may malfunction
7450 ** nevertheless. Use of the destination database connection while a
7451 ** backup is in progress might also also cause a mutex deadlock.
7452 **
7453 ** If running in [shared cache mode], the application must
7454 ** guarantee that the shared cache used by the destination database
7455 ** is not accessed while the backup is running. In practice this means
7456 ** that the application must guarantee that the disk file being
7457 ** backed up to is not accessed by any connection within the process,
7458 ** not just the specific connection that was passed to sqlite3_backup_init().
7459 **
7460 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
7461 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7462 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7463 ** APIs are not strictly speaking threadsafe. If they are invoked at the
7464 ** same time as another thread is invoking sqlite3_backup_step() it is
7465 ** possible that they return invalid values.
7466 */
7467 SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
7468 sqlite3 *pDest, /* Destination database handle */
7469 const char *zDestName, /* Destination database name */
7470 sqlite3 *pSource, /* Source database handle */
7471 const char *zSourceName /* Source database name */
7472 );
7473 SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage);
7474 SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p);
7475 SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p);
7476 SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p);
7477
7478 /*
7479 ** CAPI3REF: Unlock Notification
7480 ** METHOD: sqlite3
7481 **
7482 ** ^When running in shared-cache mode, a database operation may fail with
7483 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7484 ** individual tables within the shared-cache cannot be obtained. See
7485 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
7486 ** ^This API may be used to register a callback that SQLite will invoke
7487 ** when the connection currently holding the required lock relinquishes it.
7488 ** ^This API is only available if the library was compiled with the
7489 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7490 **
7491 ** See Also: [Using the SQLite Unlock Notification Feature].
7492 **
7493 ** ^Shared-cache locks are released when a database connection concludes
7494 ** its current transaction, either by committing it or rolling it back.
7495 **
7496 ** ^When a connection (known as the blocked connection) fails to obtain a
7497 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7498 ** identity of the database connection (the blocking connection) that
7499 ** has locked the required resource is stored internally. ^After an
7500 ** application receives an SQLITE_LOCKED error, it may call the
7501 ** sqlite3_unlock_notify() method with the blocked connection handle as
7502 ** the first argument to register for a callback that will be invoked
7503 ** when the blocking connections current transaction is concluded. ^The
7504 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7505 ** call that concludes the blocking connections transaction.
7506 **
7507 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7508 ** there is a chance that the blocking connection will have already
7509 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7510 ** If this happens, then the specified callback is invoked immediately,
7511 ** from within the call to sqlite3_unlock_notify().)^
7512 **
7513 ** ^If the blocked connection is attempting to obtain a write-lock on a
7514 ** shared-cache table, and more than one other connection currently holds
7515 ** a read-lock on the same table, then SQLite arbitrarily selects one of
7516 ** the other connections to use as the blocking connection.
7517 **
7518 ** ^(There may be at most one unlock-notify callback registered by a
7519 ** blocked connection. If sqlite3_unlock_notify() is called when the
7520 ** blocked connection already has a registered unlock-notify callback,
7521 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7522 ** called with a NULL pointer as its second argument, then any existing
7523 ** unlock-notify callback is canceled. ^The blocked connections
7524 ** unlock-notify callback may also be canceled by closing the blocked
7525 ** connection using [sqlite3_close()].
7526 **
7527 ** The unlock-notify callback is not reentrant. If an application invokes
7528 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
7529 ** crash or deadlock may be the result.
7530 **
7531 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7532 ** returns SQLITE_OK.
7533 **
7534 ** <b>Callback Invocation Details</b>
7535 **
7536 ** When an unlock-notify callback is registered, the application provides a
7537 ** single void* pointer that is passed to the callback when it is invoked.
7538 ** However, the signature of the callback function allows SQLite to pass
7539 ** it an array of void* context pointers. The first argument passed to
7540 ** an unlock-notify callback is a pointer to an array of void* pointers,
7541 ** and the second is the number of entries in the array.
7542 **
7543 ** When a blocking connections transaction is concluded, there may be
7544 ** more than one blocked connection that has registered for an unlock-notify
7545 ** callback. ^If two or more such blocked connections have specified the
7546 ** same callback function, then instead of invoking the callback function
7547 ** multiple times, it is invoked once with the set of void* context pointers
7548 ** specified by the blocked connections bundled together into an array.
7549 ** This gives the application an opportunity to prioritize any actions
7550 ** related to the set of unblocked database connections.
7551 **
7552 ** <b>Deadlock Detection</b>
7553 **
7554 ** Assuming that after registering for an unlock-notify callback a
7555 ** database waits for the callback to be issued before taking any further
7556 ** action (a reasonable assumption), then using this API may cause the
7557 ** application to deadlock. For example, if connection X is waiting for
7558 ** connection Y's transaction to be concluded, and similarly connection
7559 ** Y is waiting on connection X's transaction, then neither connection
7560 ** will proceed and the system may remain deadlocked indefinitely.
7561 **
7562 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7563 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
7564 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7565 ** unlock-notify callback is registered. The system is said to be in
7566 ** a deadlocked state if connection A has registered for an unlock-notify
7567 ** callback on the conclusion of connection B's transaction, and connection
7568 ** B has itself registered for an unlock-notify callback when connection
7569 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
7570 ** the system is also considered to be deadlocked if connection B has
7571 ** registered for an unlock-notify callback on the conclusion of connection
7572 ** C's transaction, where connection C is waiting on connection A. ^Any
7573 ** number of levels of indirection are allowed.
7574 **
7575 ** <b>The "DROP TABLE" Exception</b>
7576 **
7577 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
7578 ** always appropriate to call sqlite3_unlock_notify(). There is however,
7579 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7580 ** SQLite checks if there are any currently executing SELECT statements
7581 ** that belong to the same connection. If there are, SQLITE_LOCKED is
7582 ** returned. In this case there is no "blocking connection", so invoking
7583 ** sqlite3_unlock_notify() results in the unlock-notify callback being
7584 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
7585 ** or "DROP INDEX" query, an infinite loop might be the result.
7586 **
7587 ** One way around this problem is to check the extended error code returned
7588 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7589 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7590 ** the special "DROP TABLE/INDEX" case, the extended error code is just
7591 ** SQLITE_LOCKED.)^
7592 */
7593 SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
7594 sqlite3 *pBlocked, /* Waiting connection */
7595 void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
7596 void *pNotifyArg /* Argument to pass to xNotify */
7597 );
7598
7599
7600 /*
7601 ** CAPI3REF: String Comparison
7602 **
7603 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7604 ** and extensions to compare the contents of two buffers containing UTF-8
7605 ** strings in a case-independent fashion, using the same definition of "case
7606 ** independence" that SQLite uses internally when comparing identifiers.
7607 */
7608 SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *, const char *);
7609 SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *, const char *, int);
7610
7611 /*
7612 ** CAPI3REF: String Globbing
7613 *
7614 ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
7615 ** string X matches the [GLOB] pattern P.
7616 ** ^The definition of [GLOB] pattern matching used in
7617 ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
7618 ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
7619 ** is case sensitive.
7620 **
7621 ** Note that this routine returns zero on a match and non-zero if the strings
7622 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7623 **
7624 ** See also: [sqlite3_strlike()].
7625 */
7626 SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlob, const char *zSt r);
7627
7628 /* Begin recover virtual table patch for Chromium */
7629 /* Our patches don't conform to SQLite's amalgamation processing. Hack it. */
7630 #ifndef CHROMIUM_SQLITE_API
7631 #define CHROMIUM_SQLITE_API SQLITE_API
7632 #endif
7633 /*
7634 ** Call to initialize the recover virtual-table modules (see recover.c).
7635 **
7636 ** This could be loaded by default in main.c, but that would make the
7637 ** virtual table available to Web SQL. Breaking it out allows only
7638 ** selected users to enable it (currently sql/recovery.cc).
7639 */
7640 CHROMIUM_SQLITE_API
7641 int recoverVtableInit(sqlite3 *db);
7642 /* End recover virtual table patch for Chromium */
7643
7644 /* Begin WebDatabase patch for Chromium */
7645 /* Expose some SQLite internals for the WebDatabase vfs.
7646 ** DO NOT EXTEND THE USE OF THIS.
7647 */
7648 #ifndef CHROMIUM_SQLITE_API
7649 #define CHROMIUM_SQLITE_API SQLITE_API
7650 #endif
7651 #if defined(CHROMIUM_SQLITE_INTERNALS)
7652 #ifdef _WIN32
7653 CHROMIUM_SQLITE_API
7654 void chromium_sqlite3_initialize_win_sqlite3_file(sqlite3_file* file, HANDLE han dle);
7655 #else /* _WIN32 */
7656 CHROMIUM_SQLITE_API
7657 int chromium_sqlite3_fill_in_unix_sqlite3_file(sqlite3_vfs* pVfs,
7658 int fd,
7659 sqlite3_file* pFile,
7660 const char* zPath,
7661 int noLock,
7662 int flags);
7663 #endif /* _WIN32 */
7664 #endif /* CHROMIUM_SQLITE_INTERNALS */
7665 /* End WebDatabase patch for Chromium */
7666
7667 /*
7668 ** CAPI3REF: String LIKE Matching
7669 *
7670 ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
7671 ** string X matches the [LIKE] pattern P with escape character E.
7672 ** ^The definition of [LIKE] pattern matching used in
7673 ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
7674 ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
7675 ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
7676 ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
7677 ** insensitive - equivalent upper and lower case ASCII characters match
7678 ** one another.
7679 **
7680 ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
7681 ** only ASCII characters are case folded.
7682 **
7683 ** Note that this routine returns zero on a match and non-zero if the strings
7684 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7685 **
7686 ** See also: [sqlite3_strglob()].
7687 */
7688 SQLITE_API int SQLITE_STDCALL sqlite3_strlike(const char *zGlob, const char *zSt r, unsigned int cEsc);
7689
7690 /*
7691 ** CAPI3REF: Error Logging Interface
7692 **
7693 ** ^The [sqlite3_log()] interface writes a message into the [error log]
7694 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7695 ** ^If logging is enabled, the zFormat string and subsequent arguments are
7696 ** used with [sqlite3_snprintf()] to generate the final output string.
7697 **
7698 ** The sqlite3_log() interface is intended for use by extensions such as
7699 ** virtual tables, collating functions, and SQL functions. While there is
7700 ** nothing to prevent an application from calling sqlite3_log(), doing so
7701 ** is considered bad form.
7702 **
7703 ** The zFormat string must not be NULL.
7704 **
7705 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7706 ** will not use dynamically allocated memory. The log message is stored in
7707 ** a fixed-length buffer on the stack. If the log message is longer than
7708 ** a few hundred characters, it will be truncated to the length of the
7709 ** buffer.
7710 */
7711 SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...) ;
7712
7713 /*
7714 ** CAPI3REF: Write-Ahead Log Commit Hook
7715 ** METHOD: sqlite3
7716 **
7717 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
7718 ** is invoked each time data is committed to a database in wal mode.
7719 **
7720 ** ^(The callback is invoked by SQLite after the commit has taken place and
7721 ** the associated write-lock on the database released)^, so the implementation
7722 ** may read, write or [checkpoint] the database as required.
7723 **
7724 ** ^The first parameter passed to the callback function when it is invoked
7725 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
7726 ** registering the callback. ^The second is a copy of the database handle.
7727 ** ^The third parameter is the name of the database that was written to -
7728 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7729 ** is the number of pages currently in the write-ahead log file,
7730 ** including those that were just committed.
7731 **
7732 ** The callback function should normally return [SQLITE_OK]. ^If an error
7733 ** code is returned, that error will propagate back up through the
7734 ** SQLite code base to cause the statement that provoked the callback
7735 ** to report an error, though the commit will have still occurred. If the
7736 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7737 ** that does not correspond to any valid SQLite error code, the results
7738 ** are undefined.
7739 **
7740 ** A single database handle may have at most a single write-ahead log callback
7741 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7742 ** previously registered write-ahead log callback. ^Note that the
7743 ** [sqlite3_wal_autocheckpoint()] interface and the
7744 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7745 ** those overwrite any prior [sqlite3_wal_hook()] settings.
7746 */
7747 SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
7748 sqlite3*,
7749 int(*)(void *,sqlite3*,const char*,int),
7750 void*
7751 );
7752
7753 /*
7754 ** CAPI3REF: Configure an auto-checkpoint
7755 ** METHOD: sqlite3
7756 **
7757 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7758 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
7759 ** to automatically [checkpoint]
7760 ** after committing a transaction if there are N or
7761 ** more frames in the [write-ahead log] file. ^Passing zero or
7762 ** a negative value as the nFrame parameter disables automatic
7763 ** checkpoints entirely.
7764 **
7765 ** ^The callback registered by this function replaces any existing callback
7766 ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
7767 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7768 ** configured by this function.
7769 **
7770 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7771 ** from SQL.
7772 **
7773 ** ^Checkpoints initiated by this mechanism are
7774 ** [sqlite3_wal_checkpoint_v2|PASSIVE].
7775 **
7776 ** ^Every new [database connection] defaults to having the auto-checkpoint
7777 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7778 ** pages. The use of this interface
7779 ** is only necessary if the default setting is found to be suboptimal
7780 ** for a particular application.
7781 */
7782 SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7783
7784 /*
7785 ** CAPI3REF: Checkpoint a database
7786 ** METHOD: sqlite3
7787 **
7788 ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
7789 ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
7790 **
7791 ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
7792 ** [write-ahead log] for database X on [database connection] D to be
7793 ** transferred into the database file and for the write-ahead log to
7794 ** be reset. See the [checkpointing] documentation for addition
7795 ** information.
7796 **
7797 ** This interface used to be the only way to cause a checkpoint to
7798 ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
7799 ** interface was added. This interface is retained for backwards
7800 ** compatibility and as a convenience for applications that need to manually
7801 ** start a callback but which do not need the full power (and corresponding
7802 ** complication) of [sqlite3_wal_checkpoint_v2()].
7803 */
7804 SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zD b);
7805
7806 /*
7807 ** CAPI3REF: Checkpoint a database
7808 ** METHOD: sqlite3
7809 **
7810 ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
7811 ** operation on database X of [database connection] D in mode M. Status
7812 ** information is written back into integers pointed to by L and C.)^
7813 ** ^(The M parameter must be a valid [checkpoint mode]:)^
7814 **
7815 ** <dl>
7816 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7817 ** ^Checkpoint as many frames as possible without waiting for any database
7818 ** readers or writers to finish, then sync the database file if all frames
7819 ** in the log were checkpointed. ^The [busy-handler callback]
7820 ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
7821 ** ^On the other hand, passive mode might leave the checkpoint unfinished
7822 ** if there are concurrent readers or writers.
7823 **
7824 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
7825 ** ^This mode blocks (it invokes the
7826 ** [sqlite3_busy_handler|busy-handler callback]) until there is no
7827 ** database writer and all readers are reading from the most recent database
7828 ** snapshot. ^It then checkpoints all frames in the log file and syncs the
7829 ** database file. ^This mode blocks new database writers while it is pending,
7830 ** but new database readers are allowed to continue unimpeded.
7831 **
7832 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7833 ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
7834 ** that after checkpointing the log file it blocks (calls the
7835 ** [busy-handler callback])
7836 ** until all readers are reading from the database file only. ^This ensures
7837 ** that the next writer will restart the log file from the beginning.
7838 ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
7839 ** database writer attempts while it is pending, but does not impede readers.
7840 **
7841 ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
7842 ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
7843 ** addition that it also truncates the log file to zero bytes just prior
7844 ** to a successful return.
7845 ** </dl>
7846 **
7847 ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
7848 ** the log file or to -1 if the checkpoint could not run because
7849 ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
7850 ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
7851 ** log file (including any that were already checkpointed before the function
7852 ** was called) or to -1 if the checkpoint could not run due to an error or
7853 ** because the database is not in WAL mode. ^Note that upon successful
7854 ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
7855 ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
7856 **
7857 ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
7858 ** any other process is running a checkpoint operation at the same time, the
7859 ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
7860 ** busy-handler configured, it will not be invoked in this case.
7861 **
7862 ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
7863 ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
7864 ** obtained immediately, and a busy-handler is configured, it is invoked and
7865 ** the writer lock retried until either the busy-handler returns 0 or the lock
7866 ** is successfully obtained. ^The busy-handler is also invoked while waiting for
7867 ** database readers as described above. ^If the busy-handler returns 0 before
7868 ** the writer lock is obtained or while waiting for database readers, the
7869 ** checkpoint operation proceeds from that point in the same way as
7870 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
7871 ** without blocking any further. ^SQLITE_BUSY is returned in this case.
7872 **
7873 ** ^If parameter zDb is NULL or points to a zero length string, then the
7874 ** specified operation is attempted on all WAL databases [attached] to
7875 ** [database connection] db. In this case the
7876 ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
7877 ** an SQLITE_BUSY error is encountered when processing one or more of the
7878 ** attached WAL databases, the operation is still attempted on any remaining
7879 ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
7880 ** error occurs while processing an attached database, processing is abandoned
7881 ** and the error code is returned to the caller immediately. ^If no error
7882 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
7883 ** databases, SQLITE_OK is returned.
7884 **
7885 ** ^If database zDb is the name of an attached database that is not in WAL
7886 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
7887 ** zDb is not NULL (or a zero length string) and is not the name of any
7888 ** attached database, SQLITE_ERROR is returned to the caller.
7889 **
7890 ** ^Unless it returns SQLITE_MISUSE,
7891 ** the sqlite3_wal_checkpoint_v2() interface
7892 ** sets the error information that is queried by
7893 ** [sqlite3_errcode()] and [sqlite3_errmsg()].
7894 **
7895 ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
7896 ** from SQL.
7897 */
7898 SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
7899 sqlite3 *db, /* Database handle */
7900 const char *zDb, /* Name of attached database (or NULL) */
7901 int eMode, /* SQLITE_CHECKPOINT_* value */
7902 int *pnLog, /* OUT: Size of WAL log in frames */
7903 int *pnCkpt /* OUT: Total number of frames checkpointed */
7904 );
7905
7906 /*
7907 ** CAPI3REF: Checkpoint Mode Values
7908 ** KEYWORDS: {checkpoint mode}
7909 **
7910 ** These constants define all valid values for the "checkpoint mode" passed
7911 ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
7912 ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
7913 ** meaning of each of these checkpoint modes.
7914 */
7915 #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
7916 #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
7917 #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
7918 #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
7919
7920 /*
7921 ** CAPI3REF: Virtual Table Interface Configuration
7922 **
7923 ** This function may be called by either the [xConnect] or [xCreate] method
7924 ** of a [virtual table] implementation to configure
7925 ** various facets of the virtual table interface.
7926 **
7927 ** If this interface is invoked outside the context of an xConnect or
7928 ** xCreate virtual table method then the behavior is undefined.
7929 **
7930 ** At present, there is only one option that may be configured using
7931 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
7932 ** may be added in the future.
7933 */
7934 SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3*, int op, ...);
7935
7936 /*
7937 ** CAPI3REF: Virtual Table Configuration Options
7938 **
7939 ** These macros define the various options to the
7940 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
7941 ** can use to customize and optimize their behavior.
7942 **
7943 ** <dl>
7944 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7945 ** <dd>Calls of the form
7946 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7947 ** where X is an integer. If X is zero, then the [virtual table] whose
7948 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7949 ** support constraints. In this configuration (which is the default) if
7950 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7951 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7952 ** specified as part of the users SQL statement, regardless of the actual
7953 ** ON CONFLICT mode specified.
7954 **
7955 ** If X is non-zero, then the virtual table implementation guarantees
7956 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7957 ** any modifications to internal or persistent data structures have been made.
7958 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
7959 ** is able to roll back a statement or database transaction, and abandon
7960 ** or continue processing the current SQL statement as appropriate.
7961 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7962 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7963 ** had been ABORT.
7964 **
7965 ** Virtual table implementations that are required to handle OR REPLACE
7966 ** must do so within the [xUpdate] method. If a call to the
7967 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
7968 ** CONFLICT policy is REPLACE, the virtual table implementation should
7969 ** silently replace the appropriate rows within the xUpdate callback and
7970 ** return SQLITE_OK. Or, if this is not possible, it may return
7971 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
7972 ** constraint handling.
7973 ** </dl>
7974 */
7975 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7976
7977 /*
7978 ** CAPI3REF: Determine The Virtual Table Conflict Policy
7979 **
7980 ** This function may only be called from within a call to the [xUpdate] method
7981 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7982 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7983 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7984 ** of the SQL statement that triggered the call to the [xUpdate] method of the
7985 ** [virtual table].
7986 */
7987 SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *);
7988
7989 /*
7990 ** CAPI3REF: Conflict resolution modes
7991 ** KEYWORDS: {conflict resolution mode}
7992 **
7993 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
7994 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
7995 ** is for the SQL statement being evaluated.
7996 **
7997 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
7998 ** return value from the [sqlite3_set_authorizer()] callback and that
7999 ** [SQLITE_ABORT] is also a [result code].
8000 */
8001 #define SQLITE_ROLLBACK 1
8002 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
8003 #define SQLITE_FAIL 3
8004 /* #define SQLITE_ABORT 4 // Also an error code */
8005 #define SQLITE_REPLACE 5
8006
8007 /*
8008 ** CAPI3REF: Prepared Statement Scan Status Opcodes
8009 ** KEYWORDS: {scanstatus options}
8010 **
8011 ** The following constants can be used for the T parameter to the
8012 ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
8013 ** different metric for sqlite3_stmt_scanstatus() to return.
8014 **
8015 ** When the value returned to V is a string, space to hold that string is
8016 ** managed by the prepared statement S and will be automatically freed when
8017 ** S is finalized.
8018 **
8019 ** <dl>
8020 ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
8021 ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
8022 ** set to the total number of times that the X-th loop has run.</dd>
8023 **
8024 ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
8025 ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
8026 ** to the total number of rows examined by all iterations of the X-th loop.</dd>
8027 **
8028 ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
8029 ** <dd>^The "double" variable pointed to by the T parameter will be set to the
8030 ** query planner's estimate for the average number of rows output from each
8031 ** iteration of the X-th loop. If the query planner's estimates was accurate,
8032 ** then this value will approximate the quotient NVISIT/NLOOP and the
8033 ** product of this value for all prior loops with the same SELECTID will
8034 ** be the NLOOP value for the current loop.
8035 **
8036 ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
8037 ** <dd>^The "const char *" variable pointed to by the T parameter will be set
8038 ** to a zero-terminated UTF-8 string containing the name of the index or table
8039 ** used for the X-th loop.
8040 **
8041 ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
8042 ** <dd>^The "const char *" variable pointed to by the T parameter will be set
8043 ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
8044 ** description for the X-th loop.
8045 **
8046 ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
8047 ** <dd>^The "int" variable pointed to by the T parameter will be set to the
8048 ** "select-id" for the X-th loop. The select-id identifies which query or
8049 ** subquery the loop is part of. The main query has a select-id of zero.
8050 ** The select-id is the same value as is output in the first column
8051 ** of an [EXPLAIN QUERY PLAN] query.
8052 ** </dl>
8053 */
8054 #define SQLITE_SCANSTAT_NLOOP 0
8055 #define SQLITE_SCANSTAT_NVISIT 1
8056 #define SQLITE_SCANSTAT_EST 2
8057 #define SQLITE_SCANSTAT_NAME 3
8058 #define SQLITE_SCANSTAT_EXPLAIN 4
8059 #define SQLITE_SCANSTAT_SELECTID 5
8060
8061 /*
8062 ** CAPI3REF: Prepared Statement Scan Status
8063 ** METHOD: sqlite3_stmt
8064 **
8065 ** This interface returns information about the predicted and measured
8066 ** performance for pStmt. Advanced applications can use this
8067 ** interface to compare the predicted and the measured performance and
8068 ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
8069 **
8070 ** Since this interface is expected to be rarely used, it is only
8071 ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
8072 ** compile-time option.
8073 **
8074 ** The "iScanStatusOp" parameter determines which status information to return.
8075 ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
8076 ** of this interface is undefined.
8077 ** ^The requested measurement is written into a variable pointed to by
8078 ** the "pOut" parameter.
8079 ** Parameter "idx" identifies the specific loop to retrieve statistics for.
8080 ** Loops are numbered starting from zero. ^If idx is out of range - less than
8081 ** zero or greater than or equal to the total number of loops used to implement
8082 ** the statement - a non-zero value is returned and the variable that pOut
8083 ** points to is unchanged.
8084 **
8085 ** ^Statistics might not be available for all loops in all statements. ^In cases
8086 ** where there exist loops with no available statistics, this function behaves
8087 ** as if the loop did not exist - it returns non-zero and leave the variable
8088 ** that pOut points to unchanged.
8089 **
8090 ** See also: [sqlite3_stmt_scanstatus_reset()]
8091 */
8092 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
8093 sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
8094 int idx, /* Index of loop to report on */
8095 int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
8096 void *pOut /* Result written here */
8097 );
8098
8099 /*
8100 ** CAPI3REF: Zero Scan-Status Counters
8101 ** METHOD: sqlite3_stmt
8102 **
8103 ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
8104 **
8105 ** This API is only available if the library is built with pre-processor
8106 ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
8107 */
8108 SQLITE_API void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
8109
8110 /*
8111 ** CAPI3REF: Flush caches to disk mid-transaction
8112 **
8113 ** ^If a write-transaction is open on [database connection] D when the
8114 ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
8115 ** pages in the pager-cache that are not currently in use are written out
8116 ** to disk. A dirty page may be in use if a database cursor created by an
8117 ** active SQL statement is reading from it, or if it is page 1 of a database
8118 ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
8119 ** interface flushes caches for all schemas - "main", "temp", and
8120 ** any [attached] databases.
8121 **
8122 ** ^If this function needs to obtain extra database locks before dirty pages
8123 ** can be flushed to disk, it does so. ^If those locks cannot be obtained
8124 ** immediately and there is a busy-handler callback configured, it is invoked
8125 ** in the usual manner. ^If the required lock still cannot be obtained, then
8126 ** the database is skipped and an attempt made to flush any dirty pages
8127 ** belonging to the next (if any) database. ^If any databases are skipped
8128 ** because locks cannot be obtained, but no other error occurs, this
8129 ** function returns SQLITE_BUSY.
8130 **
8131 ** ^If any other error occurs while flushing dirty pages to disk (for
8132 ** example an IO error or out-of-memory condition), then processing is
8133 ** abandoned and an SQLite [error code] is returned to the caller immediately.
8134 **
8135 ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
8136 **
8137 ** ^This function does not set the database handle error code or message
8138 ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
8139 */
8140 SQLITE_API int SQLITE_STDCALL sqlite3_db_cacheflush(sqlite3*);
8141
8142 /*
8143 ** CAPI3REF: Database Snapshot
8144 ** KEYWORDS: {snapshot}
8145 ** EXPERIMENTAL
8146 **
8147 ** An instance of the snapshot object records the state of a [WAL mode]
8148 ** database for some specific point in history.
8149 **
8150 ** In [WAL mode], multiple [database connections] that are open on the
8151 ** same database file can each be reading a different historical version
8152 ** of the database file. When a [database connection] begins a read
8153 ** transaction, that connection sees an unchanging copy of the database
8154 ** as it existed for the point in time when the transaction first started.
8155 ** Subsequent changes to the database from other connections are not seen
8156 ** by the reader until a new read transaction is started.
8157 **
8158 ** The sqlite3_snapshot object records state information about an historical
8159 ** version of the database file so that it is possible to later open a new read
8160 ** transaction that sees that historical version of the database rather than
8161 ** the most recent version.
8162 **
8163 ** The constructor for this object is [sqlite3_snapshot_get()]. The
8164 ** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer
8165 ** to an historical snapshot (if possible). The destructor for
8166 ** sqlite3_snapshot objects is [sqlite3_snapshot_free()].
8167 */
8168 typedef struct sqlite3_snapshot sqlite3_snapshot;
8169
8170 /*
8171 ** CAPI3REF: Record A Database Snapshot
8172 ** EXPERIMENTAL
8173 **
8174 ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
8175 ** new [sqlite3_snapshot] object that records the current state of
8176 ** schema S in database connection D. ^On success, the
8177 ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
8178 ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
8179 ** ^If schema S of [database connection] D is not a [WAL mode] database
8180 ** that is in a read transaction, then [sqlite3_snapshot_get(D,S,P)]
8181 ** leaves the *P value unchanged and returns an appropriate [error code].
8182 **
8183 ** The [sqlite3_snapshot] object returned from a successful call to
8184 ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
8185 ** to avoid a memory leak.
8186 **
8187 ** The [sqlite3_snapshot_get()] interface is only available when the
8188 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8189 */
8190 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_snapshot_get(
8191 sqlite3 *db,
8192 const char *zSchema,
8193 sqlite3_snapshot **ppSnapshot
8194 );
8195
8196 /*
8197 ** CAPI3REF: Start a read transaction on an historical snapshot
8198 ** EXPERIMENTAL
8199 **
8200 ** ^The [sqlite3_snapshot_open(D,S,P)] interface attempts to move the
8201 ** read transaction that is currently open on schema S of
8202 ** [database connection] D so that it refers to historical [snapshot] P.
8203 ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
8204 ** or an appropriate [error code] if it fails.
8205 **
8206 ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
8207 ** the first operation, apart from other sqlite3_snapshot_open() calls,
8208 ** following the [BEGIN] that starts a new read transaction.
8209 ** ^A [snapshot] will fail to open if it has been overwritten by a
8210 ** [checkpoint].
8211 **
8212 ** The [sqlite3_snapshot_open()] interface is only available when the
8213 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8214 */
8215 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_snapshot_open(
8216 sqlite3 *db,
8217 const char *zSchema,
8218 sqlite3_snapshot *pSnapshot
8219 );
8220
8221 /*
8222 ** CAPI3REF: Destroy a snapshot
8223 ** EXPERIMENTAL
8224 **
8225 ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
8226 ** The application must eventually free every [sqlite3_snapshot] object
8227 ** using this routine to avoid a memory leak.
8228 **
8229 ** The [sqlite3_snapshot_free()] interface is only available when the
8230 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8231 */
8232 SQLITE_API SQLITE_EXPERIMENTAL void SQLITE_STDCALL sqlite3_snapshot_free(sqlite3 _snapshot*);
8233
8234 /*
8235 ** Undo the hack that converts floating point types to integer for
8236 ** builds on processors without floating point support.
8237 */
8238 #ifdef SQLITE_OMIT_FLOATING_POINT
8239 # undef double
8240 #endif
8241
8242 #if 0
8243 } /* End of the 'extern "C"' block */
8244 #endif
8245 #endif /* _SQLITE3_H_ */
8246
8247 /*
8248 ** 2010 August 30
8249 **
8250 ** The author disclaims copyright to this source code. In place of
8251 ** a legal notice, here is a blessing:
8252 **
8253 ** May you do good and not evil.
8254 ** May you find forgiveness for yourself and forgive others.
8255 ** May you share freely, never taking more than you give.
8256 **
8257 *************************************************************************
8258 */
8259
8260 #ifndef _SQLITE3RTREE_H_
8261 #define _SQLITE3RTREE_H_
8262
8263
8264 #if 0
8265 extern "C" {
8266 #endif
8267
8268 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
8269 typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
8270
8271 /* The double-precision datatype used by RTree depends on the
8272 ** SQLITE_RTREE_INT_ONLY compile-time option.
8273 */
8274 #ifdef SQLITE_RTREE_INT_ONLY
8275 typedef sqlite3_int64 sqlite3_rtree_dbl;
8276 #else
8277 typedef double sqlite3_rtree_dbl;
8278 #endif
8279
8280 /*
8281 ** Register a geometry callback named zGeom that can be used as part of an
8282 ** R-Tree geometry query as follows:
8283 **
8284 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
8285 */
8286 SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
8287 sqlite3 *db,
8288 const char *zGeom,
8289 int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
8290 void *pContext
8291 );
8292
8293
8294 /*
8295 ** A pointer to a structure of the following type is passed as the first
8296 ** argument to callbacks registered using rtree_geometry_callback().
8297 */
8298 struct sqlite3_rtree_geometry {
8299 void *pContext; /* Copy of pContext passed to s_r_g_c() */
8300 int nParam; /* Size of array aParam[] */
8301 sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
8302 void *pUser; /* Callback implementation user data */
8303 void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
8304 };
8305
8306 /*
8307 ** Register a 2nd-generation geometry callback named zScore that can be
8308 ** used as part of an R-Tree geometry query as follows:
8309 **
8310 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
8311 */
8312 SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
8313 sqlite3 *db,
8314 const char *zQueryFunc,
8315 int (*xQueryFunc)(sqlite3_rtree_query_info*),
8316 void *pContext,
8317 void (*xDestructor)(void*)
8318 );
8319
8320
8321 /*
8322 ** A pointer to a structure of the following type is passed as the
8323 ** argument to scored geometry callback registered using
8324 ** sqlite3_rtree_query_callback().
8325 **
8326 ** Note that the first 5 fields of this structure are identical to
8327 ** sqlite3_rtree_geometry. This structure is a subclass of
8328 ** sqlite3_rtree_geometry.
8329 */
8330 struct sqlite3_rtree_query_info {
8331 void *pContext; /* pContext from when function registered */
8332 int nParam; /* Number of function parameters */
8333 sqlite3_rtree_dbl *aParam; /* value of function parameters */
8334 void *pUser; /* callback can use this, if desired */
8335 void (*xDelUser)(void*); /* function to free pUser */
8336 sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
8337 unsigned int *anQueue; /* Number of pending entries in the queue */
8338 int nCoord; /* Number of coordinates */
8339 int iLevel; /* Level of current node or entry */
8340 int mxLevel; /* The largest iLevel value in the tree */
8341 sqlite3_int64 iRowid; /* Rowid for current entry */
8342 sqlite3_rtree_dbl rParentScore; /* Score of parent node */
8343 int eParentWithin; /* Visibility of parent node */
8344 int eWithin; /* OUT: Visiblity */
8345 sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
8346 /* The following fields are only available in 3.8.11 and later */
8347 sqlite3_value **apSqlParam; /* Original SQL values of parameters */
8348 };
8349
8350 /*
8351 ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
8352 */
8353 #define NOT_WITHIN 0 /* Object completely outside of query region */
8354 #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
8355 #define FULLY_WITHIN 2 /* Object fully contained within query region */
8356
8357
8358 #if 0
8359 } /* end of the 'extern "C"' block */
8360 #endif
8361
8362 #endif /* ifndef _SQLITE3RTREE_H_ */
8363
8364 /*
8365 ** 2014 May 31
8366 **
8367 ** The author disclaims copyright to this source code. In place of
8368 ** a legal notice, here is a blessing:
8369 **
8370 ** May you do good and not evil.
8371 ** May you find forgiveness for yourself and forgive others.
8372 ** May you share freely, never taking more than you give.
8373 **
8374 ******************************************************************************
8375 **
8376 ** Interfaces to extend FTS5. Using the interfaces defined in this file,
8377 ** FTS5 may be extended with:
8378 **
8379 ** * custom tokenizers, and
8380 ** * custom auxiliary functions.
8381 */
8382
8383
8384 #ifndef _FTS5_H
8385 #define _FTS5_H
8386
8387
8388 #if 0
8389 extern "C" {
8390 #endif
8391
8392 /*************************************************************************
8393 ** CUSTOM AUXILIARY FUNCTIONS
8394 **
8395 ** Virtual table implementations may overload SQL functions by implementing
8396 ** the sqlite3_module.xFindFunction() method.
8397 */
8398
8399 typedef struct Fts5ExtensionApi Fts5ExtensionApi;
8400 typedef struct Fts5Context Fts5Context;
8401 typedef struct Fts5PhraseIter Fts5PhraseIter;
8402
8403 typedef void (*fts5_extension_function)(
8404 const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
8405 Fts5Context *pFts, /* First arg to pass to pApi functions */
8406 sqlite3_context *pCtx, /* Context for returning result/error */
8407 int nVal, /* Number of values in apVal[] array */
8408 sqlite3_value **apVal /* Array of trailing arguments */
8409 );
8410
8411 struct Fts5PhraseIter {
8412 const unsigned char *a;
8413 const unsigned char *b;
8414 };
8415
8416 /*
8417 ** EXTENSION API FUNCTIONS
8418 **
8419 ** xUserData(pFts):
8420 ** Return a copy of the context pointer the extension function was
8421 ** registered with.
8422 **
8423 ** xColumnTotalSize(pFts, iCol, pnToken):
8424 ** If parameter iCol is less than zero, set output variable *pnToken
8425 ** to the total number of tokens in the FTS5 table. Or, if iCol is
8426 ** non-negative but less than the number of columns in the table, return
8427 ** the total number of tokens in column iCol, considering all rows in
8428 ** the FTS5 table.
8429 **
8430 ** If parameter iCol is greater than or equal to the number of columns
8431 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
8432 ** an OOM condition or IO error), an appropriate SQLite error code is
8433 ** returned.
8434 **
8435 ** xColumnCount(pFts):
8436 ** Return the number of columns in the table.
8437 **
8438 ** xColumnSize(pFts, iCol, pnToken):
8439 ** If parameter iCol is less than zero, set output variable *pnToken
8440 ** to the total number of tokens in the current row. Or, if iCol is
8441 ** non-negative but less than the number of columns in the table, set
8442 ** *pnToken to the number of tokens in column iCol of the current row.
8443 **
8444 ** If parameter iCol is greater than or equal to the number of columns
8445 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
8446 ** an OOM condition or IO error), an appropriate SQLite error code is
8447 ** returned.
8448 **
8449 ** xColumnText:
8450 ** This function attempts to retrieve the text of column iCol of the
8451 ** current document. If successful, (*pz) is set to point to a buffer
8452 ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
8453 ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
8454 ** if an error occurs, an SQLite error code is returned and the final values
8455 ** of (*pz) and (*pn) are undefined.
8456 **
8457 ** xPhraseCount:
8458 ** Returns the number of phrases in the current query expression.
8459 **
8460 ** xPhraseSize:
8461 ** Returns the number of tokens in phrase iPhrase of the query. Phrases
8462 ** are numbered starting from zero.
8463 **
8464 ** xInstCount:
8465 ** Set *pnInst to the total number of occurrences of all phrases within
8466 ** the query within the current row. Return SQLITE_OK if successful, or
8467 ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
8468 **
8469 ** xInst:
8470 ** Query for the details of phrase match iIdx within the current row.
8471 ** Phrase matches are numbered starting from zero, so the iIdx argument
8472 ** should be greater than or equal to zero and smaller than the value
8473 ** output by xInstCount().
8474 **
8475 ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
8476 ** if an error occurs.
8477 **
8478 ** xRowid:
8479 ** Returns the rowid of the current row.
8480 **
8481 ** xTokenize:
8482 ** Tokenize text using the tokenizer belonging to the FTS5 table.
8483 **
8484 ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
8485 ** This API function is used to query the FTS table for phrase iPhrase
8486 ** of the current query. Specifically, a query equivalent to:
8487 **
8488 ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
8489 **
8490 ** with $p set to a phrase equivalent to the phrase iPhrase of the
8491 ** current query is executed. For each row visited, the callback function
8492 ** passed as the fourth argument is invoked. The context and API objects
8493 ** passed to the callback function may be used to access the properties of
8494 ** each matched row. Invoking Api.xUserData() returns a copy of the pointer
8495 ** passed as the third argument to pUserData.
8496 **
8497 ** If the callback function returns any value other than SQLITE_OK, the
8498 ** query is abandoned and the xQueryPhrase function returns immediately.
8499 ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
8500 ** Otherwise, the error code is propagated upwards.
8501 **
8502 ** If the query runs to completion without incident, SQLITE_OK is returned.
8503 ** Or, if some error occurs before the query completes or is aborted by
8504 ** the callback, an SQLite error code is returned.
8505 **
8506 **
8507 ** xSetAuxdata(pFts5, pAux, xDelete)
8508 **
8509 ** Save the pointer passed as the second argument as the extension functions
8510 ** "auxiliary data". The pointer may then be retrieved by the current or any
8511 ** future invocation of the same fts5 extension function made as part of
8512 ** of the same MATCH query using the xGetAuxdata() API.
8513 **
8514 ** Each extension function is allocated a single auxiliary data slot for
8515 ** each FTS query (MATCH expression). If the extension function is invoked
8516 ** more than once for a single FTS query, then all invocations share a
8517 ** single auxiliary data context.
8518 **
8519 ** If there is already an auxiliary data pointer when this function is
8520 ** invoked, then it is replaced by the new pointer. If an xDelete callback
8521 ** was specified along with the original pointer, it is invoked at this
8522 ** point.
8523 **
8524 ** The xDelete callback, if one is specified, is also invoked on the
8525 ** auxiliary data pointer after the FTS5 query has finished.
8526 **
8527 ** If an error (e.g. an OOM condition) occurs within this function, an
8528 ** the auxiliary data is set to NULL and an error code returned. If the
8529 ** xDelete parameter was not NULL, it is invoked on the auxiliary data
8530 ** pointer before returning.
8531 **
8532 **
8533 ** xGetAuxdata(pFts5, bClear)
8534 **
8535 ** Returns the current auxiliary data pointer for the fts5 extension
8536 ** function. See the xSetAuxdata() method for details.
8537 **
8538 ** If the bClear argument is non-zero, then the auxiliary data is cleared
8539 ** (set to NULL) before this function returns. In this case the xDelete,
8540 ** if any, is not invoked.
8541 **
8542 **
8543 ** xRowCount(pFts5, pnRow)
8544 **
8545 ** This function is used to retrieve the total number of rows in the table.
8546 ** In other words, the same value that would be returned by:
8547 **
8548 ** SELECT count(*) FROM ftstable;
8549 **
8550 ** xPhraseFirst()
8551 ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
8552 ** method, to iterate through all instances of a single query phrase within
8553 ** the current row. This is the same information as is accessible via the
8554 ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
8555 ** to use, this API may be faster under some circumstances. To iterate
8556 ** through instances of phrase iPhrase, use the following code:
8557 **
8558 ** Fts5PhraseIter iter;
8559 ** int iCol, iOff;
8560 ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
8561 ** iOff>=0;
8562 ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
8563 ** ){
8564 ** // An instance of phrase iPhrase at offset iOff of column iCol
8565 ** }
8566 **
8567 ** The Fts5PhraseIter structure is defined above. Applications should not
8568 ** modify this structure directly - it should only be used as shown above
8569 ** with the xPhraseFirst() and xPhraseNext() API methods.
8570 **
8571 ** xPhraseNext()
8572 ** See xPhraseFirst above.
8573 */
8574 struct Fts5ExtensionApi {
8575 int iVersion; /* Currently always set to 1 */
8576
8577 void *(*xUserData)(Fts5Context*);
8578
8579 int (*xColumnCount)(Fts5Context*);
8580 int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
8581 int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
8582
8583 int (*xTokenize)(Fts5Context*,
8584 const char *pText, int nText, /* Text to tokenize */
8585 void *pCtx, /* Context passed to xToken() */
8586 int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
8587 );
8588
8589 int (*xPhraseCount)(Fts5Context*);
8590 int (*xPhraseSize)(Fts5Context*, int iPhrase);
8591
8592 int (*xInstCount)(Fts5Context*, int *pnInst);
8593 int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
8594
8595 sqlite3_int64 (*xRowid)(Fts5Context*);
8596 int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
8597 int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
8598
8599 int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
8600 int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
8601 );
8602 int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
8603 void *(*xGetAuxdata)(Fts5Context*, int bClear);
8604
8605 void (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
8606 void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
8607 };
8608
8609 /*
8610 ** CUSTOM AUXILIARY FUNCTIONS
8611 *************************************************************************/
8612
8613 /*************************************************************************
8614 ** CUSTOM TOKENIZERS
8615 **
8616 ** Applications may also register custom tokenizer types. A tokenizer
8617 ** is registered by providing fts5 with a populated instance of the
8618 ** following structure. All structure methods must be defined, setting
8619 ** any member of the fts5_tokenizer struct to NULL leads to undefined
8620 ** behaviour. The structure methods are expected to function as follows:
8621 **
8622 ** xCreate:
8623 ** This function is used to allocate and inititalize a tokenizer instance.
8624 ** A tokenizer instance is required to actually tokenize text.
8625 **
8626 ** The first argument passed to this function is a copy of the (void*)
8627 ** pointer provided by the application when the fts5_tokenizer object
8628 ** was registered with FTS5 (the third argument to xCreateTokenizer()).
8629 ** The second and third arguments are an array of nul-terminated strings
8630 ** containing the tokenizer arguments, if any, specified following the
8631 ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
8632 ** to create the FTS5 table.
8633 **
8634 ** The final argument is an output variable. If successful, (*ppOut)
8635 ** should be set to point to the new tokenizer handle and SQLITE_OK
8636 ** returned. If an error occurs, some value other than SQLITE_OK should
8637 ** be returned. In this case, fts5 assumes that the final value of *ppOut
8638 ** is undefined.
8639 **
8640 ** xDelete:
8641 ** This function is invoked to delete a tokenizer handle previously
8642 ** allocated using xCreate(). Fts5 guarantees that this function will
8643 ** be invoked exactly once for each successful call to xCreate().
8644 **
8645 ** xTokenize:
8646 ** This function is expected to tokenize the nText byte string indicated
8647 ** by argument pText. pText may or may not be nul-terminated. The first
8648 ** argument passed to this function is a pointer to an Fts5Tokenizer object
8649 ** returned by an earlier call to xCreate().
8650 **
8651 ** The second argument indicates the reason that FTS5 is requesting
8652 ** tokenization of the supplied text. This is always one of the following
8653 ** four values:
8654 **
8655 ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
8656 ** or removed from the FTS table. The tokenizer is being invoked to
8657 ** determine the set of tokens to add to (or delete from) the
8658 ** FTS index.
8659 **
8660 ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
8661 ** against the FTS index. The tokenizer is being called to tokenize
8662 ** a bareword or quoted string specified as part of the query.
8663 **
8664 ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
8665 ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
8666 ** followed by a "*" character, indicating that the last token
8667 ** returned by the tokenizer will be treated as a token prefix.
8668 **
8669 ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
8670 ** satisfy an fts5_api.xTokenize() request made by an auxiliary
8671 ** function. Or an fts5_api.xColumnSize() request made by the same
8672 ** on a columnsize=0 database.
8673 ** </ul>
8674 **
8675 ** For each token in the input string, the supplied callback xToken() must
8676 ** be invoked. The first argument to it should be a copy of the pointer
8677 ** passed as the second argument to xTokenize(). The third and fourth
8678 ** arguments are a pointer to a buffer containing the token text, and the
8679 ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
8680 ** of the first byte of and first byte immediately following the text from
8681 ** which the token is derived within the input.
8682 **
8683 ** The second argument passed to the xToken() callback ("tflags") should
8684 ** normally be set to 0. The exception is if the tokenizer supports
8685 ** synonyms. In this case see the discussion below for details.
8686 **
8687 ** FTS5 assumes the xToken() callback is invoked for each token in the
8688 ** order that they occur within the input text.
8689 **
8690 ** If an xToken() callback returns any value other than SQLITE_OK, then
8691 ** the tokenization should be abandoned and the xTokenize() method should
8692 ** immediately return a copy of the xToken() return value. Or, if the
8693 ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
8694 ** if an error occurs with the xTokenize() implementation itself, it
8695 ** may abandon the tokenization and return any error code other than
8696 ** SQLITE_OK or SQLITE_DONE.
8697 **
8698 ** SYNONYM SUPPORT
8699 **
8700 ** Custom tokenizers may also support synonyms. Consider a case in which a
8701 ** user wishes to query for a phrase such as "first place". Using the
8702 ** built-in tokenizers, the FTS5 query 'first + place' will match instances
8703 ** of "first place" within the document set, but not alternative forms
8704 ** such as "1st place". In some applications, it would be better to match
8705 ** all instances of "first place" or "1st place" regardless of which form
8706 ** the user specified in the MATCH query text.
8707 **
8708 ** There are several ways to approach this in FTS5:
8709 **
8710 ** <ol><li> By mapping all synonyms to a single token. In this case, the
8711 ** In the above example, this means that the tokenizer returns the
8712 ** same token for inputs "first" and "1st". Say that token is in
8713 ** fact "first", so that when the user inserts the document "I won
8714 ** 1st place" entries are added to the index for tokens "i", "won",
8715 ** "first" and "place". If the user then queries for '1st + place',
8716 ** the tokenizer substitutes "first" for "1st" and the query works
8717 ** as expected.
8718 **
8719 ** <li> By adding multiple synonyms for a single term to the FTS index.
8720 ** In this case, when tokenizing query text, the tokenizer may
8721 ** provide multiple synonyms for a single term within the document.
8722 ** FTS5 then queries the index for each synonym individually. For
8723 ** example, faced with the query:
8724 **
8725 ** <codeblock>
8726 ** ... MATCH 'first place'</codeblock>
8727 **
8728 ** the tokenizer offers both "1st" and "first" as synonyms for the
8729 ** first token in the MATCH query and FTS5 effectively runs a query
8730 ** similar to:
8731 **
8732 ** <codeblock>
8733 ** ... MATCH '(first OR 1st) place'</codeblock>
8734 **
8735 ** except that, for the purposes of auxiliary functions, the query
8736 ** still appears to contain just two phrases - "(first OR 1st)"
8737 ** being treated as a single phrase.
8738 **
8739 ** <li> By adding multiple synonyms for a single term to the FTS index.
8740 ** Using this method, when tokenizing document text, the tokenizer
8741 ** provides multiple synonyms for each token. So that when a
8742 ** document such as "I won first place" is tokenized, entries are
8743 ** added to the FTS index for "i", "won", "first", "1st" and
8744 ** "place".
8745 **
8746 ** This way, even if the tokenizer does not provide synonyms
8747 ** when tokenizing query text (it should not - to do would be
8748 ** inefficient), it doesn't matter if the user queries for
8749 ** 'first + place' or '1st + place', as there are entires in the
8750 ** FTS index corresponding to both forms of the first token.
8751 ** </ol>
8752 **
8753 ** Whether it is parsing document or query text, any call to xToken that
8754 ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
8755 ** is considered to supply a synonym for the previous token. For example,
8756 ** when parsing the document "I won first place", a tokenizer that supports
8757 ** synonyms would call xToken() 5 times, as follows:
8758 **
8759 ** <codeblock>
8760 ** xToken(pCtx, 0, "i", 1, 0, 1);
8761 ** xToken(pCtx, 0, "won", 3, 2, 5);
8762 ** xToken(pCtx, 0, "first", 5, 6, 11);
8763 ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
8764 ** xToken(pCtx, 0, "place", 5, 12, 17);
8765 **</codeblock>
8766 **
8767 ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
8768 ** xToken() is called. Multiple synonyms may be specified for a single token
8769 ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
8770 ** There is no limit to the number of synonyms that may be provided for a
8771 ** single token.
8772 **
8773 ** In many cases, method (1) above is the best approach. It does not add
8774 ** extra data to the FTS index or require FTS5 to query for multiple terms,
8775 ** so it is efficient in terms of disk space and query speed. However, it
8776 ** does not support prefix queries very well. If, as suggested above, the
8777 ** token "first" is subsituted for "1st" by the tokenizer, then the query:
8778 **
8779 ** <codeblock>
8780 ** ... MATCH '1s*'</codeblock>
8781 **
8782 ** will not match documents that contain the token "1st" (as the tokenizer
8783 ** will probably not map "1s" to any prefix of "first").
8784 **
8785 ** For full prefix support, method (3) may be preferred. In this case,
8786 ** because the index contains entries for both "first" and "1st", prefix
8787 ** queries such as 'fi*' or '1s*' will match correctly. However, because
8788 ** extra entries are added to the FTS index, this method uses more space
8789 ** within the database.
8790 **
8791 ** Method (2) offers a midpoint between (1) and (3). Using this method,
8792 ** a query such as '1s*' will match documents that contain the literal
8793 ** token "1st", but not "first" (assuming the tokenizer is not able to
8794 ** provide synonyms for prefixes). However, a non-prefix query like '1st'
8795 ** will match against "1st" and "first". This method does not require
8796 ** extra disk space, as no extra entries are added to the FTS index.
8797 ** On the other hand, it may require more CPU cycles to run MATCH queries,
8798 ** as separate queries of the FTS index are required for each synonym.
8799 **
8800 ** When using methods (2) or (3), it is important that the tokenizer only
8801 ** provide synonyms when tokenizing document text (method (2)) or query
8802 ** text (method (3)), not both. Doing so will not cause any errors, but is
8803 ** inefficient.
8804 */
8805 typedef struct Fts5Tokenizer Fts5Tokenizer;
8806 typedef struct fts5_tokenizer fts5_tokenizer;
8807 struct fts5_tokenizer {
8808 int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
8809 void (*xDelete)(Fts5Tokenizer*);
8810 int (*xTokenize)(Fts5Tokenizer*,
8811 void *pCtx,
8812 int flags, /* Mask of FTS5_TOKENIZE_* flags */
8813 const char *pText, int nText,
8814 int (*xToken)(
8815 void *pCtx, /* Copy of 2nd argument to xTokenize() */
8816 int tflags, /* Mask of FTS5_TOKEN_* flags */
8817 const char *pToken, /* Pointer to buffer containing token */
8818 int nToken, /* Size of token in bytes */
8819 int iStart, /* Byte offset of token within input text */
8820 int iEnd /* Byte offset of end of token within input text */
8821 )
8822 );
8823 };
8824
8825 /* Flags that may be passed as the third argument to xTokenize() */
8826 #define FTS5_TOKENIZE_QUERY 0x0001
8827 #define FTS5_TOKENIZE_PREFIX 0x0002
8828 #define FTS5_TOKENIZE_DOCUMENT 0x0004
8829 #define FTS5_TOKENIZE_AUX 0x0008
8830
8831 /* Flags that may be passed by the tokenizer implementation back to FTS5
8832 ** as the third argument to the supplied xToken callback. */
8833 #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
8834
8835 /*
8836 ** END OF CUSTOM TOKENIZERS
8837 *************************************************************************/
8838
8839 /*************************************************************************
8840 ** FTS5 EXTENSION REGISTRATION API
8841 */
8842 typedef struct fts5_api fts5_api;
8843 struct fts5_api {
8844 int iVersion; /* Currently always set to 2 */
8845
8846 /* Create a new tokenizer */
8847 int (*xCreateTokenizer)(
8848 fts5_api *pApi,
8849 const char *zName,
8850 void *pContext,
8851 fts5_tokenizer *pTokenizer,
8852 void (*xDestroy)(void*)
8853 );
8854
8855 /* Find an existing tokenizer */
8856 int (*xFindTokenizer)(
8857 fts5_api *pApi,
8858 const char *zName,
8859 void **ppContext,
8860 fts5_tokenizer *pTokenizer
8861 );
8862
8863 /* Create a new auxiliary function */
8864 int (*xCreateFunction)(
8865 fts5_api *pApi,
8866 const char *zName,
8867 void *pContext,
8868 fts5_extension_function xFunction,
8869 void (*xDestroy)(void*)
8870 );
8871 };
8872
8873 /*
8874 ** END OF REGISTRATION API
8875 *************************************************************************/
8876
8877 #if 0
8878 } /* end of the 'extern "C"' block */
8879 #endif
8880
8881 #endif /* _FTS5_H */
8882
8883
8884
8885 /************** End of sqlite3.h *********************************************/
8886 /************** Continuing where we left off in sqliteInt.h ******************/
8887
8888 /*
8889 ** Include the configuration header output by 'configure' if we're using the
8890 ** autoconf-based build
8891 */
8892 #ifdef _HAVE_SQLITE_CONFIG_H
8893 #include "config.h"
8894 #endif
8895
8896 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
8897 /************** Begin file sqliteLimit.h *************************************/
8898 /*
8899 ** 2007 May 7
8900 **
8901 ** The author disclaims copyright to this source code. In place of
8902 ** a legal notice, here is a blessing:
8903 **
8904 ** May you do good and not evil.
8905 ** May you find forgiveness for yourself and forgive others.
8906 ** May you share freely, never taking more than you give.
8907 **
8908 *************************************************************************
8909 **
8910 ** This file defines various limits of what SQLite can process.
8911 */
8912
8913 /*
8914 ** The maximum length of a TEXT or BLOB in bytes. This also
8915 ** limits the size of a row in a table or index.
8916 **
8917 ** The hard limit is the ability of a 32-bit signed integer
8918 ** to count the size: 2^31-1 or 2147483647.
8919 */
8920 #ifndef SQLITE_MAX_LENGTH
8921 # define SQLITE_MAX_LENGTH 1000000000
8922 #endif
8923
8924 /*
8925 ** This is the maximum number of
8926 **
8927 ** * Columns in a table
8928 ** * Columns in an index
8929 ** * Columns in a view
8930 ** * Terms in the SET clause of an UPDATE statement
8931 ** * Terms in the result set of a SELECT statement
8932 ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
8933 ** * Terms in the VALUES clause of an INSERT statement
8934 **
8935 ** The hard upper limit here is 32676. Most database people will
8936 ** tell you that in a well-normalized database, you usually should
8937 ** not have more than a dozen or so columns in any table. And if
8938 ** that is the case, there is no point in having more than a few
8939 ** dozen values in any of the other situations described above.
8940 */
8941 #ifndef SQLITE_MAX_COLUMN
8942 # define SQLITE_MAX_COLUMN 2000
8943 #endif
8944
8945 /*
8946 ** The maximum length of a single SQL statement in bytes.
8947 **
8948 ** It used to be the case that setting this value to zero would
8949 ** turn the limit off. That is no longer true. It is not possible
8950 ** to turn this limit off.
8951 */
8952 #ifndef SQLITE_MAX_SQL_LENGTH
8953 # define SQLITE_MAX_SQL_LENGTH 1000000000
8954 #endif
8955
8956 /*
8957 ** The maximum depth of an expression tree. This is limited to
8958 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
8959 ** want to place more severe limits on the complexity of an
8960 ** expression.
8961 **
8962 ** A value of 0 used to mean that the limit was not enforced.
8963 ** But that is no longer true. The limit is now strictly enforced
8964 ** at all times.
8965 */
8966 #ifndef SQLITE_MAX_EXPR_DEPTH
8967 # define SQLITE_MAX_EXPR_DEPTH 1000
8968 #endif
8969
8970 /*
8971 ** The maximum number of terms in a compound SELECT statement.
8972 ** The code generator for compound SELECT statements does one
8973 ** level of recursion for each term. A stack overflow can result
8974 ** if the number of terms is too large. In practice, most SQL
8975 ** never has more than 3 or 4 terms. Use a value of 0 to disable
8976 ** any limit on the number of terms in a compount SELECT.
8977 */
8978 #ifndef SQLITE_MAX_COMPOUND_SELECT
8979 # define SQLITE_MAX_COMPOUND_SELECT 500
8980 #endif
8981
8982 /*
8983 ** The maximum number of opcodes in a VDBE program.
8984 ** Not currently enforced.
8985 */
8986 #ifndef SQLITE_MAX_VDBE_OP
8987 # define SQLITE_MAX_VDBE_OP 25000
8988 #endif
8989
8990 /*
8991 ** The maximum number of arguments to an SQL function.
8992 */
8993 #ifndef SQLITE_MAX_FUNCTION_ARG
8994 # define SQLITE_MAX_FUNCTION_ARG 127
8995 #endif
8996
8997 /*
8998 ** The suggested maximum number of in-memory pages to use for
8999 ** the main database table and for temporary tables.
9000 **
9001 ** IMPLEMENTATION-OF: R-31093-59126 The default suggested cache size
9002 ** is 2000 pages.
9003 ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
9004 ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
9005 */
9006 #ifndef SQLITE_DEFAULT_CACHE_SIZE
9007 # define SQLITE_DEFAULT_CACHE_SIZE 2000
9008 #endif
9009
9010 /*
9011 ** The default number of frames to accumulate in the log file before
9012 ** checkpointing the database in WAL mode.
9013 */
9014 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
9015 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
9016 #endif
9017
9018 /*
9019 ** The maximum number of attached databases. This must be between 0
9020 ** and 62. The upper bound on 62 is because a 64-bit integer bitmap
9021 ** is used internally to track attached databases.
9022 */
9023 #ifndef SQLITE_MAX_ATTACHED
9024 # define SQLITE_MAX_ATTACHED 10
9025 #endif
9026
9027
9028 /*
9029 ** The maximum value of a ?nnn wildcard that the parser will accept.
9030 */
9031 #ifndef SQLITE_MAX_VARIABLE_NUMBER
9032 # define SQLITE_MAX_VARIABLE_NUMBER 999
9033 #endif
9034
9035 /* Maximum page size. The upper bound on this value is 65536. This a limit
9036 ** imposed by the use of 16-bit offsets within each page.
9037 **
9038 ** Earlier versions of SQLite allowed the user to change this value at
9039 ** compile time. This is no longer permitted, on the grounds that it creates
9040 ** a library that is technically incompatible with an SQLite library
9041 ** compiled with a different limit. If a process operating on a database
9042 ** with a page-size of 65536 bytes crashes, then an instance of SQLite
9043 ** compiled with the default page-size limit will not be able to rollback
9044 ** the aborted transaction. This could lead to database corruption.
9045 */
9046 #ifdef SQLITE_MAX_PAGE_SIZE
9047 # undef SQLITE_MAX_PAGE_SIZE
9048 #endif
9049 #define SQLITE_MAX_PAGE_SIZE 65536
9050
9051
9052 /*
9053 ** The default size of a database page.
9054 */
9055 #ifndef SQLITE_DEFAULT_PAGE_SIZE
9056 # define SQLITE_DEFAULT_PAGE_SIZE 1024
9057 #endif
9058 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
9059 # undef SQLITE_DEFAULT_PAGE_SIZE
9060 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
9061 #endif
9062
9063 /*
9064 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
9065 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
9066 ** device characteristics (sector-size and atomic write() support),
9067 ** SQLite may choose a larger value. This constant is the maximum value
9068 ** SQLite will choose on its own.
9069 */
9070 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
9071 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
9072 #endif
9073 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
9074 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
9075 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
9076 #endif
9077
9078
9079 /*
9080 ** Maximum number of pages in one database file.
9081 **
9082 ** This is really just the default value for the max_page_count pragma.
9083 ** This value can be lowered (or raised) at run-time using that the
9084 ** max_page_count macro.
9085 */
9086 #ifndef SQLITE_MAX_PAGE_COUNT
9087 # define SQLITE_MAX_PAGE_COUNT 1073741823
9088 #endif
9089
9090 /*
9091 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
9092 ** operator.
9093 */
9094 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
9095 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
9096 #endif
9097
9098 /*
9099 ** Maximum depth of recursion for triggers.
9100 **
9101 ** A value of 1 means that a trigger program will not be able to itself
9102 ** fire any triggers. A value of 0 means that no trigger programs at all
9103 ** may be executed.
9104 */
9105 #ifndef SQLITE_MAX_TRIGGER_DEPTH
9106 # define SQLITE_MAX_TRIGGER_DEPTH 1000
9107 #endif
9108
9109 /************** End of sqliteLimit.h *****************************************/
9110 /************** Continuing where we left off in sqliteInt.h ******************/
9111
9112 /* Disable nuisance warnings on Borland compilers */
9113 #if defined(__BORLANDC__)
9114 #pragma warn -rch /* unreachable code */
9115 #pragma warn -ccc /* Condition is always true or false */
9116 #pragma warn -aus /* Assigned value is never used */
9117 #pragma warn -csu /* Comparing signed and unsigned */
9118 #pragma warn -spa /* Suspicious pointer arithmetic */
9119 #endif
9120
9121 /*
9122 ** Include standard header files as necessary
9123 */
9124 #ifdef HAVE_STDINT_H
9125 #include <stdint.h>
9126 #endif
9127 #ifdef HAVE_INTTYPES_H
9128 #include <inttypes.h>
9129 #endif
9130
9131 /*
9132 ** The following macros are used to cast pointers to integers and
9133 ** integers to pointers. The way you do this varies from one compiler
9134 ** to the next, so we have developed the following set of #if statements
9135 ** to generate appropriate macros for a wide range of compilers.
9136 **
9137 ** The correct "ANSI" way to do this is to use the intptr_t type.
9138 ** Unfortunately, that typedef is not available on all compilers, or
9139 ** if it is available, it requires an #include of specific headers
9140 ** that vary from one machine to the next.
9141 **
9142 ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
9143 ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
9144 ** So we have to define the macros in different ways depending on the
9145 ** compiler.
9146 */
9147 #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
9148 # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
9149 # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
9150 #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
9151 # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
9152 # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
9153 #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
9154 # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
9155 # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
9156 #else /* Generates a warning - but it always works */
9157 # define SQLITE_INT_TO_PTR(X) ((void*)(X))
9158 # define SQLITE_PTR_TO_INT(X) ((int)(X))
9159 #endif
9160
9161 /*
9162 ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
9163 ** something between S (inclusive) and E (exclusive).
9164 **
9165 ** In other words, S is a buffer and E is a pointer to the first byte after
9166 ** the end of buffer S. This macro returns true if P points to something
9167 ** contained within the buffer S.
9168 */
9169 #if defined(HAVE_STDINT_H)
9170 # define SQLITE_WITHIN(P,S,E) \
9171 ((uintptr_t)(P)>=(uintptr_t)(S) && (uintptr_t)(P)<(uintptr_t)(E))
9172 #else
9173 # define SQLITE_WITHIN(P,S,E) ((P)>=(S) && (P)<(E))
9174 #endif
9175
9176 /*
9177 ** A macro to hint to the compiler that a function should not be
9178 ** inlined.
9179 */
9180 #if defined(__GNUC__)
9181 # define SQLITE_NOINLINE __attribute__((noinline))
9182 #elif defined(_MSC_VER) && _MSC_VER>=1310
9183 # define SQLITE_NOINLINE __declspec(noinline)
9184 #else
9185 # define SQLITE_NOINLINE
9186 #endif
9187
9188 /*
9189 ** Make sure that the compiler intrinsics we desire are enabled when
9190 ** compiling with an appropriate version of MSVC unless prevented by
9191 ** the SQLITE_DISABLE_INTRINSIC define.
9192 */
9193 #if !defined(SQLITE_DISABLE_INTRINSIC)
9194 # if defined(_MSC_VER) && _MSC_VER>=1300
9195 # if !defined(_WIN32_WCE)
9196 # include <intrin.h>
9197 # pragma intrinsic(_byteswap_ushort)
9198 # pragma intrinsic(_byteswap_ulong)
9199 # pragma intrinsic(_ReadWriteBarrier)
9200 # else
9201 # include <cmnintrin.h>
9202 # endif
9203 # endif
9204 #endif
9205
9206 /*
9207 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
9208 ** 0 means mutexes are permanently disable and the library is never
9209 ** threadsafe. 1 means the library is serialized which is the highest
9210 ** level of threadsafety. 2 means the library is multithreaded - multiple
9211 ** threads can use SQLite as long as no two threads try to use the same
9212 ** database connection at the same time.
9213 **
9214 ** Older versions of SQLite used an optional THREADSAFE macro.
9215 ** We support that for legacy.
9216 */
9217 #if !defined(SQLITE_THREADSAFE)
9218 # if defined(THREADSAFE)
9219 # define SQLITE_THREADSAFE THREADSAFE
9220 # else
9221 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
9222 # endif
9223 #endif
9224
9225 /*
9226 ** Powersafe overwrite is on by default. But can be turned off using
9227 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
9228 */
9229 #ifndef SQLITE_POWERSAFE_OVERWRITE
9230 # define SQLITE_POWERSAFE_OVERWRITE 1
9231 #endif
9232
9233 /*
9234 ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
9235 ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
9236 ** which case memory allocation statistics are disabled by default.
9237 */
9238 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
9239 # define SQLITE_DEFAULT_MEMSTATUS 1
9240 #endif
9241
9242 /*
9243 ** Exactly one of the following macros must be defined in order to
9244 ** specify which memory allocation subsystem to use.
9245 **
9246 ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
9247 ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
9248 ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
9249 ** SQLITE_MEMDEBUG // Debugging version of system malloc()
9250 **
9251 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
9252 ** assert() macro is enabled, each call into the Win32 native heap subsystem
9253 ** will cause HeapValidate to be called. If heap validation should fail, an
9254 ** assertion will be triggered.
9255 **
9256 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
9257 ** the default.
9258 */
9259 #if defined(SQLITE_SYSTEM_MALLOC) \
9260 + defined(SQLITE_WIN32_MALLOC) \
9261 + defined(SQLITE_ZERO_MALLOC) \
9262 + defined(SQLITE_MEMDEBUG)>1
9263 # error "Two or more of the following compile-time configuration options\
9264 are defined but at most one is allowed:\
9265 SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
9266 SQLITE_ZERO_MALLOC"
9267 #endif
9268 #if defined(SQLITE_SYSTEM_MALLOC) \
9269 + defined(SQLITE_WIN32_MALLOC) \
9270 + defined(SQLITE_ZERO_MALLOC) \
9271 + defined(SQLITE_MEMDEBUG)==0
9272 # define SQLITE_SYSTEM_MALLOC 1
9273 #endif
9274
9275 /*
9276 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
9277 ** sizes of memory allocations below this value where possible.
9278 */
9279 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
9280 # define SQLITE_MALLOC_SOFT_LIMIT 1024
9281 #endif
9282
9283 /*
9284 ** We need to define _XOPEN_SOURCE as follows in order to enable
9285 ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
9286 ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
9287 ** it.
9288 */
9289 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
9290 # define _XOPEN_SOURCE 600
9291 #endif
9292
9293 /*
9294 ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
9295 ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
9296 ** make it true by defining or undefining NDEBUG.
9297 **
9298 ** Setting NDEBUG makes the code smaller and faster by disabling the
9299 ** assert() statements in the code. So we want the default action
9300 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
9301 ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
9302 ** feature.
9303 */
9304 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
9305 # define NDEBUG 1
9306 #endif
9307 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
9308 # undef NDEBUG
9309 #endif
9310
9311 /*
9312 ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
9313 */
9314 #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
9315 # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
9316 #endif
9317
9318 /*
9319 ** The testcase() macro is used to aid in coverage testing. When
9320 ** doing coverage testing, the condition inside the argument to
9321 ** testcase() must be evaluated both true and false in order to
9322 ** get full branch coverage. The testcase() macro is inserted
9323 ** to help ensure adequate test coverage in places where simple
9324 ** condition/decision coverage is inadequate. For example, testcase()
9325 ** can be used to make sure boundary values are tested. For
9326 ** bitmask tests, testcase() can be used to make sure each bit
9327 ** is significant and used at least once. On switch statements
9328 ** where multiple cases go to the same block of code, testcase()
9329 ** can insure that all cases are evaluated.
9330 **
9331 */
9332 #ifdef SQLITE_COVERAGE_TEST
9333 SQLITE_PRIVATE void sqlite3Coverage(int);
9334 # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
9335 #else
9336 # define testcase(X)
9337 #endif
9338
9339 /*
9340 ** The TESTONLY macro is used to enclose variable declarations or
9341 ** other bits of code that are needed to support the arguments
9342 ** within testcase() and assert() macros.
9343 */
9344 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
9345 # define TESTONLY(X) X
9346 #else
9347 # define TESTONLY(X)
9348 #endif
9349
9350 /*
9351 ** Sometimes we need a small amount of code such as a variable initialization
9352 ** to setup for a later assert() statement. We do not want this code to
9353 ** appear when assert() is disabled. The following macro is therefore
9354 ** used to contain that setup code. The "VVA" acronym stands for
9355 ** "Verification, Validation, and Accreditation". In other words, the
9356 ** code within VVA_ONLY() will only run during verification processes.
9357 */
9358 #ifndef NDEBUG
9359 # define VVA_ONLY(X) X
9360 #else
9361 # define VVA_ONLY(X)
9362 #endif
9363
9364 /*
9365 ** The ALWAYS and NEVER macros surround boolean expressions which
9366 ** are intended to always be true or false, respectively. Such
9367 ** expressions could be omitted from the code completely. But they
9368 ** are included in a few cases in order to enhance the resilience
9369 ** of SQLite to unexpected behavior - to make the code "self-healing"
9370 ** or "ductile" rather than being "brittle" and crashing at the first
9371 ** hint of unplanned behavior.
9372 **
9373 ** In other words, ALWAYS and NEVER are added for defensive code.
9374 **
9375 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
9376 ** be true and false so that the unreachable code they specify will
9377 ** not be counted as untested code.
9378 */
9379 #if defined(SQLITE_COVERAGE_TEST)
9380 # define ALWAYS(X) (1)
9381 # define NEVER(X) (0)
9382 #elif !defined(NDEBUG)
9383 # define ALWAYS(X) ((X)?1:(assert(0),0))
9384 # define NEVER(X) ((X)?(assert(0),1):0)
9385 #else
9386 # define ALWAYS(X) (X)
9387 # define NEVER(X) (X)
9388 #endif
9389
9390 /*
9391 ** Declarations used for tracing the operating system interfaces.
9392 */
9393 #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
9394 (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
9395 extern int sqlite3OSTrace;
9396 # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
9397 # define SQLITE_HAVE_OS_TRACE
9398 #else
9399 # define OSTRACE(X)
9400 # undef SQLITE_HAVE_OS_TRACE
9401 #endif
9402
9403 /*
9404 ** Is the sqlite3ErrName() function needed in the build? Currently,
9405 ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
9406 ** OSTRACE is enabled), and by several "test*.c" files (which are
9407 ** compiled using SQLITE_TEST).
9408 */
9409 #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
9410 (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
9411 # define SQLITE_NEED_ERR_NAME
9412 #else
9413 # undef SQLITE_NEED_ERR_NAME
9414 #endif
9415
9416 /*
9417 ** Return true (non-zero) if the input is an integer that is too large
9418 ** to fit in 32-bits. This macro is used inside of various testcase()
9419 ** macros to verify that we have tested SQLite for large-file support.
9420 */
9421 #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
9422
9423 /*
9424 ** The macro unlikely() is a hint that surrounds a boolean
9425 ** expression that is usually false. Macro likely() surrounds
9426 ** a boolean expression that is usually true. These hints could,
9427 ** in theory, be used by the compiler to generate better code, but
9428 ** currently they are just comments for human readers.
9429 */
9430 #define likely(X) (X)
9431 #define unlikely(X) (X)
9432
9433 /************** Include hash.h in the middle of sqliteInt.h ******************/
9434 /************** Begin file hash.h ********************************************/
9435 /*
9436 ** 2001 September 22
9437 **
9438 ** The author disclaims copyright to this source code. In place of
9439 ** a legal notice, here is a blessing:
9440 **
9441 ** May you do good and not evil.
9442 ** May you find forgiveness for yourself and forgive others.
9443 ** May you share freely, never taking more than you give.
9444 **
9445 *************************************************************************
9446 ** This is the header file for the generic hash-table implementation
9447 ** used in SQLite.
9448 */
9449 #ifndef _SQLITE_HASH_H_
9450 #define _SQLITE_HASH_H_
9451
9452 /* Forward declarations of structures. */
9453 typedef struct Hash Hash;
9454 typedef struct HashElem HashElem;
9455
9456 /* A complete hash table is an instance of the following structure.
9457 ** The internals of this structure are intended to be opaque -- client
9458 ** code should not attempt to access or modify the fields of this structure
9459 ** directly. Change this structure only by using the routines below.
9460 ** However, some of the "procedures" and "functions" for modifying and
9461 ** accessing this structure are really macros, so we can't really make
9462 ** this structure opaque.
9463 **
9464 ** All elements of the hash table are on a single doubly-linked list.
9465 ** Hash.first points to the head of this list.
9466 **
9467 ** There are Hash.htsize buckets. Each bucket points to a spot in
9468 ** the global doubly-linked list. The contents of the bucket are the
9469 ** element pointed to plus the next _ht.count-1 elements in the list.
9470 **
9471 ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
9472 ** by a linear search of the global list. For small tables, the
9473 ** Hash.ht table is never allocated because if there are few elements
9474 ** in the table, it is faster to do a linear search than to manage
9475 ** the hash table.
9476 */
9477 struct Hash {
9478 unsigned int htsize; /* Number of buckets in the hash table */
9479 unsigned int count; /* Number of entries in this table */
9480 HashElem *first; /* The first element of the array */
9481 struct _ht { /* the hash table */
9482 int count; /* Number of entries with this hash */
9483 HashElem *chain; /* Pointer to first entry with this hash */
9484 } *ht;
9485 };
9486
9487 /* Each element in the hash table is an instance of the following
9488 ** structure. All elements are stored on a single doubly-linked list.
9489 **
9490 ** Again, this structure is intended to be opaque, but it can't really
9491 ** be opaque because it is used by macros.
9492 */
9493 struct HashElem {
9494 HashElem *next, *prev; /* Next and previous elements in the table */
9495 void *data; /* Data associated with this element */
9496 const char *pKey; /* Key associated with this element */
9497 };
9498
9499 /*
9500 ** Access routines. To delete, insert a NULL pointer.
9501 */
9502 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
9503 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
9504 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
9505 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
9506
9507 /*
9508 ** Macros for looping over all elements of a hash table. The idiom is
9509 ** like this:
9510 **
9511 ** Hash h;
9512 ** HashElem *p;
9513 ** ...
9514 ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
9515 ** SomeStructure *pData = sqliteHashData(p);
9516 ** // do something with pData
9517 ** }
9518 */
9519 #define sqliteHashFirst(H) ((H)->first)
9520 #define sqliteHashNext(E) ((E)->next)
9521 #define sqliteHashData(E) ((E)->data)
9522 /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
9523 /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
9524
9525 /*
9526 ** Number of entries in a hash table
9527 */
9528 /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
9529
9530 #endif /* _SQLITE_HASH_H_ */
9531
9532 /************** End of hash.h ************************************************/
9533 /************** Continuing where we left off in sqliteInt.h ******************/
9534 /************** Include parse.h in the middle of sqliteInt.h *****************/
9535 /************** Begin file parse.h *******************************************/
9536 #define TK_SEMI 1
9537 #define TK_EXPLAIN 2
9538 #define TK_QUERY 3
9539 #define TK_PLAN 4
9540 #define TK_BEGIN 5
9541 #define TK_TRANSACTION 6
9542 #define TK_DEFERRED 7
9543 #define TK_IMMEDIATE 8
9544 #define TK_EXCLUSIVE 9
9545 #define TK_COMMIT 10
9546 #define TK_END 11
9547 #define TK_ROLLBACK 12
9548 #define TK_SAVEPOINT 13
9549 #define TK_RELEASE 14
9550 #define TK_TO 15
9551 #define TK_TABLE 16
9552 #define TK_CREATE 17
9553 #define TK_IF 18
9554 #define TK_NOT 19
9555 #define TK_EXISTS 20
9556 #define TK_TEMP 21
9557 #define TK_LP 22
9558 #define TK_RP 23
9559 #define TK_AS 24
9560 #define TK_WITHOUT 25
9561 #define TK_COMMA 26
9562 #define TK_ID 27
9563 #define TK_INDEXED 28
9564 #define TK_ABORT 29
9565 #define TK_ACTION 30
9566 #define TK_AFTER 31
9567 #define TK_ANALYZE 32
9568 #define TK_ASC 33
9569 #define TK_ATTACH 34
9570 #define TK_BEFORE 35
9571 #define TK_BY 36
9572 #define TK_CASCADE 37
9573 #define TK_CAST 38
9574 #define TK_COLUMNKW 39
9575 #define TK_CONFLICT 40
9576 #define TK_DATABASE 41
9577 #define TK_DESC 42
9578 #define TK_DETACH 43
9579 #define TK_EACH 44
9580 #define TK_FAIL 45
9581 #define TK_FOR 46
9582 #define TK_IGNORE 47
9583 #define TK_INITIALLY 48
9584 #define TK_INSTEAD 49
9585 #define TK_LIKE_KW 50
9586 #define TK_MATCH 51
9587 #define TK_NO 52
9588 #define TK_KEY 53
9589 #define TK_OF 54
9590 #define TK_OFFSET 55
9591 #define TK_PRAGMA 56
9592 #define TK_RAISE 57
9593 #define TK_RECURSIVE 58
9594 #define TK_REPLACE 59
9595 #define TK_RESTRICT 60
9596 #define TK_ROW 61
9597 #define TK_TRIGGER 62
9598 #define TK_VACUUM 63
9599 #define TK_VIEW 64
9600 #define TK_VIRTUAL 65
9601 #define TK_WITH 66
9602 #define TK_REINDEX 67
9603 #define TK_RENAME 68
9604 #define TK_CTIME_KW 69
9605 #define TK_ANY 70
9606 #define TK_OR 71
9607 #define TK_AND 72
9608 #define TK_IS 73
9609 #define TK_BETWEEN 74
9610 #define TK_IN 75
9611 #define TK_ISNULL 76
9612 #define TK_NOTNULL 77
9613 #define TK_NE 78
9614 #define TK_EQ 79
9615 #define TK_GT 80
9616 #define TK_LE 81
9617 #define TK_LT 82
9618 #define TK_GE 83
9619 #define TK_ESCAPE 84
9620 #define TK_BITAND 85
9621 #define TK_BITOR 86
9622 #define TK_LSHIFT 87
9623 #define TK_RSHIFT 88
9624 #define TK_PLUS 89
9625 #define TK_MINUS 90
9626 #define TK_STAR 91
9627 #define TK_SLASH 92
9628 #define TK_REM 93
9629 #define TK_CONCAT 94
9630 #define TK_COLLATE 95
9631 #define TK_BITNOT 96
9632 #define TK_STRING 97
9633 #define TK_JOIN_KW 98
9634 #define TK_CONSTRAINT 99
9635 #define TK_DEFAULT 100
9636 #define TK_NULL 101
9637 #define TK_PRIMARY 102
9638 #define TK_UNIQUE 103
9639 #define TK_CHECK 104
9640 #define TK_REFERENCES 105
9641 #define TK_AUTOINCR 106
9642 #define TK_ON 107
9643 #define TK_INSERT 108
9644 #define TK_DELETE 109
9645 #define TK_UPDATE 110
9646 #define TK_SET 111
9647 #define TK_DEFERRABLE 112
9648 #define TK_FOREIGN 113
9649 #define TK_DROP 114
9650 #define TK_UNION 115
9651 #define TK_ALL 116
9652 #define TK_EXCEPT 117
9653 #define TK_INTERSECT 118
9654 #define TK_SELECT 119
9655 #define TK_VALUES 120
9656 #define TK_DISTINCT 121
9657 #define TK_DOT 122
9658 #define TK_FROM 123
9659 #define TK_JOIN 124
9660 #define TK_USING 125
9661 #define TK_ORDER 126
9662 #define TK_GROUP 127
9663 #define TK_HAVING 128
9664 #define TK_LIMIT 129
9665 #define TK_WHERE 130
9666 #define TK_INTO 131
9667 #define TK_INTEGER 132
9668 #define TK_FLOAT 133
9669 #define TK_BLOB 134
9670 #define TK_VARIABLE 135
9671 #define TK_CASE 136
9672 #define TK_WHEN 137
9673 #define TK_THEN 138
9674 #define TK_ELSE 139
9675 #define TK_INDEX 140
9676 #define TK_ALTER 141
9677 #define TK_ADD 142
9678 #define TK_TO_TEXT 143
9679 #define TK_TO_BLOB 144
9680 #define TK_TO_NUMERIC 145
9681 #define TK_TO_INT 146
9682 #define TK_TO_REAL 147
9683 #define TK_ISNOT 148
9684 #define TK_END_OF_FILE 149
9685 #define TK_UNCLOSED_STRING 150
9686 #define TK_FUNCTION 151
9687 #define TK_COLUMN 152
9688 #define TK_AGG_FUNCTION 153
9689 #define TK_AGG_COLUMN 154
9690 #define TK_UMINUS 155
9691 #define TK_UPLUS 156
9692 #define TK_REGISTER 157
9693 #define TK_ASTERISK 158
9694 #define TK_SPACE 159
9695 #define TK_ILLEGAL 160
9696
9697 /* The token codes above must all fit in 8 bits */
9698 #define TKFLG_MASK 0xff
9699
9700 /* Flags that can be added to a token code when it is not
9701 ** being stored in a u8: */
9702 #define TKFLG_DONTFOLD 0x100 /* Omit constant folding optimizations */
9703
9704 /************** End of parse.h ***********************************************/
9705 /************** Continuing where we left off in sqliteInt.h ******************/
9706 #include <stdio.h>
9707 #include <stdlib.h>
9708 #include <string.h>
9709 #include <assert.h>
9710 #include <stddef.h>
9711
9712 /*
9713 ** If compiling for a processor that lacks floating point support,
9714 ** substitute integer for floating-point
9715 */
9716 #ifdef SQLITE_OMIT_FLOATING_POINT
9717 # define double sqlite_int64
9718 # define float sqlite_int64
9719 # define LONGDOUBLE_TYPE sqlite_int64
9720 # ifndef SQLITE_BIG_DBL
9721 # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
9722 # endif
9723 # define SQLITE_OMIT_DATETIME_FUNCS 1
9724 # define SQLITE_OMIT_TRACE 1
9725 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
9726 # undef SQLITE_HAVE_ISNAN
9727 #endif
9728 #ifndef SQLITE_BIG_DBL
9729 # define SQLITE_BIG_DBL (1e99)
9730 #endif
9731
9732 /*
9733 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
9734 ** afterward. Having this macro allows us to cause the C compiler
9735 ** to omit code used by TEMP tables without messy #ifndef statements.
9736 */
9737 #ifdef SQLITE_OMIT_TEMPDB
9738 #define OMIT_TEMPDB 1
9739 #else
9740 #define OMIT_TEMPDB 0
9741 #endif
9742
9743 /*
9744 ** The "file format" number is an integer that is incremented whenever
9745 ** the VDBE-level file format changes. The following macros define the
9746 ** the default file format for new databases and the maximum file format
9747 ** that the library can read.
9748 */
9749 #define SQLITE_MAX_FILE_FORMAT 4
9750 #ifndef SQLITE_DEFAULT_FILE_FORMAT
9751 # define SQLITE_DEFAULT_FILE_FORMAT 4
9752 #endif
9753
9754 /*
9755 ** Determine whether triggers are recursive by default. This can be
9756 ** changed at run-time using a pragma.
9757 */
9758 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
9759 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
9760 #endif
9761
9762 /*
9763 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
9764 ** on the command-line
9765 */
9766 #ifndef SQLITE_TEMP_STORE
9767 # define SQLITE_TEMP_STORE 1
9768 # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
9769 #endif
9770
9771 /*
9772 ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
9773 ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
9774 ** to zero.
9775 */
9776 #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
9777 # undef SQLITE_MAX_WORKER_THREADS
9778 # define SQLITE_MAX_WORKER_THREADS 0
9779 #endif
9780 #ifndef SQLITE_MAX_WORKER_THREADS
9781 # define SQLITE_MAX_WORKER_THREADS 8
9782 #endif
9783 #ifndef SQLITE_DEFAULT_WORKER_THREADS
9784 # define SQLITE_DEFAULT_WORKER_THREADS 0
9785 #endif
9786 #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
9787 # undef SQLITE_MAX_WORKER_THREADS
9788 # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
9789 #endif
9790
9791 /*
9792 ** The default initial allocation for the pagecache when using separate
9793 ** pagecaches for each database connection. A positive number is the
9794 ** number of pages. A negative number N translations means that a buffer
9795 ** of -1024*N bytes is allocated and used for as many pages as it will hold.
9796 */
9797 #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
9798 # define SQLITE_DEFAULT_PCACHE_INITSZ 100
9799 #endif
9800
9801 /*
9802 ** GCC does not define the offsetof() macro so we'll have to do it
9803 ** ourselves.
9804 */
9805 #ifndef offsetof
9806 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
9807 #endif
9808
9809 /*
9810 ** Macros to compute minimum and maximum of two numbers.
9811 */
9812 #define MIN(A,B) ((A)<(B)?(A):(B))
9813 #define MAX(A,B) ((A)>(B)?(A):(B))
9814
9815 /*
9816 ** Swap two objects of type TYPE.
9817 */
9818 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
9819
9820 /*
9821 ** Check to see if this machine uses EBCDIC. (Yes, believe it or
9822 ** not, there are still machines out there that use EBCDIC.)
9823 */
9824 #if 'A' == '\301'
9825 # define SQLITE_EBCDIC 1
9826 #else
9827 # define SQLITE_ASCII 1
9828 #endif
9829
9830 /*
9831 ** Integers of known sizes. These typedefs might change for architectures
9832 ** where the sizes very. Preprocessor macros are available so that the
9833 ** types can be conveniently redefined at compile-type. Like this:
9834 **
9835 ** cc '-DUINTPTR_TYPE=long long int' ...
9836 */
9837 #ifndef UINT32_TYPE
9838 # ifdef HAVE_UINT32_T
9839 # define UINT32_TYPE uint32_t
9840 # else
9841 # define UINT32_TYPE unsigned int
9842 # endif
9843 #endif
9844 #ifndef UINT16_TYPE
9845 # ifdef HAVE_UINT16_T
9846 # define UINT16_TYPE uint16_t
9847 # else
9848 # define UINT16_TYPE unsigned short int
9849 # endif
9850 #endif
9851 #ifndef INT16_TYPE
9852 # ifdef HAVE_INT16_T
9853 # define INT16_TYPE int16_t
9854 # else
9855 # define INT16_TYPE short int
9856 # endif
9857 #endif
9858 #ifndef UINT8_TYPE
9859 # ifdef HAVE_UINT8_T
9860 # define UINT8_TYPE uint8_t
9861 # else
9862 # define UINT8_TYPE unsigned char
9863 # endif
9864 #endif
9865 #ifndef INT8_TYPE
9866 # ifdef HAVE_INT8_T
9867 # define INT8_TYPE int8_t
9868 # else
9869 # define INT8_TYPE signed char
9870 # endif
9871 #endif
9872 #ifndef LONGDOUBLE_TYPE
9873 # define LONGDOUBLE_TYPE long double
9874 #endif
9875 typedef sqlite_int64 i64; /* 8-byte signed integer */
9876 typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
9877 typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
9878 typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
9879 typedef INT16_TYPE i16; /* 2-byte signed integer */
9880 typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
9881 typedef INT8_TYPE i8; /* 1-byte signed integer */
9882
9883 /*
9884 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
9885 ** that can be stored in a u32 without loss of data. The value
9886 ** is 0x00000000ffffffff. But because of quirks of some compilers, we
9887 ** have to specify the value in the less intuitive manner shown:
9888 */
9889 #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
9890
9891 /*
9892 ** The datatype used to store estimates of the number of rows in a
9893 ** table or index. This is an unsigned integer type. For 99.9% of
9894 ** the world, a 32-bit integer is sufficient. But a 64-bit integer
9895 ** can be used at compile-time if desired.
9896 */
9897 #ifdef SQLITE_64BIT_STATS
9898 typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
9899 #else
9900 typedef u32 tRowcnt; /* 32-bit is the default */
9901 #endif
9902
9903 /*
9904 ** Estimated quantities used for query planning are stored as 16-bit
9905 ** logarithms. For quantity X, the value stored is 10*log2(X). This
9906 ** gives a possible range of values of approximately 1.0e986 to 1e-986.
9907 ** But the allowed values are "grainy". Not every value is representable.
9908 ** For example, quantities 16 and 17 are both represented by a LogEst
9909 ** of 40. However, since LogEst quantities are suppose to be estimates,
9910 ** not exact values, this imprecision is not a problem.
9911 **
9912 ** "LogEst" is short for "Logarithmic Estimate".
9913 **
9914 ** Examples:
9915 ** 1 -> 0 20 -> 43 10000 -> 132
9916 ** 2 -> 10 25 -> 46 25000 -> 146
9917 ** 3 -> 16 100 -> 66 1000000 -> 199
9918 ** 4 -> 20 1000 -> 99 1048576 -> 200
9919 ** 10 -> 33 1024 -> 100 4294967296 -> 320
9920 **
9921 ** The LogEst can be negative to indicate fractional values.
9922 ** Examples:
9923 **
9924 ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
9925 */
9926 typedef INT16_TYPE LogEst;
9927
9928 /*
9929 ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
9930 */
9931 #ifndef SQLITE_PTRSIZE
9932 # if defined(__SIZEOF_POINTER__)
9933 # define SQLITE_PTRSIZE __SIZEOF_POINTER__
9934 # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
9935 defined(_M_ARM) || defined(__arm__) || defined(__x86)
9936 # define SQLITE_PTRSIZE 4
9937 # else
9938 # define SQLITE_PTRSIZE 8
9939 # endif
9940 #endif
9941
9942 /*
9943 ** Macros to determine whether the machine is big or little endian,
9944 ** and whether or not that determination is run-time or compile-time.
9945 **
9946 ** For best performance, an attempt is made to guess at the byte-order
9947 ** using C-preprocessor macros. If that is unsuccessful, or if
9948 ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
9949 ** at run-time.
9950 */
9951 #if (defined(i386) || defined(__i386__) || defined(_M_IX86) || \
9952 defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
9953 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
9954 defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
9955 # define SQLITE_BYTEORDER 1234
9956 # define SQLITE_BIGENDIAN 0
9957 # define SQLITE_LITTLEENDIAN 1
9958 # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
9959 #endif
9960 #if (defined(sparc) || defined(__ppc__)) \
9961 && !defined(SQLITE_RUNTIME_BYTEORDER)
9962 # define SQLITE_BYTEORDER 4321
9963 # define SQLITE_BIGENDIAN 1
9964 # define SQLITE_LITTLEENDIAN 0
9965 # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
9966 #endif
9967 #if !defined(SQLITE_BYTEORDER)
9968 # ifdef SQLITE_AMALGAMATION
9969 const int sqlite3one = 1;
9970 # else
9971 extern const int sqlite3one;
9972 # endif
9973 # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
9974 # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
9975 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
9976 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
9977 #endif
9978
9979 /*
9980 ** Constants for the largest and smallest possible 64-bit signed integers.
9981 ** These macros are designed to work correctly on both 32-bit and 64-bit
9982 ** compilers.
9983 */
9984 #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
9985 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
9986
9987 /*
9988 ** Round up a number to the next larger multiple of 8. This is used
9989 ** to force 8-byte alignment on 64-bit architectures.
9990 */
9991 #define ROUND8(x) (((x)+7)&~7)
9992
9993 /*
9994 ** Round down to the nearest multiple of 8
9995 */
9996 #define ROUNDDOWN8(x) ((x)&~7)
9997
9998 /*
9999 ** Assert that the pointer X is aligned to an 8-byte boundary. This
10000 ** macro is used only within assert() to verify that the code gets
10001 ** all alignment restrictions correct.
10002 **
10003 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
10004 ** underlying malloc() implementation might return us 4-byte aligned
10005 ** pointers. In that case, only verify 4-byte alignment.
10006 */
10007 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
10008 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
10009 #else
10010 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
10011 #endif
10012
10013 /*
10014 ** Disable MMAP on platforms where it is known to not work
10015 */
10016 #if defined(__OpenBSD__) || defined(__QNXNTO__)
10017 # undef SQLITE_MAX_MMAP_SIZE
10018 # define SQLITE_MAX_MMAP_SIZE 0
10019 #endif
10020
10021 /*
10022 ** Default maximum size of memory used by memory-mapped I/O in the VFS
10023 */
10024 #ifdef __APPLE__
10025 # include <TargetConditionals.h>
10026 # if TARGET_OS_IPHONE
10027 # undef SQLITE_MAX_MMAP_SIZE
10028 # define SQLITE_MAX_MMAP_SIZE 0
10029 # endif
10030 #endif
10031 #ifndef SQLITE_MAX_MMAP_SIZE
10032 # if defined(__linux__) \
10033 || defined(_WIN32) \
10034 || (defined(__APPLE__) && defined(__MACH__)) \
10035 || defined(__sun) \
10036 || defined(__FreeBSD__) \
10037 || defined(__DragonFly__)
10038 # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
10039 # else
10040 # define SQLITE_MAX_MMAP_SIZE 0
10041 # endif
10042 # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
10043 #endif
10044
10045 /*
10046 ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
10047 ** default MMAP_SIZE is specified at compile-time, make sure that it does
10048 ** not exceed the maximum mmap size.
10049 */
10050 #ifndef SQLITE_DEFAULT_MMAP_SIZE
10051 # define SQLITE_DEFAULT_MMAP_SIZE 0
10052 # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
10053 #endif
10054 #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
10055 # undef SQLITE_DEFAULT_MMAP_SIZE
10056 # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
10057 #endif
10058
10059 /*
10060 ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
10061 ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
10062 ** define SQLITE_ENABLE_STAT3_OR_STAT4
10063 */
10064 #ifdef SQLITE_ENABLE_STAT4
10065 # undef SQLITE_ENABLE_STAT3
10066 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
10067 #elif SQLITE_ENABLE_STAT3
10068 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
10069 #elif SQLITE_ENABLE_STAT3_OR_STAT4
10070 # undef SQLITE_ENABLE_STAT3_OR_STAT4
10071 #endif
10072
10073 /*
10074 ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
10075 ** the Select query generator tracing logic is turned on.
10076 */
10077 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
10078 # define SELECTTRACE_ENABLED 1
10079 #else
10080 # define SELECTTRACE_ENABLED 0
10081 #endif
10082
10083 /*
10084 ** An instance of the following structure is used to store the busy-handler
10085 ** callback for a given sqlite handle.
10086 **
10087 ** The sqlite.busyHandler member of the sqlite struct contains the busy
10088 ** callback for the database handle. Each pager opened via the sqlite
10089 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
10090 ** callback is currently invoked only from within pager.c.
10091 */
10092 typedef struct BusyHandler BusyHandler;
10093 struct BusyHandler {
10094 int (*xFunc)(void *,int); /* The busy callback */
10095 void *pArg; /* First arg to busy callback */
10096 int nBusy; /* Incremented with each busy call */
10097 };
10098
10099 /*
10100 ** Name of the master database table. The master database table
10101 ** is a special table that holds the names and attributes of all
10102 ** user tables and indices.
10103 */
10104 #define MASTER_NAME "sqlite_master"
10105 #define TEMP_MASTER_NAME "sqlite_temp_master"
10106
10107 /*
10108 ** The root-page of the master database table.
10109 */
10110 #define MASTER_ROOT 1
10111
10112 /*
10113 ** The name of the schema table.
10114 */
10115 #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
10116
10117 /*
10118 ** A convenience macro that returns the number of elements in
10119 ** an array.
10120 */
10121 #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
10122
10123 /*
10124 ** Determine if the argument is a power of two
10125 */
10126 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
10127
10128 /*
10129 ** The following value as a destructor means to use sqlite3DbFree().
10130 ** The sqlite3DbFree() routine requires two parameters instead of the
10131 ** one parameter that destructors normally want. So we have to introduce
10132 ** this magic value that the code knows to handle differently. Any
10133 ** pointer will work here as long as it is distinct from SQLITE_STATIC
10134 ** and SQLITE_TRANSIENT.
10135 */
10136 #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
10137
10138 /*
10139 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
10140 ** not support Writable Static Data (WSD) such as global and static variables.
10141 ** All variables must either be on the stack or dynamically allocated from
10142 ** the heap. When WSD is unsupported, the variable declarations scattered
10143 ** throughout the SQLite code must become constants instead. The SQLITE_WSD
10144 ** macro is used for this purpose. And instead of referencing the variable
10145 ** directly, we use its constant as a key to lookup the run-time allocated
10146 ** buffer that holds real variable. The constant is also the initializer
10147 ** for the run-time allocated buffer.
10148 **
10149 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
10150 ** macros become no-ops and have zero performance impact.
10151 */
10152 #ifdef SQLITE_OMIT_WSD
10153 #define SQLITE_WSD const
10154 #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
10155 #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
10156 SQLITE_API int SQLITE_STDCALL sqlite3_wsd_init(int N, int J);
10157 SQLITE_API void *SQLITE_STDCALL sqlite3_wsd_find(void *K, int L);
10158 #else
10159 #define SQLITE_WSD
10160 #define GLOBAL(t,v) v
10161 #define sqlite3GlobalConfig sqlite3Config
10162 #endif
10163
10164 /*
10165 ** The following macros are used to suppress compiler warnings and to
10166 ** make it clear to human readers when a function parameter is deliberately
10167 ** left unused within the body of a function. This usually happens when
10168 ** a function is called via a function pointer. For example the
10169 ** implementation of an SQL aggregate step callback may not use the
10170 ** parameter indicating the number of arguments passed to the aggregate,
10171 ** if it knows that this is enforced elsewhere.
10172 **
10173 ** When a function parameter is not used at all within the body of a function,
10174 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
10175 ** However, these macros may also be used to suppress warnings related to
10176 ** parameters that may or may not be used depending on compilation options.
10177 ** For example those parameters only used in assert() statements. In these
10178 ** cases the parameters are named as per the usual conventions.
10179 */
10180 #define UNUSED_PARAMETER(x) (void)(x)
10181 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
10182
10183 /*
10184 ** Forward references to structures
10185 */
10186 typedef struct AggInfo AggInfo;
10187 typedef struct AuthContext AuthContext;
10188 typedef struct AutoincInfo AutoincInfo;
10189 typedef struct Bitvec Bitvec;
10190 typedef struct CollSeq CollSeq;
10191 typedef struct Column Column;
10192 typedef struct Db Db;
10193 typedef struct Schema Schema;
10194 typedef struct Expr Expr;
10195 typedef struct ExprList ExprList;
10196 typedef struct ExprSpan ExprSpan;
10197 typedef struct FKey FKey;
10198 typedef struct FuncDestructor FuncDestructor;
10199 typedef struct FuncDef FuncDef;
10200 typedef struct FuncDefHash FuncDefHash;
10201 typedef struct IdList IdList;
10202 typedef struct Index Index;
10203 typedef struct IndexSample IndexSample;
10204 typedef struct KeyClass KeyClass;
10205 typedef struct KeyInfo KeyInfo;
10206 typedef struct Lookaside Lookaside;
10207 typedef struct LookasideSlot LookasideSlot;
10208 typedef struct Module Module;
10209 typedef struct NameContext NameContext;
10210 typedef struct Parse Parse;
10211 typedef struct PrintfArguments PrintfArguments;
10212 typedef struct RowSet RowSet;
10213 typedef struct Savepoint Savepoint;
10214 typedef struct Select Select;
10215 typedef struct SQLiteThread SQLiteThread;
10216 typedef struct SelectDest SelectDest;
10217 typedef struct SrcList SrcList;
10218 typedef struct StrAccum StrAccum;
10219 typedef struct Table Table;
10220 typedef struct TableLock TableLock;
10221 typedef struct Token Token;
10222 typedef struct TreeView TreeView;
10223 typedef struct Trigger Trigger;
10224 typedef struct TriggerPrg TriggerPrg;
10225 typedef struct TriggerStep TriggerStep;
10226 typedef struct UnpackedRecord UnpackedRecord;
10227 typedef struct VTable VTable;
10228 typedef struct VtabCtx VtabCtx;
10229 typedef struct Walker Walker;
10230 typedef struct WhereInfo WhereInfo;
10231 typedef struct With With;
10232
10233 /*
10234 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
10235 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
10236 ** pointer types (i.e. FuncDef) defined above.
10237 */
10238 /************** Include btree.h in the middle of sqliteInt.h *****************/
10239 /************** Begin file btree.h *******************************************/
10240 /*
10241 ** 2001 September 15
10242 **
10243 ** The author disclaims copyright to this source code. In place of
10244 ** a legal notice, here is a blessing:
10245 **
10246 ** May you do good and not evil.
10247 ** May you find forgiveness for yourself and forgive others.
10248 ** May you share freely, never taking more than you give.
10249 **
10250 *************************************************************************
10251 ** This header file defines the interface that the sqlite B-Tree file
10252 ** subsystem. See comments in the source code for a detailed description
10253 ** of what each interface routine does.
10254 */
10255 #ifndef _BTREE_H_
10256 #define _BTREE_H_
10257
10258 /* TODO: This definition is just included so other modules compile. It
10259 ** needs to be revisited.
10260 */
10261 #define SQLITE_N_BTREE_META 16
10262
10263 /*
10264 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
10265 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
10266 */
10267 #ifndef SQLITE_DEFAULT_AUTOVACUUM
10268 #define SQLITE_DEFAULT_AUTOVACUUM 0
10269 #endif
10270
10271 #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
10272 #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
10273 #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
10274
10275 /*
10276 ** Forward declarations of structure
10277 */
10278 typedef struct Btree Btree;
10279 typedef struct BtCursor BtCursor;
10280 typedef struct BtShared BtShared;
10281
10282
10283 SQLITE_PRIVATE int sqlite3BtreeOpen(
10284 sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
10285 const char *zFilename, /* Name of database file to open */
10286 sqlite3 *db, /* Associated database connection */
10287 Btree **ppBtree, /* Return open Btree* here */
10288 int flags, /* Flags */
10289 int vfsFlags /* Flags passed through to VFS open */
10290 );
10291
10292 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
10293 ** following values.
10294 **
10295 ** NOTE: These values must match the corresponding PAGER_ values in
10296 ** pager.h.
10297 */
10298 #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
10299 #define BTREE_MEMORY 2 /* This is an in-memory DB */
10300 #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
10301 #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
10302
10303 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
10304 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
10305 SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
10306 #if SQLITE_MAX_MMAP_SIZE>0
10307 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
10308 #endif
10309 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
10310 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
10311 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve , int eFix);
10312 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
10313 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
10314 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
10315 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
10316 SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
10317 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
10318 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
10319 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
10320 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
10321 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
10322 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
10323 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
10324 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
10325 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
10326 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
10327 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
10328 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
10329 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
10330 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
10331 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
10332 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock );
10333 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
10334
10335 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
10336 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
10337 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
10338
10339 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
10340
10341 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
10342 ** of the flags shown below.
10343 **
10344 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
10345 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
10346 ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
10347 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
10348 ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
10349 ** indices.)
10350 */
10351 #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
10352 #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
10353
10354 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
10355 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
10356 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
10357 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
10358
10359 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
10360 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
10361
10362 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
10363
10364 /*
10365 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
10366 ** should be one of the following values. The integer values are assigned
10367 ** to constants so that the offset of the corresponding field in an
10368 ** SQLite database header may be found using the following formula:
10369 **
10370 ** offset = 36 + (idx * 4)
10371 **
10372 ** For example, the free-page-count field is located at byte offset 36 of
10373 ** the database file header. The incr-vacuum-flag field is located at
10374 ** byte offset 64 (== 36+4*7).
10375 **
10376 ** The BTREE_DATA_VERSION value is not really a value stored in the header.
10377 ** It is a read-only number computed by the pager. But we merge it with
10378 ** the header value access routines since its access pattern is the same.
10379 ** Call it a "virtual meta value".
10380 */
10381 #define BTREE_FREE_PAGE_COUNT 0
10382 #define BTREE_SCHEMA_VERSION 1
10383 #define BTREE_FILE_FORMAT 2
10384 #define BTREE_DEFAULT_CACHE_SIZE 3
10385 #define BTREE_LARGEST_ROOT_PAGE 4
10386 #define BTREE_TEXT_ENCODING 5
10387 #define BTREE_USER_VERSION 6
10388 #define BTREE_INCR_VACUUM 7
10389 #define BTREE_APPLICATION_ID 8
10390 #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
10391
10392 /*
10393 ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
10394 ** interface.
10395 **
10396 ** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
10397 **
10398 ** The first argument is an Expr* (which is guaranteed to be constant for
10399 ** the lifetime of the cursor) that defines constraints on which rows
10400 ** might be fetched with this cursor. The Expr* tree may contain
10401 ** TK_REGISTER nodes that refer to values stored in the array of registers
10402 ** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
10403 ** then the value of the node is the value in Mem[pExpr.iTable]. Any
10404 ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
10405 ** column of the b-tree of the cursor. The Expr tree will not contain
10406 ** any function calls nor subqueries nor references to b-trees other than
10407 ** the cursor being hinted.
10408 **
10409 ** The design of the _RANGE hint is aid b-tree implementations that try
10410 ** to prefetch content from remote machines - to provide those
10411 ** implementations with limits on what needs to be prefetched and thereby
10412 ** reduce network bandwidth.
10413 **
10414 ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
10415 ** standard SQLite. The other hints are provided for extentions that use
10416 ** the SQLite parser and code generator but substitute their own storage
10417 ** engine.
10418 */
10419 #define BTREE_HINT_RANGE 0 /* Range constraints on queries */
10420
10421 /*
10422 ** Values that may be OR'd together to form the argument to the
10423 ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
10424 **
10425 ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
10426 ** to be filled with content that is already in sorted order.
10427 **
10428 ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
10429 ** OP_SeekLE opcodes for a range search, but where the range of entries
10430 ** selected will all have the same key. In other words, the cursor will
10431 ** be used only for equality key searches.
10432 **
10433 */
10434 #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
10435 #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
10436
10437 /*
10438 ** Flags passed as the third argument to sqlite3BtreeCursor().
10439 **
10440 ** For read-only cursors the wrFlag argument is always zero. For read-write
10441 ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or
10442 ** (BTREE_WRCSR). If the BTREE_FORDELETE flag is set, then the cursor will
10443 ** only be used by SQLite for the following:
10444 **
10445 ** * to seek to and delete specific entries, and/or
10446 **
10447 ** * to read values that will be used to create keys that other
10448 ** BTREE_FORDELETE cursors will seek to and delete.
10449 */
10450 #define BTREE_WRCSR 0x00000004 /* read-write cursor */
10451 #define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */
10452
10453 SQLITE_PRIVATE int sqlite3BtreeCursor(
10454 Btree*, /* BTree containing table to open */
10455 int iTable, /* Index of root page */
10456 int wrFlag, /* 1 for writing. 0 for read-only */
10457 struct KeyInfo*, /* First argument to compare function */
10458 BtCursor *pCursor /* Space to write cursor structure */
10459 );
10460 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
10461 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
10462 SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
10463 #ifdef SQLITE_ENABLE_CURSOR_HINTS
10464 SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
10465 #endif
10466
10467 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
10468 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
10469 BtCursor*,
10470 UnpackedRecord *pUnKey,
10471 i64 intKey,
10472 int bias,
10473 int *pRes
10474 );
10475 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
10476 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
10477 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, int);
10478 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
10479 const void *pData, int nData,
10480 int nZero, int bias, int seekResult);
10481 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
10482 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
10483 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
10484 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
10485 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
10486 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
10487 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
10488 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
10489 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
10490 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
10491 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
10492
10493 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, i nt, int*);
10494 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
10495
10496 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
10497 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
10498 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
10499 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
10500 SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
10501 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
10502 SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
10503
10504 #ifndef NDEBUG
10505 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
10506 #endif
10507
10508 #ifndef SQLITE_OMIT_BTREECOUNT
10509 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
10510 #endif
10511
10512 #ifdef SQLITE_TEST
10513 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
10514 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
10515 #endif
10516
10517 #ifndef SQLITE_OMIT_WAL
10518 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
10519 #endif
10520
10521 /*
10522 ** If we are not using shared cache, then there is no need to
10523 ** use mutexes to access the BtShared structures. So make the
10524 ** Enter and Leave procedures no-ops.
10525 */
10526 #ifndef SQLITE_OMIT_SHARED_CACHE
10527 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
10528 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
10529 #else
10530 # define sqlite3BtreeEnter(X)
10531 # define sqlite3BtreeEnterAll(X)
10532 #endif
10533
10534 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
10535 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
10536 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
10537 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
10538 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
10539 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
10540 #ifndef NDEBUG
10541 /* These routines are used inside assert() statements only. */
10542 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
10543 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
10544 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
10545 #endif
10546 #else
10547
10548 # define sqlite3BtreeSharable(X) 0
10549 # define sqlite3BtreeLeave(X)
10550 # define sqlite3BtreeEnterCursor(X)
10551 # define sqlite3BtreeLeaveCursor(X)
10552 # define sqlite3BtreeLeaveAll(X)
10553
10554 # define sqlite3BtreeHoldsMutex(X) 1
10555 # define sqlite3BtreeHoldsAllMutexes(X) 1
10556 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
10557 #endif
10558
10559
10560 #endif /* _BTREE_H_ */
10561
10562 /************** End of btree.h ***********************************************/
10563 /************** Continuing where we left off in sqliteInt.h ******************/
10564 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
10565 /************** Begin file vdbe.h ********************************************/
10566 /*
10567 ** 2001 September 15
10568 **
10569 ** The author disclaims copyright to this source code. In place of
10570 ** a legal notice, here is a blessing:
10571 **
10572 ** May you do good and not evil.
10573 ** May you find forgiveness for yourself and forgive others.
10574 ** May you share freely, never taking more than you give.
10575 **
10576 *************************************************************************
10577 ** Header file for the Virtual DataBase Engine (VDBE)
10578 **
10579 ** This header defines the interface to the virtual database engine
10580 ** or VDBE. The VDBE implements an abstract machine that runs a
10581 ** simple program to access and modify the underlying database.
10582 */
10583 #ifndef _SQLITE_VDBE_H_
10584 #define _SQLITE_VDBE_H_
10585 /* #include <stdio.h> */
10586
10587 /*
10588 ** A single VDBE is an opaque structure named "Vdbe". Only routines
10589 ** in the source file sqliteVdbe.c are allowed to see the insides
10590 ** of this structure.
10591 */
10592 typedef struct Vdbe Vdbe;
10593
10594 /*
10595 ** The names of the following types declared in vdbeInt.h are required
10596 ** for the VdbeOp definition.
10597 */
10598 typedef struct Mem Mem;
10599 typedef struct SubProgram SubProgram;
10600
10601 /*
10602 ** A single instruction of the virtual machine has an opcode
10603 ** and as many as three operands. The instruction is recorded
10604 ** as an instance of the following structure:
10605 */
10606 struct VdbeOp {
10607 u8 opcode; /* What operation to perform */
10608 signed char p4type; /* One of the P4_xxx constants for p4 */
10609 u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
10610 u8 p5; /* Fifth parameter is an unsigned character */
10611 int p1; /* First operand */
10612 int p2; /* Second parameter (often the jump destination) */
10613 int p3; /* The third parameter */
10614 union p4union { /* fourth parameter */
10615 int i; /* Integer value if p4type==P4_INT32 */
10616 void *p; /* Generic pointer */
10617 char *z; /* Pointer to data for string (char array) types */
10618 i64 *pI64; /* Used when p4type is P4_INT64 */
10619 double *pReal; /* Used when p4type is P4_REAL */
10620 FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
10621 sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
10622 CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
10623 Mem *pMem; /* Used when p4type is P4_MEM */
10624 VTable *pVtab; /* Used when p4type is P4_VTAB */
10625 KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
10626 int *ai; /* Used when p4type is P4_INTARRAY */
10627 SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
10628 #ifdef SQLITE_ENABLE_CURSOR_HINTS
10629 Expr *pExpr; /* Used when p4type is P4_EXPR */
10630 #endif
10631 int (*xAdvance)(BtCursor *, int *);
10632 } p4;
10633 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
10634 char *zComment; /* Comment to improve readability */
10635 #endif
10636 #ifdef VDBE_PROFILE
10637 u32 cnt; /* Number of times this instruction was executed */
10638 u64 cycles; /* Total time spent executing this instruction */
10639 #endif
10640 #ifdef SQLITE_VDBE_COVERAGE
10641 int iSrcLine; /* Source-code line that generated this opcode */
10642 #endif
10643 };
10644 typedef struct VdbeOp VdbeOp;
10645
10646
10647 /*
10648 ** A sub-routine used to implement a trigger program.
10649 */
10650 struct SubProgram {
10651 VdbeOp *aOp; /* Array of opcodes for sub-program */
10652 int nOp; /* Elements in aOp[] */
10653 int nMem; /* Number of memory cells required */
10654 int nCsr; /* Number of cursors required */
10655 int nOnce; /* Number of OP_Once instructions */
10656 void *token; /* id that may be used to recursive triggers */
10657 SubProgram *pNext; /* Next sub-program already visited */
10658 };
10659
10660 /*
10661 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
10662 ** it takes up less space.
10663 */
10664 struct VdbeOpList {
10665 u8 opcode; /* What operation to perform */
10666 signed char p1; /* First operand */
10667 signed char p2; /* Second parameter (often the jump destination) */
10668 signed char p3; /* Third parameter */
10669 };
10670 typedef struct VdbeOpList VdbeOpList;
10671
10672 /*
10673 ** Allowed values of VdbeOp.p4type
10674 */
10675 #define P4_NOTUSED 0 /* The P4 parameter is not used */
10676 #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
10677 #define P4_STATIC (-2) /* Pointer to a static string */
10678 #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
10679 #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
10680 #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
10681 #define P4_EXPR (-7) /* P4 is a pointer to an Expr tree */
10682 #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
10683 #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
10684 #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
10685 #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
10686 #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
10687 #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
10688 #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
10689 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
10690 #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
10691 #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
10692 #define P4_FUNCCTX (-20) /* P4 is a pointer to an sqlite3_context object */
10693
10694 /* Error message codes for OP_Halt */
10695 #define P5_ConstraintNotNull 1
10696 #define P5_ConstraintUnique 2
10697 #define P5_ConstraintCheck 3
10698 #define P5_ConstraintFK 4
10699
10700 /*
10701 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
10702 ** number of columns of data returned by the statement.
10703 */
10704 #define COLNAME_NAME 0
10705 #define COLNAME_DECLTYPE 1
10706 #define COLNAME_DATABASE 2
10707 #define COLNAME_TABLE 3
10708 #define COLNAME_COLUMN 4
10709 #ifdef SQLITE_ENABLE_COLUMN_METADATA
10710 # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
10711 #else
10712 # ifdef SQLITE_OMIT_DECLTYPE
10713 # define COLNAME_N 1 /* Store only the name */
10714 # else
10715 # define COLNAME_N 2 /* Store the name and decltype */
10716 # endif
10717 #endif
10718
10719 /*
10720 ** The following macro converts a relative address in the p2 field
10721 ** of a VdbeOp structure into a negative number so that
10722 ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
10723 ** the macro again restores the address.
10724 */
10725 #define ADDR(X) (-1-(X))
10726
10727 /*
10728 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
10729 ** header file that defines a number for each opcode used by the VDBE.
10730 */
10731 /************** Include opcodes.h in the middle of vdbe.h ********************/
10732 /************** Begin file opcodes.h *****************************************/
10733 /* Automatically generated. Do not edit */
10734 /* See the tool/mkopcodeh.tcl script for details */
10735 #define OP_Savepoint 1
10736 #define OP_AutoCommit 2
10737 #define OP_Transaction 3
10738 #define OP_SorterNext 4
10739 #define OP_PrevIfOpen 5
10740 #define OP_NextIfOpen 6
10741 #define OP_Prev 7
10742 #define OP_Next 8
10743 #define OP_Checkpoint 9
10744 #define OP_JournalMode 10
10745 #define OP_Vacuum 11
10746 #define OP_VFilter 12 /* synopsis: iplan=r[P3] zplan='P4' */
10747 #define OP_VUpdate 13 /* synopsis: data=r[P3@P2] */
10748 #define OP_Goto 14
10749 #define OP_Gosub 15
10750 #define OP_Return 16
10751 #define OP_InitCoroutine 17
10752 #define OP_EndCoroutine 18
10753 #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
10754 #define OP_Yield 20
10755 #define OP_HaltIfNull 21 /* synopsis: if r[P3]=null halt */
10756 #define OP_Halt 22
10757 #define OP_Integer 23 /* synopsis: r[P2]=P1 */
10758 #define OP_Int64 24 /* synopsis: r[P2]=P4 */
10759 #define OP_String 25 /* synopsis: r[P2]='P4' (len=P1) */
10760 #define OP_Null 26 /* synopsis: r[P2..P3]=NULL */
10761 #define OP_SoftNull 27 /* synopsis: r[P1]=NULL */
10762 #define OP_Blob 28 /* synopsis: r[P2]=P4 (len=P1) */
10763 #define OP_Variable 29 /* synopsis: r[P2]=parameter(P1,P4) */
10764 #define OP_Move 30 /* synopsis: r[P2@P3]=r[P1@P3] */
10765 #define OP_Copy 31 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
10766 #define OP_SCopy 32 /* synopsis: r[P2]=r[P1] */
10767 #define OP_IntCopy 33 /* synopsis: r[P2]=r[P1] */
10768 #define OP_ResultRow 34 /* synopsis: output=r[P1@P2] */
10769 #define OP_CollSeq 35
10770 #define OP_Function0 36 /* synopsis: r[P3]=func(r[P2@P5]) */
10771 #define OP_Function 37 /* synopsis: r[P3]=func(r[P2@P5]) */
10772 #define OP_AddImm 38 /* synopsis: r[P1]=r[P1]+P2 */
10773 #define OP_MustBeInt 39
10774 #define OP_RealAffinity 40
10775 #define OP_Cast 41 /* synopsis: affinity(r[P1]) */
10776 #define OP_Permutation 42
10777 #define OP_Compare 43 /* synopsis: r[P1@P3] <-> r[P2@P3] */
10778 #define OP_Jump 44
10779 #define OP_Once 45
10780 #define OP_If 46
10781 #define OP_IfNot 47
10782 #define OP_Column 48 /* synopsis: r[P3]=PX */
10783 #define OP_Affinity 49 /* synopsis: affinity(r[P1@P2]) */
10784 #define OP_MakeRecord 50 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
10785 #define OP_Count 51 /* synopsis: r[P2]=count() */
10786 #define OP_ReadCookie 52
10787 #define OP_SetCookie 53
10788 #define OP_ReopenIdx 54 /* synopsis: root=P2 iDb=P3 */
10789 #define OP_OpenRead 55 /* synopsis: root=P2 iDb=P3 */
10790 #define OP_OpenWrite 56 /* synopsis: root=P2 iDb=P3 */
10791 #define OP_OpenAutoindex 57 /* synopsis: nColumn=P2 */
10792 #define OP_OpenEphemeral 58 /* synopsis: nColumn=P2 */
10793 #define OP_SorterOpen 59
10794 #define OP_SequenceTest 60 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
10795 #define OP_OpenPseudo 61 /* synopsis: P3 columns in r[P2] */
10796 #define OP_Close 62
10797 #define OP_ColumnsUsed 63
10798 #define OP_SeekLT 64 /* synopsis: key=r[P3@P4] */
10799 #define OP_SeekLE 65 /* synopsis: key=r[P3@P4] */
10800 #define OP_SeekGE 66 /* synopsis: key=r[P3@P4] */
10801 #define OP_SeekGT 67 /* synopsis: key=r[P3@P4] */
10802 #define OP_Seek 68 /* synopsis: intkey=r[P2] */
10803 #define OP_NoConflict 69 /* synopsis: key=r[P3@P4] */
10804 #define OP_NotFound 70 /* synopsis: key=r[P3@P4] */
10805 #define OP_Or 71 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
10806 #define OP_And 72 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
10807 #define OP_Found 73 /* synopsis: key=r[P3@P4] */
10808 #define OP_NotExists 74 /* synopsis: intkey=r[P3] */
10809 #define OP_Sequence 75 /* synopsis: r[P2]=cursor[P1].ctr++ */
10810 #define OP_IsNull 76 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
10811 #define OP_NotNull 77 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL got o P2 */
10812 #define OP_Ne 78 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
10813 #define OP_Eq 79 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
10814 #define OP_Gt 80 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
10815 #define OP_Le 81 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
10816 #define OP_Lt 82 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
10817 #define OP_Ge 83 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
10818 #define OP_NewRowid 84 /* synopsis: r[P2]=rowid */
10819 #define OP_BitAnd 85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] * /
10820 #define OP_BitOr 86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
10821 #define OP_ShiftLeft 87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
10822 #define OP_ShiftRight 88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
10823 #define OP_Add 89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
10824 #define OP_Subtract 90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
10825 #define OP_Multiply 91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
10826 #define OP_Divide 92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
10827 #define OP_Remainder 93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
10828 #define OP_Concat 94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] * /
10829 #define OP_Insert 95 /* synopsis: intkey=r[P3] data=r[P2] */
10830 #define OP_BitNot 96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
10831 #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
10832 #define OP_InsertInt 98 /* synopsis: intkey=P3 data=r[P2] */
10833 #define OP_Delete 99
10834 #define OP_ResetCount 100
10835 #define OP_SorterCompare 101 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
10836 #define OP_SorterData 102 /* synopsis: r[P2]=data */
10837 #define OP_RowKey 103 /* synopsis: r[P2]=key */
10838 #define OP_RowData 104 /* synopsis: r[P2]=data */
10839 #define OP_Rowid 105 /* synopsis: r[P2]=rowid */
10840 #define OP_NullRow 106
10841 #define OP_Last 107
10842 #define OP_SorterSort 108
10843 #define OP_Sort 109
10844 #define OP_Rewind 110
10845 #define OP_SorterInsert 111
10846 #define OP_IdxInsert 112 /* synopsis: key=r[P2] */
10847 #define OP_IdxDelete 113 /* synopsis: key=r[P2@P3] */
10848 #define OP_IdxRowid 114 /* synopsis: r[P2]=rowid */
10849 #define OP_IdxLE 115 /* synopsis: key=r[P3@P4] */
10850 #define OP_IdxGT 116 /* synopsis: key=r[P3@P4] */
10851 #define OP_IdxLT 117 /* synopsis: key=r[P3@P4] */
10852 #define OP_IdxGE 118 /* synopsis: key=r[P3@P4] */
10853 #define OP_Destroy 119
10854 #define OP_Clear 120
10855 #define OP_ResetSorter 121
10856 #define OP_CreateIndex 122 /* synopsis: r[P2]=root iDb=P1 */
10857 #define OP_CreateTable 123 /* synopsis: r[P2]=root iDb=P1 */
10858 #define OP_ParseSchema 124
10859 #define OP_LoadAnalysis 125
10860 #define OP_DropTable 126
10861 #define OP_DropIndex 127
10862 #define OP_DropTrigger 128
10863 #define OP_IntegrityCk 129
10864 #define OP_RowSetAdd 130 /* synopsis: rowset(P1)=r[P2] */
10865 #define OP_RowSetRead 131 /* synopsis: r[P3]=rowset(P1) */
10866 #define OP_RowSetTest 132 /* synopsis: if r[P3] in rowset(P1) goto P2 */
10867 #define OP_Real 133 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
10868 #define OP_Program 134
10869 #define OP_Param 135
10870 #define OP_FkCounter 136 /* synopsis: fkctr[P1]+=P2 */
10871 #define OP_FkIfZero 137 /* synopsis: if fkctr[P1]==0 goto P2 */
10872 #define OP_MemMax 138 /* synopsis: r[P1]=max(r[P1],r[P2]) */
10873 #define OP_IfPos 139 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
10874 #define OP_SetIfNotPos 140 /* synopsis: if r[P1]<=0 then r[P2]=P3 */
10875 #define OP_IfNotZero 141 /* synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2 */
10876 #define OP_DecrJumpZero 142 /* synopsis: if (--r[P1])==0 goto P2 */
10877 #define OP_JumpZeroIncr 143 /* synopsis: if (r[P1]++)==0 ) goto P2 */
10878 #define OP_AggStep0 144 /* synopsis: accum=r[P3] step(r[P2@P5]) */
10879 #define OP_AggStep 145 /* synopsis: accum=r[P3] step(r[P2@P5]) */
10880 #define OP_AggFinal 146 /* synopsis: accum=r[P1] N=P2 */
10881 #define OP_IncrVacuum 147
10882 #define OP_Expire 148
10883 #define OP_TableLock 149 /* synopsis: iDb=P1 root=P2 write=P3 */
10884 #define OP_VBegin 150
10885 #define OP_VCreate 151
10886 #define OP_VDestroy 152
10887 #define OP_VOpen 153
10888 #define OP_VColumn 154 /* synopsis: r[P3]=vcolumn(P2) */
10889 #define OP_VNext 155
10890 #define OP_VRename 156
10891 #define OP_Pagecount 157
10892 #define OP_MaxPgcnt 158
10893 #define OP_Init 159 /* synopsis: Start at P2 */
10894 #define OP_CursorHint 160
10895 #define OP_Noop 161
10896 #define OP_Explain 162
10897
10898 /* Properties such as "out2" or "jump" that are specified in
10899 ** comments following the "case" for each opcode in the vdbe.c
10900 ** are encoded into bitvectors as follows:
10901 */
10902 #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
10903 #define OPFLG_IN1 0x0002 /* in1: P1 is an input */
10904 #define OPFLG_IN2 0x0004 /* in2: P2 is an input */
10905 #define OPFLG_IN3 0x0008 /* in3: P3 is an input */
10906 #define OPFLG_OUT2 0x0010 /* out2: P2 is an output */
10907 #define OPFLG_OUT3 0x0020 /* out3: P3 is an output */
10908 #define OPFLG_INITIALIZER {\
10909 /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01,\
10910 /* 8 */ 0x01, 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01,\
10911 /* 16 */ 0x02, 0x01, 0x02, 0x12, 0x03, 0x08, 0x00, 0x10,\
10912 /* 24 */ 0x10, 0x10, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00,\
10913 /* 32 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x02, 0x03,\
10914 /* 40 */ 0x02, 0x02, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03,\
10915 /* 48 */ 0x00, 0x00, 0x00, 0x10, 0x10, 0x08, 0x00, 0x00,\
10916 /* 56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
10917 /* 64 */ 0x09, 0x09, 0x09, 0x09, 0x04, 0x09, 0x09, 0x26,\
10918 /* 72 */ 0x26, 0x09, 0x09, 0x10, 0x03, 0x03, 0x0b, 0x0b,\
10919 /* 80 */ 0x0b, 0x0b, 0x0b, 0x0b, 0x10, 0x26, 0x26, 0x26,\
10920 /* 88 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00,\
10921 /* 96 */ 0x12, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
10922 /* 104 */ 0x00, 0x10, 0x00, 0x01, 0x01, 0x01, 0x01, 0x04,\
10923 /* 112 */ 0x04, 0x00, 0x10, 0x01, 0x01, 0x01, 0x01, 0x10,\
10924 /* 120 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00,\
10925 /* 128 */ 0x00, 0x00, 0x06, 0x23, 0x0b, 0x10, 0x01, 0x10,\
10926 /* 136 */ 0x00, 0x01, 0x04, 0x03, 0x06, 0x03, 0x03, 0x03,\
10927 /* 144 */ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,\
10928 /* 152 */ 0x00, 0x00, 0x00, 0x01, 0x00, 0x10, 0x10, 0x01,\
10929 /* 160 */ 0x00, 0x00, 0x00,}
10930
10931 /************** End of opcodes.h *********************************************/
10932 /************** Continuing where we left off in vdbe.h ***********************/
10933
10934 /*
10935 ** Prototypes for the VDBE interface. See comments on the implementation
10936 ** for a description of what each of these routines does.
10937 */
10938 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
10939 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
10940 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
10941 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
10942 SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
10943 SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
10944 SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
10945 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
10946 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
10947 SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
10948 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
10949 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, i nt iLineno);
10950 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
10951 SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
10952 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
10953 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
10954 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
10955 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
10956 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
10957 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
10958 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
10959 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N) ;
10960 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
10961 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
10962 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
10963 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
10964 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
10965 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
10966 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
10967 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
10968 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
10969 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
10970 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
10971 #ifdef SQLITE_DEBUG
10972 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
10973 #endif
10974 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
10975 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
10976 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
10977 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
10978 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)( void*));
10979 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
10980 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
10981 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
10982 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
10983 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
10984 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
10985 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
10986 #ifndef SQLITE_OMIT_TRACE
10987 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
10988 #endif
10989 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
10990
10991 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRec ord*);
10992 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
10993 SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedR ecord *, int);
10994 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
10995
10996 typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
10997 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
10998
10999 #ifndef SQLITE_OMIT_TRIGGER
11000 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
11001 #endif
11002
11003 /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
11004 ** each VDBE opcode.
11005 **
11006 ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
11007 ** comments in VDBE programs that show key decision points in the code
11008 ** generator.
11009 */
11010 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
11011 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
11012 # define VdbeComment(X) sqlite3VdbeComment X
11013 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
11014 # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
11015 # ifdef SQLITE_ENABLE_MODULE_COMMENTS
11016 # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
11017 # else
11018 # define VdbeModuleComment(X)
11019 # endif
11020 #else
11021 # define VdbeComment(X)
11022 # define VdbeNoopComment(X)
11023 # define VdbeModuleComment(X)
11024 #endif
11025
11026 /*
11027 ** The VdbeCoverage macros are used to set a coverage testing point
11028 ** for VDBE branch instructions. The coverage testing points are line
11029 ** numbers in the sqlite3.c source file. VDBE branch coverage testing
11030 ** only works with an amalagmation build. That's ok since a VDBE branch
11031 ** coverage build designed for testing the test suite only. No application
11032 ** should ever ship with VDBE branch coverage measuring turned on.
11033 **
11034 ** VdbeCoverage(v) // Mark the previously coded instruction
11035 ** // as a branch
11036 **
11037 ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
11038 **
11039 ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
11040 **
11041 ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
11042 **
11043 ** Every VDBE branch operation must be tagged with one of the macros above.
11044 ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
11045 ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
11046 ** routine in vdbe.c, alerting the developer to the missed tag.
11047 */
11048 #ifdef SQLITE_VDBE_COVERAGE
11049 SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
11050 # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
11051 # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
11052 # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
11053 # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
11054 # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
11055 #else
11056 # define VdbeCoverage(v)
11057 # define VdbeCoverageIf(v,x)
11058 # define VdbeCoverageAlwaysTaken(v)
11059 # define VdbeCoverageNeverTaken(v)
11060 # define VDBE_OFFSET_LINENO(x) 0
11061 #endif
11062
11063 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
11064 SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const ch ar*);
11065 #else
11066 # define sqlite3VdbeScanStatus(a,b,c,d,e)
11067 #endif
11068
11069 #endif
11070
11071 /************** End of vdbe.h ************************************************/
11072 /************** Continuing where we left off in sqliteInt.h ******************/
11073 /************** Include pager.h in the middle of sqliteInt.h *****************/
11074 /************** Begin file pager.h *******************************************/
11075 /*
11076 ** 2001 September 15
11077 **
11078 ** The author disclaims copyright to this source code. In place of
11079 ** a legal notice, here is a blessing:
11080 **
11081 ** May you do good and not evil.
11082 ** May you find forgiveness for yourself and forgive others.
11083 ** May you share freely, never taking more than you give.
11084 **
11085 *************************************************************************
11086 ** This header file defines the interface that the sqlite page cache
11087 ** subsystem. The page cache subsystem reads and writes a file a page
11088 ** at a time and provides a journal for rollback.
11089 */
11090
11091 #ifndef _PAGER_H_
11092 #define _PAGER_H_
11093
11094 /*
11095 ** Default maximum size for persistent journal files. A negative
11096 ** value means no limit. This value may be overridden using the
11097 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
11098 */
11099 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
11100 #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
11101 #endif
11102
11103 /*
11104 ** The type used to represent a page number. The first page in a file
11105 ** is called page 1. 0 is used to represent "not a page".
11106 */
11107 typedef u32 Pgno;
11108
11109 /*
11110 ** Each open file is managed by a separate instance of the "Pager" structure.
11111 */
11112 typedef struct Pager Pager;
11113
11114 /*
11115 ** Handle type for pages.
11116 */
11117 typedef struct PgHdr DbPage;
11118
11119 /*
11120 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
11121 ** reserved for working around a windows/posix incompatibility). It is
11122 ** used in the journal to signify that the remainder of the journal file
11123 ** is devoted to storing a master journal name - there are no more pages to
11124 ** roll back. See comments for function writeMasterJournal() in pager.c
11125 ** for details.
11126 */
11127 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
11128
11129 /*
11130 ** Allowed values for the flags parameter to sqlite3PagerOpen().
11131 **
11132 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
11133 */
11134 #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
11135 #define PAGER_MEMORY 0x0002 /* In-memory database */
11136
11137 /*
11138 ** Valid values for the second argument to sqlite3PagerLockingMode().
11139 */
11140 #define PAGER_LOCKINGMODE_QUERY -1
11141 #define PAGER_LOCKINGMODE_NORMAL 0
11142 #define PAGER_LOCKINGMODE_EXCLUSIVE 1
11143
11144 /*
11145 ** Numeric constants that encode the journalmode.
11146 */
11147 #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
11148 #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
11149 #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
11150 #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
11151 #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
11152 #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
11153 #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
11154
11155 /*
11156 ** Flags that make up the mask passed to sqlite3PagerGet().
11157 */
11158 #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
11159 #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
11160
11161 /*
11162 ** Flags for sqlite3PagerSetFlags()
11163 */
11164 #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
11165 #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
11166 #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
11167 #define PAGER_SYNCHRONOUS_MASK 0x03 /* Mask for three values above */
11168 #define PAGER_FULLFSYNC 0x04 /* PRAGMA fullfsync=ON */
11169 #define PAGER_CKPT_FULLFSYNC 0x08 /* PRAGMA checkpoint_fullfsync=ON */
11170 #define PAGER_CACHESPILL 0x10 /* PRAGMA cache_spill=ON */
11171 #define PAGER_FLAGS_MASK 0x1c /* All above except SYNCHRONOUS */
11172
11173 /*
11174 ** The remainder of this file contains the declarations of the functions
11175 ** that make up the Pager sub-system API. See source code comments for
11176 ** a detailed description of each routine.
11177 */
11178
11179 /* Open and close a Pager connection. */
11180 SQLITE_PRIVATE int sqlite3PagerOpen(
11181 sqlite3_vfs*,
11182 Pager **ppPager,
11183 const char*,
11184 int,
11185 int,
11186 int,
11187 void(*)(DbPage*)
11188 );
11189 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
11190 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
11191
11192 /* Functions used to configure a Pager object. */
11193 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
11194 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
11195 #ifdef SQLITE_HAS_CODEC
11196 SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
11197 #endif
11198 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
11199 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
11200 SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
11201 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
11202 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
11203 SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
11204 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
11205 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
11206 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
11207 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
11208 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
11209 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
11210 SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
11211
11212 /* Functions used to obtain and release page references. */
11213 SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, in t clrFlag);
11214 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
11215 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
11216 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
11217 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
11218
11219 /* Operations on page references. */
11220 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
11221 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
11222 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
11223 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
11224 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
11225 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
11226
11227 /* Functions used to manage pager transactions and savepoints. */
11228 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
11229 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
11230 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
11231 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
11232 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
11233 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
11234 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
11235 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
11236 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
11237 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
11238
11239 #ifndef SQLITE_OMIT_WAL
11240 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
11241 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
11242 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
11243 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
11244 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
11245 # ifdef SQLITE_ENABLE_SNAPSHOT
11246 SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **p pSnapshot);
11247 SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *p Snapshot);
11248 # endif
11249 #endif
11250
11251 #ifdef SQLITE_ENABLE_ZIPVFS
11252 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
11253 #endif
11254
11255 /* Functions used to query pager state and configuration. */
11256 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
11257 SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
11258 #ifdef SQLITE_DEBUG
11259 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
11260 #endif
11261 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
11262 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
11263 SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
11264 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
11265 SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
11266 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
11267 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
11268 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
11269 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
11270 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
11271 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
11272 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
11273
11274 /* Functions used to truncate the database file. */
11275 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
11276
11277 SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
11278
11279 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
11280 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
11281 #endif
11282
11283 /* Functions to support testing and debugging. */
11284 #if !defined(NDEBUG) || defined(SQLITE_TEST)
11285 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
11286 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
11287 #endif
11288 #ifdef SQLITE_TEST
11289 SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
11290 SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
11291 void disable_simulated_io_errors(void);
11292 void enable_simulated_io_errors(void);
11293 #else
11294 # define disable_simulated_io_errors()
11295 # define enable_simulated_io_errors()
11296 #endif
11297
11298 #endif /* _PAGER_H_ */
11299
11300 /************** End of pager.h ***********************************************/
11301 /************** Continuing where we left off in sqliteInt.h ******************/
11302 /************** Include pcache.h in the middle of sqliteInt.h ****************/
11303 /************** Begin file pcache.h ******************************************/
11304 /*
11305 ** 2008 August 05
11306 **
11307 ** The author disclaims copyright to this source code. In place of
11308 ** a legal notice, here is a blessing:
11309 **
11310 ** May you do good and not evil.
11311 ** May you find forgiveness for yourself and forgive others.
11312 ** May you share freely, never taking more than you give.
11313 **
11314 *************************************************************************
11315 ** This header file defines the interface that the sqlite page cache
11316 ** subsystem.
11317 */
11318
11319 #ifndef _PCACHE_H_
11320
11321 typedef struct PgHdr PgHdr;
11322 typedef struct PCache PCache;
11323
11324 /*
11325 ** Every page in the cache is controlled by an instance of the following
11326 ** structure.
11327 */
11328 struct PgHdr {
11329 sqlite3_pcache_page *pPage; /* Pcache object page handle */
11330 void *pData; /* Page data */
11331 void *pExtra; /* Extra content */
11332 PgHdr *pDirty; /* Transient list of dirty pages */
11333 Pager *pPager; /* The pager this page is part of */
11334 Pgno pgno; /* Page number for this page */
11335 #ifdef SQLITE_CHECK_PAGES
11336 u32 pageHash; /* Hash of page content */
11337 #endif
11338 u16 flags; /* PGHDR flags defined below */
11339
11340 /**********************************************************************
11341 ** Elements above are public. All that follows is private to pcache.c
11342 ** and should not be accessed by other modules.
11343 */
11344 i16 nRef; /* Number of users of this page */
11345 PCache *pCache; /* Cache that owns this page */
11346
11347 PgHdr *pDirtyNext; /* Next element in list of dirty pages */
11348 PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
11349 };
11350
11351 /* Bit values for PgHdr.flags */
11352 #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
11353 #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
11354 #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
11355 #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
11356 ** writing this page to the database */
11357 #define PGHDR_NEED_READ 0x010 /* Content is unread */
11358 #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
11359 #define PGHDR_MMAP 0x040 /* This is an mmap page object */
11360
11361 /* Initialize and shutdown the page cache subsystem */
11362 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
11363 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
11364
11365 /* Page cache buffer management:
11366 ** These routines implement SQLITE_CONFIG_PAGECACHE.
11367 */
11368 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
11369
11370 /* Create a new pager cache.
11371 ** Under memory stress, invoke xStress to try to make pages clean.
11372 ** Only clean and unpinned pages can be reclaimed.
11373 */
11374 SQLITE_PRIVATE int sqlite3PcacheOpen(
11375 int szPage, /* Size of every page */
11376 int szExtra, /* Extra space associated with each page */
11377 int bPurgeable, /* True if pages are on backing store */
11378 int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
11379 void *pStress, /* Argument to xStress */
11380 PCache *pToInit /* Preallocated space for the PCache */
11381 );
11382
11383 /* Modify the page-size after the cache has been created. */
11384 SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
11385
11386 /* Return the size in bytes of a PCache object. Used to preallocate
11387 ** storage space.
11388 */
11389 SQLITE_PRIVATE int sqlite3PcacheSize(void);
11390
11391 /* One release per successful fetch. Page is pinned until released.
11392 ** Reference counted.
11393 */
11394 SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int create Flag);
11395 SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page** );
11396 SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_pag e *pPage);
11397 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
11398
11399 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
11400 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is mark ed dirty */
11401 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
11402 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pa ges as clean */
11403
11404 /* Change a page number. Used by incr-vacuum. */
11405 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
11406
11407 /* Remove all pages with pgno>x. Reset the cache if x==0 */
11408 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
11409
11410 /* Get a list of all dirty pages in the cache, sorted by page number */
11411 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
11412
11413 /* Reset and close the cache object */
11414 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
11415
11416 /* Clear flags from pages of the page cache */
11417 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
11418
11419 /* Discard the contents of the cache */
11420 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
11421
11422 /* Return the total number of outstanding page references */
11423 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
11424
11425 /* Increment the reference count of an existing page */
11426 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
11427
11428 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
11429
11430 /* Return the total number of pages stored in the cache */
11431 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
11432
11433 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
11434 /* Iterate through all dirty pages currently stored in the cache. This
11435 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
11436 ** library is built.
11437 */
11438 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHd r *));
11439 #endif
11440
11441 /* Set and get the suggested cache-size for the specified pager-cache.
11442 **
11443 ** If no global maximum is configured, then the system attempts to limit
11444 ** the total number of pages cached by purgeable pager-caches to the sum
11445 ** of the suggested cache-sizes.
11446 */
11447 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
11448 #ifdef SQLITE_TEST
11449 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
11450 #endif
11451
11452 /* Set or get the suggested spill-size for the specified pager-cache.
11453 **
11454 ** The spill-size is the minimum number of pages in cache before the cache
11455 ** will attempt to spill dirty pages by calling xStress.
11456 */
11457 SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
11458
11459 /* Free up as much memory as possible from the page cache */
11460 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
11461
11462 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
11463 /* Try to return memory used by the pcache module to the main memory heap */
11464 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
11465 #endif
11466
11467 #ifdef SQLITE_TEST
11468 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
11469 #endif
11470
11471 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
11472
11473 /* Return the header size */
11474 SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
11475 SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
11476
11477 #endif /* _PCACHE_H_ */
11478
11479 /************** End of pcache.h **********************************************/
11480 /************** Continuing where we left off in sqliteInt.h ******************/
11481
11482 /************** Include os.h in the middle of sqliteInt.h ********************/
11483 /************** Begin file os.h **********************************************/
11484 /*
11485 ** 2001 September 16
11486 **
11487 ** The author disclaims copyright to this source code. In place of
11488 ** a legal notice, here is a blessing:
11489 **
11490 ** May you do good and not evil.
11491 ** May you find forgiveness for yourself and forgive others.
11492 ** May you share freely, never taking more than you give.
11493 **
11494 ******************************************************************************
11495 **
11496 ** This header file (together with is companion C source-code file
11497 ** "os.c") attempt to abstract the underlying operating system so that
11498 ** the SQLite library will work on both POSIX and windows systems.
11499 **
11500 ** This header file is #include-ed by sqliteInt.h and thus ends up
11501 ** being included by every source file.
11502 */
11503 #ifndef _SQLITE_OS_H_
11504 #define _SQLITE_OS_H_
11505
11506 /*
11507 ** Attempt to automatically detect the operating system and setup the
11508 ** necessary pre-processor macros for it.
11509 */
11510 /************** Include os_setup.h in the middle of os.h *********************/
11511 /************** Begin file os_setup.h ****************************************/
11512 /*
11513 ** 2013 November 25
11514 **
11515 ** The author disclaims copyright to this source code. In place of
11516 ** a legal notice, here is a blessing:
11517 **
11518 ** May you do good and not evil.
11519 ** May you find forgiveness for yourself and forgive others.
11520 ** May you share freely, never taking more than you give.
11521 **
11522 ******************************************************************************
11523 **
11524 ** This file contains pre-processor directives related to operating system
11525 ** detection and/or setup.
11526 */
11527 #ifndef _OS_SETUP_H_
11528 #define _OS_SETUP_H_
11529
11530 /*
11531 ** Figure out if we are dealing with Unix, Windows, or some other operating
11532 ** system.
11533 **
11534 ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
11535 ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
11536 ** the three will be 1. The other two will be 0.
11537 */
11538 #if defined(SQLITE_OS_OTHER)
11539 # if SQLITE_OS_OTHER==1
11540 # undef SQLITE_OS_UNIX
11541 # define SQLITE_OS_UNIX 0
11542 # undef SQLITE_OS_WIN
11543 # define SQLITE_OS_WIN 0
11544 # else
11545 # undef SQLITE_OS_OTHER
11546 # endif
11547 #endif
11548 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
11549 # define SQLITE_OS_OTHER 0
11550 # ifndef SQLITE_OS_WIN
11551 # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
11552 defined(__MINGW32__) || defined(__BORLANDC__)
11553 # define SQLITE_OS_WIN 1
11554 # define SQLITE_OS_UNIX 0
11555 # else
11556 # define SQLITE_OS_WIN 0
11557 # define SQLITE_OS_UNIX 1
11558 # endif
11559 # else
11560 # define SQLITE_OS_UNIX 0
11561 # endif
11562 #else
11563 # ifndef SQLITE_OS_WIN
11564 # define SQLITE_OS_WIN 0
11565 # endif
11566 #endif
11567
11568 #endif /* _OS_SETUP_H_ */
11569
11570 /************** End of os_setup.h ********************************************/
11571 /************** Continuing where we left off in os.h *************************/
11572
11573 /* If the SET_FULLSYNC macro is not defined above, then make it
11574 ** a no-op
11575 */
11576 #ifndef SET_FULLSYNC
11577 # define SET_FULLSYNC(x,y)
11578 #endif
11579
11580 /*
11581 ** The default size of a disk sector
11582 */
11583 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
11584 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
11585 #endif
11586
11587 /*
11588 ** Temporary files are named starting with this prefix followed by 16 random
11589 ** alphanumeric characters, and no file extension. They are stored in the
11590 ** OS's standard temporary file directory, and are deleted prior to exit.
11591 ** If sqlite is being embedded in another program, you may wish to change the
11592 ** prefix to reflect your program's name, so that if your program exits
11593 ** prematurely, old temporary files can be easily identified. This can be done
11594 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
11595 **
11596 ** 2006-10-31: The default prefix used to be "sqlite_". But then
11597 ** Mcafee started using SQLite in their anti-virus product and it
11598 ** started putting files with the "sqlite" name in the c:/temp folder.
11599 ** This annoyed many windows users. Those users would then do a
11600 ** Google search for "sqlite", find the telephone numbers of the
11601 ** developers and call to wake them up at night and complain.
11602 ** For this reason, the default name prefix is changed to be "sqlite"
11603 ** spelled backwards. So the temp files are still identified, but
11604 ** anybody smart enough to figure out the code is also likely smart
11605 ** enough to know that calling the developer will not help get rid
11606 ** of the file.
11607 */
11608 #ifndef SQLITE_TEMP_FILE_PREFIX
11609 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
11610 #endif
11611
11612 /*
11613 ** The following values may be passed as the second argument to
11614 ** sqlite3OsLock(). The various locks exhibit the following semantics:
11615 **
11616 ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
11617 ** RESERVED: A single process may hold a RESERVED lock on a file at
11618 ** any time. Other processes may hold and obtain new SHARED locks.
11619 ** PENDING: A single process may hold a PENDING lock on a file at
11620 ** any one time. Existing SHARED locks may persist, but no new
11621 ** SHARED locks may be obtained by other processes.
11622 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
11623 **
11624 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
11625 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
11626 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
11627 ** sqlite3OsLock().
11628 */
11629 #define NO_LOCK 0
11630 #define SHARED_LOCK 1
11631 #define RESERVED_LOCK 2
11632 #define PENDING_LOCK 3
11633 #define EXCLUSIVE_LOCK 4
11634
11635 /*
11636 ** File Locking Notes: (Mostly about windows but also some info for Unix)
11637 **
11638 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
11639 ** those functions are not available. So we use only LockFile() and
11640 ** UnlockFile().
11641 **
11642 ** LockFile() prevents not just writing but also reading by other processes.
11643 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
11644 ** byte out of a specific range of bytes. The lock byte is obtained at
11645 ** random so two separate readers can probably access the file at the
11646 ** same time, unless they are unlucky and choose the same lock byte.
11647 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
11648 ** There can only be one writer. A RESERVED_LOCK is obtained by locking
11649 ** a single byte of the file that is designated as the reserved lock byte.
11650 ** A PENDING_LOCK is obtained by locking a designated byte different from
11651 ** the RESERVED_LOCK byte.
11652 **
11653 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
11654 ** which means we can use reader/writer locks. When reader/writer locks
11655 ** are used, the lock is placed on the same range of bytes that is used
11656 ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
11657 ** will support two or more Win95 readers or two or more WinNT readers.
11658 ** But a single Win95 reader will lock out all WinNT readers and a single
11659 ** WinNT reader will lock out all other Win95 readers.
11660 **
11661 ** The following #defines specify the range of bytes used for locking.
11662 ** SHARED_SIZE is the number of bytes available in the pool from which
11663 ** a random byte is selected for a shared lock. The pool of bytes for
11664 ** shared locks begins at SHARED_FIRST.
11665 **
11666 ** The same locking strategy and
11667 ** byte ranges are used for Unix. This leaves open the possibility of having
11668 ** clients on win95, winNT, and unix all talking to the same shared file
11669 ** and all locking correctly. To do so would require that samba (or whatever
11670 ** tool is being used for file sharing) implements locks correctly between
11671 ** windows and unix. I'm guessing that isn't likely to happen, but by
11672 ** using the same locking range we are at least open to the possibility.
11673 **
11674 ** Locking in windows is manditory. For this reason, we cannot store
11675 ** actual data in the bytes used for locking. The pager never allocates
11676 ** the pages involved in locking therefore. SHARED_SIZE is selected so
11677 ** that all locks will fit on a single page even at the minimum page size.
11678 ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
11679 ** is set high so that we don't have to allocate an unused page except
11680 ** for very large databases. But one should test the page skipping logic
11681 ** by setting PENDING_BYTE low and running the entire regression suite.
11682 **
11683 ** Changing the value of PENDING_BYTE results in a subtly incompatible
11684 ** file format. Depending on how it is changed, you might not notice
11685 ** the incompatibility right away, even running a full regression test.
11686 ** The default location of PENDING_BYTE is the first byte past the
11687 ** 1GB boundary.
11688 **
11689 */
11690 #ifdef SQLITE_OMIT_WSD
11691 # define PENDING_BYTE (0x40000000)
11692 #else
11693 # define PENDING_BYTE sqlite3PendingByte
11694 #endif
11695 #define RESERVED_BYTE (PENDING_BYTE+1)
11696 #define SHARED_FIRST (PENDING_BYTE+2)
11697 #define SHARED_SIZE 510
11698
11699 /*
11700 ** Wrapper around OS specific sqlite3_os_init() function.
11701 */
11702 SQLITE_PRIVATE int sqlite3OsInit(void);
11703
11704 /*
11705 ** Functions for accessing sqlite3_file methods
11706 */
11707 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
11708 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
11709 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offse t);
11710 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
11711 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
11712 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
11713 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
11714 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
11715 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
11716 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
11717 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
11718 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
11719 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
11720 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
11721 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
11722 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
11723 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
11724 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
11725 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
11726 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
11727
11728
11729 /*
11730 ** Functions for accessing sqlite3_vfs methods
11731 */
11732 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int , int *);
11733 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
11734 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOu t);
11735 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
11736 #ifndef SQLITE_OMIT_LOAD_EXTENSION
11737 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
11738 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
11739 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void) ;
11740 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
11741 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
11742 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
11743 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
11744 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
11745
11746 /*
11747 ** Convenience functions for opening and closing files using
11748 ** sqlite3_malloc() to obtain space for the file-handle structure.
11749 */
11750 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
11751 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
11752
11753 #endif /* _SQLITE_OS_H_ */
11754
11755 /************** End of os.h **************************************************/
11756 /************** Continuing where we left off in sqliteInt.h ******************/
11757 /************** Include mutex.h in the middle of sqliteInt.h *****************/
11758 /************** Begin file mutex.h *******************************************/
11759 /*
11760 ** 2007 August 28
11761 **
11762 ** The author disclaims copyright to this source code. In place of
11763 ** a legal notice, here is a blessing:
11764 **
11765 ** May you do good and not evil.
11766 ** May you find forgiveness for yourself and forgive others.
11767 ** May you share freely, never taking more than you give.
11768 **
11769 *************************************************************************
11770 **
11771 ** This file contains the common header for all mutex implementations.
11772 ** The sqliteInt.h header #includes this file so that it is available
11773 ** to all source files. We break it out in an effort to keep the code
11774 ** better organized.
11775 **
11776 ** NOTE: source files should *not* #include this header file directly.
11777 ** Source files should #include the sqliteInt.h file and let that file
11778 ** include this one indirectly.
11779 */
11780
11781
11782 /*
11783 ** Figure out what version of the code to use. The choices are
11784 **
11785 ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
11786 ** mutexes implementation cannot be overridden
11787 ** at start-time.
11788 **
11789 ** SQLITE_MUTEX_NOOP For single-threaded applications. No
11790 ** mutual exclusion is provided. But this
11791 ** implementation can be overridden at
11792 ** start-time.
11793 **
11794 ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
11795 **
11796 ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
11797 */
11798 #if !SQLITE_THREADSAFE
11799 # define SQLITE_MUTEX_OMIT
11800 #endif
11801 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
11802 # if SQLITE_OS_UNIX
11803 # define SQLITE_MUTEX_PTHREADS
11804 # elif SQLITE_OS_WIN
11805 # define SQLITE_MUTEX_W32
11806 # else
11807 # define SQLITE_MUTEX_NOOP
11808 # endif
11809 #endif
11810
11811 #ifdef SQLITE_MUTEX_OMIT
11812 /*
11813 ** If this is a no-op implementation, implement everything as macros.
11814 */
11815 #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
11816 #define sqlite3_mutex_free(X)
11817 #define sqlite3_mutex_enter(X)
11818 #define sqlite3_mutex_try(X) SQLITE_OK
11819 #define sqlite3_mutex_leave(X)
11820 #define sqlite3_mutex_held(X) ((void)(X),1)
11821 #define sqlite3_mutex_notheld(X) ((void)(X),1)
11822 #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
11823 #define sqlite3MutexInit() SQLITE_OK
11824 #define sqlite3MutexEnd()
11825 #define MUTEX_LOGIC(X)
11826 #else
11827 #define MUTEX_LOGIC(X) X
11828 #endif /* defined(SQLITE_MUTEX_OMIT) */
11829
11830 /************** End of mutex.h ***********************************************/
11831 /************** Continuing where we left off in sqliteInt.h ******************/
11832
11833
11834 /*
11835 ** Each database file to be accessed by the system is an instance
11836 ** of the following structure. There are normally two of these structures
11837 ** in the sqlite.aDb[] array. aDb[0] is the main database file and
11838 ** aDb[1] is the database file used to hold temporary tables. Additional
11839 ** databases may be attached.
11840 */
11841 struct Db {
11842 char *zName; /* Name of this database */
11843 Btree *pBt; /* The B*Tree structure for this database file */
11844 u8 safety_level; /* How aggressive at syncing data to disk */
11845 Schema *pSchema; /* Pointer to database schema (possibly shared) */
11846 };
11847
11848 /*
11849 ** An instance of the following structure stores a database schema.
11850 **
11851 ** Most Schema objects are associated with a Btree. The exception is
11852 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
11853 ** In shared cache mode, a single Schema object can be shared by multiple
11854 ** Btrees that refer to the same underlying BtShared object.
11855 **
11856 ** Schema objects are automatically deallocated when the last Btree that
11857 ** references them is destroyed. The TEMP Schema is manually freed by
11858 ** sqlite3_close().
11859 *
11860 ** A thread must be holding a mutex on the corresponding Btree in order
11861 ** to access Schema content. This implies that the thread must also be
11862 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
11863 ** For a TEMP Schema, only the connection mutex is required.
11864 */
11865 struct Schema {
11866 int schema_cookie; /* Database schema version number for this file */
11867 int iGeneration; /* Generation counter. Incremented with each change */
11868 Hash tblHash; /* All tables indexed by name */
11869 Hash idxHash; /* All (named) indices indexed by name */
11870 Hash trigHash; /* All triggers indexed by name */
11871 Hash fkeyHash; /* All foreign keys by referenced table name */
11872 Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
11873 u8 file_format; /* Schema format version for this file */
11874 u8 enc; /* Text encoding used by this database */
11875 u16 schemaFlags; /* Flags associated with this schema */
11876 int cache_size; /* Number of pages to use in the cache */
11877 };
11878
11879 /*
11880 ** These macros can be used to test, set, or clear bits in the
11881 ** Db.pSchema->flags field.
11882 */
11883 #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
11884 #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
11885 #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
11886 #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
11887
11888 /*
11889 ** Allowed values for the DB.pSchema->flags field.
11890 **
11891 ** The DB_SchemaLoaded flag is set after the database schema has been
11892 ** read into internal hash tables.
11893 **
11894 ** DB_UnresetViews means that one or more views have column names that
11895 ** have been filled out. If the schema changes, these column names might
11896 ** changes and so the view will need to be reset.
11897 */
11898 #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
11899 #define DB_UnresetViews 0x0002 /* Some views have defined column names */
11900 #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
11901
11902 /*
11903 ** The number of different kinds of things that can be limited
11904 ** using the sqlite3_limit() interface.
11905 */
11906 #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
11907
11908 /*
11909 ** Lookaside malloc is a set of fixed-size buffers that can be used
11910 ** to satisfy small transient memory allocation requests for objects
11911 ** associated with a particular database connection. The use of
11912 ** lookaside malloc provides a significant performance enhancement
11913 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
11914 ** SQL statements.
11915 **
11916 ** The Lookaside structure holds configuration information about the
11917 ** lookaside malloc subsystem. Each available memory allocation in
11918 ** the lookaside subsystem is stored on a linked list of LookasideSlot
11919 ** objects.
11920 **
11921 ** Lookaside allocations are only allowed for objects that are associated
11922 ** with a particular database connection. Hence, schema information cannot
11923 ** be stored in lookaside because in shared cache mode the schema information
11924 ** is shared by multiple database connections. Therefore, while parsing
11925 ** schema information, the Lookaside.bEnabled flag is cleared so that
11926 ** lookaside allocations are not used to construct the schema objects.
11927 */
11928 struct Lookaside {
11929 u16 sz; /* Size of each buffer in bytes */
11930 u8 bEnabled; /* False to disable new lookaside allocations */
11931 u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
11932 int nOut; /* Number of buffers currently checked out */
11933 int mxOut; /* Highwater mark for nOut */
11934 int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
11935 LookasideSlot *pFree; /* List of available buffers */
11936 void *pStart; /* First byte of available memory space */
11937 void *pEnd; /* First byte past end of available space */
11938 };
11939 struct LookasideSlot {
11940 LookasideSlot *pNext; /* Next buffer in the list of free buffers */
11941 };
11942
11943 /*
11944 ** A hash table for function definitions.
11945 **
11946 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
11947 ** Collisions are on the FuncDef.pHash chain.
11948 */
11949 struct FuncDefHash {
11950 FuncDef *a[23]; /* Hash table for functions */
11951 };
11952
11953 #ifdef SQLITE_USER_AUTHENTICATION
11954 /*
11955 ** Information held in the "sqlite3" database connection object and used
11956 ** to manage user authentication.
11957 */
11958 typedef struct sqlite3_userauth sqlite3_userauth;
11959 struct sqlite3_userauth {
11960 u8 authLevel; /* Current authentication level */
11961 int nAuthPW; /* Size of the zAuthPW in bytes */
11962 char *zAuthPW; /* Password used to authenticate */
11963 char *zAuthUser; /* User name used to authenticate */
11964 };
11965
11966 /* Allowed values for sqlite3_userauth.authLevel */
11967 #define UAUTH_Unknown 0 /* Authentication not yet checked */
11968 #define UAUTH_Fail 1 /* User authentication failed */
11969 #define UAUTH_User 2 /* Authenticated as a normal user */
11970 #define UAUTH_Admin 3 /* Authenticated as an administrator */
11971
11972 /* Functions used only by user authorization logic */
11973 SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
11974 SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
11975 SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
11976 SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
11977
11978 #endif /* SQLITE_USER_AUTHENTICATION */
11979
11980 /*
11981 ** typedef for the authorization callback function.
11982 */
11983 #ifdef SQLITE_USER_AUTHENTICATION
11984 typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
11985 const char*, const char*);
11986 #else
11987 typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
11988 const char*);
11989 #endif
11990
11991
11992 /*
11993 ** Each database connection is an instance of the following structure.
11994 */
11995 struct sqlite3 {
11996 sqlite3_vfs *pVfs; /* OS Interface */
11997 struct Vdbe *pVdbe; /* List of active virtual machines */
11998 CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
11999 sqlite3_mutex *mutex; /* Connection mutex */
12000 Db *aDb; /* All backends */
12001 int nDb; /* Number of backends currently in use */
12002 int flags; /* Miscellaneous flags. See below */
12003 i64 lastRowid; /* ROWID of most recent insert (see above) */
12004 i64 szMmap; /* Default mmap_size setting */
12005 unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
12006 int errCode; /* Most recent error code (SQLITE_*) */
12007 int errMask; /* & result codes with this before returning */
12008 u16 dbOptFlags; /* Flags to enable/disable optimizations */
12009 u8 enc; /* Text encoding */
12010 u8 autoCommit; /* The auto-commit flag. */
12011 u8 temp_store; /* 1: file 2: memory 0: default */
12012 u8 mallocFailed; /* True if we have seen a malloc failure */
12013 u8 dfltLockMode; /* Default locking-mode for attached dbs */
12014 signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
12015 u8 suppressErr; /* Do not issue error messages if true */
12016 u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
12017 u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
12018 int nextPagesize; /* Pagesize after VACUUM if >0 */
12019 u32 magic; /* Magic number for detect library misuse */
12020 int nChange; /* Value returned by sqlite3_changes() */
12021 int nTotalChange; /* Value returned by sqlite3_total_changes() */
12022 int aLimit[SQLITE_N_LIMIT]; /* Limits */
12023 int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
12024 struct sqlite3InitInfo { /* Information used during initialization */
12025 int newTnum; /* Rootpage of table being initialized */
12026 u8 iDb; /* Which db file is being initialized */
12027 u8 busy; /* TRUE if currently initializing */
12028 u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
12029 u8 imposterTable; /* Building an imposter table */
12030 } init;
12031 int nVdbeActive; /* Number of VDBEs currently running */
12032 int nVdbeRead; /* Number of active VDBEs that read or write */
12033 int nVdbeWrite; /* Number of active VDBEs that read and write */
12034 int nVdbeExec; /* Number of nested calls to VdbeExec() */
12035 int nVDestroy; /* Number of active OP_VDestroy operations */
12036 int nExtension; /* Number of loaded extensions */
12037 void **aExtension; /* Array of shared library handles */
12038 void (*xTrace)(void*,const char*); /* Trace function */
12039 void *pTraceArg; /* Argument to the trace function */
12040 void (*xProfile)(void*,const char*,u64); /* Profiling function */
12041 void *pProfileArg; /* Argument to profile function */
12042 void *pCommitArg; /* Argument to xCommitCallback() */
12043 int (*xCommitCallback)(void*); /* Invoked at every commit. */
12044 void *pRollbackArg; /* Argument to xRollbackCallback() */
12045 void (*xRollbackCallback)(void*); /* Invoked at every commit. */
12046 void *pUpdateArg;
12047 void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
12048 #ifndef SQLITE_OMIT_WAL
12049 int (*xWalCallback)(void *, sqlite3 *, const char *, int);
12050 void *pWalArg;
12051 #endif
12052 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
12053 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
12054 void *pCollNeededArg;
12055 sqlite3_value *pErr; /* Most recent error message */
12056 union {
12057 volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
12058 double notUsed1; /* Spacer */
12059 } u1;
12060 Lookaside lookaside; /* Lookaside malloc configuration */
12061 #ifndef SQLITE_OMIT_AUTHORIZATION
12062 sqlite3_xauth xAuth; /* Access authorization function */
12063 void *pAuthArg; /* 1st argument to the access auth function */
12064 #endif
12065 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
12066 int (*xProgress)(void *); /* The progress callback */
12067 void *pProgressArg; /* Argument to the progress callback */
12068 unsigned nProgressOps; /* Number of opcodes for progress callback */
12069 #endif
12070 #ifndef SQLITE_OMIT_VIRTUALTABLE
12071 int nVTrans; /* Allocated size of aVTrans */
12072 Hash aModule; /* populated by sqlite3_create_module() */
12073 VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
12074 VTable **aVTrans; /* Virtual tables with open transactions */
12075 VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
12076 #endif
12077 FuncDefHash aFunc; /* Hash table of connection functions */
12078 Hash aCollSeq; /* All collating sequences */
12079 BusyHandler busyHandler; /* Busy callback */
12080 Db aDbStatic[2]; /* Static space for the 2 default backends */
12081 Savepoint *pSavepoint; /* List of active savepoints */
12082 int busyTimeout; /* Busy handler timeout, in msec */
12083 int nSavepoint; /* Number of non-transaction savepoints */
12084 int nStatement; /* Number of nested statement-transactions */
12085 i64 nDeferredCons; /* Net deferred constraints this transaction. */
12086 i64 nDeferredImmCons; /* Net deferred immediate constraints */
12087 int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
12088 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12089 /* The following variables are all protected by the STATIC_MASTER
12090 ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
12091 **
12092 ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
12093 ** unlock so that it can proceed.
12094 **
12095 ** When X.pBlockingConnection==Y, that means that something that X tried
12096 ** tried to do recently failed with an SQLITE_LOCKED error due to locks
12097 ** held by Y.
12098 */
12099 sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
12100 sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
12101 void *pUnlockArg; /* Argument to xUnlockNotify */
12102 void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
12103 sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
12104 #endif
12105 #ifdef SQLITE_USER_AUTHENTICATION
12106 sqlite3_userauth auth; /* User authentication information */
12107 #endif
12108 };
12109
12110 /*
12111 ** A macro to discover the encoding of a database.
12112 */
12113 #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
12114 #define ENC(db) ((db)->enc)
12115
12116 /*
12117 ** Possible values for the sqlite3.flags.
12118 */
12119 #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
12120 #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
12121 #define SQLITE_FullFSync 0x00000004 /* Use full fsync on the backend */
12122 #define SQLITE_CkptFullFSync 0x00000008 /* Use full fsync for checkpoint */
12123 #define SQLITE_CacheSpill 0x00000010 /* OK to spill pager cache */
12124 #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
12125 #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
12126 #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
12127 /* DELETE, or UPDATE and return */
12128 /* the count using a callback. */
12129 #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
12130 /* result set is empty */
12131 #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
12132 #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
12133 #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
12134 #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
12135 #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
12136 #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
12137 #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
12138 #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
12139 #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
12140 #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
12141 #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
12142 #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
12143 #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
12144 #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
12145 #define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */
12146 #define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */
12147 #define SQLITE_QueryOnly 0x02000000 /* Disable database changes */
12148 #define SQLITE_VdbeEQP 0x04000000 /* Debug EXPLAIN QUERY PLAN */
12149 #define SQLITE_Vacuum 0x08000000 /* Currently in a VACUUM */
12150 #define SQLITE_CellSizeCk 0x10000000 /* Check btree cell sizes on load */
12151
12152
12153 /*
12154 ** Bits of the sqlite3.dbOptFlags field that are used by the
12155 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
12156 ** selectively disable various optimizations.
12157 */
12158 #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
12159 #define SQLITE_ColumnCache 0x0002 /* Column cache */
12160 #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
12161 #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
12162 /* not used 0x0010 // Was: SQLITE_IdxRealAsInt */
12163 #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
12164 #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
12165 #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
12166 #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
12167 #define SQLITE_Transitive 0x0200 /* Transitive constraints */
12168 #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
12169 #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
12170 #define SQLITE_CursorHints 0x2000 /* Add OP_CursorHint opcodes */
12171 #define SQLITE_AllOpts 0xffff /* All optimizations */
12172
12173 /*
12174 ** Macros for testing whether or not optimizations are enabled or disabled.
12175 */
12176 #ifndef SQLITE_OMIT_BUILTIN_TEST
12177 #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
12178 #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
12179 #else
12180 #define OptimizationDisabled(db, mask) 0
12181 #define OptimizationEnabled(db, mask) 1
12182 #endif
12183
12184 /*
12185 ** Return true if it OK to factor constant expressions into the initialization
12186 ** code. The argument is a Parse object for the code generator.
12187 */
12188 #define ConstFactorOk(P) ((P)->okConstFactor)
12189
12190 /*
12191 ** Possible values for the sqlite.magic field.
12192 ** The numbers are obtained at random and have no special meaning, other
12193 ** than being distinct from one another.
12194 */
12195 #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
12196 #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
12197 #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
12198 #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
12199 #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
12200 #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
12201
12202 /*
12203 ** Each SQL function is defined by an instance of the following
12204 ** structure. A pointer to this structure is stored in the sqlite.aFunc
12205 ** hash table. When multiple functions have the same name, the hash table
12206 ** points to a linked list of these structures.
12207 */
12208 struct FuncDef {
12209 i16 nArg; /* Number of arguments. -1 means unlimited */
12210 u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
12211 void *pUserData; /* User data parameter */
12212 FuncDef *pNext; /* Next function with same name */
12213 void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
12214 void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
12215 void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
12216 char *zName; /* SQL name of the function. */
12217 FuncDef *pHash; /* Next with a different name but the same hash */
12218 FuncDestructor *pDestructor; /* Reference counted destructor function */
12219 };
12220
12221 /*
12222 ** This structure encapsulates a user-function destructor callback (as
12223 ** configured using create_function_v2()) and a reference counter. When
12224 ** create_function_v2() is called to create a function with a destructor,
12225 ** a single object of this type is allocated. FuncDestructor.nRef is set to
12226 ** the number of FuncDef objects created (either 1 or 3, depending on whether
12227 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
12228 ** member of each of the new FuncDef objects is set to point to the allocated
12229 ** FuncDestructor.
12230 **
12231 ** Thereafter, when one of the FuncDef objects is deleted, the reference
12232 ** count on this object is decremented. When it reaches 0, the destructor
12233 ** is invoked and the FuncDestructor structure freed.
12234 */
12235 struct FuncDestructor {
12236 int nRef;
12237 void (*xDestroy)(void *);
12238 void *pUserData;
12239 };
12240
12241 /*
12242 ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
12243 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
12244 ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
12245 ** are assert() statements in the code to verify this.
12246 */
12247 #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
12248 #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
12249 #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
12250 #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
12251 #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
12252 #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
12253 #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
12254 #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
12255 #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
12256 #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
12257 #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
12258 #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
12259 #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
12260 ** single query - might change over time */
12261
12262 /*
12263 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
12264 ** used to create the initializers for the FuncDef structures.
12265 **
12266 ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
12267 ** Used to create a scalar function definition of a function zName
12268 ** implemented by C function xFunc that accepts nArg arguments. The
12269 ** value passed as iArg is cast to a (void*) and made available
12270 ** as the user-data (sqlite3_user_data()) for the function. If
12271 ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
12272 **
12273 ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
12274 ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
12275 **
12276 ** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
12277 ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
12278 ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
12279 ** and functions like sqlite_version() that can change, but not during
12280 ** a single query.
12281 **
12282 ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
12283 ** Used to create an aggregate function definition implemented by
12284 ** the C functions xStep and xFinal. The first four parameters
12285 ** are interpreted in the same way as the first 4 parameters to
12286 ** FUNCTION().
12287 **
12288 ** LIKEFUNC(zName, nArg, pArg, flags)
12289 ** Used to create a scalar function definition of a function zName
12290 ** that accepts nArg arguments and is implemented by a call to C
12291 ** function likeFunc. Argument pArg is cast to a (void *) and made
12292 ** available as the function user-data (sqlite3_user_data()). The
12293 ** FuncDef.flags variable is set to the value passed as the flags
12294 ** parameter.
12295 */
12296 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
12297 {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
12298 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
12299 #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
12300 {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
12301 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
12302 #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
12303 {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
12304 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
12305 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
12306 {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
12307 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
12308 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
12309 {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
12310 pArg, 0, xFunc, 0, 0, #zName, 0, 0}
12311 #define LIKEFUNC(zName, nArg, arg, flags) \
12312 {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
12313 (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
12314 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
12315 {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
12316 SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
12317 #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
12318 {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
12319 SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
12320
12321 /*
12322 ** All current savepoints are stored in a linked list starting at
12323 ** sqlite3.pSavepoint. The first element in the list is the most recently
12324 ** opened savepoint. Savepoints are added to the list by the vdbe
12325 ** OP_Savepoint instruction.
12326 */
12327 struct Savepoint {
12328 char *zName; /* Savepoint name (nul-terminated) */
12329 i64 nDeferredCons; /* Number of deferred fk violations */
12330 i64 nDeferredImmCons; /* Number of deferred imm fk. */
12331 Savepoint *pNext; /* Parent savepoint (if any) */
12332 };
12333
12334 /*
12335 ** The following are used as the second parameter to sqlite3Savepoint(),
12336 ** and as the P1 argument to the OP_Savepoint instruction.
12337 */
12338 #define SAVEPOINT_BEGIN 0
12339 #define SAVEPOINT_RELEASE 1
12340 #define SAVEPOINT_ROLLBACK 2
12341
12342
12343 /*
12344 ** Each SQLite module (virtual table definition) is defined by an
12345 ** instance of the following structure, stored in the sqlite3.aModule
12346 ** hash table.
12347 */
12348 struct Module {
12349 const sqlite3_module *pModule; /* Callback pointers */
12350 const char *zName; /* Name passed to create_module() */
12351 void *pAux; /* pAux passed to create_module() */
12352 void (*xDestroy)(void *); /* Module destructor function */
12353 Table *pEpoTab; /* Eponymous table for this module */
12354 };
12355
12356 /*
12357 ** information about each column of an SQL table is held in an instance
12358 ** of this structure.
12359 */
12360 struct Column {
12361 char *zName; /* Name of this column */
12362 Expr *pDflt; /* Default value of this column */
12363 char *zDflt; /* Original text of the default value */
12364 char *zType; /* Data type for this column */
12365 char *zColl; /* Collating sequence. If NULL, use the default */
12366 u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
12367 char affinity; /* One of the SQLITE_AFF_... values */
12368 u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */
12369 u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
12370 };
12371
12372 /* Allowed values for Column.colFlags:
12373 */
12374 #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
12375 #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
12376
12377 /*
12378 ** A "Collating Sequence" is defined by an instance of the following
12379 ** structure. Conceptually, a collating sequence consists of a name and
12380 ** a comparison routine that defines the order of that sequence.
12381 **
12382 ** If CollSeq.xCmp is NULL, it means that the
12383 ** collating sequence is undefined. Indices built on an undefined
12384 ** collating sequence may not be read or written.
12385 */
12386 struct CollSeq {
12387 char *zName; /* Name of the collating sequence, UTF-8 encoded */
12388 u8 enc; /* Text encoding handled by xCmp() */
12389 void *pUser; /* First argument to xCmp() */
12390 int (*xCmp)(void*,int, const void*, int, const void*);
12391 void (*xDel)(void*); /* Destructor for pUser */
12392 };
12393
12394 /*
12395 ** A sort order can be either ASC or DESC.
12396 */
12397 #define SQLITE_SO_ASC 0 /* Sort in ascending order */
12398 #define SQLITE_SO_DESC 1 /* Sort in ascending order */
12399 #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
12400
12401 /*
12402 ** Column affinity types.
12403 **
12404 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
12405 ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
12406 ** the speed a little by numbering the values consecutively.
12407 **
12408 ** But rather than start with 0 or 1, we begin with 'A'. That way,
12409 ** when multiple affinity types are concatenated into a string and
12410 ** used as the P4 operand, they will be more readable.
12411 **
12412 ** Note also that the numeric types are grouped together so that testing
12413 ** for a numeric type is a single comparison. And the BLOB type is first.
12414 */
12415 #define SQLITE_AFF_BLOB 'A'
12416 #define SQLITE_AFF_TEXT 'B'
12417 #define SQLITE_AFF_NUMERIC 'C'
12418 #define SQLITE_AFF_INTEGER 'D'
12419 #define SQLITE_AFF_REAL 'E'
12420
12421 #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
12422
12423 /*
12424 ** The SQLITE_AFF_MASK values masks off the significant bits of an
12425 ** affinity value.
12426 */
12427 #define SQLITE_AFF_MASK 0x47
12428
12429 /*
12430 ** Additional bit values that can be ORed with an affinity without
12431 ** changing the affinity.
12432 **
12433 ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
12434 ** It causes an assert() to fire if either operand to a comparison
12435 ** operator is NULL. It is added to certain comparison operators to
12436 ** prove that the operands are always NOT NULL.
12437 */
12438 #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
12439 #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
12440 #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
12441 #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
12442
12443 /*
12444 ** An object of this type is created for each virtual table present in
12445 ** the database schema.
12446 **
12447 ** If the database schema is shared, then there is one instance of this
12448 ** structure for each database connection (sqlite3*) that uses the shared
12449 ** schema. This is because each database connection requires its own unique
12450 ** instance of the sqlite3_vtab* handle used to access the virtual table
12451 ** implementation. sqlite3_vtab* handles can not be shared between
12452 ** database connections, even when the rest of the in-memory database
12453 ** schema is shared, as the implementation often stores the database
12454 ** connection handle passed to it via the xConnect() or xCreate() method
12455 ** during initialization internally. This database connection handle may
12456 ** then be used by the virtual table implementation to access real tables
12457 ** within the database. So that they appear as part of the callers
12458 ** transaction, these accesses need to be made via the same database
12459 ** connection as that used to execute SQL operations on the virtual table.
12460 **
12461 ** All VTable objects that correspond to a single table in a shared
12462 ** database schema are initially stored in a linked-list pointed to by
12463 ** the Table.pVTable member variable of the corresponding Table object.
12464 ** When an sqlite3_prepare() operation is required to access the virtual
12465 ** table, it searches the list for the VTable that corresponds to the
12466 ** database connection doing the preparing so as to use the correct
12467 ** sqlite3_vtab* handle in the compiled query.
12468 **
12469 ** When an in-memory Table object is deleted (for example when the
12470 ** schema is being reloaded for some reason), the VTable objects are not
12471 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
12472 ** immediately. Instead, they are moved from the Table.pVTable list to
12473 ** another linked list headed by the sqlite3.pDisconnect member of the
12474 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
12475 ** next time a statement is prepared using said sqlite3*. This is done
12476 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
12477 ** Refer to comments above function sqlite3VtabUnlockList() for an
12478 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
12479 ** list without holding the corresponding sqlite3.mutex mutex.
12480 **
12481 ** The memory for objects of this type is always allocated by
12482 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
12483 ** the first argument.
12484 */
12485 struct VTable {
12486 sqlite3 *db; /* Database connection associated with this table */
12487 Module *pMod; /* Pointer to module implementation */
12488 sqlite3_vtab *pVtab; /* Pointer to vtab instance */
12489 int nRef; /* Number of pointers to this structure */
12490 u8 bConstraint; /* True if constraints are supported */
12491 int iSavepoint; /* Depth of the SAVEPOINT stack */
12492 VTable *pNext; /* Next in linked list (see above) */
12493 };
12494
12495 /*
12496 ** The schema for each SQL table and view is represented in memory
12497 ** by an instance of the following structure.
12498 */
12499 struct Table {
12500 char *zName; /* Name of the table or view */
12501 Column *aCol; /* Information about each column */
12502 Index *pIndex; /* List of SQL indexes on this table. */
12503 Select *pSelect; /* NULL for tables. Points to definition if a view. */
12504 FKey *pFKey; /* Linked list of all foreign keys in this table */
12505 char *zColAff; /* String defining the affinity of each column */
12506 ExprList *pCheck; /* All CHECK constraints */
12507 /* ... also used as column name list in a VIEW */
12508 int tnum; /* Root BTree page for this table */
12509 i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
12510 i16 nCol; /* Number of columns in this table */
12511 u16 nRef; /* Number of pointers to this Table */
12512 LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
12513 LogEst szTabRow; /* Estimated size of each table row in bytes */
12514 #ifdef SQLITE_ENABLE_COSTMULT
12515 LogEst costMult; /* Cost multiplier for using this table */
12516 #endif
12517 u8 tabFlags; /* Mask of TF_* values */
12518 u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
12519 #ifndef SQLITE_OMIT_ALTERTABLE
12520 int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
12521 #endif
12522 #ifndef SQLITE_OMIT_VIRTUALTABLE
12523 int nModuleArg; /* Number of arguments to the module */
12524 char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */
12525 VTable *pVTable; /* List of VTable objects. */
12526 #endif
12527 Trigger *pTrigger; /* List of triggers stored in pSchema */
12528 Schema *pSchema; /* Schema that contains this table */
12529 Table *pNextZombie; /* Next on the Parse.pZombieTab list */
12530 };
12531
12532 /*
12533 ** Allowed values for Table.tabFlags.
12534 **
12535 ** TF_OOOHidden applies to tables or view that have hidden columns that are
12536 ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
12537 ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
12538 ** the TF_OOOHidden attribute would apply in this case. Such tables require
12539 ** special handling during INSERT processing.
12540 */
12541 #define TF_Readonly 0x01 /* Read-only system table */
12542 #define TF_Ephemeral 0x02 /* An ephemeral table */
12543 #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
12544 #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
12545 #define TF_Virtual 0x10 /* Is a virtual table */
12546 #define TF_WithoutRowid 0x20 /* No rowid. PRIMARY KEY is the key */
12547 #define TF_NoVisibleRowid 0x40 /* No user-visible "rowid" column */
12548 #define TF_OOOHidden 0x80 /* Out-of-Order hidden columns */
12549
12550
12551 /*
12552 ** Test to see whether or not a table is a virtual table. This is
12553 ** done as a macro so that it will be optimized out when virtual
12554 ** table support is omitted from the build.
12555 */
12556 #ifndef SQLITE_OMIT_VIRTUALTABLE
12557 # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
12558 #else
12559 # define IsVirtual(X) 0
12560 #endif
12561
12562 /*
12563 ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
12564 ** only works for non-virtual tables (ordinary tables and views) and is
12565 ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
12566 ** IsHiddenColumn() macro is general purpose.
12567 */
12568 #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
12569 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
12570 # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
12571 #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
12572 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
12573 # define IsOrdinaryHiddenColumn(X) 0
12574 #else
12575 # define IsHiddenColumn(X) 0
12576 # define IsOrdinaryHiddenColumn(X) 0
12577 #endif
12578
12579
12580 /* Does the table have a rowid */
12581 #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
12582 #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
12583
12584 /*
12585 ** Each foreign key constraint is an instance of the following structure.
12586 **
12587 ** A foreign key is associated with two tables. The "from" table is
12588 ** the table that contains the REFERENCES clause that creates the foreign
12589 ** key. The "to" table is the table that is named in the REFERENCES clause.
12590 ** Consider this example:
12591 **
12592 ** CREATE TABLE ex1(
12593 ** a INTEGER PRIMARY KEY,
12594 ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
12595 ** );
12596 **
12597 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
12598 ** Equivalent names:
12599 **
12600 ** from-table == child-table
12601 ** to-table == parent-table
12602 **
12603 ** Each REFERENCES clause generates an instance of the following structure
12604 ** which is attached to the from-table. The to-table need not exist when
12605 ** the from-table is created. The existence of the to-table is not checked.
12606 **
12607 ** The list of all parents for child Table X is held at X.pFKey.
12608 **
12609 ** A list of all children for a table named Z (which might not even exist)
12610 ** is held in Schema.fkeyHash with a hash key of Z.
12611 */
12612 struct FKey {
12613 Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
12614 FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
12615 char *zTo; /* Name of table that the key points to (aka: Parent) */
12616 FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
12617 FKey *pPrevTo; /* Previous with the same zTo */
12618 int nCol; /* Number of columns in this key */
12619 /* EV: R-30323-21917 */
12620 u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
12621 u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
12622 Trigger *apTrigger[2];/* Triggers for aAction[] actions */
12623 struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
12624 int iFrom; /* Index of column in pFrom */
12625 char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
12626 } aCol[1]; /* One entry for each of nCol columns */
12627 };
12628
12629 /*
12630 ** SQLite supports many different ways to resolve a constraint
12631 ** error. ROLLBACK processing means that a constraint violation
12632 ** causes the operation in process to fail and for the current transaction
12633 ** to be rolled back. ABORT processing means the operation in process
12634 ** fails and any prior changes from that one operation are backed out,
12635 ** but the transaction is not rolled back. FAIL processing means that
12636 ** the operation in progress stops and returns an error code. But prior
12637 ** changes due to the same operation are not backed out and no rollback
12638 ** occurs. IGNORE means that the particular row that caused the constraint
12639 ** error is not inserted or updated. Processing continues and no error
12640 ** is returned. REPLACE means that preexisting database rows that caused
12641 ** a UNIQUE constraint violation are removed so that the new insert or
12642 ** update can proceed. Processing continues and no error is reported.
12643 **
12644 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
12645 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
12646 ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
12647 ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
12648 ** referenced table row is propagated into the row that holds the
12649 ** foreign key.
12650 **
12651 ** The following symbolic values are used to record which type
12652 ** of action to take.
12653 */
12654 #define OE_None 0 /* There is no constraint to check */
12655 #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
12656 #define OE_Abort 2 /* Back out changes but do no rollback transaction */
12657 #define OE_Fail 3 /* Stop the operation but leave all prior changes */
12658 #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
12659 #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
12660
12661 #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
12662 #define OE_SetNull 7 /* Set the foreign key value to NULL */
12663 #define OE_SetDflt 8 /* Set the foreign key value to its default */
12664 #define OE_Cascade 9 /* Cascade the changes */
12665
12666 #define OE_Default 10 /* Do whatever the default action is */
12667
12668
12669 /*
12670 ** An instance of the following structure is passed as the first
12671 ** argument to sqlite3VdbeKeyCompare and is used to control the
12672 ** comparison of the two index keys.
12673 **
12674 ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
12675 ** are nField slots for the columns of an index then one extra slot
12676 ** for the rowid at the end.
12677 */
12678 struct KeyInfo {
12679 u32 nRef; /* Number of references to this KeyInfo object */
12680 u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
12681 u16 nField; /* Number of key columns in the index */
12682 u16 nXField; /* Number of columns beyond the key columns */
12683 sqlite3 *db; /* The database connection */
12684 u8 *aSortOrder; /* Sort order for each column. */
12685 CollSeq *aColl[1]; /* Collating sequence for each term of the key */
12686 };
12687
12688 /*
12689 ** This object holds a record which has been parsed out into individual
12690 ** fields, for the purposes of doing a comparison.
12691 **
12692 ** A record is an object that contains one or more fields of data.
12693 ** Records are used to store the content of a table row and to store
12694 ** the key of an index. A blob encoding of a record is created by
12695 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
12696 ** OP_Column opcode.
12697 **
12698 ** An instance of this object serves as a "key" for doing a search on
12699 ** an index b+tree. The goal of the search is to find the entry that
12700 ** is closed to the key described by this object. This object might hold
12701 ** just a prefix of the key. The number of fields is given by
12702 ** pKeyInfo->nField.
12703 **
12704 ** The r1 and r2 fields are the values to return if this key is less than
12705 ** or greater than a key in the btree, respectively. These are normally
12706 ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
12707 ** is in DESC order.
12708 **
12709 ** The key comparison functions actually return default_rc when they find
12710 ** an equals comparison. default_rc can be -1, 0, or +1. If there are
12711 ** multiple entries in the b-tree with the same key (when only looking
12712 ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
12713 ** cause the search to find the last match, or +1 to cause the search to
12714 ** find the first match.
12715 **
12716 ** The key comparison functions will set eqSeen to true if they ever
12717 ** get and equal results when comparing this structure to a b-tree record.
12718 ** When default_rc!=0, the search might end up on the record immediately
12719 ** before the first match or immediately after the last match. The
12720 ** eqSeen field will indicate whether or not an exact match exists in the
12721 ** b-tree.
12722 */
12723 struct UnpackedRecord {
12724 KeyInfo *pKeyInfo; /* Collation and sort-order information */
12725 Mem *aMem; /* Values */
12726 u16 nField; /* Number of entries in apMem[] */
12727 i8 default_rc; /* Comparison result if keys are equal */
12728 u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
12729 i8 r1; /* Value to return if (lhs > rhs) */
12730 i8 r2; /* Value to return if (rhs < lhs) */
12731 u8 eqSeen; /* True if an equality comparison has been seen */
12732 };
12733
12734
12735 /*
12736 ** Each SQL index is represented in memory by an
12737 ** instance of the following structure.
12738 **
12739 ** The columns of the table that are to be indexed are described
12740 ** by the aiColumn[] field of this structure. For example, suppose
12741 ** we have the following table and index:
12742 **
12743 ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
12744 ** CREATE INDEX Ex2 ON Ex1(c3,c1);
12745 **
12746 ** In the Table structure describing Ex1, nCol==3 because there are
12747 ** three columns in the table. In the Index structure describing
12748 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
12749 ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
12750 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
12751 ** The second column to be indexed (c1) has an index of 0 in
12752 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
12753 **
12754 ** The Index.onError field determines whether or not the indexed columns
12755 ** must be unique and what to do if they are not. When Index.onError=OE_None,
12756 ** it means this is not a unique index. Otherwise it is a unique index
12757 ** and the value of Index.onError indicate the which conflict resolution
12758 ** algorithm to employ whenever an attempt is made to insert a non-unique
12759 ** element.
12760 **
12761 ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
12762 ** generate VDBE code (as opposed to parsing one read from an sqlite_master
12763 ** table as part of parsing an existing database schema), transient instances
12764 ** of this structure may be created. In this case the Index.tnum variable is
12765 ** used to store the address of a VDBE instruction, not a database page
12766 ** number (it cannot - the database page is not allocated until the VDBE
12767 ** program is executed). See convertToWithoutRowidTable() for details.
12768 */
12769 struct Index {
12770 char *zName; /* Name of this index */
12771 i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
12772 LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
12773 Table *pTable; /* The SQL table being indexed */
12774 char *zColAff; /* String defining the affinity of each column */
12775 Index *pNext; /* The next index associated with the same table */
12776 Schema *pSchema; /* Schema containing this index */
12777 u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
12778 const char **azColl; /* Array of collation sequence names for index */
12779 Expr *pPartIdxWhere; /* WHERE clause for partial indices */
12780 ExprList *aColExpr; /* Column expressions */
12781 int tnum; /* DB Page containing root of this index */
12782 LogEst szIdxRow; /* Estimated average row size in bytes */
12783 u16 nKeyCol; /* Number of columns forming the key */
12784 u16 nColumn; /* Number of columns stored in the index */
12785 u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
12786 unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
12787 unsigned bUnordered:1; /* Use this index for == or IN queries only */
12788 unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
12789 unsigned isResized:1; /* True if resizeIndexObject() has been called */
12790 unsigned isCovering:1; /* True if this is a covering index */
12791 unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
12792 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
12793 int nSample; /* Number of elements in aSample[] */
12794 int nSampleCol; /* Size of IndexSample.anEq[] and so on */
12795 tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
12796 IndexSample *aSample; /* Samples of the left-most key */
12797 tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
12798 tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
12799 #endif
12800 };
12801
12802 /*
12803 ** Allowed values for Index.idxType
12804 */
12805 #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
12806 #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
12807 #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
12808
12809 /* Return true if index X is a PRIMARY KEY index */
12810 #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
12811
12812 /* Return true if index X is a UNIQUE index */
12813 #define IsUniqueIndex(X) ((X)->onError!=OE_None)
12814
12815 /* The Index.aiColumn[] values are normally positive integer. But
12816 ** there are some negative values that have special meaning:
12817 */
12818 #define XN_ROWID (-1) /* Indexed column is the rowid */
12819 #define XN_EXPR (-2) /* Indexed column is an expression */
12820
12821 /*
12822 ** Each sample stored in the sqlite_stat3 table is represented in memory
12823 ** using a structure of this type. See documentation at the top of the
12824 ** analyze.c source file for additional information.
12825 */
12826 struct IndexSample {
12827 void *p; /* Pointer to sampled record */
12828 int n; /* Size of record in bytes */
12829 tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
12830 tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
12831 tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
12832 };
12833
12834 /*
12835 ** Each token coming out of the lexer is an instance of
12836 ** this structure. Tokens are also used as part of an expression.
12837 **
12838 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
12839 ** may contain random values. Do not make any assumptions about Token.dyn
12840 ** and Token.n when Token.z==0.
12841 */
12842 struct Token {
12843 const char *z; /* Text of the token. Not NULL-terminated! */
12844 unsigned int n; /* Number of characters in this token */
12845 };
12846
12847 /*
12848 ** An instance of this structure contains information needed to generate
12849 ** code for a SELECT that contains aggregate functions.
12850 **
12851 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
12852 ** pointer to this structure. The Expr.iColumn field is the index in
12853 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
12854 ** code for that node.
12855 **
12856 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
12857 ** original Select structure that describes the SELECT statement. These
12858 ** fields do not need to be freed when deallocating the AggInfo structure.
12859 */
12860 struct AggInfo {
12861 u8 directMode; /* Direct rendering mode means take data directly
12862 ** from source tables rather than from accumulators */
12863 u8 useSortingIdx; /* In direct mode, reference the sorting index rather
12864 ** than the source table */
12865 int sortingIdx; /* Cursor number of the sorting index */
12866 int sortingIdxPTab; /* Cursor number of pseudo-table */
12867 int nSortingColumn; /* Number of columns in the sorting index */
12868 int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
12869 ExprList *pGroupBy; /* The group by clause */
12870 struct AggInfo_col { /* For each column used in source tables */
12871 Table *pTab; /* Source table */
12872 int iTable; /* Cursor number of the source table */
12873 int iColumn; /* Column number within the source table */
12874 int iSorterColumn; /* Column number in the sorting index */
12875 int iMem; /* Memory location that acts as accumulator */
12876 Expr *pExpr; /* The original expression */
12877 } *aCol;
12878 int nColumn; /* Number of used entries in aCol[] */
12879 int nAccumulator; /* Number of columns that show through to the output.
12880 ** Additional columns are used only as parameters to
12881 ** aggregate functions */
12882 struct AggInfo_func { /* For each aggregate function */
12883 Expr *pExpr; /* Expression encoding the function */
12884 FuncDef *pFunc; /* The aggregate function implementation */
12885 int iMem; /* Memory location that acts as accumulator */
12886 int iDistinct; /* Ephemeral table used to enforce DISTINCT */
12887 } *aFunc;
12888 int nFunc; /* Number of entries in aFunc[] */
12889 };
12890
12891 /*
12892 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
12893 ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
12894 ** than 32767 we have to make it 32-bit. 16-bit is preferred because
12895 ** it uses less memory in the Expr object, which is a big memory user
12896 ** in systems with lots of prepared statements. And few applications
12897 ** need more than about 10 or 20 variables. But some extreme users want
12898 ** to have prepared statements with over 32767 variables, and for them
12899 ** the option is available (at compile-time).
12900 */
12901 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
12902 typedef i16 ynVar;
12903 #else
12904 typedef int ynVar;
12905 #endif
12906
12907 /*
12908 ** Each node of an expression in the parse tree is an instance
12909 ** of this structure.
12910 **
12911 ** Expr.op is the opcode. The integer parser token codes are reused
12912 ** as opcodes here. For example, the parser defines TK_GE to be an integer
12913 ** code representing the ">=" operator. This same integer code is reused
12914 ** to represent the greater-than-or-equal-to operator in the expression
12915 ** tree.
12916 **
12917 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
12918 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
12919 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
12920 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
12921 ** then Expr.token contains the name of the function.
12922 **
12923 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
12924 ** binary operator. Either or both may be NULL.
12925 **
12926 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
12927 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
12928 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
12929 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
12930 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
12931 ** valid.
12932 **
12933 ** An expression of the form ID or ID.ID refers to a column in a table.
12934 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
12935 ** the integer cursor number of a VDBE cursor pointing to that table and
12936 ** Expr.iColumn is the column number for the specific column. If the
12937 ** expression is used as a result in an aggregate SELECT, then the
12938 ** value is also stored in the Expr.iAgg column in the aggregate so that
12939 ** it can be accessed after all aggregates are computed.
12940 **
12941 ** If the expression is an unbound variable marker (a question mark
12942 ** character '?' in the original SQL) then the Expr.iTable holds the index
12943 ** number for that variable.
12944 **
12945 ** If the expression is a subquery then Expr.iColumn holds an integer
12946 ** register number containing the result of the subquery. If the
12947 ** subquery gives a constant result, then iTable is -1. If the subquery
12948 ** gives a different answer at different times during statement processing
12949 ** then iTable is the address of a subroutine that computes the subquery.
12950 **
12951 ** If the Expr is of type OP_Column, and the table it is selecting from
12952 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
12953 ** corresponding table definition.
12954 **
12955 ** ALLOCATION NOTES:
12956 **
12957 ** Expr objects can use a lot of memory space in database schema. To
12958 ** help reduce memory requirements, sometimes an Expr object will be
12959 ** truncated. And to reduce the number of memory allocations, sometimes
12960 ** two or more Expr objects will be stored in a single memory allocation,
12961 ** together with Expr.zToken strings.
12962 **
12963 ** If the EP_Reduced and EP_TokenOnly flags are set when
12964 ** an Expr object is truncated. When EP_Reduced is set, then all
12965 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
12966 ** are contained within the same memory allocation. Note, however, that
12967 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
12968 ** allocated, regardless of whether or not EP_Reduced is set.
12969 */
12970 struct Expr {
12971 u8 op; /* Operation performed by this node */
12972 char affinity; /* The affinity of the column or 0 if not a column */
12973 u32 flags; /* Various flags. EP_* See below */
12974 union {
12975 char *zToken; /* Token value. Zero terminated and dequoted */
12976 int iValue; /* Non-negative integer value if EP_IntValue */
12977 } u;
12978
12979 /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
12980 ** space is allocated for the fields below this point. An attempt to
12981 ** access them will result in a segfault or malfunction.
12982 *********************************************************************/
12983
12984 Expr *pLeft; /* Left subnode */
12985 Expr *pRight; /* Right subnode */
12986 union {
12987 ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
12988 Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
12989 } x;
12990
12991 /* If the EP_Reduced flag is set in the Expr.flags mask, then no
12992 ** space is allocated for the fields below this point. An attempt to
12993 ** access them will result in a segfault or malfunction.
12994 *********************************************************************/
12995
12996 #if SQLITE_MAX_EXPR_DEPTH>0
12997 int nHeight; /* Height of the tree headed by this node */
12998 #endif
12999 int iTable; /* TK_COLUMN: cursor number of table holding column
13000 ** TK_REGISTER: register number
13001 ** TK_TRIGGER: 1 -> new, 0 -> old
13002 ** EP_Unlikely: 134217728 times likelihood */
13003 ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
13004 ** TK_VARIABLE: variable number (always >= 1). */
13005 i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
13006 i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
13007 u8 op2; /* TK_REGISTER: original value of Expr.op
13008 ** TK_COLUMN: the value of p5 for OP_Column
13009 ** TK_AGG_FUNCTION: nesting depth */
13010 AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
13011 Table *pTab; /* Table for TK_COLUMN expressions. */
13012 };
13013
13014 /*
13015 ** The following are the meanings of bits in the Expr.flags field.
13016 */
13017 #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
13018 #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
13019 #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
13020 #define EP_Error 0x000008 /* Expression contains one or more errors */
13021 #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
13022 #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
13023 #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
13024 #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
13025 #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
13026 #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
13027 #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
13028 #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
13029 #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
13030 #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
13031 #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
13032 #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
13033 #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
13034 #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
13035 #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
13036 #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
13037 #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
13038 #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
13039 #define EP_Alias 0x400000 /* Is an alias for a result set column */
13040
13041 /*
13042 ** Combinations of two or more EP_* flags
13043 */
13044 #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
13045
13046 /*
13047 ** These macros can be used to test, set, or clear bits in the
13048 ** Expr.flags field.
13049 */
13050 #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
13051 #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
13052 #define ExprSetProperty(E,P) (E)->flags|=(P)
13053 #define ExprClearProperty(E,P) (E)->flags&=~(P)
13054
13055 /* The ExprSetVVAProperty() macro is used for Verification, Validation,
13056 ** and Accreditation only. It works like ExprSetProperty() during VVA
13057 ** processes but is a no-op for delivery.
13058 */
13059 #ifdef SQLITE_DEBUG
13060 # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
13061 #else
13062 # define ExprSetVVAProperty(E,P)
13063 #endif
13064
13065 /*
13066 ** Macros to determine the number of bytes required by a normal Expr
13067 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
13068 ** and an Expr struct with the EP_TokenOnly flag set.
13069 */
13070 #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
13071 #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
13072 #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
13073
13074 /*
13075 ** Flags passed to the sqlite3ExprDup() function. See the header comment
13076 ** above sqlite3ExprDup() for details.
13077 */
13078 #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
13079
13080 /*
13081 ** A list of expressions. Each expression may optionally have a
13082 ** name. An expr/name combination can be used in several ways, such
13083 ** as the list of "expr AS ID" fields following a "SELECT" or in the
13084 ** list of "ID = expr" items in an UPDATE. A list of expressions can
13085 ** also be used as the argument to a function, in which case the a.zName
13086 ** field is not used.
13087 **
13088 ** By default the Expr.zSpan field holds a human-readable description of
13089 ** the expression that is used in the generation of error messages and
13090 ** column labels. In this case, Expr.zSpan is typically the text of a
13091 ** column expression as it exists in a SELECT statement. However, if
13092 ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
13093 ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
13094 ** form is used for name resolution with nested FROM clauses.
13095 */
13096 struct ExprList {
13097 int nExpr; /* Number of expressions on the list */
13098 struct ExprList_item { /* For each expression in the list */
13099 Expr *pExpr; /* The list of expressions */
13100 char *zName; /* Token associated with this expression */
13101 char *zSpan; /* Original text of the expression */
13102 u8 sortOrder; /* 1 for DESC or 0 for ASC */
13103 unsigned done :1; /* A flag to indicate when processing is finished */
13104 unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
13105 unsigned reusable :1; /* Constant expression is reusable */
13106 union {
13107 struct {
13108 u16 iOrderByCol; /* For ORDER BY, column number in result set */
13109 u16 iAlias; /* Index into Parse.aAlias[] for zName */
13110 } x;
13111 int iConstExprReg; /* Register in which Expr value is cached */
13112 } u;
13113 } *a; /* Alloc a power of two greater or equal to nExpr */
13114 };
13115
13116 /*
13117 ** An instance of this structure is used by the parser to record both
13118 ** the parse tree for an expression and the span of input text for an
13119 ** expression.
13120 */
13121 struct ExprSpan {
13122 Expr *pExpr; /* The expression parse tree */
13123 const char *zStart; /* First character of input text */
13124 const char *zEnd; /* One character past the end of input text */
13125 };
13126
13127 /*
13128 ** An instance of this structure can hold a simple list of identifiers,
13129 ** such as the list "a,b,c" in the following statements:
13130 **
13131 ** INSERT INTO t(a,b,c) VALUES ...;
13132 ** CREATE INDEX idx ON t(a,b,c);
13133 ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
13134 **
13135 ** The IdList.a.idx field is used when the IdList represents the list of
13136 ** column names after a table name in an INSERT statement. In the statement
13137 **
13138 ** INSERT INTO t(a,b,c) ...
13139 **
13140 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
13141 */
13142 struct IdList {
13143 struct IdList_item {
13144 char *zName; /* Name of the identifier */
13145 int idx; /* Index in some Table.aCol[] of a column named zName */
13146 } *a;
13147 int nId; /* Number of identifiers on the list */
13148 };
13149
13150 /*
13151 ** The bitmask datatype defined below is used for various optimizations.
13152 **
13153 ** Changing this from a 64-bit to a 32-bit type limits the number of
13154 ** tables in a join to 32 instead of 64. But it also reduces the size
13155 ** of the library by 738 bytes on ix86.
13156 */
13157 typedef u64 Bitmask;
13158
13159 /*
13160 ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
13161 */
13162 #define BMS ((int)(sizeof(Bitmask)*8))
13163
13164 /*
13165 ** A bit in a Bitmask
13166 */
13167 #define MASKBIT(n) (((Bitmask)1)<<(n))
13168 #define MASKBIT32(n) (((unsigned int)1)<<(n))
13169
13170 /*
13171 ** The following structure describes the FROM clause of a SELECT statement.
13172 ** Each table or subquery in the FROM clause is a separate element of
13173 ** the SrcList.a[] array.
13174 **
13175 ** With the addition of multiple database support, the following structure
13176 ** can also be used to describe a particular table such as the table that
13177 ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
13178 ** such a table must be a simple name: ID. But in SQLite, the table can
13179 ** now be identified by a database name, a dot, then the table name: ID.ID.
13180 **
13181 ** The jointype starts out showing the join type between the current table
13182 ** and the next table on the list. The parser builds the list this way.
13183 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
13184 ** jointype expresses the join between the table and the previous table.
13185 **
13186 ** In the colUsed field, the high-order bit (bit 63) is set if the table
13187 ** contains more than 63 columns and the 64-th or later column is used.
13188 */
13189 struct SrcList {
13190 int nSrc; /* Number of tables or subqueries in the FROM clause */
13191 u32 nAlloc; /* Number of entries allocated in a[] below */
13192 struct SrcList_item {
13193 Schema *pSchema; /* Schema to which this item is fixed */
13194 char *zDatabase; /* Name of database holding this table */
13195 char *zName; /* Name of the table */
13196 char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
13197 Table *pTab; /* An SQL table corresponding to zName */
13198 Select *pSelect; /* A SELECT statement used in place of a table name */
13199 int addrFillSub; /* Address of subroutine to manifest a subquery */
13200 int regReturn; /* Register holding return address of addrFillSub */
13201 int regResult; /* Registers holding results of a co-routine */
13202 struct {
13203 u8 jointype; /* Type of join between this able and the previous */
13204 unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
13205 unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
13206 unsigned isTabFunc :1; /* True if table-valued-function syntax */
13207 unsigned isCorrelated :1; /* True if sub-query is correlated */
13208 unsigned viaCoroutine :1; /* Implemented as a co-routine */
13209 unsigned isRecursive :1; /* True for recursive reference in WITH */
13210 } fg;
13211 #ifndef SQLITE_OMIT_EXPLAIN
13212 u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
13213 #endif
13214 int iCursor; /* The VDBE cursor number used to access this table */
13215 Expr *pOn; /* The ON clause of a join */
13216 IdList *pUsing; /* The USING clause of a join */
13217 Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
13218 union {
13219 char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
13220 ExprList *pFuncArg; /* Arguments to table-valued-function */
13221 } u1;
13222 Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
13223 } a[1]; /* One entry for each identifier on the list */
13224 };
13225
13226 /*
13227 ** Permitted values of the SrcList.a.jointype field
13228 */
13229 #define JT_INNER 0x0001 /* Any kind of inner or cross join */
13230 #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
13231 #define JT_NATURAL 0x0004 /* True for a "natural" join */
13232 #define JT_LEFT 0x0008 /* Left outer join */
13233 #define JT_RIGHT 0x0010 /* Right outer join */
13234 #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
13235 #define JT_ERROR 0x0040 /* unknown or unsupported join type */
13236
13237
13238 /*
13239 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
13240 ** and the WhereInfo.wctrlFlags member.
13241 */
13242 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
13243 #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
13244 #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
13245 #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
13246 #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
13247 #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
13248 #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
13249 #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
13250 #define WHERE_NO_AUTOINDEX 0x0080 /* Disallow automatic indexes */
13251 #define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */
13252 #define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */
13253 #define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
13254 #define WHERE_SORTBYGROUP 0x0800 /* Support sqlite3WhereIsSorted() */
13255 #define WHERE_REOPEN_IDX 0x1000 /* Try to use OP_ReopenIdx */
13256 #define WHERE_ONEPASS_MULTIROW 0x2000 /* ONEPASS is ok with multiple rows */
13257
13258 /* Allowed return values from sqlite3WhereIsDistinct()
13259 */
13260 #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
13261 #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
13262 #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
13263 #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
13264
13265 /*
13266 ** A NameContext defines a context in which to resolve table and column
13267 ** names. The context consists of a list of tables (the pSrcList) field and
13268 ** a list of named expression (pEList). The named expression list may
13269 ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
13270 ** to the table being operated on by INSERT, UPDATE, or DELETE. The
13271 ** pEList corresponds to the result set of a SELECT and is NULL for
13272 ** other statements.
13273 **
13274 ** NameContexts can be nested. When resolving names, the inner-most
13275 ** context is searched first. If no match is found, the next outer
13276 ** context is checked. If there is still no match, the next context
13277 ** is checked. This process continues until either a match is found
13278 ** or all contexts are check. When a match is found, the nRef member of
13279 ** the context containing the match is incremented.
13280 **
13281 ** Each subquery gets a new NameContext. The pNext field points to the
13282 ** NameContext in the parent query. Thus the process of scanning the
13283 ** NameContext list corresponds to searching through successively outer
13284 ** subqueries looking for a match.
13285 */
13286 struct NameContext {
13287 Parse *pParse; /* The parser */
13288 SrcList *pSrcList; /* One or more tables used to resolve names */
13289 ExprList *pEList; /* Optional list of result-set columns */
13290 AggInfo *pAggInfo; /* Information about aggregates at this level */
13291 NameContext *pNext; /* Next outer name context. NULL for outermost */
13292 int nRef; /* Number of names resolved by this context */
13293 int nErr; /* Number of errors encountered while resolving names */
13294 u16 ncFlags; /* Zero or more NC_* flags defined below */
13295 };
13296
13297 /*
13298 ** Allowed values for the NameContext, ncFlags field.
13299 **
13300 ** Note: NC_MinMaxAgg must have the same value as SF_MinMaxAgg and
13301 ** SQLITE_FUNC_MINMAX.
13302 **
13303 */
13304 #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
13305 #define NC_HasAgg 0x0002 /* One or more aggregate functions seen */
13306 #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
13307 #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
13308 #define NC_PartIdx 0x0010 /* True if resolving a partial index WHERE */
13309 #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
13310 #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
13311
13312 /*
13313 ** An instance of the following structure contains all information
13314 ** needed to generate code for a single SELECT statement.
13315 **
13316 ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
13317 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
13318 ** limit and nOffset to the value of the offset (or 0 if there is not
13319 ** offset). But later on, nLimit and nOffset become the memory locations
13320 ** in the VDBE that record the limit and offset counters.
13321 **
13322 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
13323 ** These addresses must be stored so that we can go back and fill in
13324 ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
13325 ** the number of columns in P2 can be computed at the same time
13326 ** as the OP_OpenEphm instruction is coded because not
13327 ** enough information about the compound query is known at that point.
13328 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
13329 ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
13330 ** sequences for the ORDER BY clause.
13331 */
13332 struct Select {
13333 ExprList *pEList; /* The fields of the result */
13334 u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
13335 u16 selFlags; /* Various SF_* values */
13336 int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
13337 #if SELECTTRACE_ENABLED
13338 char zSelName[12]; /* Symbolic name of this SELECT use for debugging */
13339 #endif
13340 int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
13341 u64 nSelectRow; /* Estimated number of result rows */
13342 SrcList *pSrc; /* The FROM clause */
13343 Expr *pWhere; /* The WHERE clause */
13344 ExprList *pGroupBy; /* The GROUP BY clause */
13345 Expr *pHaving; /* The HAVING clause */
13346 ExprList *pOrderBy; /* The ORDER BY clause */
13347 Select *pPrior; /* Prior select in a compound select statement */
13348 Select *pNext; /* Next select to the left in a compound */
13349 Expr *pLimit; /* LIMIT expression. NULL means not used. */
13350 Expr *pOffset; /* OFFSET expression. NULL means not used. */
13351 With *pWith; /* WITH clause attached to this select. Or NULL. */
13352 };
13353
13354 /*
13355 ** Allowed values for Select.selFlags. The "SF" prefix stands for
13356 ** "Select Flag".
13357 */
13358 #define SF_Distinct 0x0001 /* Output should be DISTINCT */
13359 #define SF_All 0x0002 /* Includes the ALL keyword */
13360 #define SF_Resolved 0x0004 /* Identifiers have been resolved */
13361 #define SF_Aggregate 0x0008 /* Contains aggregate functions */
13362 #define SF_UsesEphemeral 0x0010 /* Uses the OpenEphemeral opcode */
13363 #define SF_Expanded 0x0020 /* sqlite3SelectExpand() called on this */
13364 #define SF_HasTypeInfo 0x0040 /* FROM subqueries have Table metadata */
13365 #define SF_Compound 0x0080 /* Part of a compound query */
13366 #define SF_Values 0x0100 /* Synthesized from VALUES clause */
13367 #define SF_MultiValue 0x0200 /* Single VALUES term with multiple rows */
13368 #define SF_NestedFrom 0x0400 /* Part of a parenthesized FROM clause */
13369 #define SF_MaybeConvert 0x0800 /* Need convertCompoundSelectToSubquery() */
13370 #define SF_MinMaxAgg 0x1000 /* Aggregate containing min() or max() */
13371 #define SF_Recursive 0x2000 /* The recursive part of a recursive CTE */
13372 #define SF_Converted 0x4000 /* By convertCompoundSelectToSubquery() */
13373 #define SF_IncludeHidden 0x8000 /* Include hidden columns in output */
13374
13375
13376 /*
13377 ** The results of a SELECT can be distributed in several ways, as defined
13378 ** by one of the following macros. The "SRT" prefix means "SELECT Result
13379 ** Type".
13380 **
13381 ** SRT_Union Store results as a key in a temporary index
13382 ** identified by pDest->iSDParm.
13383 **
13384 ** SRT_Except Remove results from the temporary index pDest->iSDParm.
13385 **
13386 ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
13387 ** set is not empty.
13388 **
13389 ** SRT_Discard Throw the results away. This is used by SELECT
13390 ** statements within triggers whose only purpose is
13391 ** the side-effects of functions.
13392 **
13393 ** All of the above are free to ignore their ORDER BY clause. Those that
13394 ** follow must honor the ORDER BY clause.
13395 **
13396 ** SRT_Output Generate a row of output (using the OP_ResultRow
13397 ** opcode) for each row in the result set.
13398 **
13399 ** SRT_Mem Only valid if the result is a single column.
13400 ** Store the first column of the first result row
13401 ** in register pDest->iSDParm then abandon the rest
13402 ** of the query. This destination implies "LIMIT 1".
13403 **
13404 ** SRT_Set The result must be a single column. Store each
13405 ** row of result as the key in table pDest->iSDParm.
13406 ** Apply the affinity pDest->affSdst before storing
13407 ** results. Used to implement "IN (SELECT ...)".
13408 **
13409 ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
13410 ** the result there. The cursor is left open after
13411 ** returning. This is like SRT_Table except that
13412 ** this destination uses OP_OpenEphemeral to create
13413 ** the table first.
13414 **
13415 ** SRT_Coroutine Generate a co-routine that returns a new row of
13416 ** results each time it is invoked. The entry point
13417 ** of the co-routine is stored in register pDest->iSDParm
13418 ** and the result row is stored in pDest->nDest registers
13419 ** starting with pDest->iSdst.
13420 **
13421 ** SRT_Table Store results in temporary table pDest->iSDParm.
13422 ** SRT_Fifo This is like SRT_EphemTab except that the table
13423 ** is assumed to already be open. SRT_Fifo has
13424 ** the additional property of being able to ignore
13425 ** the ORDER BY clause.
13426 **
13427 ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
13428 ** But also use temporary table pDest->iSDParm+1 as
13429 ** a record of all prior results and ignore any duplicate
13430 ** rows. Name means: "Distinct Fifo".
13431 **
13432 ** SRT_Queue Store results in priority queue pDest->iSDParm (really
13433 ** an index). Append a sequence number so that all entries
13434 ** are distinct.
13435 **
13436 ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
13437 ** the same record has never been stored before. The
13438 ** index at pDest->iSDParm+1 hold all prior stores.
13439 */
13440 #define SRT_Union 1 /* Store result as keys in an index */
13441 #define SRT_Except 2 /* Remove result from a UNION index */
13442 #define SRT_Exists 3 /* Store 1 if the result is not empty */
13443 #define SRT_Discard 4 /* Do not save the results anywhere */
13444 #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
13445 #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
13446 #define SRT_Queue 7 /* Store result in an queue */
13447 #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
13448
13449 /* The ORDER BY clause is ignored for all of the above */
13450 #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
13451
13452 #define SRT_Output 9 /* Output each row of result */
13453 #define SRT_Mem 10 /* Store result in a memory cell */
13454 #define SRT_Set 11 /* Store results as keys in an index */
13455 #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
13456 #define SRT_Coroutine 13 /* Generate a single row of result */
13457 #define SRT_Table 14 /* Store result as data with an automatic rowid */
13458
13459 /*
13460 ** An instance of this object describes where to put of the results of
13461 ** a SELECT statement.
13462 */
13463 struct SelectDest {
13464 u8 eDest; /* How to dispose of the results. On of SRT_* above. */
13465 char affSdst; /* Affinity used when eDest==SRT_Set */
13466 int iSDParm; /* A parameter used by the eDest disposal method */
13467 int iSdst; /* Base register where results are written */
13468 int nSdst; /* Number of registers allocated */
13469 ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
13470 };
13471
13472 /*
13473 ** During code generation of statements that do inserts into AUTOINCREMENT
13474 ** tables, the following information is attached to the Table.u.autoInc.p
13475 ** pointer of each autoincrement table to record some side information that
13476 ** the code generator needs. We have to keep per-table autoincrement
13477 ** information in case inserts are down within triggers. Triggers do not
13478 ** normally coordinate their activities, but we do need to coordinate the
13479 ** loading and saving of autoincrement information.
13480 */
13481 struct AutoincInfo {
13482 AutoincInfo *pNext; /* Next info block in a list of them all */
13483 Table *pTab; /* Table this info block refers to */
13484 int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
13485 int regCtr; /* Memory register holding the rowid counter */
13486 };
13487
13488 /*
13489 ** Size of the column cache
13490 */
13491 #ifndef SQLITE_N_COLCACHE
13492 # define SQLITE_N_COLCACHE 10
13493 #endif
13494
13495 /*
13496 ** At least one instance of the following structure is created for each
13497 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
13498 ** statement. All such objects are stored in the linked list headed at
13499 ** Parse.pTriggerPrg and deleted once statement compilation has been
13500 ** completed.
13501 **
13502 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
13503 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
13504 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
13505 ** The Parse.pTriggerPrg list never contains two entries with the same
13506 ** values for both pTrigger and orconf.
13507 **
13508 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
13509 ** accessed (or set to 0 for triggers fired as a result of INSERT
13510 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
13511 ** a mask of new.* columns used by the program.
13512 */
13513 struct TriggerPrg {
13514 Trigger *pTrigger; /* Trigger this program was coded from */
13515 TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
13516 SubProgram *pProgram; /* Program implementing pTrigger/orconf */
13517 int orconf; /* Default ON CONFLICT policy */
13518 u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
13519 };
13520
13521 /*
13522 ** The yDbMask datatype for the bitmask of all attached databases.
13523 */
13524 #if SQLITE_MAX_ATTACHED>30
13525 typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
13526 # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
13527 # define DbMaskZero(M) memset((M),0,sizeof(M))
13528 # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
13529 # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
13530 # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
13531 #else
13532 typedef unsigned int yDbMask;
13533 # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
13534 # define DbMaskZero(M) (M)=0
13535 # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
13536 # define DbMaskAllZero(M) (M)==0
13537 # define DbMaskNonZero(M) (M)!=0
13538 #endif
13539
13540 /*
13541 ** An SQL parser context. A copy of this structure is passed through
13542 ** the parser and down into all the parser action routine in order to
13543 ** carry around information that is global to the entire parse.
13544 **
13545 ** The structure is divided into two parts. When the parser and code
13546 ** generate call themselves recursively, the first part of the structure
13547 ** is constant but the second part is reset at the beginning and end of
13548 ** each recursion.
13549 **
13550 ** The nTableLock and aTableLock variables are only used if the shared-cache
13551 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
13552 ** used to store the set of table-locks required by the statement being
13553 ** compiled. Function sqlite3TableLock() is used to add entries to the
13554 ** list.
13555 */
13556 struct Parse {
13557 sqlite3 *db; /* The main database structure */
13558 char *zErrMsg; /* An error message */
13559 Vdbe *pVdbe; /* An engine for executing database bytecode */
13560 int rc; /* Return code from execution */
13561 u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
13562 u8 checkSchema; /* Causes schema cookie check after an error */
13563 u8 nested; /* Number of nested calls to the parser/code generator */
13564 u8 nTempReg; /* Number of temporary registers in aTempReg[] */
13565 u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
13566 u8 mayAbort; /* True if statement may throw an ABORT exception */
13567 u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
13568 u8 okConstFactor; /* OK to factor out constants */
13569 int aTempReg[8]; /* Holding area for temporary registers */
13570 int nRangeReg; /* Size of the temporary register block */
13571 int iRangeReg; /* First register in temporary register block */
13572 int nErr; /* Number of errors seen */
13573 int nTab; /* Number of previously allocated VDBE cursors */
13574 int nMem; /* Number of memory cells used so far */
13575 int nSet; /* Number of sets used so far */
13576 int nOnce; /* Number of OP_Once instructions so far */
13577 int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
13578 int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
13579 int iFixedOp; /* Never back out opcodes iFixedOp-1 or earlier */
13580 int ckBase; /* Base register of data during check constraints */
13581 int iSelfTab; /* Table of an index whose exprs are being coded */
13582 int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
13583 int iCacheCnt; /* Counter used to generate aColCache[].lru values */
13584 int nLabel; /* Number of labels used */
13585 int *aLabel; /* Space to hold the labels */
13586 struct yColCache {
13587 int iTable; /* Table cursor number */
13588 i16 iColumn; /* Table column number */
13589 u8 tempReg; /* iReg is a temp register that needs to be freed */
13590 int iLevel; /* Nesting level */
13591 int iReg; /* Reg with value of this column. 0 means none. */
13592 int lru; /* Least recently used entry has the smallest value */
13593 } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
13594 ExprList *pConstExpr;/* Constant expressions */
13595 Token constraintName;/* Name of the constraint currently being parsed */
13596 yDbMask writeMask; /* Start a write transaction on these databases */
13597 yDbMask cookieMask; /* Bitmask of schema verified databases */
13598 int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
13599 int regRowid; /* Register holding rowid of CREATE TABLE entry */
13600 int regRoot; /* Register holding root page number for new objects */
13601 int nMaxArg; /* Max args passed to user function by sub-program */
13602 #if SELECTTRACE_ENABLED
13603 int nSelect; /* Number of SELECT statements seen */
13604 int nSelectIndent; /* How far to indent SELECTTRACE() output */
13605 #endif
13606 #ifndef SQLITE_OMIT_SHARED_CACHE
13607 int nTableLock; /* Number of locks in aTableLock */
13608 TableLock *aTableLock; /* Required table locks for shared-cache mode */
13609 #endif
13610 AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
13611
13612 /* Information used while coding trigger programs. */
13613 Parse *pToplevel; /* Parse structure for main program (or NULL) */
13614 Table *pTriggerTab; /* Table triggers are being coded for */
13615 int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */
13616 u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
13617 u32 oldmask; /* Mask of old.* columns referenced */
13618 u32 newmask; /* Mask of new.* columns referenced */
13619 u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
13620 u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
13621 u8 disableTriggers; /* True to disable triggers */
13622
13623 /************************************************************************
13624 ** Above is constant between recursions. Below is reset before and after
13625 ** each recursion. The boundary between these two regions is determined
13626 ** using offsetof(Parse,nVar) so the nVar field must be the first field
13627 ** in the recursive region.
13628 ************************************************************************/
13629
13630 int nVar; /* Number of '?' variables seen in the SQL so far */
13631 int nzVar; /* Number of available slots in azVar[] */
13632 u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
13633 u8 explain; /* True if the EXPLAIN flag is found on the query */
13634 #ifndef SQLITE_OMIT_VIRTUALTABLE
13635 u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
13636 int nVtabLock; /* Number of virtual tables to lock */
13637 #endif
13638 int nAlias; /* Number of aliased result set columns */
13639 int nHeight; /* Expression tree height of current sub-select */
13640 #ifndef SQLITE_OMIT_EXPLAIN
13641 int iSelectId; /* ID of current select for EXPLAIN output */
13642 int iNextSelectId; /* Next available select ID for EXPLAIN output */
13643 #endif
13644 char **azVar; /* Pointers to names of parameters */
13645 Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
13646 const char *zTail; /* All SQL text past the last semicolon parsed */
13647 Table *pNewTable; /* A table being constructed by CREATE TABLE */
13648 Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
13649 const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
13650 Token sNameToken; /* Token with unqualified schema object name */
13651 Token sLastToken; /* The last token parsed */
13652 #ifndef SQLITE_OMIT_VIRTUALTABLE
13653 Token sArg; /* Complete text of a module argument */
13654 Table **apVtabLock; /* Pointer to virtual tables needing locking */
13655 #endif
13656 Table *pZombieTab; /* List of Table objects to delete after code gen */
13657 TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
13658 With *pWith; /* Current WITH clause, or NULL */
13659 With *pWithToFree; /* Free this WITH object at the end of the parse */
13660 };
13661
13662 /*
13663 ** Return true if currently inside an sqlite3_declare_vtab() call.
13664 */
13665 #ifdef SQLITE_OMIT_VIRTUALTABLE
13666 #define IN_DECLARE_VTAB 0
13667 #else
13668 #define IN_DECLARE_VTAB (pParse->declareVtab)
13669 #endif
13670
13671 /*
13672 ** An instance of the following structure can be declared on a stack and used
13673 ** to save the Parse.zAuthContext value so that it can be restored later.
13674 */
13675 struct AuthContext {
13676 const char *zAuthContext; /* Put saved Parse.zAuthContext here */
13677 Parse *pParse; /* The Parse structure */
13678 };
13679
13680 /*
13681 ** Bitfield flags for P5 value in various opcodes.
13682 */
13683 #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
13684 #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
13685 #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
13686 #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
13687 #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
13688 #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
13689 #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
13690 #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
13691 #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
13692 #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
13693 #define OPFLAG_FORDELETE 0x08 /* OP_Open is opening for-delete csr */
13694 #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
13695 #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
13696
13697 /*
13698 * Each trigger present in the database schema is stored as an instance of
13699 * struct Trigger.
13700 *
13701 * Pointers to instances of struct Trigger are stored in two ways.
13702 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
13703 * database). This allows Trigger structures to be retrieved by name.
13704 * 2. All triggers associated with a single table form a linked list, using the
13705 * pNext member of struct Trigger. A pointer to the first element of the
13706 * linked list is stored as the "pTrigger" member of the associated
13707 * struct Table.
13708 *
13709 * The "step_list" member points to the first element of a linked list
13710 * containing the SQL statements specified as the trigger program.
13711 */
13712 struct Trigger {
13713 char *zName; /* The name of the trigger */
13714 char *table; /* The table or view to which the trigger applies */
13715 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
13716 u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
13717 Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
13718 IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
13719 the <column-list> is stored here */
13720 Schema *pSchema; /* Schema containing the trigger */
13721 Schema *pTabSchema; /* Schema containing the table */
13722 TriggerStep *step_list; /* Link list of trigger program steps */
13723 Trigger *pNext; /* Next trigger associated with the table */
13724 };
13725
13726 /*
13727 ** A trigger is either a BEFORE or an AFTER trigger. The following constants
13728 ** determine which.
13729 **
13730 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
13731 ** In that cases, the constants below can be ORed together.
13732 */
13733 #define TRIGGER_BEFORE 1
13734 #define TRIGGER_AFTER 2
13735
13736 /*
13737 * An instance of struct TriggerStep is used to store a single SQL statement
13738 * that is a part of a trigger-program.
13739 *
13740 * Instances of struct TriggerStep are stored in a singly linked list (linked
13741 * using the "pNext" member) referenced by the "step_list" member of the
13742 * associated struct Trigger instance. The first element of the linked list is
13743 * the first step of the trigger-program.
13744 *
13745 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
13746 * "SELECT" statement. The meanings of the other members is determined by the
13747 * value of "op" as follows:
13748 *
13749 * (op == TK_INSERT)
13750 * orconf -> stores the ON CONFLICT algorithm
13751 * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
13752 * this stores a pointer to the SELECT statement. Otherwise NULL.
13753 * zTarget -> Dequoted name of the table to insert into.
13754 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
13755 * this stores values to be inserted. Otherwise NULL.
13756 * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
13757 * statement, then this stores the column-names to be
13758 * inserted into.
13759 *
13760 * (op == TK_DELETE)
13761 * zTarget -> Dequoted name of the table to delete from.
13762 * pWhere -> The WHERE clause of the DELETE statement if one is specified.
13763 * Otherwise NULL.
13764 *
13765 * (op == TK_UPDATE)
13766 * zTarget -> Dequoted name of the table to update.
13767 * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
13768 * Otherwise NULL.
13769 * pExprList -> A list of the columns to update and the expressions to update
13770 * them to. See sqlite3Update() documentation of "pChanges"
13771 * argument.
13772 *
13773 */
13774 struct TriggerStep {
13775 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
13776 u8 orconf; /* OE_Rollback etc. */
13777 Trigger *pTrig; /* The trigger that this step is a part of */
13778 Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
13779 char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
13780 Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
13781 ExprList *pExprList; /* SET clause for UPDATE. */
13782 IdList *pIdList; /* Column names for INSERT */
13783 TriggerStep *pNext; /* Next in the link-list */
13784 TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
13785 };
13786
13787 /*
13788 ** The following structure contains information used by the sqliteFix...
13789 ** routines as they walk the parse tree to make database references
13790 ** explicit.
13791 */
13792 typedef struct DbFixer DbFixer;
13793 struct DbFixer {
13794 Parse *pParse; /* The parsing context. Error messages written here */
13795 Schema *pSchema; /* Fix items to this schema */
13796 int bVarOnly; /* Check for variable references only */
13797 const char *zDb; /* Make sure all objects are contained in this database */
13798 const char *zType; /* Type of the container - used for error messages */
13799 const Token *pName; /* Name of the container - used for error messages */
13800 };
13801
13802 /*
13803 ** An objected used to accumulate the text of a string where we
13804 ** do not necessarily know how big the string will be in the end.
13805 */
13806 struct StrAccum {
13807 sqlite3 *db; /* Optional database for lookaside. Can be NULL */
13808 char *zBase; /* A base allocation. Not from malloc. */
13809 char *zText; /* The string collected so far */
13810 u32 nChar; /* Length of the string so far */
13811 u32 nAlloc; /* Amount of space allocated in zText */
13812 u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
13813 u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
13814 u8 bMalloced; /* zText points to allocated space */
13815 };
13816 #define STRACCUM_NOMEM 1
13817 #define STRACCUM_TOOBIG 2
13818
13819 /*
13820 ** A pointer to this structure is used to communicate information
13821 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
13822 */
13823 typedef struct {
13824 sqlite3 *db; /* The database being initialized */
13825 char **pzErrMsg; /* Error message stored here */
13826 int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
13827 int rc; /* Result code stored here */
13828 } InitData;
13829
13830 /*
13831 ** Structure containing global configuration data for the SQLite library.
13832 **
13833 ** This structure also contains some state information.
13834 */
13835 struct Sqlite3Config {
13836 int bMemstat; /* True to enable memory status */
13837 int bCoreMutex; /* True to enable core mutexing */
13838 int bFullMutex; /* True to enable full mutexing */
13839 int bOpenUri; /* True to interpret filenames as URIs */
13840 int bUseCis; /* Use covering indices for full-scans */
13841 int mxStrlen; /* Maximum string length */
13842 int neverCorrupt; /* Database is always well-formed */
13843 int szLookaside; /* Default lookaside buffer size */
13844 int nLookaside; /* Default lookaside buffer count */
13845 sqlite3_mem_methods m; /* Low-level memory allocation interface */
13846 sqlite3_mutex_methods mutex; /* Low-level mutex interface */
13847 sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
13848 void *pHeap; /* Heap storage space */
13849 int nHeap; /* Size of pHeap[] */
13850 int mnReq, mxReq; /* Min and max heap requests sizes */
13851 sqlite3_int64 szMmap; /* mmap() space per open file */
13852 sqlite3_int64 mxMmap; /* Maximum value for szMmap */
13853 void *pScratch; /* Scratch memory */
13854 int szScratch; /* Size of each scratch buffer */
13855 int nScratch; /* Number of scratch buffers */
13856 void *pPage; /* Page cache memory */
13857 int szPage; /* Size of each page in pPage[] */
13858 int nPage; /* Number of pages in pPage[] */
13859 int mxParserStack; /* maximum depth of the parser stack */
13860 int sharedCacheEnabled; /* true if shared-cache mode enabled */
13861 u32 szPma; /* Maximum Sorter PMA size */
13862 /* The above might be initialized to non-zero. The following need to always
13863 ** initially be zero, however. */
13864 int isInit; /* True after initialization has finished */
13865 int inProgress; /* True while initialization in progress */
13866 int isMutexInit; /* True after mutexes are initialized */
13867 int isMallocInit; /* True after malloc is initialized */
13868 int isPCacheInit; /* True after malloc is initialized */
13869 int nRefInitMutex; /* Number of users of pInitMutex */
13870 sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
13871 void (*xLog)(void*,int,const char*); /* Function for logging */
13872 void *pLogArg; /* First argument to xLog() */
13873 #ifdef SQLITE_ENABLE_SQLLOG
13874 void(*xSqllog)(void*,sqlite3*,const char*, int);
13875 void *pSqllogArg;
13876 #endif
13877 #ifdef SQLITE_VDBE_COVERAGE
13878 /* The following callback (if not NULL) is invoked on every VDBE branch
13879 ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
13880 */
13881 void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */
13882 void *pVdbeBranchArg; /* 1st argument */
13883 #endif
13884 #ifndef SQLITE_OMIT_BUILTIN_TEST
13885 int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
13886 #endif
13887 int bLocaltimeFault; /* True to fail localtime() calls */
13888 };
13889
13890 /*
13891 ** This macro is used inside of assert() statements to indicate that
13892 ** the assert is only valid on a well-formed database. Instead of:
13893 **
13894 ** assert( X );
13895 **
13896 ** One writes:
13897 **
13898 ** assert( X || CORRUPT_DB );
13899 **
13900 ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
13901 ** that the database is definitely corrupt, only that it might be corrupt.
13902 ** For most test cases, CORRUPT_DB is set to false using a special
13903 ** sqlite3_test_control(). This enables assert() statements to prove
13904 ** things that are always true for well-formed databases.
13905 */
13906 #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
13907
13908 /*
13909 ** Context pointer passed down through the tree-walk.
13910 */
13911 struct Walker {
13912 int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
13913 int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
13914 void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
13915 Parse *pParse; /* Parser context. */
13916 int walkerDepth; /* Number of subqueries */
13917 u8 eCode; /* A small processing code */
13918 union { /* Extra data for callback */
13919 NameContext *pNC; /* Naming context */
13920 int n; /* A counter */
13921 int iCur; /* A cursor number */
13922 SrcList *pSrcList; /* FROM clause */
13923 struct SrcCount *pSrcCount; /* Counting column references */
13924 struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
13925 } u;
13926 };
13927
13928 /* Forward declarations */
13929 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
13930 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
13931 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
13932 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
13933 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
13934 SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
13935
13936 /*
13937 ** Return code from the parse-tree walking primitives and their
13938 ** callbacks.
13939 */
13940 #define WRC_Continue 0 /* Continue down into children */
13941 #define WRC_Prune 1 /* Omit children but continue walking siblings */
13942 #define WRC_Abort 2 /* Abandon the tree walk */
13943
13944 /*
13945 ** An instance of this structure represents a set of one or more CTEs
13946 ** (common table expressions) created by a single WITH clause.
13947 */
13948 struct With {
13949 int nCte; /* Number of CTEs in the WITH clause */
13950 With *pOuter; /* Containing WITH clause, or NULL */
13951 struct Cte { /* For each CTE in the WITH clause.... */
13952 char *zName; /* Name of this CTE */
13953 ExprList *pCols; /* List of explicit column names, or NULL */
13954 Select *pSelect; /* The definition of this CTE */
13955 const char *zCteErr; /* Error message for circular references */
13956 } a[1];
13957 };
13958
13959 #ifdef SQLITE_DEBUG
13960 /*
13961 ** An instance of the TreeView object is used for printing the content of
13962 ** data structures on sqlite3DebugPrintf() using a tree-like view.
13963 */
13964 struct TreeView {
13965 int iLevel; /* Which level of the tree we are on */
13966 u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
13967 };
13968 #endif /* SQLITE_DEBUG */
13969
13970 /*
13971 ** Assuming zIn points to the first byte of a UTF-8 character,
13972 ** advance zIn to point to the first byte of the next UTF-8 character.
13973 */
13974 #define SQLITE_SKIP_UTF8(zIn) { \
13975 if( (*(zIn++))>=0xc0 ){ \
13976 while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
13977 } \
13978 }
13979
13980 /*
13981 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
13982 ** the same name but without the _BKPT suffix. These macros invoke
13983 ** routines that report the line-number on which the error originated
13984 ** using sqlite3_log(). The routines also provide a convenient place
13985 ** to set a debugger breakpoint.
13986 */
13987 SQLITE_PRIVATE int sqlite3CorruptError(int);
13988 SQLITE_PRIVATE int sqlite3MisuseError(int);
13989 SQLITE_PRIVATE int sqlite3CantopenError(int);
13990 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
13991 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
13992 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
13993
13994
13995 /*
13996 ** FTS4 is really an extension for FTS3. It is enabled using the
13997 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
13998 ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
13999 */
14000 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
14001 # define SQLITE_ENABLE_FTS3 1
14002 #endif
14003
14004 /*
14005 ** The ctype.h header is needed for non-ASCII systems. It is also
14006 ** needed by FTS3 when FTS3 is included in the amalgamation.
14007 */
14008 #if !defined(SQLITE_ASCII) || \
14009 (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
14010 # include <ctype.h>
14011 #endif
14012
14013 /*
14014 ** The CoreServices.h and CoreFoundation.h headers are needed for excluding a
14015 ** -journal file from Time Machine backups when its associated database has
14016 ** previously been excluded by the client code.
14017 */
14018 #if defined(__APPLE__)
14019 #include <CoreServices/CoreServices.h>
14020 #include <CoreFoundation/CoreFoundation.h>
14021 #endif
14022
14023 /*
14024 ** The following macros mimic the standard library functions toupper(),
14025 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
14026 ** sqlite versions only work for ASCII characters, regardless of locale.
14027 */
14028 #ifdef SQLITE_ASCII
14029 # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
14030 # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
14031 # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
14032 # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
14033 # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
14034 # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
14035 # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
14036 #else
14037 # define sqlite3Toupper(x) toupper((unsigned char)(x))
14038 # define sqlite3Isspace(x) isspace((unsigned char)(x))
14039 # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
14040 # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
14041 # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
14042 # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
14043 # define sqlite3Tolower(x) tolower((unsigned char)(x))
14044 #endif
14045 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
14046 SQLITE_PRIVATE int sqlite3IsIdChar(u8);
14047 #endif
14048
14049 /*
14050 ** Internal function prototypes
14051 */
14052 #define sqlite3StrICmp sqlite3_stricmp
14053 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
14054 #define sqlite3StrNICmp sqlite3_strnicmp
14055
14056 SQLITE_PRIVATE int sqlite3MallocInit(void);
14057 SQLITE_PRIVATE void sqlite3MallocEnd(void);
14058 SQLITE_PRIVATE void *sqlite3Malloc(u64);
14059 SQLITE_PRIVATE void *sqlite3MallocZero(u64);
14060 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
14061 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
14062 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
14063 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
14064 SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
14065 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
14066 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
14067 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
14068 SQLITE_PRIVATE int sqlite3MallocSize(void*);
14069 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
14070 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
14071 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
14072 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
14073 SQLITE_PRIVATE void sqlite3PageFree(void*);
14074 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
14075 #ifndef SQLITE_OMIT_BUILTIN_TEST
14076 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
14077 #endif
14078 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
14079
14080 /*
14081 ** On systems with ample stack space and that support alloca(), make
14082 ** use of alloca() to obtain space for large automatic objects. By default,
14083 ** obtain space from malloc().
14084 **
14085 ** The alloca() routine never returns NULL. This will cause code paths
14086 ** that deal with sqlite3StackAlloc() failures to be unreachable.
14087 */
14088 #ifdef SQLITE_USE_ALLOCA
14089 # define sqlite3StackAllocRaw(D,N) alloca(N)
14090 # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
14091 # define sqlite3StackFree(D,P)
14092 #else
14093 # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
14094 # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
14095 # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
14096 #endif
14097
14098 #ifdef SQLITE_ENABLE_MEMSYS3
14099 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
14100 #endif
14101 #ifdef SQLITE_ENABLE_MEMSYS5
14102 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
14103 #endif
14104
14105
14106 #ifndef SQLITE_MUTEX_OMIT
14107 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
14108 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
14109 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
14110 SQLITE_PRIVATE int sqlite3MutexInit(void);
14111 SQLITE_PRIVATE int sqlite3MutexEnd(void);
14112 #endif
14113 #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
14114 SQLITE_PRIVATE void sqlite3MemoryBarrier(void);
14115 #else
14116 # define sqlite3MemoryBarrier()
14117 #endif
14118
14119 SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
14120 SQLITE_PRIVATE void sqlite3StatusUp(int, int);
14121 SQLITE_PRIVATE void sqlite3StatusDown(int, int);
14122 SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
14123
14124 /* Access to mutexes used by sqlite3_status() */
14125 SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
14126 SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
14127
14128 #ifndef SQLITE_OMIT_FLOATING_POINT
14129 SQLITE_PRIVATE int sqlite3IsNaN(double);
14130 #else
14131 # define sqlite3IsNaN(X) 0
14132 #endif
14133
14134 /*
14135 ** An instance of the following structure holds information about SQL
14136 ** functions arguments that are the parameters to the printf() function.
14137 */
14138 struct PrintfArguments {
14139 int nArg; /* Total number of arguments */
14140 int nUsed; /* Number of arguments used so far */
14141 sqlite3_value **apArg; /* The argument values */
14142 };
14143
14144 #define SQLITE_PRINTF_INTERNAL 0x01
14145 #define SQLITE_PRINTF_SQLFUNC 0x02
14146 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, u32, const char*, va_list);
14147 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, u32, const char*, ...);
14148 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
14149 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
14150 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
14151 SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
14152 #endif
14153 #if defined(SQLITE_TEST)
14154 SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
14155 #endif
14156
14157 #if defined(SQLITE_DEBUG)
14158 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
14159 SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, co nst char*);
14160 SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
14161 SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8);
14162 #endif
14163
14164
14165 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
14166 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
14167 SQLITE_PRIVATE int sqlite3Dequote(char*);
14168 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
14169 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
14170 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
14171 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
14172 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
14173 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
14174 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
14175 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
14176 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
14177 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
14178 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
14179 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
14180 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
14181 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
14182 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
14183 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
14184 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
14185 SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
14186 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
14187 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
14188 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
14189 SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
14190 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
14191 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
14192 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
14193 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
14194 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
14195 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
14196 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
14197 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
14198 SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
14199 SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
14200 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
14201 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
14202 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
14203 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
14204 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
14205 #if SQLITE_ENABLE_HIDDEN_COLUMNS
14206 SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*);
14207 #else
14208 # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
14209 #endif
14210 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
14211 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
14212 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
14213 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
14214 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
14215 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
14216 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
14217 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
14218 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
14219 sqlite3_vfs**,char**,char **);
14220 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
14221 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
14222
14223 #ifdef SQLITE_OMIT_BUILTIN_TEST
14224 # define sqlite3FaultSim(X) SQLITE_OK
14225 #else
14226 SQLITE_PRIVATE int sqlite3FaultSim(int);
14227 #endif
14228
14229 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
14230 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
14231 SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
14232 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
14233 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
14234 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
14235 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
14236 #ifndef SQLITE_OMIT_BUILTIN_TEST
14237 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
14238 #endif
14239
14240 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
14241 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
14242 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
14243 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
14244 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
14245
14246 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Sele ct*,int,int);
14247
14248 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
14249 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
14250 #else
14251 # define sqlite3ViewGetColumnNames(A,B) 0
14252 #endif
14253
14254 #if SQLITE_MAX_ATTACHED>30
14255 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
14256 #endif
14257 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
14258 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
14259 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
14260 #ifndef SQLITE_OMIT_AUTOINCREMENT
14261 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
14262 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
14263 #else
14264 # define sqlite3AutoincrementBegin(X)
14265 # define sqlite3AutoincrementEnd(X)
14266 #endif
14267 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
14268 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
14269 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
14270 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
14271 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
14272 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*) ;
14273 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, T oken*,
14274 Token*, Select*, Expr*, IdList*);
14275 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
14276 SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
14277 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
14278 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
14279 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
14280 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
14281 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
14282 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
14283 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList* ,int,Token*,
14284 Expr*, int, int);
14285 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
14286 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
14287 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList *,
14288 Expr*,ExprList*,u16,Expr*,Expr*);
14289 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
14290 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
14291 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
14292 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
14293 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
14294 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Exp r*,char*);
14295 #endif
14296 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
14297 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
14298 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,Expr List*,u16,int);
14299 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
14300 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
14301 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
14302 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
14303 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
14304 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
14305 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
14306 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
14307 #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
14308 #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
14309 #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
14310 SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int );
14311 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
14312 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int) ;
14313 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int );
14314 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
14315 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
14316 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
14317 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
14318 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
14319 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
14320 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
14321 SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
14322 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
14323 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
14324 SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
14325 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
14326 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
14327 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
14328 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
14329 #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
14330 #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
14331 #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
14332 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
14333 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
14334 SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
14335 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
14336 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const ch ar*);
14337 SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_it em *);
14338 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
14339 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
14340 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
14341 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
14342 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
14343 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
14344 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
14345 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
14346 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
14347 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
14348 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
14349 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
14350 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
14351 #ifndef SQLITE_OMIT_BUILTIN_TEST
14352 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
14353 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
14354 #endif
14355 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
14356 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
14357 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
14358 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
14359 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
14360 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
14361 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
14362 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
14363 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
14364 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
14365 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
14366 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
14367 SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
14368 #ifdef SQLITE_ENABLE_CURSOR_HINTS
14369 SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
14370 #endif
14371 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
14372 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
14373 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
14374 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
14375 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
14376 Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
14377 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int* , int);
14378 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,I ndex*,int);
14379 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
14380 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,i nt,int,
14381 u8,u8,int,int*);
14382 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int, int,int);
14383 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
14384 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
14385 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
14386 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
14387 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
14388 SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
14389 SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
14390 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
14391 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
14392 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
14393 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
14394 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
14395 #if SELECTTRACE_ENABLED
14396 SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
14397 #else
14398 # define sqlite3SelectSetName(A,B)
14399 #endif
14400 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
14401 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
14402 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
14403 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
14404 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
14405 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
14406 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
14407 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
14408
14409 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
14410 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
14411 #endif
14412
14413 #ifndef SQLITE_OMIT_TRIGGER
14414 SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*, SrcList*,
14415 Expr*,int, int);
14416 SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
14417 SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
14418 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
14419 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
14420 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
14421 SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, i nt, Table *,
14422 int, int, int);
14423 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, i nt, int, int);
14424 void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
14425 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
14426 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
14427 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
14428 Select*,u8);
14429 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList* , Expr*, u8);
14430 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
14431 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
14432 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
14433 SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Tab le*,int);
14434 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
14435 # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
14436 #else
14437 # define sqlite3TriggersExist(B,C,D,E,F) 0
14438 # define sqlite3DeleteTrigger(A,B)
14439 # define sqlite3DropTriggerPtr(A,B)
14440 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
14441 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
14442 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
14443 # define sqlite3TriggerList(X, Y) 0
14444 # define sqlite3ParseToplevel(p) p
14445 # define sqlite3IsToplevel(p) 1
14446 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
14447 #endif
14448
14449 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
14450 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList* , int);
14451 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
14452 #ifndef SQLITE_OMIT_AUTHORIZATION
14453 SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
14454 SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, cons t char*);
14455 SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
14456 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
14457 SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int) ;
14458 #else
14459 # define sqlite3AuthRead(a,b,c,d)
14460 # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
14461 # define sqlite3AuthContextPush(a,b,c)
14462 # define sqlite3AuthContextPop(a) ((void)(a))
14463 #endif
14464 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
14465 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
14466 SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Tok en*);
14467 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
14468 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
14469 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
14470 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
14471 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
14472 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
14473 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
14474 SQLITE_PRIVATE int sqlite3Atoi(const char*);
14475 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
14476 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
14477 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
14478 SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
14479 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
14480 #ifndef SQLITE_OMIT_VIRTUALTABLE
14481 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
14482 #endif
14483 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
14484
14485 /*
14486 ** Routines to read and write variable-length integers. These used to
14487 ** be defined locally, but now we use the varint routines in the util.c
14488 ** file.
14489 */
14490 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
14491 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
14492 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
14493 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
14494
14495 /*
14496 ** The common case is for a varint to be a single byte. They following
14497 ** macros handle the common case without a procedure call, but then call
14498 ** the procedure for larger varints.
14499 */
14500 #define getVarint32(A,B) \
14501 (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
14502 #define putVarint32(A,B) \
14503 (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
14504 sqlite3PutVarint((A),(B)))
14505 #define getVarint sqlite3GetVarint
14506 #define putVarint sqlite3PutVarint
14507
14508
14509 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
14510 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
14511 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
14512 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
14513 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
14514 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
14515 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
14516 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
14517 SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
14518 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
14519 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
14520 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
14521
14522 #if defined(SQLITE_NEED_ERR_NAME)
14523 SQLITE_PRIVATE const char *sqlite3ErrName(int);
14524 #endif
14525
14526 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
14527 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
14528 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
14529 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
14530 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
14531 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Toke n*, int);
14532 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
14533 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
14534 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
14535 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
14536 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
14537 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
14538 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
14539 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
14540 SQLITE_PRIVATE int sqlite3AbsInt32(int);
14541 #ifdef SQLITE_ENABLE_8_3_NAMES
14542 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
14543 #else
14544 # define sqlite3FileSuffix3(X,Y)
14545 #endif
14546 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
14547
14548 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
14549 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
14550 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
14551 void(*)(void*));
14552 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
14553 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
14554 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
14555 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
14556 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
14557 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
14558 #ifndef SQLITE_AMALGAMATION
14559 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
14560 SQLITE_PRIVATE const char sqlite3StrBINARY[];
14561 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
14562 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
14563 SQLITE_PRIVATE const Token sqlite3IntTokens[];
14564 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
14565 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
14566 #ifndef SQLITE_OMIT_WSD
14567 SQLITE_PRIVATE int sqlite3PendingByte;
14568 #endif
14569 #endif
14570 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
14571 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
14572 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
14573 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
14574 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
14575 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
14576 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
14577 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
14578 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
14579 SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
14580 SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, c onst char*);
14581 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
14582 SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
14583 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
14584 SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList *);
14585 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
14586 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
14587 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
14588 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
14589 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
14590 SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
14591 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
14592 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
14593 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
14594 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
14595 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
14596 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
14597 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
14598 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
14599 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
14600 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
14601 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
14602 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
14603 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
14604 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
14605 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
14606 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
14607 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
14608 #ifdef SQLITE_DEBUG
14609 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
14610 #endif
14611 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
14612 void (*)(sqlite3_context*,int,sqlite3_value **),
14613 void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
14614 FuncDestructor *pDestructor
14615 );
14616 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
14617 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
14618
14619 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
14620 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
14621 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
14622 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
14623 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
14624 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
14625 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
14626 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
14627
14628 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
14629 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
14630
14631 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
14632 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
14633 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr *,u8,int,int*);
14634 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**) ;
14635 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
14636 SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_v alue**);
14637 #endif
14638
14639 /*
14640 ** The interface to the LEMON-generated parser
14641 */
14642 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
14643 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
14644 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
14645 #ifdef YYTRACKMAXSTACKDEPTH
14646 SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
14647 #endif
14648
14649 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
14650 #ifndef SQLITE_OMIT_LOAD_EXTENSION
14651 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
14652 #else
14653 # define sqlite3CloseExtensions(X)
14654 #endif
14655
14656 #ifndef SQLITE_OMIT_SHARED_CACHE
14657 SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
14658 #else
14659 #define sqlite3TableLock(v,w,x,y,z)
14660 #endif
14661
14662 #ifdef SQLITE_TEST
14663 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
14664 #endif
14665
14666 #ifdef SQLITE_OMIT_VIRTUALTABLE
14667 # define sqlite3VtabClear(Y)
14668 # define sqlite3VtabSync(X,Y) SQLITE_OK
14669 # define sqlite3VtabRollback(X)
14670 # define sqlite3VtabCommit(X)
14671 # define sqlite3VtabInSync(db) 0
14672 # define sqlite3VtabLock(X)
14673 # define sqlite3VtabUnlock(X)
14674 # define sqlite3VtabUnlockList(X)
14675 # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
14676 # define sqlite3GetVTable(X,Y) ((VTable*)0)
14677 #else
14678 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
14679 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
14680 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
14681 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
14682 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
14683 SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
14684 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
14685 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
14686 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
14687 SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
14688 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
14689 # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
14690 #endif
14691 SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
14692 SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
14693 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
14694 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
14695 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
14696 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
14697 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
14698 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
14699 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
14700 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
14701 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
14702 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg , Expr*);
14703 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**) ;
14704 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
14705 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
14706 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
14707 SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
14708 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
14709 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
14710 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
14711 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
14712 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
14713 #ifndef SQLITE_OMIT_WAL
14714 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
14715 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
14716 #endif
14717 #ifndef SQLITE_OMIT_CTE
14718 SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
14719 SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
14720 SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
14721 #else
14722 #define sqlite3WithPush(x,y,z)
14723 #define sqlite3WithDelete(x,y)
14724 #endif
14725
14726 /* Declarations for functions in fkey.c. All of these are replaced by
14727 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
14728 ** key functionality is available. If OMIT_TRIGGER is defined but
14729 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
14730 ** this case foreign keys are parsed, but no other functionality is
14731 ** provided (enforcement of FK constraints requires the triggers sub-system).
14732 */
14733 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
14734 SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
14735 SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
14736 SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int );
14737 SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
14738 SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
14739 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
14740 #else
14741 #define sqlite3FkActions(a,b,c,d,e,f)
14742 #define sqlite3FkCheck(a,b,c,d,e,f)
14743 #define sqlite3FkDropTable(a,b,c)
14744 #define sqlite3FkOldmask(a,b) 0
14745 #define sqlite3FkRequired(a,b,c,d) 0
14746 #endif
14747 #ifndef SQLITE_OMIT_FOREIGN_KEY
14748 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
14749 SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
14750 #else
14751 #define sqlite3FkDelete(a,b)
14752 #define sqlite3FkLocateIndex(a,b,c,d,e)
14753 #endif
14754
14755
14756 /*
14757 ** Available fault injectors. Should be numbered beginning with 0.
14758 */
14759 #define SQLITE_FAULTINJECTOR_MALLOC 0
14760 #define SQLITE_FAULTINJECTOR_COUNT 1
14761
14762 /*
14763 ** The interface to the code in fault.c used for identifying "benign"
14764 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
14765 ** is not defined.
14766 */
14767 #ifndef SQLITE_OMIT_BUILTIN_TEST
14768 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
14769 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
14770 #else
14771 #define sqlite3BeginBenignMalloc()
14772 #define sqlite3EndBenignMalloc()
14773 #endif
14774
14775 /*
14776 ** Allowed return values from sqlite3FindInIndex()
14777 */
14778 #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
14779 #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
14780 #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
14781 #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
14782 #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
14783 /*
14784 ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
14785 */
14786 #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
14787 #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
14788 #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
14789 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*);
14790
14791 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
14792 SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_fil e *, int, int);
14793 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
14794 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
14795 SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p);
14796 #else
14797 #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
14798 #define sqlite3JournalExists(p) 1
14799 #endif
14800
14801 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
14802 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
14803 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
14804
14805 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
14806 #if SQLITE_MAX_EXPR_DEPTH>0
14807 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
14808 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
14809 #else
14810 #define sqlite3SelectExprHeight(x) 0
14811 #define sqlite3ExprCheckHeight(x,y)
14812 #endif
14813
14814 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
14815 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
14816
14817 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
14818 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
14819 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
14820 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
14821 #else
14822 #define sqlite3ConnectionBlocked(x,y)
14823 #define sqlite3ConnectionUnlocked(x)
14824 #define sqlite3ConnectionClosed(x)
14825 #endif
14826
14827 #ifdef SQLITE_DEBUG
14828 SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
14829 #endif
14830
14831 /*
14832 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
14833 ** sqlite3IoTrace is a pointer to a printf-like routine used to
14834 ** print I/O tracing messages.
14835 */
14836 #ifdef SQLITE_ENABLE_IOTRACE
14837 # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
14838 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
14839 SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
14840 #else
14841 # define IOTRACE(A)
14842 # define sqlite3VdbeIOTraceSql(X)
14843 #endif
14844
14845 /*
14846 ** These routines are available for the mem2.c debugging memory allocator
14847 ** only. They are used to verify that different "types" of memory
14848 ** allocations are properly tracked by the system.
14849 **
14850 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
14851 ** the MEMTYPE_* macros defined below. The type must be a bitmask with
14852 ** a single bit set.
14853 **
14854 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
14855 ** argument match the type set by the previous sqlite3MemdebugSetType().
14856 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
14857 **
14858 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
14859 ** argument match the type set by the previous sqlite3MemdebugSetType().
14860 **
14861 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
14862 ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
14863 ** it might have been allocated by lookaside, except the allocation was
14864 ** too large or lookaside was already full. It is important to verify
14865 ** that allocations that might have been satisfied by lookaside are not
14866 ** passed back to non-lookaside free() routines. Asserts such as the
14867 ** example above are placed on the non-lookaside free() routines to verify
14868 ** this constraint.
14869 **
14870 ** All of this is no-op for a production build. It only comes into
14871 ** play when the SQLITE_MEMDEBUG compile-time option is used.
14872 */
14873 #ifdef SQLITE_MEMDEBUG
14874 SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
14875 SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
14876 SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
14877 #else
14878 # define sqlite3MemdebugSetType(X,Y) /* no-op */
14879 # define sqlite3MemdebugHasType(X,Y) 1
14880 # define sqlite3MemdebugNoType(X,Y) 1
14881 #endif
14882 #define MEMTYPE_HEAP 0x01 /* General heap allocations */
14883 #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
14884 #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
14885 #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
14886
14887 /*
14888 ** Threading interface
14889 */
14890 #if SQLITE_MAX_WORKER_THREADS>0
14891 SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
14892 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
14893 #endif
14894
14895 #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
14896 SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
14897 #endif
14898
14899 #endif /* _SQLITEINT_H_ */
14900
14901 /************** End of sqliteInt.h *******************************************/
14902 /************** Begin file global.c ******************************************/
14903 /*
14904 ** 2008 June 13
14905 **
14906 ** The author disclaims copyright to this source code. In place of
14907 ** a legal notice, here is a blessing:
14908 **
14909 ** May you do good and not evil.
14910 ** May you find forgiveness for yourself and forgive others.
14911 ** May you share freely, never taking more than you give.
14912 **
14913 *************************************************************************
14914 **
14915 ** This file contains definitions of global variables and constants.
14916 */
14917 /* #include "sqliteInt.h" */
14918
14919 /* An array to map all upper-case characters into their corresponding
14920 ** lower-case character.
14921 **
14922 ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
14923 ** handle case conversions for the UTF character set since the tables
14924 ** involved are nearly as big or bigger than SQLite itself.
14925 */
14926 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
14927 #ifdef SQLITE_ASCII
14928 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
14929 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
14930 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
14931 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
14932 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
14933 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
14934 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
14935 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
14936 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
14937 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
14938 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
14939 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
14940 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
14941 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
14942 252,253,254,255
14943 #endif
14944 #ifdef SQLITE_EBCDIC
14945 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
14946 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
14947 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
14948 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
14949 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
14950 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
14951 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
14952 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
14953 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
14954 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
14955 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
14956 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
14957 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
14958 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
14959 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
14960 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
14961 #endif
14962 };
14963
14964 /*
14965 ** The following 256 byte lookup table is used to support SQLites built-in
14966 ** equivalents to the following standard library functions:
14967 **
14968 ** isspace() 0x01
14969 ** isalpha() 0x02
14970 ** isdigit() 0x04
14971 ** isalnum() 0x06
14972 ** isxdigit() 0x08
14973 ** toupper() 0x20
14974 ** SQLite identifier character 0x40
14975 **
14976 ** Bit 0x20 is set if the mapped character requires translation to upper
14977 ** case. i.e. if the character is a lower-case ASCII character.
14978 ** If x is a lower-case ASCII character, then its upper-case equivalent
14979 ** is (x - 0x20). Therefore toupper() can be implemented as:
14980 **
14981 ** (x & ~(map[x]&0x20))
14982 **
14983 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
14984 ** array. tolower() is used more often than toupper() by SQLite.
14985 **
14986 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
14987 ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
14988 ** non-ASCII UTF character. Hence the test for whether or not a character is
14989 ** part of an identifier is 0x46.
14990 **
14991 ** SQLite's versions are identical to the standard versions assuming a
14992 ** locale of "C". They are implemented as macros in sqliteInt.h.
14993 */
14994 #ifdef SQLITE_ASCII
14995 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
14996 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
14997 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
14998 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
14999 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
15000 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
15001 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
15002 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
15003 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
15004
15005 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
15006 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
15007 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
15008 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
15009 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
15010 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
15011 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
15012 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
15013
15014 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
15015 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
15016 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
15017 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
15018 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
15019 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
15020 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
15021 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
15022
15023 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
15024 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
15025 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
15026 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
15027 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
15028 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
15029 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
15030 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
15031 };
15032 #endif
15033
15034 /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
15035 ** compatibility for legacy applications, the URI filename capability is
15036 ** disabled by default.
15037 **
15038 ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
15039 ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
15040 **
15041 ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
15042 ** disabled. The default value may be changed by compiling with the
15043 ** SQLITE_USE_URI symbol defined.
15044 */
15045 #ifndef SQLITE_USE_URI
15046 # define SQLITE_USE_URI 0
15047 #endif
15048
15049 /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
15050 ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
15051 ** that compile-time option is omitted.
15052 */
15053 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
15054 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
15055 #endif
15056
15057 /* The minimum PMA size is set to this value multiplied by the database
15058 ** page size in bytes.
15059 */
15060 #ifndef SQLITE_SORTER_PMASZ
15061 # define SQLITE_SORTER_PMASZ 250
15062 #endif
15063
15064 /*
15065 ** The following singleton contains the global configuration for
15066 ** the SQLite library.
15067 */
15068 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
15069 SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
15070 1, /* bCoreMutex */
15071 SQLITE_THREADSAFE==1, /* bFullMutex */
15072 SQLITE_USE_URI, /* bOpenUri */
15073 SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
15074 0x7ffffffe, /* mxStrlen */
15075 0, /* neverCorrupt */
15076 128, /* szLookaside */
15077 500, /* nLookaside */
15078 {0,0,0,0,0,0,0,0}, /* m */
15079 {0,0,0,0,0,0,0,0,0}, /* mutex */
15080 {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
15081 (void*)0, /* pHeap */
15082 0, /* nHeap */
15083 0, 0, /* mnHeap, mxHeap */
15084 SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
15085 SQLITE_MAX_MMAP_SIZE, /* mxMmap */
15086 (void*)0, /* pScratch */
15087 0, /* szScratch */
15088 0, /* nScratch */
15089 (void*)0, /* pPage */
15090 0, /* szPage */
15091 SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
15092 0, /* mxParserStack */
15093 0, /* sharedCacheEnabled */
15094 SQLITE_SORTER_PMASZ, /* szPma */
15095 /* All the rest should always be initialized to zero */
15096 0, /* isInit */
15097 0, /* inProgress */
15098 0, /* isMutexInit */
15099 0, /* isMallocInit */
15100 0, /* isPCacheInit */
15101 0, /* nRefInitMutex */
15102 0, /* pInitMutex */
15103 0, /* xLog */
15104 0, /* pLogArg */
15105 #ifdef SQLITE_ENABLE_SQLLOG
15106 0, /* xSqllog */
15107 0, /* pSqllogArg */
15108 #endif
15109 #ifdef SQLITE_VDBE_COVERAGE
15110 0, /* xVdbeBranch */
15111 0, /* pVbeBranchArg */
15112 #endif
15113 #ifndef SQLITE_OMIT_BUILTIN_TEST
15114 0, /* xTestCallback */
15115 #endif
15116 0 /* bLocaltimeFault */
15117 };
15118
15119 /*
15120 ** Hash table for global functions - functions common to all
15121 ** database connections. After initialization, this table is
15122 ** read-only.
15123 */
15124 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
15125
15126 /*
15127 ** Constant tokens for values 0 and 1.
15128 */
15129 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
15130 { "0", 1 },
15131 { "1", 1 }
15132 };
15133
15134
15135 /*
15136 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
15137 ** 1-gibabyte boundary) in a compatible database. SQLite never uses
15138 ** the database page that contains the pending byte. It never attempts
15139 ** to read or write that page. The pending byte page is set assign
15140 ** for use by the VFS layers as space for managing file locks.
15141 **
15142 ** During testing, it is often desirable to move the pending byte to
15143 ** a different position in the file. This allows code that has to
15144 ** deal with the pending byte to run on files that are much smaller
15145 ** than 1 GiB. The sqlite3_test_control() interface can be used to
15146 ** move the pending byte.
15147 **
15148 ** IMPORTANT: Changing the pending byte to any value other than
15149 ** 0x40000000 results in an incompatible database file format!
15150 ** Changing the pending byte during operation will result in undefined
15151 ** and incorrect behavior.
15152 */
15153 #ifndef SQLITE_OMIT_WSD
15154 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
15155 #endif
15156
15157 /* #include "opcodes.h" */
15158 /*
15159 ** Properties of opcodes. The OPFLG_INITIALIZER macro is
15160 ** created by mkopcodeh.awk during compilation. Data is obtained
15161 ** from the comments following the "case OP_xxxx:" statements in
15162 ** the vdbe.c file.
15163 */
15164 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
15165
15166 /*
15167 ** Name of the default collating sequence
15168 */
15169 SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
15170
15171 /************** End of global.c **********************************************/
15172 /************** Begin file ctime.c *******************************************/
15173 /*
15174 ** 2010 February 23
15175 **
15176 ** The author disclaims copyright to this source code. In place of
15177 ** a legal notice, here is a blessing:
15178 **
15179 ** May you do good and not evil.
15180 ** May you find forgiveness for yourself and forgive others.
15181 ** May you share freely, never taking more than you give.
15182 **
15183 *************************************************************************
15184 **
15185 ** This file implements routines used to report what compile-time options
15186 ** SQLite was built with.
15187 */
15188
15189 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
15190
15191 /* #include "sqliteInt.h" */
15192
15193 /*
15194 ** An array of names of all compile-time options. This array should
15195 ** be sorted A-Z.
15196 **
15197 ** This array looks large, but in a typical installation actually uses
15198 ** only a handful of compile-time options, so most times this array is usually
15199 ** rather short and uses little memory space.
15200 */
15201 static const char * const azCompileOpt[] = {
15202
15203 /* These macros are provided to "stringify" the value of the define
15204 ** for those options in which the value is meaningful. */
15205 #define CTIMEOPT_VAL_(opt) #opt
15206 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
15207
15208 #if SQLITE_32BIT_ROWID
15209 "32BIT_ROWID",
15210 #endif
15211 #if SQLITE_4_BYTE_ALIGNED_MALLOC
15212 "4_BYTE_ALIGNED_MALLOC",
15213 #endif
15214 #if SQLITE_CASE_SENSITIVE_LIKE
15215 "CASE_SENSITIVE_LIKE",
15216 #endif
15217 #if SQLITE_CHECK_PAGES
15218 "CHECK_PAGES",
15219 #endif
15220 #if SQLITE_COVERAGE_TEST
15221 "COVERAGE_TEST",
15222 #endif
15223 #if SQLITE_DEBUG
15224 "DEBUG",
15225 #endif
15226 #if SQLITE_DEFAULT_LOCKING_MODE
15227 "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
15228 #endif
15229 #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
15230 "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
15231 #endif
15232 #if SQLITE_DISABLE_DIRSYNC
15233 "DISABLE_DIRSYNC",
15234 #endif
15235 #if SQLITE_DISABLE_LFS
15236 "DISABLE_LFS",
15237 #endif
15238 #if SQLITE_ENABLE_8_3_NAMES
15239 "ENABLE_8_3_NAMES",
15240 #endif
15241 #if SQLITE_ENABLE_API_ARMOR
15242 "ENABLE_API_ARMOR",
15243 #endif
15244 #if SQLITE_ENABLE_ATOMIC_WRITE
15245 "ENABLE_ATOMIC_WRITE",
15246 #endif
15247 #if SQLITE_ENABLE_CEROD
15248 "ENABLE_CEROD",
15249 #endif
15250 #if SQLITE_ENABLE_COLUMN_METADATA
15251 "ENABLE_COLUMN_METADATA",
15252 #endif
15253 #if SQLITE_ENABLE_DBSTAT_VTAB
15254 "ENABLE_DBSTAT_VTAB",
15255 #endif
15256 #if SQLITE_ENABLE_EXPENSIVE_ASSERT
15257 "ENABLE_EXPENSIVE_ASSERT",
15258 #endif
15259 #if SQLITE_ENABLE_FTS1
15260 "ENABLE_FTS1",
15261 #endif
15262 #if SQLITE_ENABLE_FTS2
15263 "ENABLE_FTS2",
15264 #endif
15265 #if SQLITE_ENABLE_FTS3
15266 "ENABLE_FTS3",
15267 #endif
15268 #if SQLITE_ENABLE_FTS3_PARENTHESIS
15269 "ENABLE_FTS3_PARENTHESIS",
15270 #endif
15271 #if SQLITE_ENABLE_FTS4
15272 "ENABLE_FTS4",
15273 #endif
15274 #if SQLITE_ENABLE_FTS5
15275 "ENABLE_FTS5",
15276 #endif
15277 #if SQLITE_ENABLE_ICU
15278 "ENABLE_ICU",
15279 #endif
15280 #if SQLITE_ENABLE_IOTRACE
15281 "ENABLE_IOTRACE",
15282 #endif
15283 #if SQLITE_ENABLE_JSON1
15284 "ENABLE_JSON1",
15285 #endif
15286 #if SQLITE_ENABLE_LOAD_EXTENSION
15287 "ENABLE_LOAD_EXTENSION",
15288 #endif
15289 #if SQLITE_ENABLE_LOCKING_STYLE
15290 "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
15291 #endif
15292 #if SQLITE_ENABLE_MEMORY_MANAGEMENT
15293 "ENABLE_MEMORY_MANAGEMENT",
15294 #endif
15295 #if SQLITE_ENABLE_MEMSYS3
15296 "ENABLE_MEMSYS3",
15297 #endif
15298 #if SQLITE_ENABLE_MEMSYS5
15299 "ENABLE_MEMSYS5",
15300 #endif
15301 #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
15302 "ENABLE_OVERSIZE_CELL_CHECK",
15303 #endif
15304 #if SQLITE_ENABLE_RTREE
15305 "ENABLE_RTREE",
15306 #endif
15307 #if defined(SQLITE_ENABLE_STAT4)
15308 "ENABLE_STAT4",
15309 #elif defined(SQLITE_ENABLE_STAT3)
15310 "ENABLE_STAT3",
15311 #endif
15312 #if SQLITE_ENABLE_UNLOCK_NOTIFY
15313 "ENABLE_UNLOCK_NOTIFY",
15314 #endif
15315 #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
15316 "ENABLE_UPDATE_DELETE_LIMIT",
15317 #endif
15318 #if SQLITE_HAS_CODEC
15319 "HAS_CODEC",
15320 #endif
15321 #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
15322 "HAVE_ISNAN",
15323 #endif
15324 #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15325 "HOMEGROWN_RECURSIVE_MUTEX",
15326 #endif
15327 #if SQLITE_IGNORE_AFP_LOCK_ERRORS
15328 "IGNORE_AFP_LOCK_ERRORS",
15329 #endif
15330 #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
15331 "IGNORE_FLOCK_LOCK_ERRORS",
15332 #endif
15333 #ifdef SQLITE_INT64_TYPE
15334 "INT64_TYPE",
15335 #endif
15336 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
15337 "LIKE_DOESNT_MATCH_BLOBS",
15338 #endif
15339 #if SQLITE_LOCK_TRACE
15340 "LOCK_TRACE",
15341 #endif
15342 #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
15343 "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
15344 #endif
15345 #ifdef SQLITE_MAX_SCHEMA_RETRY
15346 "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
15347 #endif
15348 #if SQLITE_MEMDEBUG
15349 "MEMDEBUG",
15350 #endif
15351 #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
15352 "MIXED_ENDIAN_64BIT_FLOAT",
15353 #endif
15354 #if SQLITE_NO_SYNC
15355 "NO_SYNC",
15356 #endif
15357 #if SQLITE_OMIT_ALTERTABLE
15358 "OMIT_ALTERTABLE",
15359 #endif
15360 #if SQLITE_OMIT_ANALYZE
15361 "OMIT_ANALYZE",
15362 #endif
15363 #if SQLITE_OMIT_ATTACH
15364 "OMIT_ATTACH",
15365 #endif
15366 #if SQLITE_OMIT_AUTHORIZATION
15367 "OMIT_AUTHORIZATION",
15368 #endif
15369 #if SQLITE_OMIT_AUTOINCREMENT
15370 "OMIT_AUTOINCREMENT",
15371 #endif
15372 #if SQLITE_OMIT_AUTOINIT
15373 "OMIT_AUTOINIT",
15374 #endif
15375 #if SQLITE_OMIT_AUTOMATIC_INDEX
15376 "OMIT_AUTOMATIC_INDEX",
15377 #endif
15378 #if SQLITE_OMIT_AUTORESET
15379 "OMIT_AUTORESET",
15380 #endif
15381 #if SQLITE_OMIT_AUTOVACUUM
15382 "OMIT_AUTOVACUUM",
15383 #endif
15384 #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
15385 "OMIT_BETWEEN_OPTIMIZATION",
15386 #endif
15387 #if SQLITE_OMIT_BLOB_LITERAL
15388 "OMIT_BLOB_LITERAL",
15389 #endif
15390 #if SQLITE_OMIT_BTREECOUNT
15391 "OMIT_BTREECOUNT",
15392 #endif
15393 #if SQLITE_OMIT_BUILTIN_TEST
15394 "OMIT_BUILTIN_TEST",
15395 #endif
15396 #if SQLITE_OMIT_CAST
15397 "OMIT_CAST",
15398 #endif
15399 #if SQLITE_OMIT_CHECK
15400 "OMIT_CHECK",
15401 #endif
15402 #if SQLITE_OMIT_COMPLETE
15403 "OMIT_COMPLETE",
15404 #endif
15405 #if SQLITE_OMIT_COMPOUND_SELECT
15406 "OMIT_COMPOUND_SELECT",
15407 #endif
15408 #if SQLITE_OMIT_CTE
15409 "OMIT_CTE",
15410 #endif
15411 #if SQLITE_OMIT_DATETIME_FUNCS
15412 "OMIT_DATETIME_FUNCS",
15413 #endif
15414 #if SQLITE_OMIT_DECLTYPE
15415 "OMIT_DECLTYPE",
15416 #endif
15417 #if SQLITE_OMIT_DEPRECATED
15418 "OMIT_DEPRECATED",
15419 #endif
15420 #if SQLITE_OMIT_DISKIO
15421 "OMIT_DISKIO",
15422 #endif
15423 #if SQLITE_OMIT_EXPLAIN
15424 "OMIT_EXPLAIN",
15425 #endif
15426 #if SQLITE_OMIT_FLAG_PRAGMAS
15427 "OMIT_FLAG_PRAGMAS",
15428 #endif
15429 #if SQLITE_OMIT_FLOATING_POINT
15430 "OMIT_FLOATING_POINT",
15431 #endif
15432 #if SQLITE_OMIT_FOREIGN_KEY
15433 "OMIT_FOREIGN_KEY",
15434 #endif
15435 #if SQLITE_OMIT_GET_TABLE
15436 "OMIT_GET_TABLE",
15437 #endif
15438 #if SQLITE_OMIT_INCRBLOB
15439 "OMIT_INCRBLOB",
15440 #endif
15441 #if SQLITE_OMIT_INTEGRITY_CHECK
15442 "OMIT_INTEGRITY_CHECK",
15443 #endif
15444 #if SQLITE_OMIT_LIKE_OPTIMIZATION
15445 "OMIT_LIKE_OPTIMIZATION",
15446 #endif
15447 #if SQLITE_OMIT_LOAD_EXTENSION
15448 "OMIT_LOAD_EXTENSION",
15449 #endif
15450 #if SQLITE_OMIT_LOCALTIME
15451 "OMIT_LOCALTIME",
15452 #endif
15453 #if SQLITE_OMIT_LOOKASIDE
15454 "OMIT_LOOKASIDE",
15455 #endif
15456 #if SQLITE_OMIT_MEMORYDB
15457 "OMIT_MEMORYDB",
15458 #endif
15459 #if SQLITE_OMIT_OR_OPTIMIZATION
15460 "OMIT_OR_OPTIMIZATION",
15461 #endif
15462 #if SQLITE_OMIT_PAGER_PRAGMAS
15463 "OMIT_PAGER_PRAGMAS",
15464 #endif
15465 #if SQLITE_OMIT_PRAGMA
15466 "OMIT_PRAGMA",
15467 #endif
15468 #if SQLITE_OMIT_PROGRESS_CALLBACK
15469 "OMIT_PROGRESS_CALLBACK",
15470 #endif
15471 #if SQLITE_OMIT_QUICKBALANCE
15472 "OMIT_QUICKBALANCE",
15473 #endif
15474 #if SQLITE_OMIT_REINDEX
15475 "OMIT_REINDEX",
15476 #endif
15477 #if SQLITE_OMIT_SCHEMA_PRAGMAS
15478 "OMIT_SCHEMA_PRAGMAS",
15479 #endif
15480 #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
15481 "OMIT_SCHEMA_VERSION_PRAGMAS",
15482 #endif
15483 #if SQLITE_OMIT_SHARED_CACHE
15484 "OMIT_SHARED_CACHE",
15485 #endif
15486 #if SQLITE_OMIT_SUBQUERY
15487 "OMIT_SUBQUERY",
15488 #endif
15489 #if SQLITE_OMIT_TCL_VARIABLE
15490 "OMIT_TCL_VARIABLE",
15491 #endif
15492 #if SQLITE_OMIT_TEMPDB
15493 "OMIT_TEMPDB",
15494 #endif
15495 #if SQLITE_OMIT_TRACE
15496 "OMIT_TRACE",
15497 #endif
15498 #if SQLITE_OMIT_TRIGGER
15499 "OMIT_TRIGGER",
15500 #endif
15501 #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
15502 "OMIT_TRUNCATE_OPTIMIZATION",
15503 #endif
15504 #if SQLITE_OMIT_UTF16
15505 "OMIT_UTF16",
15506 #endif
15507 #if SQLITE_OMIT_VACUUM
15508 "OMIT_VACUUM",
15509 #endif
15510 #if SQLITE_OMIT_VIEW
15511 "OMIT_VIEW",
15512 #endif
15513 #if SQLITE_OMIT_VIRTUALTABLE
15514 "OMIT_VIRTUALTABLE",
15515 #endif
15516 #if SQLITE_OMIT_WAL
15517 "OMIT_WAL",
15518 #endif
15519 #if SQLITE_OMIT_WSD
15520 "OMIT_WSD",
15521 #endif
15522 #if SQLITE_OMIT_XFER_OPT
15523 "OMIT_XFER_OPT",
15524 #endif
15525 #if SQLITE_PERFORMANCE_TRACE
15526 "PERFORMANCE_TRACE",
15527 #endif
15528 #if SQLITE_PROXY_DEBUG
15529 "PROXY_DEBUG",
15530 #endif
15531 #if SQLITE_RTREE_INT_ONLY
15532 "RTREE_INT_ONLY",
15533 #endif
15534 #if SQLITE_SECURE_DELETE
15535 "SECURE_DELETE",
15536 #endif
15537 #if SQLITE_SMALL_STACK
15538 "SMALL_STACK",
15539 #endif
15540 #if SQLITE_SOUNDEX
15541 "SOUNDEX",
15542 #endif
15543 #if SQLITE_SYSTEM_MALLOC
15544 "SYSTEM_MALLOC",
15545 #endif
15546 #if SQLITE_TCL
15547 "TCL",
15548 #endif
15549 #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
15550 "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
15551 #endif
15552 #if SQLITE_TEST
15553 "TEST",
15554 #endif
15555 #if defined(SQLITE_THREADSAFE)
15556 "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
15557 #endif
15558 #if SQLITE_USE_ALLOCA
15559 "USE_ALLOCA",
15560 #endif
15561 #if SQLITE_USER_AUTHENTICATION
15562 "USER_AUTHENTICATION",
15563 #endif
15564 #if SQLITE_WIN32_MALLOC
15565 "WIN32_MALLOC",
15566 #endif
15567 #if SQLITE_ZERO_MALLOC
15568 "ZERO_MALLOC"
15569 #endif
15570 };
15571
15572 /*
15573 ** Given the name of a compile-time option, return true if that option
15574 ** was used and false if not.
15575 **
15576 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
15577 ** is not required for a match.
15578 */
15579 SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName){
15580 int i, n;
15581
15582 #if SQLITE_ENABLE_API_ARMOR
15583 if( zOptName==0 ){
15584 (void)SQLITE_MISUSE_BKPT;
15585 return 0;
15586 }
15587 #endif
15588 if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
15589 n = sqlite3Strlen30(zOptName);
15590
15591 /* Since ArraySize(azCompileOpt) is normally in single digits, a
15592 ** linear search is adequate. No need for a binary search. */
15593 for(i=0; i<ArraySize(azCompileOpt); i++){
15594 if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
15595 && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
15596 ){
15597 return 1;
15598 }
15599 }
15600 return 0;
15601 }
15602
15603 /*
15604 ** Return the N-th compile-time option string. If N is out of range,
15605 ** return a NULL pointer.
15606 */
15607 SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N){
15608 if( N>=0 && N<ArraySize(azCompileOpt) ){
15609 return azCompileOpt[N];
15610 }
15611 return 0;
15612 }
15613
15614 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
15615
15616 /************** End of ctime.c ***********************************************/
15617 /************** Begin file status.c ******************************************/
15618 /*
15619 ** 2008 June 18
15620 **
15621 ** The author disclaims copyright to this source code. In place of
15622 ** a legal notice, here is a blessing:
15623 **
15624 ** May you do good and not evil.
15625 ** May you find forgiveness for yourself and forgive others.
15626 ** May you share freely, never taking more than you give.
15627 **
15628 *************************************************************************
15629 **
15630 ** This module implements the sqlite3_status() interface and related
15631 ** functionality.
15632 */
15633 /* #include "sqliteInt.h" */
15634 /************** Include vdbeInt.h in the middle of status.c ******************/
15635 /************** Begin file vdbeInt.h *****************************************/
15636 /*
15637 ** 2003 September 6
15638 **
15639 ** The author disclaims copyright to this source code. In place of
15640 ** a legal notice, here is a blessing:
15641 **
15642 ** May you do good and not evil.
15643 ** May you find forgiveness for yourself and forgive others.
15644 ** May you share freely, never taking more than you give.
15645 **
15646 *************************************************************************
15647 ** This is the header file for information that is private to the
15648 ** VDBE. This information used to all be at the top of the single
15649 ** source code file "vdbe.c". When that file became too big (over
15650 ** 6000 lines long) it was split up into several smaller files and
15651 ** this header information was factored out.
15652 */
15653 #ifndef _VDBEINT_H_
15654 #define _VDBEINT_H_
15655
15656 /*
15657 ** The maximum number of times that a statement will try to reparse
15658 ** itself before giving up and returning SQLITE_SCHEMA.
15659 */
15660 #ifndef SQLITE_MAX_SCHEMA_RETRY
15661 # define SQLITE_MAX_SCHEMA_RETRY 50
15662 #endif
15663
15664 /*
15665 ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
15666 ** "explain" P4 display logic is enabled.
15667 */
15668 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
15669 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
15670 # define VDBE_DISPLAY_P4 1
15671 #else
15672 # define VDBE_DISPLAY_P4 0
15673 #endif
15674
15675 /*
15676 ** SQL is translated into a sequence of instructions to be
15677 ** executed by a virtual machine. Each instruction is an instance
15678 ** of the following structure.
15679 */
15680 typedef struct VdbeOp Op;
15681
15682 /*
15683 ** Boolean values
15684 */
15685 typedef unsigned Bool;
15686
15687 /* Opaque type used by code in vdbesort.c */
15688 typedef struct VdbeSorter VdbeSorter;
15689
15690 /* Opaque type used by the explainer */
15691 typedef struct Explain Explain;
15692
15693 /* Elements of the linked list at Vdbe.pAuxData */
15694 typedef struct AuxData AuxData;
15695
15696 /* Types of VDBE cursors */
15697 #define CURTYPE_BTREE 0
15698 #define CURTYPE_SORTER 1
15699 #define CURTYPE_VTAB 2
15700 #define CURTYPE_PSEUDO 3
15701
15702 /*
15703 ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
15704 **
15705 ** * A b-tree cursor
15706 ** - In the main database or in an ephemeral database
15707 ** - On either an index or a table
15708 ** * A sorter
15709 ** * A virtual table
15710 ** * A one-row "pseudotable" stored in a single register
15711 */
15712 struct VdbeCursor {
15713 u8 eCurType; /* One of the CURTYPE_* values above */
15714 i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
15715 u8 nullRow; /* True if pointing to a row with no data */
15716 u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
15717 u8 isTable; /* True for rowid tables. False for indexes */
15718 #ifdef SQLITE_DEBUG
15719 u8 seekOp; /* Most recent seek operation on this cursor */
15720 #endif
15721 Bool isEphemeral:1; /* True for an ephemeral table */
15722 Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
15723 Bool isOrdered:1; /* True if the underlying table is BTREE_UNORDERED */
15724 Pgno pgnoRoot; /* Root page of the open btree cursor */
15725 i16 nField; /* Number of fields in the header */
15726 u16 nHdrParsed; /* Number of header fields parsed so far */
15727 union {
15728 BtCursor *pCursor; /* CURTYPE_BTREE. Btree cursor */
15729 sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
15730 int pseudoTableReg; /* CURTYPE_PSEUDO. Reg holding content. */
15731 VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
15732 } uc;
15733 Btree *pBt; /* Separate file holding temporary table */
15734 KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
15735 int seekResult; /* Result of previous sqlite3BtreeMoveto() */
15736 i64 seqCount; /* Sequence counter */
15737 i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
15738 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
15739 u64 maskUsed; /* Mask of columns used by this cursor */
15740 #endif
15741
15742 /* Cached information about the header for the data record that the
15743 ** cursor is currently pointing to. Only valid if cacheStatus matches
15744 ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
15745 ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
15746 ** the cache is out of date.
15747 **
15748 ** aRow might point to (ephemeral) data for the current row, or it might
15749 ** be NULL.
15750 */
15751 u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
15752 u32 payloadSize; /* Total number of bytes in the record */
15753 u32 szRow; /* Byte available in aRow */
15754 u32 iHdrOffset; /* Offset to next unparsed byte of the header */
15755 const u8 *aRow; /* Data for the current row, if all on one page */
15756 u32 *aOffset; /* Pointer to aType[nField] */
15757 u32 aType[1]; /* Type values for all entries in the record */
15758 /* 2*nField extra array elements allocated for aType[], beyond the one
15759 ** static element declared in the structure. nField total array slots for
15760 ** aType[] and nField+1 array slots for aOffset[] */
15761 };
15762 typedef struct VdbeCursor VdbeCursor;
15763
15764 /*
15765 ** When a sub-program is executed (OP_Program), a structure of this type
15766 ** is allocated to store the current value of the program counter, as
15767 ** well as the current memory cell array and various other frame specific
15768 ** values stored in the Vdbe struct. When the sub-program is finished,
15769 ** these values are copied back to the Vdbe from the VdbeFrame structure,
15770 ** restoring the state of the VM to as it was before the sub-program
15771 ** began executing.
15772 **
15773 ** The memory for a VdbeFrame object is allocated and managed by a memory
15774 ** cell in the parent (calling) frame. When the memory cell is deleted or
15775 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
15776 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
15777 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
15778 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
15779 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
15780 ** child frame are released.
15781 **
15782 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
15783 ** set to NULL if the currently executing frame is the main program.
15784 */
15785 typedef struct VdbeFrame VdbeFrame;
15786 struct VdbeFrame {
15787 Vdbe *v; /* VM this frame belongs to */
15788 VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
15789 Op *aOp; /* Program instructions for parent frame */
15790 i64 *anExec; /* Event counters from parent frame */
15791 Mem *aMem; /* Array of memory cells for parent frame */
15792 u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
15793 VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
15794 void *token; /* Copy of SubProgram.token */
15795 i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
15796 int nCursor; /* Number of entries in apCsr */
15797 int pc; /* Program Counter in parent (calling) frame */
15798 int nOp; /* Size of aOp array */
15799 int nMem; /* Number of entries in aMem */
15800 int nOnceFlag; /* Number of entries in aOnceFlag */
15801 int nChildMem; /* Number of memory cells for child frame */
15802 int nChildCsr; /* Number of cursors for child frame */
15803 int nChange; /* Statement changes (Vdbe.nChange) */
15804 int nDbChange; /* Value of db->nChange */
15805 };
15806
15807 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
15808
15809 /*
15810 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
15811 */
15812 #define CACHE_STALE 0
15813
15814 /*
15815 ** Internally, the vdbe manipulates nearly all SQL values as Mem
15816 ** structures. Each Mem struct may cache multiple representations (string,
15817 ** integer etc.) of the same value.
15818 */
15819 struct Mem {
15820 union MemValue {
15821 double r; /* Real value used when MEM_Real is set in flags */
15822 i64 i; /* Integer value used when MEM_Int is set in flags */
15823 int nZero; /* Used when bit MEM_Zero is set in flags */
15824 FuncDef *pDef; /* Used only when flags==MEM_Agg */
15825 RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
15826 VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
15827 } u;
15828 u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
15829 u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
15830 u8 eSubtype; /* Subtype for this value */
15831 int n; /* Number of characters in string value, excluding '\0' */
15832 char *z; /* String or BLOB value */
15833 /* ShallowCopy only needs to copy the information above */
15834 char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
15835 int szMalloc; /* Size of the zMalloc allocation */
15836 u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
15837 sqlite3 *db; /* The associated database connection */
15838 void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
15839 #ifdef SQLITE_DEBUG
15840 Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
15841 void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
15842 #endif
15843 };
15844
15845 /*
15846 ** Size of struct Mem not including the Mem.zMalloc member or anything that
15847 ** follows.
15848 */
15849 #define MEMCELLSIZE offsetof(Mem,zMalloc)
15850
15851 /* One or more of the following flags are set to indicate the validOK
15852 ** representations of the value stored in the Mem struct.
15853 **
15854 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
15855 ** No other flags may be set in this case.
15856 **
15857 ** If the MEM_Str flag is set then Mem.z points at a string representation.
15858 ** Usually this is encoded in the same unicode encoding as the main
15859 ** database (see below for exceptions). If the MEM_Term flag is also
15860 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
15861 ** flags may coexist with the MEM_Str flag.
15862 */
15863 #define MEM_Null 0x0001 /* Value is NULL */
15864 #define MEM_Str 0x0002 /* Value is a string */
15865 #define MEM_Int 0x0004 /* Value is an integer */
15866 #define MEM_Real 0x0008 /* Value is a real number */
15867 #define MEM_Blob 0x0010 /* Value is a BLOB */
15868 #define MEM_AffMask 0x001f /* Mask of affinity bits */
15869 #define MEM_RowSet 0x0020 /* Value is a RowSet object */
15870 #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
15871 #define MEM_Undefined 0x0080 /* Value is undefined */
15872 #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
15873 #define MEM_TypeMask 0x01ff /* Mask of type bits */
15874
15875
15876 /* Whenever Mem contains a valid string or blob representation, one of
15877 ** the following flags must be set to determine the memory management
15878 ** policy for Mem.z. The MEM_Term flag tells us whether or not the
15879 ** string is \000 or \u0000 terminated
15880 */
15881 #define MEM_Term 0x0200 /* String rep is nul terminated */
15882 #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
15883 #define MEM_Static 0x0800 /* Mem.z points to a static string */
15884 #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
15885 #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
15886 #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
15887 #ifdef SQLITE_OMIT_INCRBLOB
15888 #undef MEM_Zero
15889 #define MEM_Zero 0x0000
15890 #endif
15891
15892 /*
15893 ** Clear any existing type flags from a Mem and replace them with f
15894 */
15895 #define MemSetTypeFlag(p, f) \
15896 ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
15897
15898 /*
15899 ** Return true if a memory cell is not marked as invalid. This macro
15900 ** is for use inside assert() statements only.
15901 */
15902 #ifdef SQLITE_DEBUG
15903 #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
15904 #endif
15905
15906 /*
15907 ** Each auxiliary data pointer stored by a user defined function
15908 ** implementation calling sqlite3_set_auxdata() is stored in an instance
15909 ** of this structure. All such structures associated with a single VM
15910 ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
15911 ** when the VM is halted (if not before).
15912 */
15913 struct AuxData {
15914 int iOp; /* Instruction number of OP_Function opcode */
15915 int iArg; /* Index of function argument. */
15916 void *pAux; /* Aux data pointer */
15917 void (*xDelete)(void *); /* Destructor for the aux data */
15918 AuxData *pNext; /* Next element in list */
15919 };
15920
15921 /*
15922 ** The "context" argument for an installable function. A pointer to an
15923 ** instance of this structure is the first argument to the routines used
15924 ** implement the SQL functions.
15925 **
15926 ** There is a typedef for this structure in sqlite.h. So all routines,
15927 ** even the public interface to SQLite, can use a pointer to this structure.
15928 ** But this file is the only place where the internal details of this
15929 ** structure are known.
15930 **
15931 ** This structure is defined inside of vdbeInt.h because it uses substructures
15932 ** (Mem) which are only defined there.
15933 */
15934 struct sqlite3_context {
15935 Mem *pOut; /* The return value is stored here */
15936 FuncDef *pFunc; /* Pointer to function information */
15937 Mem *pMem; /* Memory cell used to store aggregate context */
15938 Vdbe *pVdbe; /* The VM that owns this context */
15939 int iOp; /* Instruction number of OP_Function */
15940 int isError; /* Error code returned by the function. */
15941 u8 skipFlag; /* Skip accumulator loading if true */
15942 u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
15943 u8 argc; /* Number of arguments */
15944 sqlite3_value *argv[1]; /* Argument set */
15945 };
15946
15947 /*
15948 ** An Explain object accumulates indented output which is helpful
15949 ** in describing recursive data structures.
15950 */
15951 struct Explain {
15952 Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
15953 StrAccum str; /* The string being accumulated */
15954 int nIndent; /* Number of elements in aIndent */
15955 u16 aIndent[100]; /* Levels of indentation */
15956 char zBase[100]; /* Initial space */
15957 };
15958
15959 /* A bitfield type for use inside of structures. Always follow with :N where
15960 ** N is the number of bits.
15961 */
15962 typedef unsigned bft; /* Bit Field Type */
15963
15964 typedef struct ScanStatus ScanStatus;
15965 struct ScanStatus {
15966 int addrExplain; /* OP_Explain for loop */
15967 int addrLoop; /* Address of "loops" counter */
15968 int addrVisit; /* Address of "rows visited" counter */
15969 int iSelectID; /* The "Select-ID" for this loop */
15970 LogEst nEst; /* Estimated output rows per loop */
15971 char *zName; /* Name of table or index */
15972 };
15973
15974 /*
15975 ** An instance of the virtual machine. This structure contains the complete
15976 ** state of the virtual machine.
15977 **
15978 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
15979 ** is really a pointer to an instance of this structure.
15980 */
15981 struct Vdbe {
15982 sqlite3 *db; /* The database connection that owns this statement */
15983 Op *aOp; /* Space to hold the virtual machine's program */
15984 Mem *aMem; /* The memory locations */
15985 Mem **apArg; /* Arguments to currently executing user function */
15986 Mem *aColName; /* Column names to return */
15987 Mem *pResultSet; /* Pointer to an array of results */
15988 Parse *pParse; /* Parsing context used to create this Vdbe */
15989 int nMem; /* Number of memory locations currently allocated */
15990 int nOp; /* Number of instructions in the program */
15991 int nCursor; /* Number of slots in apCsr[] */
15992 u32 magic; /* Magic number for sanity checking */
15993 char *zErrMsg; /* Error message written here */
15994 Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
15995 VdbeCursor **apCsr; /* One element of this array for each open cursor */
15996 Mem *aVar; /* Values for the OP_Variable opcode. */
15997 char **azVar; /* Name of variables */
15998 ynVar nVar; /* Number of entries in aVar[] */
15999 ynVar nzVar; /* Number of entries in azVar[] */
16000 u32 cacheCtr; /* VdbeCursor row cache generation counter */
16001 int pc; /* The program counter */
16002 int rc; /* Value to return */
16003 #ifdef SQLITE_DEBUG
16004 int rcApp; /* errcode set by sqlite3_result_error_code() */
16005 #endif
16006 u16 nResColumn; /* Number of columns in one row of the result set */
16007 u8 errorAction; /* Recovery action to do in case of an error */
16008 u8 minWriteFileFormat; /* Minimum file format for writable database files */
16009 bft explain:2; /* True if EXPLAIN present on SQL command */
16010 bft changeCntOn:1; /* True to update the change-counter */
16011 bft expired:1; /* True if the VM needs to be recompiled */
16012 bft runOnlyOnce:1; /* Automatically expire on reset */
16013 bft usesStmtJournal:1; /* True if uses a statement journal */
16014 bft readOnly:1; /* True for statements that do not write */
16015 bft bIsReader:1; /* True for statements that read */
16016 bft isPrepareV2:1; /* True if prepared with prepare_v2() */
16017 bft doingRerun:1; /* True if rerunning after an auto-reprepare */
16018 int nChange; /* Number of db changes made since last reset */
16019 yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
16020 yDbMask lockMask; /* Subset of btreeMask that requires a lock */
16021 int iStatement; /* Statement number (or 0 if has not opened stmt) */
16022 u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
16023 #ifndef SQLITE_OMIT_TRACE
16024 i64 startTime; /* Time when query started - used for profiling */
16025 #endif
16026 i64 iCurrentTime; /* Value of julianday('now') for this statement */
16027 i64 nFkConstraint; /* Number of imm. FK constraints this VM */
16028 i64 nStmtDefCons; /* Number of def. constraints when stmt started */
16029 i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
16030 char *zSql; /* Text of the SQL statement that generated this */
16031 void *pFree; /* Free this when deleting the vdbe */
16032 VdbeFrame *pFrame; /* Parent frame */
16033 VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
16034 int nFrame; /* Number of frames in pFrame list */
16035 u32 expmask; /* Binding to these vars invalidates VM */
16036 SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
16037 int nOnceFlag; /* Size of array aOnceFlag[] */
16038 u8 *aOnceFlag; /* Flags for OP_Once */
16039 AuxData *pAuxData; /* Linked list of auxdata allocations */
16040 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
16041 i64 *anExec; /* Number of times each op has been executed */
16042 int nScan; /* Entries in aScan[] */
16043 ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
16044 #endif
16045 };
16046
16047 /*
16048 ** The following are allowed values for Vdbe.magic
16049 */
16050 #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
16051 #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
16052 #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
16053 #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
16054
16055 /*
16056 ** Function prototypes
16057 */
16058 SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
16059 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
16060 void sqliteVdbePopStack(Vdbe*,int);
16061 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
16062 SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
16063 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
16064 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
16065 #endif
16066 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
16067 SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
16068 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
16069 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
16070 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
16071 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
16072
16073 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
16074 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord* ,int*);
16075 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
16076 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
16077 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
16078 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
16079 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
16080 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
16081 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
16082 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
16083 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
16084 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
16085 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void *));
16086 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
16087 #ifdef SQLITE_OMIT_FLOATING_POINT
16088 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
16089 #else
16090 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
16091 #endif
16092 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
16093 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
16094 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
16095 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
16096 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
16097 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
16098 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
16099 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
16100 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
16101 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
16102 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
16103 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
16104 SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
16105 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
16106 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
16107 #define VdbeMemDynamic(X) \
16108 (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
16109 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
16110 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
16111 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
16112 SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
16113 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
16114 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
16115 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
16116 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
16117
16118 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
16119 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
16120 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
16121 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
16122 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
16123 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
16124 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
16125 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
16126
16127 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
16128 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
16129 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
16130 #else
16131 # define sqlite3VdbeEnter(X)
16132 # define sqlite3VdbeLeave(X)
16133 #endif
16134
16135 #ifdef SQLITE_DEBUG
16136 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
16137 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
16138 #endif
16139
16140 #ifndef SQLITE_OMIT_FOREIGN_KEY
16141 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
16142 #else
16143 # define sqlite3VdbeCheckFk(p,i) 0
16144 #endif
16145
16146 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
16147 #ifdef SQLITE_DEBUG
16148 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
16149 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
16150 #endif
16151 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
16152
16153 #ifndef SQLITE_OMIT_INCRBLOB
16154 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
16155 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
16156 #else
16157 #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
16158 #define ExpandBlob(P) SQLITE_OK
16159 #endif
16160
16161 #endif /* !defined(_VDBEINT_H_) */
16162
16163 /************** End of vdbeInt.h *********************************************/
16164 /************** Continuing where we left off in status.c *********************/
16165
16166 /*
16167 ** Variables in which to record status information.
16168 */
16169 #if SQLITE_PTRSIZE>4
16170 typedef sqlite3_int64 sqlite3StatValueType;
16171 #else
16172 typedef u32 sqlite3StatValueType;
16173 #endif
16174 typedef struct sqlite3StatType sqlite3StatType;
16175 static SQLITE_WSD struct sqlite3StatType {
16176 sqlite3StatValueType nowValue[10]; /* Current value */
16177 sqlite3StatValueType mxValue[10]; /* Maximum value */
16178 } sqlite3Stat = { {0,}, {0,} };
16179
16180 /*
16181 ** Elements of sqlite3Stat[] are protected by either the memory allocator
16182 ** mutex, or by the pcache1 mutex. The following array determines which.
16183 */
16184 static const char statMutex[] = {
16185 0, /* SQLITE_STATUS_MEMORY_USED */
16186 1, /* SQLITE_STATUS_PAGECACHE_USED */
16187 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
16188 0, /* SQLITE_STATUS_SCRATCH_USED */
16189 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
16190 0, /* SQLITE_STATUS_MALLOC_SIZE */
16191 0, /* SQLITE_STATUS_PARSER_STACK */
16192 1, /* SQLITE_STATUS_PAGECACHE_SIZE */
16193 0, /* SQLITE_STATUS_SCRATCH_SIZE */
16194 0, /* SQLITE_STATUS_MALLOC_COUNT */
16195 };
16196
16197
16198 /* The "wsdStat" macro will resolve to the status information
16199 ** state vector. If writable static data is unsupported on the target,
16200 ** we have to locate the state vector at run-time. In the more common
16201 ** case where writable static data is supported, wsdStat can refer directly
16202 ** to the "sqlite3Stat" state vector declared above.
16203 */
16204 #ifdef SQLITE_OMIT_WSD
16205 # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
16206 # define wsdStat x[0]
16207 #else
16208 # define wsdStatInit
16209 # define wsdStat sqlite3Stat
16210 #endif
16211
16212 /*
16213 ** Return the current value of a status parameter. The caller must
16214 ** be holding the appropriate mutex.
16215 */
16216 SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
16217 wsdStatInit;
16218 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
16219 assert( op>=0 && op<ArraySize(statMutex) );
16220 assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
16221 : sqlite3MallocMutex()) );
16222 return wsdStat.nowValue[op];
16223 }
16224
16225 /*
16226 ** Add N to the value of a status record. The caller must hold the
16227 ** appropriate mutex. (Locking is checked by assert()).
16228 **
16229 ** The StatusUp() routine can accept positive or negative values for N.
16230 ** The value of N is added to the current status value and the high-water
16231 ** mark is adjusted if necessary.
16232 **
16233 ** The StatusDown() routine lowers the current value by N. The highwater
16234 ** mark is unchanged. N must be non-negative for StatusDown().
16235 */
16236 SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
16237 wsdStatInit;
16238 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
16239 assert( op>=0 && op<ArraySize(statMutex) );
16240 assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
16241 : sqlite3MallocMutex()) );
16242 wsdStat.nowValue[op] += N;
16243 if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
16244 wsdStat.mxValue[op] = wsdStat.nowValue[op];
16245 }
16246 }
16247 SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
16248 wsdStatInit;
16249 assert( N>=0 );
16250 assert( op>=0 && op<ArraySize(statMutex) );
16251 assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
16252 : sqlite3MallocMutex()) );
16253 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
16254 wsdStat.nowValue[op] -= N;
16255 }
16256
16257 /*
16258 ** Adjust the highwater mark if necessary.
16259 ** The caller must hold the appropriate mutex.
16260 */
16261 SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
16262 sqlite3StatValueType newValue;
16263 wsdStatInit;
16264 assert( X>=0 );
16265 newValue = (sqlite3StatValueType)X;
16266 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
16267 assert( op>=0 && op<ArraySize(statMutex) );
16268 assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
16269 : sqlite3MallocMutex()) );
16270 assert( op==SQLITE_STATUS_MALLOC_SIZE
16271 || op==SQLITE_STATUS_PAGECACHE_SIZE
16272 || op==SQLITE_STATUS_SCRATCH_SIZE
16273 || op==SQLITE_STATUS_PARSER_STACK );
16274 if( newValue>wsdStat.mxValue[op] ){
16275 wsdStat.mxValue[op] = newValue;
16276 }
16277 }
16278
16279 /*
16280 ** Query status information.
16281 */
16282 SQLITE_API int SQLITE_STDCALL sqlite3_status64(
16283 int op,
16284 sqlite3_int64 *pCurrent,
16285 sqlite3_int64 *pHighwater,
16286 int resetFlag
16287 ){
16288 sqlite3_mutex *pMutex;
16289 wsdStatInit;
16290 if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
16291 return SQLITE_MISUSE_BKPT;
16292 }
16293 #ifdef SQLITE_ENABLE_API_ARMOR
16294 if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
16295 #endif
16296 pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
16297 sqlite3_mutex_enter(pMutex);
16298 *pCurrent = wsdStat.nowValue[op];
16299 *pHighwater = wsdStat.mxValue[op];
16300 if( resetFlag ){
16301 wsdStat.mxValue[op] = wsdStat.nowValue[op];
16302 }
16303 sqlite3_mutex_leave(pMutex);
16304 (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
16305 return SQLITE_OK;
16306 }
16307 SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwa ter, int resetFlag){
16308 sqlite3_int64 iCur, iHwtr;
16309 int rc;
16310 #ifdef SQLITE_ENABLE_API_ARMOR
16311 if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
16312 #endif
16313 rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
16314 if( rc==0 ){
16315 *pCurrent = (int)iCur;
16316 *pHighwater = (int)iHwtr;
16317 }
16318 return rc;
16319 }
16320
16321 /*
16322 ** Query status information for a single database connection
16323 */
16324 SQLITE_API int SQLITE_STDCALL sqlite3_db_status(
16325 sqlite3 *db, /* The database connection whose status is desired */
16326 int op, /* Status verb */
16327 int *pCurrent, /* Write current value here */
16328 int *pHighwater, /* Write high-water mark here */
16329 int resetFlag /* Reset high-water mark if true */
16330 ){
16331 int rc = SQLITE_OK; /* Return code */
16332 #ifdef SQLITE_ENABLE_API_ARMOR
16333 if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
16334 return SQLITE_MISUSE_BKPT;
16335 }
16336 #endif
16337 sqlite3_mutex_enter(db->mutex);
16338 switch( op ){
16339 case SQLITE_DBSTATUS_LOOKASIDE_USED: {
16340 *pCurrent = db->lookaside.nOut;
16341 *pHighwater = db->lookaside.mxOut;
16342 if( resetFlag ){
16343 db->lookaside.mxOut = db->lookaside.nOut;
16344 }
16345 break;
16346 }
16347
16348 case SQLITE_DBSTATUS_LOOKASIDE_HIT:
16349 case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
16350 case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
16351 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
16352 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
16353 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
16354 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
16355 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
16356 *pCurrent = 0;
16357 *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
16358 if( resetFlag ){
16359 db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
16360 }
16361 break;
16362 }
16363
16364 /*
16365 ** Return an approximation for the amount of memory currently used
16366 ** by all pagers associated with the given database connection. The
16367 ** highwater mark is meaningless and is returned as zero.
16368 */
16369 case SQLITE_DBSTATUS_CACHE_USED: {
16370 int totalUsed = 0;
16371 int i;
16372 sqlite3BtreeEnterAll(db);
16373 for(i=0; i<db->nDb; i++){
16374 Btree *pBt = db->aDb[i].pBt;
16375 if( pBt ){
16376 Pager *pPager = sqlite3BtreePager(pBt);
16377 totalUsed += sqlite3PagerMemUsed(pPager);
16378 }
16379 }
16380 sqlite3BtreeLeaveAll(db);
16381 *pCurrent = totalUsed;
16382 *pHighwater = 0;
16383 break;
16384 }
16385
16386 /*
16387 ** *pCurrent gets an accurate estimate of the amount of memory used
16388 ** to store the schema for all databases (main, temp, and any ATTACHed
16389 ** databases. *pHighwater is set to zero.
16390 */
16391 case SQLITE_DBSTATUS_SCHEMA_USED: {
16392 int i; /* Used to iterate through schemas */
16393 int nByte = 0; /* Used to accumulate return value */
16394
16395 sqlite3BtreeEnterAll(db);
16396 db->pnBytesFreed = &nByte;
16397 for(i=0; i<db->nDb; i++){
16398 Schema *pSchema = db->aDb[i].pSchema;
16399 if( ALWAYS(pSchema!=0) ){
16400 HashElem *p;
16401
16402 nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
16403 pSchema->tblHash.count
16404 + pSchema->trigHash.count
16405 + pSchema->idxHash.count
16406 + pSchema->fkeyHash.count
16407 );
16408 nByte += sqlite3_msize(pSchema->tblHash.ht);
16409 nByte += sqlite3_msize(pSchema->trigHash.ht);
16410 nByte += sqlite3_msize(pSchema->idxHash.ht);
16411 nByte += sqlite3_msize(pSchema->fkeyHash.ht);
16412
16413 for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
16414 sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
16415 }
16416 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
16417 sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
16418 }
16419 }
16420 }
16421 db->pnBytesFreed = 0;
16422 sqlite3BtreeLeaveAll(db);
16423
16424 *pHighwater = 0;
16425 *pCurrent = nByte;
16426 break;
16427 }
16428
16429 /*
16430 ** *pCurrent gets an accurate estimate of the amount of memory used
16431 ** to store all prepared statements.
16432 ** *pHighwater is set to zero.
16433 */
16434 case SQLITE_DBSTATUS_STMT_USED: {
16435 struct Vdbe *pVdbe; /* Used to iterate through VMs */
16436 int nByte = 0; /* Used to accumulate return value */
16437
16438 db->pnBytesFreed = &nByte;
16439 for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
16440 sqlite3VdbeClearObject(db, pVdbe);
16441 sqlite3DbFree(db, pVdbe);
16442 }
16443 db->pnBytesFreed = 0;
16444
16445 *pHighwater = 0; /* IMP: R-64479-57858 */
16446 *pCurrent = nByte;
16447
16448 break;
16449 }
16450
16451 /*
16452 ** Set *pCurrent to the total cache hits or misses encountered by all
16453 ** pagers the database handle is connected to. *pHighwater is always set
16454 ** to zero.
16455 */
16456 case SQLITE_DBSTATUS_CACHE_HIT:
16457 case SQLITE_DBSTATUS_CACHE_MISS:
16458 case SQLITE_DBSTATUS_CACHE_WRITE:{
16459 int i;
16460 int nRet = 0;
16461 assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
16462 assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
16463
16464 for(i=0; i<db->nDb; i++){
16465 if( db->aDb[i].pBt ){
16466 Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
16467 sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
16468 }
16469 }
16470 *pHighwater = 0; /* IMP: R-42420-56072 */
16471 /* IMP: R-54100-20147 */
16472 /* IMP: R-29431-39229 */
16473 *pCurrent = nRet;
16474 break;
16475 }
16476
16477 /* Set *pCurrent to non-zero if there are unresolved deferred foreign
16478 ** key constraints. Set *pCurrent to zero if all foreign key constraints
16479 ** have been satisfied. The *pHighwater is always set to zero.
16480 */
16481 case SQLITE_DBSTATUS_DEFERRED_FKS: {
16482 *pHighwater = 0; /* IMP: R-11967-56545 */
16483 *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
16484 break;
16485 }
16486
16487 default: {
16488 rc = SQLITE_ERROR;
16489 }
16490 }
16491 sqlite3_mutex_leave(db->mutex);
16492 return rc;
16493 }
16494
16495 /************** End of status.c **********************************************/
16496 /************** Begin file date.c ********************************************/
16497 /*
16498 ** 2003 October 31
16499 **
16500 ** The author disclaims copyright to this source code. In place of
16501 ** a legal notice, here is a blessing:
16502 **
16503 ** May you do good and not evil.
16504 ** May you find forgiveness for yourself and forgive others.
16505 ** May you share freely, never taking more than you give.
16506 **
16507 *************************************************************************
16508 ** This file contains the C functions that implement date and time
16509 ** functions for SQLite.
16510 **
16511 ** There is only one exported symbol in this file - the function
16512 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
16513 ** All other code has file scope.
16514 **
16515 ** SQLite processes all times and dates as julian day numbers. The
16516 ** dates and times are stored as the number of days since noon
16517 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
16518 ** calendar system.
16519 **
16520 ** 1970-01-01 00:00:00 is JD 2440587.5
16521 ** 2000-01-01 00:00:00 is JD 2451544.5
16522 **
16523 ** This implementation requires years to be expressed as a 4-digit number
16524 ** which means that only dates between 0000-01-01 and 9999-12-31 can
16525 ** be represented, even though julian day numbers allow a much wider
16526 ** range of dates.
16527 **
16528 ** The Gregorian calendar system is used for all dates and times,
16529 ** even those that predate the Gregorian calendar. Historians usually
16530 ** use the julian calendar for dates prior to 1582-10-15 and for some
16531 ** dates afterwards, depending on locale. Beware of this difference.
16532 **
16533 ** The conversion algorithms are implemented based on descriptions
16534 ** in the following text:
16535 **
16536 ** Jean Meeus
16537 ** Astronomical Algorithms, 2nd Edition, 1998
16538 ** ISBM 0-943396-61-1
16539 ** Willmann-Bell, Inc
16540 ** Richmond, Virginia (USA)
16541 */
16542 /* #include "sqliteInt.h" */
16543 /* #include <stdlib.h> */
16544 /* #include <assert.h> */
16545 #include <time.h>
16546
16547 #ifndef SQLITE_OMIT_DATETIME_FUNCS
16548
16549
16550 /*
16551 ** A structure for holding a single date and time.
16552 */
16553 typedef struct DateTime DateTime;
16554 struct DateTime {
16555 sqlite3_int64 iJD; /* The julian day number times 86400000 */
16556 int Y, M, D; /* Year, month, and day */
16557 int h, m; /* Hour and minutes */
16558 int tz; /* Timezone offset in minutes */
16559 double s; /* Seconds */
16560 char validYMD; /* True (1) if Y,M,D are valid */
16561 char validHMS; /* True (1) if h,m,s are valid */
16562 char validJD; /* True (1) if iJD is valid */
16563 char validTZ; /* True (1) if tz is valid */
16564 char tzSet; /* Timezone was set explicitly */
16565 };
16566
16567
16568 /*
16569 ** Convert zDate into one or more integers. Additional arguments
16570 ** come in groups of 5 as follows:
16571 **
16572 ** N number of digits in the integer
16573 ** min minimum allowed value of the integer
16574 ** max maximum allowed value of the integer
16575 ** nextC first character after the integer
16576 ** pVal where to write the integers value.
16577 **
16578 ** Conversions continue until one with nextC==0 is encountered.
16579 ** The function returns the number of successful conversions.
16580 */
16581 static int getDigits(const char *zDate, ...){
16582 va_list ap;
16583 int val;
16584 int N;
16585 int min;
16586 int max;
16587 int nextC;
16588 int *pVal;
16589 int cnt = 0;
16590 va_start(ap, zDate);
16591 do{
16592 N = va_arg(ap, int);
16593 min = va_arg(ap, int);
16594 max = va_arg(ap, int);
16595 nextC = va_arg(ap, int);
16596 pVal = va_arg(ap, int*);
16597 val = 0;
16598 while( N-- ){
16599 if( !sqlite3Isdigit(*zDate) ){
16600 goto end_getDigits;
16601 }
16602 val = val*10 + *zDate - '0';
16603 zDate++;
16604 }
16605 if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
16606 goto end_getDigits;
16607 }
16608 *pVal = val;
16609 zDate++;
16610 cnt++;
16611 }while( nextC );
16612 end_getDigits:
16613 va_end(ap);
16614 return cnt;
16615 }
16616
16617 /*
16618 ** Parse a timezone extension on the end of a date-time.
16619 ** The extension is of the form:
16620 **
16621 ** (+/-)HH:MM
16622 **
16623 ** Or the "zulu" notation:
16624 **
16625 ** Z
16626 **
16627 ** If the parse is successful, write the number of minutes
16628 ** of change in p->tz and return 0. If a parser error occurs,
16629 ** return non-zero.
16630 **
16631 ** A missing specifier is not considered an error.
16632 */
16633 static int parseTimezone(const char *zDate, DateTime *p){
16634 int sgn = 0;
16635 int nHr, nMn;
16636 int c;
16637 while( sqlite3Isspace(*zDate) ){ zDate++; }
16638 p->tz = 0;
16639 c = *zDate;
16640 if( c=='-' ){
16641 sgn = -1;
16642 }else if( c=='+' ){
16643 sgn = +1;
16644 }else if( c=='Z' || c=='z' ){
16645 zDate++;
16646 goto zulu_time;
16647 }else{
16648 return c!=0;
16649 }
16650 zDate++;
16651 if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
16652 return 1;
16653 }
16654 zDate += 5;
16655 p->tz = sgn*(nMn + nHr*60);
16656 zulu_time:
16657 while( sqlite3Isspace(*zDate) ){ zDate++; }
16658 p->tzSet = 1;
16659 return *zDate!=0;
16660 }
16661
16662 /*
16663 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
16664 ** The HH, MM, and SS must each be exactly 2 digits. The
16665 ** fractional seconds FFFF can be one or more digits.
16666 **
16667 ** Return 1 if there is a parsing error and 0 on success.
16668 */
16669 static int parseHhMmSs(const char *zDate, DateTime *p){
16670 int h, m, s;
16671 double ms = 0.0;
16672 if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
16673 return 1;
16674 }
16675 zDate += 5;
16676 if( *zDate==':' ){
16677 zDate++;
16678 if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
16679 return 1;
16680 }
16681 zDate += 2;
16682 if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
16683 double rScale = 1.0;
16684 zDate++;
16685 while( sqlite3Isdigit(*zDate) ){
16686 ms = ms*10.0 + *zDate - '0';
16687 rScale *= 10.0;
16688 zDate++;
16689 }
16690 ms /= rScale;
16691 }
16692 }else{
16693 s = 0;
16694 }
16695 p->validJD = 0;
16696 p->validHMS = 1;
16697 p->h = h;
16698 p->m = m;
16699 p->s = s + ms;
16700 if( parseTimezone(zDate, p) ) return 1;
16701 p->validTZ = (p->tz!=0)?1:0;
16702 return 0;
16703 }
16704
16705 /*
16706 ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
16707 ** that the YYYY-MM-DD is according to the Gregorian calendar.
16708 **
16709 ** Reference: Meeus page 61
16710 */
16711 static void computeJD(DateTime *p){
16712 int Y, M, D, A, B, X1, X2;
16713
16714 if( p->validJD ) return;
16715 if( p->validYMD ){
16716 Y = p->Y;
16717 M = p->M;
16718 D = p->D;
16719 }else{
16720 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
16721 M = 1;
16722 D = 1;
16723 }
16724 if( M<=2 ){
16725 Y--;
16726 M += 12;
16727 }
16728 A = Y/100;
16729 B = 2 - A + (A/4);
16730 X1 = 36525*(Y+4716)/100;
16731 X2 = 306001*(M+1)/10000;
16732 p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
16733 p->validJD = 1;
16734 if( p->validHMS ){
16735 p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
16736 if( p->validTZ ){
16737 p->iJD -= p->tz*60000;
16738 p->validYMD = 0;
16739 p->validHMS = 0;
16740 p->validTZ = 0;
16741 }
16742 }
16743 }
16744
16745 /*
16746 ** Parse dates of the form
16747 **
16748 ** YYYY-MM-DD HH:MM:SS.FFF
16749 ** YYYY-MM-DD HH:MM:SS
16750 ** YYYY-MM-DD HH:MM
16751 ** YYYY-MM-DD
16752 **
16753 ** Write the result into the DateTime structure and return 0
16754 ** on success and 1 if the input string is not a well-formed
16755 ** date.
16756 */
16757 static int parseYyyyMmDd(const char *zDate, DateTime *p){
16758 int Y, M, D, neg;
16759
16760 if( zDate[0]=='-' ){
16761 zDate++;
16762 neg = 1;
16763 }else{
16764 neg = 0;
16765 }
16766 if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
16767 return 1;
16768 }
16769 zDate += 10;
16770 while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
16771 if( parseHhMmSs(zDate, p)==0 ){
16772 /* We got the time */
16773 }else if( *zDate==0 ){
16774 p->validHMS = 0;
16775 }else{
16776 return 1;
16777 }
16778 p->validJD = 0;
16779 p->validYMD = 1;
16780 p->Y = neg ? -Y : Y;
16781 p->M = M;
16782 p->D = D;
16783 if( p->validTZ ){
16784 computeJD(p);
16785 }
16786 return 0;
16787 }
16788
16789 /*
16790 ** Set the time to the current time reported by the VFS.
16791 **
16792 ** Return the number of errors.
16793 */
16794 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
16795 p->iJD = sqlite3StmtCurrentTime(context);
16796 if( p->iJD>0 ){
16797 p->validJD = 1;
16798 return 0;
16799 }else{
16800 return 1;
16801 }
16802 }
16803
16804 /*
16805 ** Attempt to parse the given string into a julian day number. Return
16806 ** the number of errors.
16807 **
16808 ** The following are acceptable forms for the input string:
16809 **
16810 ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
16811 ** DDDD.DD
16812 ** now
16813 **
16814 ** In the first form, the +/-HH:MM is always optional. The fractional
16815 ** seconds extension (the ".FFF") is optional. The seconds portion
16816 ** (":SS.FFF") is option. The year and date can be omitted as long
16817 ** as there is a time string. The time string can be omitted as long
16818 ** as there is a year and date.
16819 */
16820 static int parseDateOrTime(
16821 sqlite3_context *context,
16822 const char *zDate,
16823 DateTime *p
16824 ){
16825 double r;
16826 if( parseYyyyMmDd(zDate,p)==0 ){
16827 return 0;
16828 }else if( parseHhMmSs(zDate, p)==0 ){
16829 return 0;
16830 }else if( sqlite3StrICmp(zDate,"now")==0){
16831 return setDateTimeToCurrent(context, p);
16832 }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
16833 p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
16834 p->validJD = 1;
16835 return 0;
16836 }
16837 return 1;
16838 }
16839
16840 /*
16841 ** Compute the Year, Month, and Day from the julian day number.
16842 */
16843 static void computeYMD(DateTime *p){
16844 int Z, A, B, C, D, E, X1;
16845 if( p->validYMD ) return;
16846 if( !p->validJD ){
16847 p->Y = 2000;
16848 p->M = 1;
16849 p->D = 1;
16850 }else{
16851 Z = (int)((p->iJD + 43200000)/86400000);
16852 A = (int)((Z - 1867216.25)/36524.25);
16853 A = Z + 1 + A - (A/4);
16854 B = A + 1524;
16855 C = (int)((B - 122.1)/365.25);
16856 D = (36525*(C&32767))/100;
16857 E = (int)((B-D)/30.6001);
16858 X1 = (int)(30.6001*E);
16859 p->D = B - D - X1;
16860 p->M = E<14 ? E-1 : E-13;
16861 p->Y = p->M>2 ? C - 4716 : C - 4715;
16862 }
16863 p->validYMD = 1;
16864 }
16865
16866 /*
16867 ** Compute the Hour, Minute, and Seconds from the julian day number.
16868 */
16869 static void computeHMS(DateTime *p){
16870 int s;
16871 if( p->validHMS ) return;
16872 computeJD(p);
16873 s = (int)((p->iJD + 43200000) % 86400000);
16874 p->s = s/1000.0;
16875 s = (int)p->s;
16876 p->s -= s;
16877 p->h = s/3600;
16878 s -= p->h*3600;
16879 p->m = s/60;
16880 p->s += s - p->m*60;
16881 p->validHMS = 1;
16882 }
16883
16884 /*
16885 ** Compute both YMD and HMS
16886 */
16887 static void computeYMD_HMS(DateTime *p){
16888 computeYMD(p);
16889 computeHMS(p);
16890 }
16891
16892 /*
16893 ** Clear the YMD and HMS and the TZ
16894 */
16895 static void clearYMD_HMS_TZ(DateTime *p){
16896 p->validYMD = 0;
16897 p->validHMS = 0;
16898 p->validTZ = 0;
16899 }
16900
16901 /*
16902 ** On recent Windows platforms, the localtime_s() function is available
16903 ** as part of the "Secure CRT". It is essentially equivalent to
16904 ** localtime_r() available under most POSIX platforms, except that the
16905 ** order of the parameters is reversed.
16906 **
16907 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
16908 **
16909 ** If the user has not indicated to use localtime_r() or localtime_s()
16910 ** already, check for an MSVC build environment that provides
16911 ** localtime_s().
16912 */
16913 #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
16914 && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
16915 #undef HAVE_LOCALTIME_S
16916 #define HAVE_LOCALTIME_S 1
16917 #endif
16918
16919 #ifndef SQLITE_OMIT_LOCALTIME
16920 /*
16921 ** The following routine implements the rough equivalent of localtime_r()
16922 ** using whatever operating-system specific localtime facility that
16923 ** is available. This routine returns 0 on success and
16924 ** non-zero on any kind of error.
16925 **
16926 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
16927 ** routine will always fail.
16928 **
16929 ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
16930 ** library function localtime_r() is used to assist in the calculation of
16931 ** local time.
16932 */
16933 static int osLocaltime(time_t *t, struct tm *pTm){
16934 int rc;
16935 #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
16936 struct tm *pX;
16937 #if SQLITE_THREADSAFE>0
16938 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
16939 #endif
16940 sqlite3_mutex_enter(mutex);
16941 pX = localtime(t);
16942 #ifndef SQLITE_OMIT_BUILTIN_TEST
16943 if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
16944 #endif
16945 if( pX ) *pTm = *pX;
16946 sqlite3_mutex_leave(mutex);
16947 rc = pX==0;
16948 #else
16949 #ifndef SQLITE_OMIT_BUILTIN_TEST
16950 if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
16951 #endif
16952 #if HAVE_LOCALTIME_R
16953 rc = localtime_r(t, pTm)==0;
16954 #else
16955 rc = localtime_s(pTm, t);
16956 #endif /* HAVE_LOCALTIME_R */
16957 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
16958 return rc;
16959 }
16960 #endif /* SQLITE_OMIT_LOCALTIME */
16961
16962
16963 #ifndef SQLITE_OMIT_LOCALTIME
16964 /*
16965 ** Compute the difference (in milliseconds) between localtime and UTC
16966 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
16967 ** return this value and set *pRc to SQLITE_OK.
16968 **
16969 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
16970 ** is undefined in this case.
16971 */
16972 static sqlite3_int64 localtimeOffset(
16973 DateTime *p, /* Date at which to calculate offset */
16974 sqlite3_context *pCtx, /* Write error here if one occurs */
16975 int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
16976 ){
16977 DateTime x, y;
16978 time_t t;
16979 struct tm sLocal;
16980
16981 /* Initialize the contents of sLocal to avoid a compiler warning. */
16982 memset(&sLocal, 0, sizeof(sLocal));
16983
16984 x = *p;
16985 computeYMD_HMS(&x);
16986 if( x.Y<1971 || x.Y>=2038 ){
16987 /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
16988 ** works for years between 1970 and 2037. For dates outside this range,
16989 ** SQLite attempts to map the year into an equivalent year within this
16990 ** range, do the calculation, then map the year back.
16991 */
16992 x.Y = 2000;
16993 x.M = 1;
16994 x.D = 1;
16995 x.h = 0;
16996 x.m = 0;
16997 x.s = 0.0;
16998 } else {
16999 int s = (int)(x.s + 0.5);
17000 x.s = s;
17001 }
17002 x.tz = 0;
17003 x.validJD = 0;
17004 computeJD(&x);
17005 t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
17006 if( osLocaltime(&t, &sLocal) ){
17007 sqlite3_result_error(pCtx, "local time unavailable", -1);
17008 *pRc = SQLITE_ERROR;
17009 return 0;
17010 }
17011 y.Y = sLocal.tm_year + 1900;
17012 y.M = sLocal.tm_mon + 1;
17013 y.D = sLocal.tm_mday;
17014 y.h = sLocal.tm_hour;
17015 y.m = sLocal.tm_min;
17016 y.s = sLocal.tm_sec;
17017 y.validYMD = 1;
17018 y.validHMS = 1;
17019 y.validJD = 0;
17020 y.validTZ = 0;
17021 computeJD(&y);
17022 *pRc = SQLITE_OK;
17023 return y.iJD - x.iJD;
17024 }
17025 #endif /* SQLITE_OMIT_LOCALTIME */
17026
17027 /*
17028 ** Process a modifier to a date-time stamp. The modifiers are
17029 ** as follows:
17030 **
17031 ** NNN days
17032 ** NNN hours
17033 ** NNN minutes
17034 ** NNN.NNNN seconds
17035 ** NNN months
17036 ** NNN years
17037 ** start of month
17038 ** start of year
17039 ** start of week
17040 ** start of day
17041 ** weekday N
17042 ** unixepoch
17043 ** localtime
17044 ** utc
17045 **
17046 ** Return 0 on success and 1 if there is any kind of error. If the error
17047 ** is in a system call (i.e. localtime()), then an error message is written
17048 ** to context pCtx. If the error is an unrecognized modifier, no error is
17049 ** written to pCtx.
17050 */
17051 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
17052 int rc = 1;
17053 int n;
17054 double r;
17055 char *z, zBuf[30];
17056 z = zBuf;
17057 for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
17058 z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
17059 }
17060 z[n] = 0;
17061 switch( z[0] ){
17062 #ifndef SQLITE_OMIT_LOCALTIME
17063 case 'l': {
17064 /* localtime
17065 **
17066 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
17067 ** show local time.
17068 */
17069 if( strcmp(z, "localtime")==0 ){
17070 computeJD(p);
17071 p->iJD += localtimeOffset(p, pCtx, &rc);
17072 clearYMD_HMS_TZ(p);
17073 }
17074 break;
17075 }
17076 #endif
17077 case 'u': {
17078 /*
17079 ** unixepoch
17080 **
17081 ** Treat the current value of p->iJD as the number of
17082 ** seconds since 1970. Convert to a real julian day number.
17083 */
17084 if( strcmp(z, "unixepoch")==0 && p->validJD ){
17085 p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
17086 clearYMD_HMS_TZ(p);
17087 rc = 0;
17088 }
17089 #ifndef SQLITE_OMIT_LOCALTIME
17090 else if( strcmp(z, "utc")==0 ){
17091 if( p->tzSet==0 ){
17092 sqlite3_int64 c1;
17093 computeJD(p);
17094 c1 = localtimeOffset(p, pCtx, &rc);
17095 if( rc==SQLITE_OK ){
17096 p->iJD -= c1;
17097 clearYMD_HMS_TZ(p);
17098 p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
17099 }
17100 p->tzSet = 1;
17101 }else{
17102 rc = SQLITE_OK;
17103 }
17104 }
17105 #endif
17106 break;
17107 }
17108 case 'w': {
17109 /*
17110 ** weekday N
17111 **
17112 ** Move the date to the same time on the next occurrence of
17113 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
17114 ** date is already on the appropriate weekday, this is a no-op.
17115 */
17116 if( strncmp(z, "weekday ", 8)==0
17117 && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
17118 && (n=(int)r)==r && n>=0 && r<7 ){
17119 sqlite3_int64 Z;
17120 computeYMD_HMS(p);
17121 p->validTZ = 0;
17122 p->validJD = 0;
17123 computeJD(p);
17124 Z = ((p->iJD + 129600000)/86400000) % 7;
17125 if( Z>n ) Z -= 7;
17126 p->iJD += (n - Z)*86400000;
17127 clearYMD_HMS_TZ(p);
17128 rc = 0;
17129 }
17130 break;
17131 }
17132 case 's': {
17133 /*
17134 ** start of TTTTT
17135 **
17136 ** Move the date backwards to the beginning of the current day,
17137 ** or month or year.
17138 */
17139 if( strncmp(z, "start of ", 9)!=0 ) break;
17140 z += 9;
17141 computeYMD(p);
17142 p->validHMS = 1;
17143 p->h = p->m = 0;
17144 p->s = 0.0;
17145 p->validTZ = 0;
17146 p->validJD = 0;
17147 if( strcmp(z,"month")==0 ){
17148 p->D = 1;
17149 rc = 0;
17150 }else if( strcmp(z,"year")==0 ){
17151 computeYMD(p);
17152 p->M = 1;
17153 p->D = 1;
17154 rc = 0;
17155 }else if( strcmp(z,"day")==0 ){
17156 rc = 0;
17157 }
17158 break;
17159 }
17160 case '+':
17161 case '-':
17162 case '0':
17163 case '1':
17164 case '2':
17165 case '3':
17166 case '4':
17167 case '5':
17168 case '6':
17169 case '7':
17170 case '8':
17171 case '9': {
17172 double rRounder;
17173 for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
17174 if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
17175 rc = 1;
17176 break;
17177 }
17178 if( z[n]==':' ){
17179 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
17180 ** specified number of hours, minutes, seconds, and fractional seconds
17181 ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
17182 ** omitted.
17183 */
17184 const char *z2 = z;
17185 DateTime tx;
17186 sqlite3_int64 day;
17187 if( !sqlite3Isdigit(*z2) ) z2++;
17188 memset(&tx, 0, sizeof(tx));
17189 if( parseHhMmSs(z2, &tx) ) break;
17190 computeJD(&tx);
17191 tx.iJD -= 43200000;
17192 day = tx.iJD/86400000;
17193 tx.iJD -= day*86400000;
17194 if( z[0]=='-' ) tx.iJD = -tx.iJD;
17195 computeJD(p);
17196 clearYMD_HMS_TZ(p);
17197 p->iJD += tx.iJD;
17198 rc = 0;
17199 break;
17200 }
17201 z += n;
17202 while( sqlite3Isspace(*z) ) z++;
17203 n = sqlite3Strlen30(z);
17204 if( n>10 || n<3 ) break;
17205 if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
17206 computeJD(p);
17207 rc = 0;
17208 rRounder = r<0 ? -0.5 : +0.5;
17209 if( n==3 && strcmp(z,"day")==0 ){
17210 p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
17211 }else if( n==4 && strcmp(z,"hour")==0 ){
17212 p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
17213 }else if( n==6 && strcmp(z,"minute")==0 ){
17214 p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
17215 }else if( n==6 && strcmp(z,"second")==0 ){
17216 p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
17217 }else if( n==5 && strcmp(z,"month")==0 ){
17218 int x, y;
17219 computeYMD_HMS(p);
17220 p->M += (int)r;
17221 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
17222 p->Y += x;
17223 p->M -= x*12;
17224 p->validJD = 0;
17225 computeJD(p);
17226 y = (int)r;
17227 if( y!=r ){
17228 p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
17229 }
17230 }else if( n==4 && strcmp(z,"year")==0 ){
17231 int y = (int)r;
17232 computeYMD_HMS(p);
17233 p->Y += y;
17234 p->validJD = 0;
17235 computeJD(p);
17236 if( y!=r ){
17237 p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
17238 }
17239 }else{
17240 rc = 1;
17241 }
17242 clearYMD_HMS_TZ(p);
17243 break;
17244 }
17245 default: {
17246 break;
17247 }
17248 }
17249 return rc;
17250 }
17251
17252 /*
17253 ** Process time function arguments. argv[0] is a date-time stamp.
17254 ** argv[1] and following are modifiers. Parse them all and write
17255 ** the resulting time into the DateTime structure p. Return 0
17256 ** on success and 1 if there are any errors.
17257 **
17258 ** If there are zero parameters (if even argv[0] is undefined)
17259 ** then assume a default value of "now" for argv[0].
17260 */
17261 static int isDate(
17262 sqlite3_context *context,
17263 int argc,
17264 sqlite3_value **argv,
17265 DateTime *p
17266 ){
17267 int i;
17268 const unsigned char *z;
17269 int eType;
17270 memset(p, 0, sizeof(*p));
17271 if( argc==0 ){
17272 return setDateTimeToCurrent(context, p);
17273 }
17274 if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
17275 || eType==SQLITE_INTEGER ){
17276 p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
17277 p->validJD = 1;
17278 }else{
17279 z = sqlite3_value_text(argv[0]);
17280 if( !z || parseDateOrTime(context, (char*)z, p) ){
17281 return 1;
17282 }
17283 }
17284 for(i=1; i<argc; i++){
17285 z = sqlite3_value_text(argv[i]);
17286 if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
17287 }
17288 return 0;
17289 }
17290
17291
17292 /*
17293 ** The following routines implement the various date and time functions
17294 ** of SQLite.
17295 */
17296
17297 /*
17298 ** julianday( TIMESTRING, MOD, MOD, ...)
17299 **
17300 ** Return the julian day number of the date specified in the arguments
17301 */
17302 static void juliandayFunc(
17303 sqlite3_context *context,
17304 int argc,
17305 sqlite3_value **argv
17306 ){
17307 DateTime x;
17308 if( isDate(context, argc, argv, &x)==0 ){
17309 computeJD(&x);
17310 sqlite3_result_double(context, x.iJD/86400000.0);
17311 }
17312 }
17313
17314 /*
17315 ** datetime( TIMESTRING, MOD, MOD, ...)
17316 **
17317 ** Return YYYY-MM-DD HH:MM:SS
17318 */
17319 static void datetimeFunc(
17320 sqlite3_context *context,
17321 int argc,
17322 sqlite3_value **argv
17323 ){
17324 DateTime x;
17325 if( isDate(context, argc, argv, &x)==0 ){
17326 char zBuf[100];
17327 computeYMD_HMS(&x);
17328 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
17329 x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
17330 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
17331 }
17332 }
17333
17334 /*
17335 ** time( TIMESTRING, MOD, MOD, ...)
17336 **
17337 ** Return HH:MM:SS
17338 */
17339 static void timeFunc(
17340 sqlite3_context *context,
17341 int argc,
17342 sqlite3_value **argv
17343 ){
17344 DateTime x;
17345 if( isDate(context, argc, argv, &x)==0 ){
17346 char zBuf[100];
17347 computeHMS(&x);
17348 sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
17349 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
17350 }
17351 }
17352
17353 /*
17354 ** date( TIMESTRING, MOD, MOD, ...)
17355 **
17356 ** Return YYYY-MM-DD
17357 */
17358 static void dateFunc(
17359 sqlite3_context *context,
17360 int argc,
17361 sqlite3_value **argv
17362 ){
17363 DateTime x;
17364 if( isDate(context, argc, argv, &x)==0 ){
17365 char zBuf[100];
17366 computeYMD(&x);
17367 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
17368 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
17369 }
17370 }
17371
17372 /*
17373 ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
17374 **
17375 ** Return a string described by FORMAT. Conversions as follows:
17376 **
17377 ** %d day of month
17378 ** %f ** fractional seconds SS.SSS
17379 ** %H hour 00-24
17380 ** %j day of year 000-366
17381 ** %J ** julian day number
17382 ** %m month 01-12
17383 ** %M minute 00-59
17384 ** %s seconds since 1970-01-01
17385 ** %S seconds 00-59
17386 ** %w day of week 0-6 sunday==0
17387 ** %W week of year 00-53
17388 ** %Y year 0000-9999
17389 ** %% %
17390 */
17391 static void strftimeFunc(
17392 sqlite3_context *context,
17393 int argc,
17394 sqlite3_value **argv
17395 ){
17396 DateTime x;
17397 u64 n;
17398 size_t i,j;
17399 char *z;
17400 sqlite3 *db;
17401 const char *zFmt;
17402 char zBuf[100];
17403 if( argc==0 ) return;
17404 zFmt = (const char*)sqlite3_value_text(argv[0]);
17405 if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
17406 db = sqlite3_context_db_handle(context);
17407 for(i=0, n=1; zFmt[i]; i++, n++){
17408 if( zFmt[i]=='%' ){
17409 switch( zFmt[i+1] ){
17410 case 'd':
17411 case 'H':
17412 case 'm':
17413 case 'M':
17414 case 'S':
17415 case 'W':
17416 n++;
17417 /* fall thru */
17418 case 'w':
17419 case '%':
17420 break;
17421 case 'f':
17422 n += 8;
17423 break;
17424 case 'j':
17425 n += 3;
17426 break;
17427 case 'Y':
17428 n += 8;
17429 break;
17430 case 's':
17431 case 'J':
17432 n += 50;
17433 break;
17434 default:
17435 return; /* ERROR. return a NULL */
17436 }
17437 i++;
17438 }
17439 }
17440 testcase( n==sizeof(zBuf)-1 );
17441 testcase( n==sizeof(zBuf) );
17442 testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
17443 testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
17444 if( n<sizeof(zBuf) ){
17445 z = zBuf;
17446 }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
17447 sqlite3_result_error_toobig(context);
17448 return;
17449 }else{
17450 z = sqlite3DbMallocRaw(db, (int)n);
17451 if( z==0 ){
17452 sqlite3_result_error_nomem(context);
17453 return;
17454 }
17455 }
17456 computeJD(&x);
17457 computeYMD_HMS(&x);
17458 for(i=j=0; zFmt[i]; i++){
17459 if( zFmt[i]!='%' ){
17460 z[j++] = zFmt[i];
17461 }else{
17462 i++;
17463 switch( zFmt[i] ){
17464 case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
17465 case 'f': {
17466 double s = x.s;
17467 if( s>59.999 ) s = 59.999;
17468 sqlite3_snprintf(7, &z[j],"%06.3f", s);
17469 j += sqlite3Strlen30(&z[j]);
17470 break;
17471 }
17472 case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
17473 case 'W': /* Fall thru */
17474 case 'j': {
17475 int nDay; /* Number of days since 1st day of year */
17476 DateTime y = x;
17477 y.validJD = 0;
17478 y.M = 1;
17479 y.D = 1;
17480 computeJD(&y);
17481 nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
17482 if( zFmt[i]=='W' ){
17483 int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
17484 wd = (int)(((x.iJD+43200000)/86400000)%7);
17485 sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
17486 j += 2;
17487 }else{
17488 sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
17489 j += 3;
17490 }
17491 break;
17492 }
17493 case 'J': {
17494 sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
17495 j+=sqlite3Strlen30(&z[j]);
17496 break;
17497 }
17498 case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
17499 case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
17500 case 's': {
17501 sqlite3_snprintf(30,&z[j],"%lld",
17502 (i64)(x.iJD/1000 - 21086676*(i64)10000));
17503 j += sqlite3Strlen30(&z[j]);
17504 break;
17505 }
17506 case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
17507 case 'w': {
17508 z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
17509 break;
17510 }
17511 case 'Y': {
17512 sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
17513 break;
17514 }
17515 default: z[j++] = '%'; break;
17516 }
17517 }
17518 }
17519 z[j] = 0;
17520 sqlite3_result_text(context, z, -1,
17521 z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
17522 }
17523
17524 /*
17525 ** current_time()
17526 **
17527 ** This function returns the same value as time('now').
17528 */
17529 static void ctimeFunc(
17530 sqlite3_context *context,
17531 int NotUsed,
17532 sqlite3_value **NotUsed2
17533 ){
17534 UNUSED_PARAMETER2(NotUsed, NotUsed2);
17535 timeFunc(context, 0, 0);
17536 }
17537
17538 /*
17539 ** current_date()
17540 **
17541 ** This function returns the same value as date('now').
17542 */
17543 static void cdateFunc(
17544 sqlite3_context *context,
17545 int NotUsed,
17546 sqlite3_value **NotUsed2
17547 ){
17548 UNUSED_PARAMETER2(NotUsed, NotUsed2);
17549 dateFunc(context, 0, 0);
17550 }
17551
17552 /*
17553 ** current_timestamp()
17554 **
17555 ** This function returns the same value as datetime('now').
17556 */
17557 static void ctimestampFunc(
17558 sqlite3_context *context,
17559 int NotUsed,
17560 sqlite3_value **NotUsed2
17561 ){
17562 UNUSED_PARAMETER2(NotUsed, NotUsed2);
17563 datetimeFunc(context, 0, 0);
17564 }
17565 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
17566
17567 #ifdef SQLITE_OMIT_DATETIME_FUNCS
17568 /*
17569 ** If the library is compiled to omit the full-scale date and time
17570 ** handling (to get a smaller binary), the following minimal version
17571 ** of the functions current_time(), current_date() and current_timestamp()
17572 ** are included instead. This is to support column declarations that
17573 ** include "DEFAULT CURRENT_TIME" etc.
17574 **
17575 ** This function uses the C-library functions time(), gmtime()
17576 ** and strftime(). The format string to pass to strftime() is supplied
17577 ** as the user-data for the function.
17578 */
17579 static void currentTimeFunc(
17580 sqlite3_context *context,
17581 int argc,
17582 sqlite3_value **argv
17583 ){
17584 time_t t;
17585 char *zFormat = (char *)sqlite3_user_data(context);
17586 sqlite3 *db;
17587 sqlite3_int64 iT;
17588 struct tm *pTm;
17589 struct tm sNow;
17590 char zBuf[20];
17591
17592 UNUSED_PARAMETER(argc);
17593 UNUSED_PARAMETER(argv);
17594
17595 iT = sqlite3StmtCurrentTime(context);
17596 if( iT<=0 ) return;
17597 t = iT/1000 - 10000*(sqlite3_int64)21086676;
17598 #if HAVE_GMTIME_R
17599 pTm = gmtime_r(&t, &sNow);
17600 #else
17601 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
17602 pTm = gmtime(&t);
17603 if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
17604 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
17605 #endif
17606 if( pTm ){
17607 strftime(zBuf, 20, zFormat, &sNow);
17608 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
17609 }
17610 }
17611 #endif
17612
17613 /*
17614 ** This function registered all of the above C functions as SQL
17615 ** functions. This should be the only routine in this file with
17616 ** external linkage.
17617 */
17618 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
17619 static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
17620 #ifndef SQLITE_OMIT_DATETIME_FUNCS
17621 DFUNCTION(julianday, -1, 0, 0, juliandayFunc ),
17622 DFUNCTION(date, -1, 0, 0, dateFunc ),
17623 DFUNCTION(time, -1, 0, 0, timeFunc ),
17624 DFUNCTION(datetime, -1, 0, 0, datetimeFunc ),
17625 DFUNCTION(strftime, -1, 0, 0, strftimeFunc ),
17626 DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
17627 DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
17628 DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
17629 #else
17630 STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
17631 STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
17632 STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
17633 #endif
17634 };
17635 int i;
17636 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
17637 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
17638
17639 for(i=0; i<ArraySize(aDateTimeFuncs); i++){
17640 sqlite3FuncDefInsert(pHash, &aFunc[i]);
17641 }
17642 }
17643
17644 /************** End of date.c ************************************************/
17645 /************** Begin file os.c **********************************************/
17646 /*
17647 ** 2005 November 29
17648 **
17649 ** The author disclaims copyright to this source code. In place of
17650 ** a legal notice, here is a blessing:
17651 **
17652 ** May you do good and not evil.
17653 ** May you find forgiveness for yourself and forgive others.
17654 ** May you share freely, never taking more than you give.
17655 **
17656 ******************************************************************************
17657 **
17658 ** This file contains OS interface code that is common to all
17659 ** architectures.
17660 */
17661 #define _SQLITE_OS_C_ 1
17662 /* #include "sqliteInt.h" */
17663 #undef _SQLITE_OS_C_
17664
17665 /*
17666 ** The default SQLite sqlite3_vfs implementations do not allocate
17667 ** memory (actually, os_unix.c allocates a small amount of memory
17668 ** from within OsOpen()), but some third-party implementations may.
17669 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
17670 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
17671 **
17672 ** The following functions are instrumented for malloc() failure
17673 ** testing:
17674 **
17675 ** sqlite3OsRead()
17676 ** sqlite3OsWrite()
17677 ** sqlite3OsSync()
17678 ** sqlite3OsFileSize()
17679 ** sqlite3OsLock()
17680 ** sqlite3OsCheckReservedLock()
17681 ** sqlite3OsFileControl()
17682 ** sqlite3OsShmMap()
17683 ** sqlite3OsOpen()
17684 ** sqlite3OsDelete()
17685 ** sqlite3OsAccess()
17686 ** sqlite3OsFullPathname()
17687 **
17688 */
17689 #if defined(SQLITE_TEST)
17690 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
17691 #define DO_OS_MALLOC_TEST(x) \
17692 if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
17693 void *pTstAlloc = sqlite3Malloc(10); \
17694 if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
17695 sqlite3_free(pTstAlloc); \
17696 }
17697 #else
17698 #define DO_OS_MALLOC_TEST(x)
17699 #endif
17700
17701 /*
17702 ** The following routines are convenience wrappers around methods
17703 ** of the sqlite3_file object. This is mostly just syntactic sugar. All
17704 ** of this would be completely automatic if SQLite were coded using
17705 ** C++ instead of plain old C.
17706 */
17707 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
17708 int rc = SQLITE_OK;
17709 if( pId->pMethods ){
17710 rc = pId->pMethods->xClose(pId);
17711 pId->pMethods = 0;
17712 }
17713 return rc;
17714 }
17715 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offs et){
17716 DO_OS_MALLOC_TEST(id);
17717 return id->pMethods->xRead(id, pBuf, amt, offset);
17718 }
17719 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i 64 offset){
17720 DO_OS_MALLOC_TEST(id);
17721 return id->pMethods->xWrite(id, pBuf, amt, offset);
17722 }
17723 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
17724 return id->pMethods->xTruncate(id, size);
17725 }
17726 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
17727 DO_OS_MALLOC_TEST(id);
17728 return id->pMethods->xSync(id, flags);
17729 }
17730 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
17731 DO_OS_MALLOC_TEST(id);
17732 return id->pMethods->xFileSize(id, pSize);
17733 }
17734 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
17735 DO_OS_MALLOC_TEST(id);
17736 return id->pMethods->xLock(id, lockType);
17737 }
17738 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
17739 return id->pMethods->xUnlock(id, lockType);
17740 }
17741 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
17742 DO_OS_MALLOC_TEST(id);
17743 return id->pMethods->xCheckReservedLock(id, pResOut);
17744 }
17745
17746 /*
17747 ** Use sqlite3OsFileControl() when we are doing something that might fail
17748 ** and we need to know about the failures. Use sqlite3OsFileControlHint()
17749 ** when simply tossing information over the wall to the VFS and we do not
17750 ** really care if the VFS receives and understands the information since it
17751 ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
17752 ** routine has no return value since the return value would be meaningless.
17753 */
17754 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
17755 #ifdef SQLITE_TEST
17756 if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
17757 /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
17758 ** is using a regular VFS, it is called after the corresponding
17759 ** transaction has been committed. Injecting a fault at this point
17760 ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
17761 ** but the transaction is committed anyway.
17762 **
17763 ** The core must call OsFileControl() though, not OsFileControlHint(),
17764 ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
17765 ** means the commit really has failed and an error should be returned
17766 ** to the user. */
17767 DO_OS_MALLOC_TEST(id);
17768 }
17769 #endif
17770 return id->pMethods->xFileControl(id, op, pArg);
17771 }
17772 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pAr g){
17773 (void)id->pMethods->xFileControl(id, op, pArg);
17774 }
17775
17776 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
17777 int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
17778 return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
17779 }
17780 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
17781 return id->pMethods->xDeviceCharacteristics(id);
17782 }
17783 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int fla gs){
17784 return id->pMethods->xShmLock(id, offset, n, flags);
17785 }
17786 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
17787 id->pMethods->xShmBarrier(id);
17788 }
17789 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
17790 return id->pMethods->xShmUnmap(id, deleteFlag);
17791 }
17792 SQLITE_PRIVATE int sqlite3OsShmMap(
17793 sqlite3_file *id, /* Database file handle */
17794 int iPage,
17795 int pgsz,
17796 int bExtend, /* True to extend file if necessary */
17797 void volatile **pp /* OUT: Pointer to mapping */
17798 ){
17799 DO_OS_MALLOC_TEST(id);
17800 return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
17801 }
17802
17803 #if SQLITE_MAX_MMAP_SIZE>0
17804 /* The real implementation of xFetch and xUnfetch */
17805 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **p p){
17806 DO_OS_MALLOC_TEST(id);
17807 return id->pMethods->xFetch(id, iOff, iAmt, pp);
17808 }
17809 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
17810 return id->pMethods->xUnfetch(id, iOff, p);
17811 }
17812 #else
17813 /* No-op stubs to use when memory-mapped I/O is disabled */
17814 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **p p){
17815 *pp = 0;
17816 return SQLITE_OK;
17817 }
17818 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
17819 return SQLITE_OK;
17820 }
17821 #endif
17822
17823 /*
17824 ** The next group of routines are convenience wrappers around the
17825 ** VFS methods.
17826 */
17827 SQLITE_PRIVATE int sqlite3OsOpen(
17828 sqlite3_vfs *pVfs,
17829 const char *zPath,
17830 sqlite3_file *pFile,
17831 int flags,
17832 int *pFlagsOut
17833 ){
17834 int rc;
17835 DO_OS_MALLOC_TEST(0);
17836 /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
17837 ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
17838 ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
17839 ** reaching the VFS. */
17840 rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
17841 assert( rc==SQLITE_OK || pFile->pMethods==0 );
17842 return rc;
17843 }
17844 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dir Sync){
17845 DO_OS_MALLOC_TEST(0);
17846 assert( dirSync==0 || dirSync==1 );
17847 return pVfs->xDelete(pVfs, zPath, dirSync);
17848 }
17849 SQLITE_PRIVATE int sqlite3OsAccess(
17850 sqlite3_vfs *pVfs,
17851 const char *zPath,
17852 int flags,
17853 int *pResOut
17854 ){
17855 DO_OS_MALLOC_TEST(0);
17856 return pVfs->xAccess(pVfs, zPath, flags, pResOut);
17857 }
17858 SQLITE_PRIVATE int sqlite3OsFullPathname(
17859 sqlite3_vfs *pVfs,
17860 const char *zPath,
17861 int nPathOut,
17862 char *zPathOut
17863 ){
17864 DO_OS_MALLOC_TEST(0);
17865 zPathOut[0] = 0;
17866 return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
17867 }
17868 #ifndef SQLITE_OMIT_LOAD_EXTENSION
17869 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
17870 return pVfs->xDlOpen(pVfs, zPath);
17871 }
17872 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut ){
17873 pVfs->xDlError(pVfs, nByte, zBufOut);
17874 }
17875 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
17876 return pVfs->xDlSym(pVfs, pHdle, zSym);
17877 }
17878 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
17879 pVfs->xDlClose(pVfs, pHandle);
17880 }
17881 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
17882 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufO ut){
17883 return pVfs->xRandomness(pVfs, nByte, zBufOut);
17884 }
17885 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
17886 return pVfs->xSleep(pVfs, nMicro);
17887 }
17888 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p TimeOut){
17889 int rc;
17890 /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
17891 ** method to get the current date and time if that method is available
17892 ** (if iVersion is 2 or greater and the function pointer is not NULL) and
17893 ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
17894 ** unavailable.
17895 */
17896 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
17897 rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
17898 }else{
17899 double r;
17900 rc = pVfs->xCurrentTime(pVfs, &r);
17901 *pTimeOut = (sqlite3_int64)(r*86400000.0);
17902 }
17903 return rc;
17904 }
17905
17906 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
17907 sqlite3_vfs *pVfs,
17908 const char *zFile,
17909 sqlite3_file **ppFile,
17910 int flags,
17911 int *pOutFlags
17912 ){
17913 int rc = SQLITE_NOMEM;
17914 sqlite3_file *pFile;
17915 pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
17916 if( pFile ){
17917 rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
17918 if( rc!=SQLITE_OK ){
17919 sqlite3_free(pFile);
17920 }else{
17921 *ppFile = pFile;
17922 }
17923 }
17924 return rc;
17925 }
17926 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
17927 int rc = SQLITE_OK;
17928 assert( pFile );
17929 rc = sqlite3OsClose(pFile);
17930 sqlite3_free(pFile);
17931 return rc;
17932 }
17933
17934 /*
17935 ** This function is a wrapper around the OS specific implementation of
17936 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
17937 ** ability to simulate a malloc failure, so that the handling of an
17938 ** error in sqlite3_os_init() by the upper layers can be tested.
17939 */
17940 SQLITE_PRIVATE int sqlite3OsInit(void){
17941 void *p = sqlite3_malloc(10);
17942 if( p==0 ) return SQLITE_NOMEM;
17943 sqlite3_free(p);
17944 return sqlite3_os_init();
17945 }
17946
17947 /*
17948 ** The list of all registered VFS implementations.
17949 */
17950 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
17951 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
17952
17953 /*
17954 ** Locate a VFS by name. If no name is given, simply return the
17955 ** first VFS on the list.
17956 */
17957 SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfs){
17958 sqlite3_vfs *pVfs = 0;
17959 #if SQLITE_THREADSAFE
17960 sqlite3_mutex *mutex;
17961 #endif
17962 #ifndef SQLITE_OMIT_AUTOINIT
17963 int rc = sqlite3_initialize();
17964 if( rc ) return 0;
17965 #endif
17966 #if SQLITE_THREADSAFE
17967 mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
17968 #endif
17969 sqlite3_mutex_enter(mutex);
17970 for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
17971 if( zVfs==0 ) break;
17972 if( strcmp(zVfs, pVfs->zName)==0 ) break;
17973 }
17974 sqlite3_mutex_leave(mutex);
17975 return pVfs;
17976 }
17977
17978 /*
17979 ** Unlink a VFS from the linked list
17980 */
17981 static void vfsUnlink(sqlite3_vfs *pVfs){
17982 assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
17983 if( pVfs==0 ){
17984 /* No-op */
17985 }else if( vfsList==pVfs ){
17986 vfsList = pVfs->pNext;
17987 }else if( vfsList ){
17988 sqlite3_vfs *p = vfsList;
17989 while( p->pNext && p->pNext!=pVfs ){
17990 p = p->pNext;
17991 }
17992 if( p->pNext==pVfs ){
17993 p->pNext = pVfs->pNext;
17994 }
17995 }
17996 }
17997
17998 /*
17999 ** Register a VFS with the system. It is harmless to register the same
18000 ** VFS multiple times. The new VFS becomes the default if makeDflt is
18001 ** true.
18002 */
18003 SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDf lt){
18004 MUTEX_LOGIC(sqlite3_mutex *mutex;)
18005 #ifndef SQLITE_OMIT_AUTOINIT
18006 int rc = sqlite3_initialize();
18007 if( rc ) return rc;
18008 #endif
18009 #ifdef SQLITE_ENABLE_API_ARMOR
18010 if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
18011 #endif
18012
18013 MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
18014 sqlite3_mutex_enter(mutex);
18015 vfsUnlink(pVfs);
18016 if( makeDflt || vfsList==0 ){
18017 pVfs->pNext = vfsList;
18018 vfsList = pVfs;
18019 }else{
18020 pVfs->pNext = vfsList->pNext;
18021 vfsList->pNext = pVfs;
18022 }
18023 assert(vfsList);
18024 sqlite3_mutex_leave(mutex);
18025 return SQLITE_OK;
18026 }
18027
18028 /*
18029 ** Unregister a VFS so that it is no longer accessible.
18030 */
18031 SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
18032 #if SQLITE_THREADSAFE
18033 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
18034 #endif
18035 sqlite3_mutex_enter(mutex);
18036 vfsUnlink(pVfs);
18037 sqlite3_mutex_leave(mutex);
18038 return SQLITE_OK;
18039 }
18040
18041 /************** End of os.c **************************************************/
18042 /************** Begin file fault.c *******************************************/
18043 /*
18044 ** 2008 Jan 22
18045 **
18046 ** The author disclaims copyright to this source code. In place of
18047 ** a legal notice, here is a blessing:
18048 **
18049 ** May you do good and not evil.
18050 ** May you find forgiveness for yourself and forgive others.
18051 ** May you share freely, never taking more than you give.
18052 **
18053 *************************************************************************
18054 **
18055 ** This file contains code to support the concept of "benign"
18056 ** malloc failures (when the xMalloc() or xRealloc() method of the
18057 ** sqlite3_mem_methods structure fails to allocate a block of memory
18058 ** and returns 0).
18059 **
18060 ** Most malloc failures are non-benign. After they occur, SQLite
18061 ** abandons the current operation and returns an error code (usually
18062 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
18063 ** fatal. For example, if a malloc fails while resizing a hash table, this
18064 ** is completely recoverable simply by not carrying out the resize. The
18065 ** hash table will continue to function normally. So a malloc failure
18066 ** during a hash table resize is a benign fault.
18067 */
18068
18069 /* #include "sqliteInt.h" */
18070
18071 #ifndef SQLITE_OMIT_BUILTIN_TEST
18072
18073 /*
18074 ** Global variables.
18075 */
18076 typedef struct BenignMallocHooks BenignMallocHooks;
18077 static SQLITE_WSD struct BenignMallocHooks {
18078 void (*xBenignBegin)(void);
18079 void (*xBenignEnd)(void);
18080 } sqlite3Hooks = { 0, 0 };
18081
18082 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
18083 ** structure. If writable static data is unsupported on the target,
18084 ** we have to locate the state vector at run-time. In the more common
18085 ** case where writable static data is supported, wsdHooks can refer directly
18086 ** to the "sqlite3Hooks" state vector declared above.
18087 */
18088 #ifdef SQLITE_OMIT_WSD
18089 # define wsdHooksInit \
18090 BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
18091 # define wsdHooks x[0]
18092 #else
18093 # define wsdHooksInit
18094 # define wsdHooks sqlite3Hooks
18095 #endif
18096
18097
18098 /*
18099 ** Register hooks to call when sqlite3BeginBenignMalloc() and
18100 ** sqlite3EndBenignMalloc() are called, respectively.
18101 */
18102 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
18103 void (*xBenignBegin)(void),
18104 void (*xBenignEnd)(void)
18105 ){
18106 wsdHooksInit;
18107 wsdHooks.xBenignBegin = xBenignBegin;
18108 wsdHooks.xBenignEnd = xBenignEnd;
18109 }
18110
18111 /*
18112 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
18113 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
18114 ** indicates that subsequent malloc failures are non-benign.
18115 */
18116 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
18117 wsdHooksInit;
18118 if( wsdHooks.xBenignBegin ){
18119 wsdHooks.xBenignBegin();
18120 }
18121 }
18122 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
18123 wsdHooksInit;
18124 if( wsdHooks.xBenignEnd ){
18125 wsdHooks.xBenignEnd();
18126 }
18127 }
18128
18129 #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
18130
18131 /************** End of fault.c ***********************************************/
18132 /************** Begin file mem0.c ********************************************/
18133 /*
18134 ** 2008 October 28
18135 **
18136 ** The author disclaims copyright to this source code. In place of
18137 ** a legal notice, here is a blessing:
18138 **
18139 ** May you do good and not evil.
18140 ** May you find forgiveness for yourself and forgive others.
18141 ** May you share freely, never taking more than you give.
18142 **
18143 *************************************************************************
18144 **
18145 ** This file contains a no-op memory allocation drivers for use when
18146 ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
18147 ** here always fail. SQLite will not operate with these drivers. These
18148 ** are merely placeholders. Real drivers must be substituted using
18149 ** sqlite3_config() before SQLite will operate.
18150 */
18151 /* #include "sqliteInt.h" */
18152
18153 /*
18154 ** This version of the memory allocator is the default. It is
18155 ** used when no other memory allocator is specified using compile-time
18156 ** macros.
18157 */
18158 #ifdef SQLITE_ZERO_MALLOC
18159
18160 /*
18161 ** No-op versions of all memory allocation routines
18162 */
18163 static void *sqlite3MemMalloc(int nByte){ return 0; }
18164 static void sqlite3MemFree(void *pPrior){ return; }
18165 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
18166 static int sqlite3MemSize(void *pPrior){ return 0; }
18167 static int sqlite3MemRoundup(int n){ return n; }
18168 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
18169 static void sqlite3MemShutdown(void *NotUsed){ return; }
18170
18171 /*
18172 ** This routine is the only routine in this file with external linkage.
18173 **
18174 ** Populate the low-level memory allocation function pointers in
18175 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
18176 */
18177 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
18178 static const sqlite3_mem_methods defaultMethods = {
18179 sqlite3MemMalloc,
18180 sqlite3MemFree,
18181 sqlite3MemRealloc,
18182 sqlite3MemSize,
18183 sqlite3MemRoundup,
18184 sqlite3MemInit,
18185 sqlite3MemShutdown,
18186 0
18187 };
18188 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
18189 }
18190
18191 #endif /* SQLITE_ZERO_MALLOC */
18192
18193 /************** End of mem0.c ************************************************/
18194 /************** Begin file mem1.c ********************************************/
18195 /*
18196 ** 2007 August 14
18197 **
18198 ** The author disclaims copyright to this source code. In place of
18199 ** a legal notice, here is a blessing:
18200 **
18201 ** May you do good and not evil.
18202 ** May you find forgiveness for yourself and forgive others.
18203 ** May you share freely, never taking more than you give.
18204 **
18205 *************************************************************************
18206 **
18207 ** This file contains low-level memory allocation drivers for when
18208 ** SQLite will use the standard C-library malloc/realloc/free interface
18209 ** to obtain the memory it needs.
18210 **
18211 ** This file contains implementations of the low-level memory allocation
18212 ** routines specified in the sqlite3_mem_methods object. The content of
18213 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
18214 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
18215 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
18216 ** default configuration is to use memory allocation routines in this
18217 ** file.
18218 **
18219 ** C-preprocessor macro summary:
18220 **
18221 ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
18222 ** the malloc_usable_size() interface exists
18223 ** on the target platform. Or, this symbol
18224 ** can be set manually, if desired.
18225 ** If an equivalent interface exists by
18226 ** a different name, using a separate -D
18227 ** option to rename it.
18228 **
18229 ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
18230 ** memory allocator. Set this symbol to enable
18231 ** building on older macs.
18232 **
18233 ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
18234 ** _msize() on windows systems. This might
18235 ** be necessary when compiling for Delphi,
18236 ** for example.
18237 */
18238 /* #include "sqliteInt.h" */
18239
18240 /*
18241 ** This version of the memory allocator is the default. It is
18242 ** used when no other memory allocator is specified using compile-time
18243 ** macros.
18244 */
18245 #ifdef SQLITE_SYSTEM_MALLOC
18246 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
18247
18248 /*
18249 ** Use the zone allocator available on apple products unless the
18250 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
18251 */
18252 #include <sys/sysctl.h>
18253 #include <malloc/malloc.h>
18254 #include <libkern/OSAtomic.h>
18255 static malloc_zone_t* _sqliteZone_;
18256 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
18257 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
18258 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
18259 #define SQLITE_MALLOCSIZE(x) \
18260 (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
18261
18262 #else /* if not __APPLE__ */
18263
18264 /*
18265 ** Use standard C library malloc and free on non-Apple systems.
18266 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
18267 */
18268 #define SQLITE_MALLOC(x) malloc(x)
18269 #define SQLITE_FREE(x) free(x)
18270 #define SQLITE_REALLOC(x,y) realloc((x),(y))
18271
18272 /*
18273 ** The malloc.h header file is needed for malloc_usable_size() function
18274 ** on some systems (e.g. Linux).
18275 */
18276 #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
18277 # define SQLITE_USE_MALLOC_H 1
18278 # define SQLITE_USE_MALLOC_USABLE_SIZE 1
18279 /*
18280 ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
18281 ** use of _msize() is automatic, but can be disabled by compiling with
18282 ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
18283 ** the malloc.h header file.
18284 */
18285 #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
18286 # define SQLITE_USE_MALLOC_H
18287 # define SQLITE_USE_MSIZE
18288 #endif
18289
18290 /*
18291 ** Include the malloc.h header file, if necessary. Also set define macro
18292 ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
18293 ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
18294 ** The memory size function can always be overridden manually by defining
18295 ** the macro SQLITE_MALLOCSIZE to the desired function name.
18296 */
18297 #if defined(SQLITE_USE_MALLOC_H)
18298 # include <malloc.h>
18299 # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
18300 # if !defined(SQLITE_MALLOCSIZE)
18301 # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
18302 # endif
18303 # elif defined(SQLITE_USE_MSIZE)
18304 # if !defined(SQLITE_MALLOCSIZE)
18305 # define SQLITE_MALLOCSIZE _msize
18306 # endif
18307 # endif
18308 #endif /* defined(SQLITE_USE_MALLOC_H) */
18309
18310 #endif /* __APPLE__ or not __APPLE__ */
18311
18312 /*
18313 ** Like malloc(), but remember the size of the allocation
18314 ** so that we can find it later using sqlite3MemSize().
18315 **
18316 ** For this low-level routine, we are guaranteed that nByte>0 because
18317 ** cases of nByte<=0 will be intercepted and dealt with by higher level
18318 ** routines.
18319 */
18320 static void *sqlite3MemMalloc(int nByte){
18321 #ifdef SQLITE_MALLOCSIZE
18322 void *p = SQLITE_MALLOC( nByte );
18323 if( p==0 ){
18324 testcase( sqlite3GlobalConfig.xLog!=0 );
18325 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
18326 }
18327 return p;
18328 #else
18329 sqlite3_int64 *p;
18330 assert( nByte>0 );
18331 nByte = ROUND8(nByte);
18332 p = SQLITE_MALLOC( nByte+8 );
18333 if( p ){
18334 p[0] = nByte;
18335 p++;
18336 }else{
18337 testcase( sqlite3GlobalConfig.xLog!=0 );
18338 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
18339 }
18340 return (void *)p;
18341 #endif
18342 }
18343
18344 /*
18345 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
18346 ** or sqlite3MemRealloc().
18347 **
18348 ** For this low-level routine, we already know that pPrior!=0 since
18349 ** cases where pPrior==0 will have been intecepted and dealt with
18350 ** by higher-level routines.
18351 */
18352 static void sqlite3MemFree(void *pPrior){
18353 #ifdef SQLITE_MALLOCSIZE
18354 SQLITE_FREE(pPrior);
18355 #else
18356 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
18357 assert( pPrior!=0 );
18358 p--;
18359 SQLITE_FREE(p);
18360 #endif
18361 }
18362
18363 /*
18364 ** Report the allocated size of a prior return from xMalloc()
18365 ** or xRealloc().
18366 */
18367 static int sqlite3MemSize(void *pPrior){
18368 #ifdef SQLITE_MALLOCSIZE
18369 assert( pPrior!=0 );
18370 return (int)SQLITE_MALLOCSIZE(pPrior);
18371 #else
18372 sqlite3_int64 *p;
18373 assert( pPrior!=0 );
18374 p = (sqlite3_int64*)pPrior;
18375 p--;
18376 return (int)p[0];
18377 #endif
18378 }
18379
18380 /*
18381 ** Like realloc(). Resize an allocation previously obtained from
18382 ** sqlite3MemMalloc().
18383 **
18384 ** For this low-level interface, we know that pPrior!=0. Cases where
18385 ** pPrior==0 while have been intercepted by higher-level routine and
18386 ** redirected to xMalloc. Similarly, we know that nByte>0 because
18387 ** cases where nByte<=0 will have been intercepted by higher-level
18388 ** routines and redirected to xFree.
18389 */
18390 static void *sqlite3MemRealloc(void *pPrior, int nByte){
18391 #ifdef SQLITE_MALLOCSIZE
18392 void *p = SQLITE_REALLOC(pPrior, nByte);
18393 if( p==0 ){
18394 testcase( sqlite3GlobalConfig.xLog!=0 );
18395 sqlite3_log(SQLITE_NOMEM,
18396 "failed memory resize %u to %u bytes",
18397 SQLITE_MALLOCSIZE(pPrior), nByte);
18398 }
18399 return p;
18400 #else
18401 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
18402 assert( pPrior!=0 && nByte>0 );
18403 assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
18404 p--;
18405 p = SQLITE_REALLOC(p, nByte+8 );
18406 if( p ){
18407 p[0] = nByte;
18408 p++;
18409 }else{
18410 testcase( sqlite3GlobalConfig.xLog!=0 );
18411 sqlite3_log(SQLITE_NOMEM,
18412 "failed memory resize %u to %u bytes",
18413 sqlite3MemSize(pPrior), nByte);
18414 }
18415 return (void*)p;
18416 #endif
18417 }
18418
18419 /*
18420 ** Round up a request size to the next valid allocation size.
18421 */
18422 static int sqlite3MemRoundup(int n){
18423 return ROUND8(n);
18424 }
18425
18426 /*
18427 ** Initialize this module.
18428 */
18429 static int sqlite3MemInit(void *NotUsed){
18430 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
18431 int cpuCount;
18432 size_t len;
18433 if( _sqliteZone_ ){
18434 return SQLITE_OK;
18435 }
18436 len = sizeof(cpuCount);
18437 /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
18438 sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
18439 if( cpuCount>1 ){
18440 /* defer MT decisions to system malloc */
18441 _sqliteZone_ = malloc_default_zone();
18442 }else{
18443 /* only 1 core, use our own zone to contention over global locks,
18444 ** e.g. we have our own dedicated locks */
18445 bool success;
18446 malloc_zone_t* newzone = malloc_create_zone(4096, 0);
18447 malloc_set_zone_name(newzone, "Sqlite_Heap");
18448 do{
18449 success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
18450 (void * volatile *)&_sqliteZone_);
18451 }while(!_sqliteZone_);
18452 if( !success ){
18453 /* somebody registered a zone first */
18454 malloc_destroy_zone(newzone);
18455 }
18456 }
18457 #endif
18458 UNUSED_PARAMETER(NotUsed);
18459 return SQLITE_OK;
18460 }
18461
18462 /*
18463 ** Deinitialize this module.
18464 */
18465 static void sqlite3MemShutdown(void *NotUsed){
18466 UNUSED_PARAMETER(NotUsed);
18467 return;
18468 }
18469
18470 /*
18471 ** This routine is the only routine in this file with external linkage.
18472 **
18473 ** Populate the low-level memory allocation function pointers in
18474 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
18475 */
18476 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
18477 static const sqlite3_mem_methods defaultMethods = {
18478 sqlite3MemMalloc,
18479 sqlite3MemFree,
18480 sqlite3MemRealloc,
18481 sqlite3MemSize,
18482 sqlite3MemRoundup,
18483 sqlite3MemInit,
18484 sqlite3MemShutdown,
18485 0
18486 };
18487 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
18488 }
18489
18490 #endif /* SQLITE_SYSTEM_MALLOC */
18491
18492 /************** End of mem1.c ************************************************/
18493 /************** Begin file mem2.c ********************************************/
18494 /*
18495 ** 2007 August 15
18496 **
18497 ** The author disclaims copyright to this source code. In place of
18498 ** a legal notice, here is a blessing:
18499 **
18500 ** May you do good and not evil.
18501 ** May you find forgiveness for yourself and forgive others.
18502 ** May you share freely, never taking more than you give.
18503 **
18504 *************************************************************************
18505 **
18506 ** This file contains low-level memory allocation drivers for when
18507 ** SQLite will use the standard C-library malloc/realloc/free interface
18508 ** to obtain the memory it needs while adding lots of additional debugging
18509 ** information to each allocation in order to help detect and fix memory
18510 ** leaks and memory usage errors.
18511 **
18512 ** This file contains implementations of the low-level memory allocation
18513 ** routines specified in the sqlite3_mem_methods object.
18514 */
18515 /* #include "sqliteInt.h" */
18516
18517 /*
18518 ** This version of the memory allocator is used only if the
18519 ** SQLITE_MEMDEBUG macro is defined
18520 */
18521 #ifdef SQLITE_MEMDEBUG
18522
18523 /*
18524 ** The backtrace functionality is only available with GLIBC
18525 */
18526 #ifdef __GLIBC__
18527 extern int backtrace(void**,int);
18528 extern void backtrace_symbols_fd(void*const*,int,int);
18529 #else
18530 # define backtrace(A,B) 1
18531 # define backtrace_symbols_fd(A,B,C)
18532 #endif
18533 /* #include <stdio.h> */
18534
18535 /*
18536 ** Each memory allocation looks like this:
18537 **
18538 ** ------------------------------------------------------------------------
18539 ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
18540 ** ------------------------------------------------------------------------
18541 **
18542 ** The application code sees only a pointer to the allocation. We have
18543 ** to back up from the allocation pointer to find the MemBlockHdr. The
18544 ** MemBlockHdr tells us the size of the allocation and the number of
18545 ** backtrace pointers. There is also a guard word at the end of the
18546 ** MemBlockHdr.
18547 */
18548 struct MemBlockHdr {
18549 i64 iSize; /* Size of this allocation */
18550 struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
18551 char nBacktrace; /* Number of backtraces on this alloc */
18552 char nBacktraceSlots; /* Available backtrace slots */
18553 u8 nTitle; /* Bytes of title; includes '\0' */
18554 u8 eType; /* Allocation type code */
18555 int iForeGuard; /* Guard word for sanity */
18556 };
18557
18558 /*
18559 ** Guard words
18560 */
18561 #define FOREGUARD 0x80F5E153
18562 #define REARGUARD 0xE4676B53
18563
18564 /*
18565 ** Number of malloc size increments to track.
18566 */
18567 #define NCSIZE 1000
18568
18569 /*
18570 ** All of the static variables used by this module are collected
18571 ** into a single structure named "mem". This is to keep the
18572 ** static variables organized and to reduce namespace pollution
18573 ** when this module is combined with other in the amalgamation.
18574 */
18575 static struct {
18576
18577 /*
18578 ** Mutex to control access to the memory allocation subsystem.
18579 */
18580 sqlite3_mutex *mutex;
18581
18582 /*
18583 ** Head and tail of a linked list of all outstanding allocations
18584 */
18585 struct MemBlockHdr *pFirst;
18586 struct MemBlockHdr *pLast;
18587
18588 /*
18589 ** The number of levels of backtrace to save in new allocations.
18590 */
18591 int nBacktrace;
18592 void (*xBacktrace)(int, int, void **);
18593
18594 /*
18595 ** Title text to insert in front of each block
18596 */
18597 int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
18598 char zTitle[100]; /* The title text */
18599
18600 /*
18601 ** sqlite3MallocDisallow() increments the following counter.
18602 ** sqlite3MallocAllow() decrements it.
18603 */
18604 int disallow; /* Do not allow memory allocation */
18605
18606 /*
18607 ** Gather statistics on the sizes of memory allocations.
18608 ** nAlloc[i] is the number of allocation attempts of i*8
18609 ** bytes. i==NCSIZE is the number of allocation attempts for
18610 ** sizes more than NCSIZE*8 bytes.
18611 */
18612 int nAlloc[NCSIZE]; /* Total number of allocations */
18613 int nCurrent[NCSIZE]; /* Current number of allocations */
18614 int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
18615
18616 } mem;
18617
18618
18619 /*
18620 ** Adjust memory usage statistics
18621 */
18622 static void adjustStats(int iSize, int increment){
18623 int i = ROUND8(iSize)/8;
18624 if( i>NCSIZE-1 ){
18625 i = NCSIZE - 1;
18626 }
18627 if( increment>0 ){
18628 mem.nAlloc[i]++;
18629 mem.nCurrent[i]++;
18630 if( mem.nCurrent[i]>mem.mxCurrent[i] ){
18631 mem.mxCurrent[i] = mem.nCurrent[i];
18632 }
18633 }else{
18634 mem.nCurrent[i]--;
18635 assert( mem.nCurrent[i]>=0 );
18636 }
18637 }
18638
18639 /*
18640 ** Given an allocation, find the MemBlockHdr for that allocation.
18641 **
18642 ** This routine checks the guards at either end of the allocation and
18643 ** if they are incorrect it asserts.
18644 */
18645 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
18646 struct MemBlockHdr *p;
18647 int *pInt;
18648 u8 *pU8;
18649 int nReserve;
18650
18651 p = (struct MemBlockHdr*)pAllocation;
18652 p--;
18653 assert( p->iForeGuard==(int)FOREGUARD );
18654 nReserve = ROUND8(p->iSize);
18655 pInt = (int*)pAllocation;
18656 pU8 = (u8*)pAllocation;
18657 assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
18658 /* This checks any of the "extra" bytes allocated due
18659 ** to rounding up to an 8 byte boundary to ensure
18660 ** they haven't been overwritten.
18661 */
18662 while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
18663 return p;
18664 }
18665
18666 /*
18667 ** Return the number of bytes currently allocated at address p.
18668 */
18669 static int sqlite3MemSize(void *p){
18670 struct MemBlockHdr *pHdr;
18671 if( !p ){
18672 return 0;
18673 }
18674 pHdr = sqlite3MemsysGetHeader(p);
18675 return (int)pHdr->iSize;
18676 }
18677
18678 /*
18679 ** Initialize the memory allocation subsystem.
18680 */
18681 static int sqlite3MemInit(void *NotUsed){
18682 UNUSED_PARAMETER(NotUsed);
18683 assert( (sizeof(struct MemBlockHdr)&7) == 0 );
18684 if( !sqlite3GlobalConfig.bMemstat ){
18685 /* If memory status is enabled, then the malloc.c wrapper will already
18686 ** hold the STATIC_MEM mutex when the routines here are invoked. */
18687 mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18688 }
18689 return SQLITE_OK;
18690 }
18691
18692 /*
18693 ** Deinitialize the memory allocation subsystem.
18694 */
18695 static void sqlite3MemShutdown(void *NotUsed){
18696 UNUSED_PARAMETER(NotUsed);
18697 mem.mutex = 0;
18698 }
18699
18700 /*
18701 ** Round up a request size to the next valid allocation size.
18702 */
18703 static int sqlite3MemRoundup(int n){
18704 return ROUND8(n);
18705 }
18706
18707 /*
18708 ** Fill a buffer with pseudo-random bytes. This is used to preset
18709 ** the content of a new memory allocation to unpredictable values and
18710 ** to clear the content of a freed allocation to unpredictable values.
18711 */
18712 static void randomFill(char *pBuf, int nByte){
18713 unsigned int x, y, r;
18714 x = SQLITE_PTR_TO_INT(pBuf);
18715 y = nByte | 1;
18716 while( nByte >= 4 ){
18717 x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
18718 y = y*1103515245 + 12345;
18719 r = x ^ y;
18720 *(int*)pBuf = r;
18721 pBuf += 4;
18722 nByte -= 4;
18723 }
18724 while( nByte-- > 0 ){
18725 x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
18726 y = y*1103515245 + 12345;
18727 r = x ^ y;
18728 *(pBuf++) = r & 0xff;
18729 }
18730 }
18731
18732 /*
18733 ** Allocate nByte bytes of memory.
18734 */
18735 static void *sqlite3MemMalloc(int nByte){
18736 struct MemBlockHdr *pHdr;
18737 void **pBt;
18738 char *z;
18739 int *pInt;
18740 void *p = 0;
18741 int totalSize;
18742 int nReserve;
18743 sqlite3_mutex_enter(mem.mutex);
18744 assert( mem.disallow==0 );
18745 nReserve = ROUND8(nByte);
18746 totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
18747 mem.nBacktrace*sizeof(void*) + mem.nTitle;
18748 p = malloc(totalSize);
18749 if( p ){
18750 z = p;
18751 pBt = (void**)&z[mem.nTitle];
18752 pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
18753 pHdr->pNext = 0;
18754 pHdr->pPrev = mem.pLast;
18755 if( mem.pLast ){
18756 mem.pLast->pNext = pHdr;
18757 }else{
18758 mem.pFirst = pHdr;
18759 }
18760 mem.pLast = pHdr;
18761 pHdr->iForeGuard = FOREGUARD;
18762 pHdr->eType = MEMTYPE_HEAP;
18763 pHdr->nBacktraceSlots = mem.nBacktrace;
18764 pHdr->nTitle = mem.nTitle;
18765 if( mem.nBacktrace ){
18766 void *aAddr[40];
18767 pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
18768 memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
18769 assert(pBt[0]);
18770 if( mem.xBacktrace ){
18771 mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
18772 }
18773 }else{
18774 pHdr->nBacktrace = 0;
18775 }
18776 if( mem.nTitle ){
18777 memcpy(z, mem.zTitle, mem.nTitle);
18778 }
18779 pHdr->iSize = nByte;
18780 adjustStats(nByte, +1);
18781 pInt = (int*)&pHdr[1];
18782 pInt[nReserve/sizeof(int)] = REARGUARD;
18783 randomFill((char*)pInt, nByte);
18784 memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
18785 p = (void*)pInt;
18786 }
18787 sqlite3_mutex_leave(mem.mutex);
18788 return p;
18789 }
18790
18791 /*
18792 ** Free memory.
18793 */
18794 static void sqlite3MemFree(void *pPrior){
18795 struct MemBlockHdr *pHdr;
18796 void **pBt;
18797 char *z;
18798 assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
18799 || mem.mutex!=0 );
18800 pHdr = sqlite3MemsysGetHeader(pPrior);
18801 pBt = (void**)pHdr;
18802 pBt -= pHdr->nBacktraceSlots;
18803 sqlite3_mutex_enter(mem.mutex);
18804 if( pHdr->pPrev ){
18805 assert( pHdr->pPrev->pNext==pHdr );
18806 pHdr->pPrev->pNext = pHdr->pNext;
18807 }else{
18808 assert( mem.pFirst==pHdr );
18809 mem.pFirst = pHdr->pNext;
18810 }
18811 if( pHdr->pNext ){
18812 assert( pHdr->pNext->pPrev==pHdr );
18813 pHdr->pNext->pPrev = pHdr->pPrev;
18814 }else{
18815 assert( mem.pLast==pHdr );
18816 mem.pLast = pHdr->pPrev;
18817 }
18818 z = (char*)pBt;
18819 z -= pHdr->nTitle;
18820 adjustStats((int)pHdr->iSize, -1);
18821 randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
18822 (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
18823 free(z);
18824 sqlite3_mutex_leave(mem.mutex);
18825 }
18826
18827 /*
18828 ** Change the size of an existing memory allocation.
18829 **
18830 ** For this debugging implementation, we *always* make a copy of the
18831 ** allocation into a new place in memory. In this way, if the
18832 ** higher level code is using pointer to the old allocation, it is
18833 ** much more likely to break and we are much more liking to find
18834 ** the error.
18835 */
18836 static void *sqlite3MemRealloc(void *pPrior, int nByte){
18837 struct MemBlockHdr *pOldHdr;
18838 void *pNew;
18839 assert( mem.disallow==0 );
18840 assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
18841 pOldHdr = sqlite3MemsysGetHeader(pPrior);
18842 pNew = sqlite3MemMalloc(nByte);
18843 if( pNew ){
18844 memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
18845 if( nByte>pOldHdr->iSize ){
18846 randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
18847 }
18848 sqlite3MemFree(pPrior);
18849 }
18850 return pNew;
18851 }
18852
18853 /*
18854 ** Populate the low-level memory allocation function pointers in
18855 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
18856 */
18857 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
18858 static const sqlite3_mem_methods defaultMethods = {
18859 sqlite3MemMalloc,
18860 sqlite3MemFree,
18861 sqlite3MemRealloc,
18862 sqlite3MemSize,
18863 sqlite3MemRoundup,
18864 sqlite3MemInit,
18865 sqlite3MemShutdown,
18866 0
18867 };
18868 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
18869 }
18870
18871 /*
18872 ** Set the "type" of an allocation.
18873 */
18874 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
18875 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
18876 struct MemBlockHdr *pHdr;
18877 pHdr = sqlite3MemsysGetHeader(p);
18878 assert( pHdr->iForeGuard==FOREGUARD );
18879 pHdr->eType = eType;
18880 }
18881 }
18882
18883 /*
18884 ** Return TRUE if the mask of type in eType matches the type of the
18885 ** allocation p. Also return true if p==NULL.
18886 **
18887 ** This routine is designed for use within an assert() statement, to
18888 ** verify the type of an allocation. For example:
18889 **
18890 ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
18891 */
18892 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
18893 int rc = 1;
18894 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
18895 struct MemBlockHdr *pHdr;
18896 pHdr = sqlite3MemsysGetHeader(p);
18897 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
18898 if( (pHdr->eType&eType)==0 ){
18899 rc = 0;
18900 }
18901 }
18902 return rc;
18903 }
18904
18905 /*
18906 ** Return TRUE if the mask of type in eType matches no bits of the type of the
18907 ** allocation p. Also return true if p==NULL.
18908 **
18909 ** This routine is designed for use within an assert() statement, to
18910 ** verify the type of an allocation. For example:
18911 **
18912 ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18913 */
18914 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
18915 int rc = 1;
18916 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
18917 struct MemBlockHdr *pHdr;
18918 pHdr = sqlite3MemsysGetHeader(p);
18919 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
18920 if( (pHdr->eType&eType)!=0 ){
18921 rc = 0;
18922 }
18923 }
18924 return rc;
18925 }
18926
18927 /*
18928 ** Set the number of backtrace levels kept for each allocation.
18929 ** A value of zero turns off backtracing. The number is always rounded
18930 ** up to a multiple of 2.
18931 */
18932 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
18933 if( depth<0 ){ depth = 0; }
18934 if( depth>20 ){ depth = 20; }
18935 depth = (depth+1)&0xfe;
18936 mem.nBacktrace = depth;
18937 }
18938
18939 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int , void **)){
18940 mem.xBacktrace = xBacktrace;
18941 }
18942
18943 /*
18944 ** Set the title string for subsequent allocations.
18945 */
18946 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
18947 unsigned int n = sqlite3Strlen30(zTitle) + 1;
18948 sqlite3_mutex_enter(mem.mutex);
18949 if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
18950 memcpy(mem.zTitle, zTitle, n);
18951 mem.zTitle[n] = 0;
18952 mem.nTitle = ROUND8(n);
18953 sqlite3_mutex_leave(mem.mutex);
18954 }
18955
18956 SQLITE_PRIVATE void sqlite3MemdebugSync(){
18957 struct MemBlockHdr *pHdr;
18958 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
18959 void **pBt = (void**)pHdr;
18960 pBt -= pHdr->nBacktraceSlots;
18961 mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
18962 }
18963 }
18964
18965 /*
18966 ** Open the file indicated and write a log of all unfreed memory
18967 ** allocations into that log.
18968 */
18969 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
18970 FILE *out;
18971 struct MemBlockHdr *pHdr;
18972 void **pBt;
18973 int i;
18974 out = fopen(zFilename, "w");
18975 if( out==0 ){
18976 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
18977 zFilename);
18978 return;
18979 }
18980 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
18981 char *z = (char*)pHdr;
18982 z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
18983 fprintf(out, "**** %lld bytes at %p from %s ****\n",
18984 pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
18985 if( pHdr->nBacktrace ){
18986 fflush(out);
18987 pBt = (void**)pHdr;
18988 pBt -= pHdr->nBacktraceSlots;
18989 backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
18990 fprintf(out, "\n");
18991 }
18992 }
18993 fprintf(out, "COUNTS:\n");
18994 for(i=0; i<NCSIZE-1; i++){
18995 if( mem.nAlloc[i] ){
18996 fprintf(out, " %5d: %10d %10d %10d\n",
18997 i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
18998 }
18999 }
19000 if( mem.nAlloc[NCSIZE-1] ){
19001 fprintf(out, " %5d: %10d %10d %10d\n",
19002 NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
19003 mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
19004 }
19005 fclose(out);
19006 }
19007
19008 /*
19009 ** Return the number of times sqlite3MemMalloc() has been called.
19010 */
19011 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
19012 int i;
19013 int nTotal = 0;
19014 for(i=0; i<NCSIZE; i++){
19015 nTotal += mem.nAlloc[i];
19016 }
19017 return nTotal;
19018 }
19019
19020
19021 #endif /* SQLITE_MEMDEBUG */
19022
19023 /************** End of mem2.c ************************************************/
19024 /************** Begin file mem3.c ********************************************/
19025 /*
19026 ** 2007 October 14
19027 **
19028 ** The author disclaims copyright to this source code. In place of
19029 ** a legal notice, here is a blessing:
19030 **
19031 ** May you do good and not evil.
19032 ** May you find forgiveness for yourself and forgive others.
19033 ** May you share freely, never taking more than you give.
19034 **
19035 *************************************************************************
19036 ** This file contains the C functions that implement a memory
19037 ** allocation subsystem for use by SQLite.
19038 **
19039 ** This version of the memory allocation subsystem omits all
19040 ** use of malloc(). The SQLite user supplies a block of memory
19041 ** before calling sqlite3_initialize() from which allocations
19042 ** are made and returned by the xMalloc() and xRealloc()
19043 ** implementations. Once sqlite3_initialize() has been called,
19044 ** the amount of memory available to SQLite is fixed and cannot
19045 ** be changed.
19046 **
19047 ** This version of the memory allocation subsystem is included
19048 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
19049 */
19050 /* #include "sqliteInt.h" */
19051
19052 /*
19053 ** This version of the memory allocator is only built into the library
19054 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
19055 ** mean that the library will use a memory-pool by default, just that
19056 ** it is available. The mempool allocator is activated by calling
19057 ** sqlite3_config().
19058 */
19059 #ifdef SQLITE_ENABLE_MEMSYS3
19060
19061 /*
19062 ** Maximum size (in Mem3Blocks) of a "small" chunk.
19063 */
19064 #define MX_SMALL 10
19065
19066
19067 /*
19068 ** Number of freelist hash slots
19069 */
19070 #define N_HASH 61
19071
19072 /*
19073 ** A memory allocation (also called a "chunk") consists of two or
19074 ** more blocks where each block is 8 bytes. The first 8 bytes are
19075 ** a header that is not returned to the user.
19076 **
19077 ** A chunk is two or more blocks that is either checked out or
19078 ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
19079 ** size of the allocation in blocks if the allocation is free.
19080 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
19081 ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
19082 ** is true if the previous chunk is checked out and false if the
19083 ** previous chunk is free. The u.hdr.prevSize field is the size of
19084 ** the previous chunk in blocks if the previous chunk is on the
19085 ** freelist. If the previous chunk is checked out, then
19086 ** u.hdr.prevSize can be part of the data for that chunk and should
19087 ** not be read or written.
19088 **
19089 ** We often identify a chunk by its index in mem3.aPool[]. When
19090 ** this is done, the chunk index refers to the second block of
19091 ** the chunk. In this way, the first chunk has an index of 1.
19092 ** A chunk index of 0 means "no such chunk" and is the equivalent
19093 ** of a NULL pointer.
19094 **
19095 ** The second block of free chunks is of the form u.list. The
19096 ** two fields form a double-linked list of chunks of related sizes.
19097 ** Pointers to the head of the list are stored in mem3.aiSmall[]
19098 ** for smaller chunks and mem3.aiHash[] for larger chunks.
19099 **
19100 ** The second block of a chunk is user data if the chunk is checked
19101 ** out. If a chunk is checked out, the user data may extend into
19102 ** the u.hdr.prevSize value of the following chunk.
19103 */
19104 typedef struct Mem3Block Mem3Block;
19105 struct Mem3Block {
19106 union {
19107 struct {
19108 u32 prevSize; /* Size of previous chunk in Mem3Block elements */
19109 u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
19110 } hdr;
19111 struct {
19112 u32 next; /* Index in mem3.aPool[] of next free chunk */
19113 u32 prev; /* Index in mem3.aPool[] of previous free chunk */
19114 } list;
19115 } u;
19116 };
19117
19118 /*
19119 ** All of the static variables used by this module are collected
19120 ** into a single structure named "mem3". This is to keep the
19121 ** static variables organized and to reduce namespace pollution
19122 ** when this module is combined with other in the amalgamation.
19123 */
19124 static SQLITE_WSD struct Mem3Global {
19125 /*
19126 ** Memory available for allocation. nPool is the size of the array
19127 ** (in Mem3Blocks) pointed to by aPool less 2.
19128 */
19129 u32 nPool;
19130 Mem3Block *aPool;
19131
19132 /*
19133 ** True if we are evaluating an out-of-memory callback.
19134 */
19135 int alarmBusy;
19136
19137 /*
19138 ** Mutex to control access to the memory allocation subsystem.
19139 */
19140 sqlite3_mutex *mutex;
19141
19142 /*
19143 ** The minimum amount of free space that we have seen.
19144 */
19145 u32 mnMaster;
19146
19147 /*
19148 ** iMaster is the index of the master chunk. Most new allocations
19149 ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
19150 ** of the current master. iMaster is 0 if there is not master chunk.
19151 ** The master chunk is not in either the aiHash[] or aiSmall[].
19152 */
19153 u32 iMaster;
19154 u32 szMaster;
19155
19156 /*
19157 ** Array of lists of free blocks according to the block size
19158 ** for smaller chunks, or a hash on the block size for larger
19159 ** chunks.
19160 */
19161 u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
19162 u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
19163 } mem3 = { 97535575 };
19164
19165 #define mem3 GLOBAL(struct Mem3Global, mem3)
19166
19167 /*
19168 ** Unlink the chunk at mem3.aPool[i] from list it is currently
19169 ** on. *pRoot is the list that i is a member of.
19170 */
19171 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
19172 u32 next = mem3.aPool[i].u.list.next;
19173 u32 prev = mem3.aPool[i].u.list.prev;
19174 assert( sqlite3_mutex_held(mem3.mutex) );
19175 if( prev==0 ){
19176 *pRoot = next;
19177 }else{
19178 mem3.aPool[prev].u.list.next = next;
19179 }
19180 if( next ){
19181 mem3.aPool[next].u.list.prev = prev;
19182 }
19183 mem3.aPool[i].u.list.next = 0;
19184 mem3.aPool[i].u.list.prev = 0;
19185 }
19186
19187 /*
19188 ** Unlink the chunk at index i from
19189 ** whatever list is currently a member of.
19190 */
19191 static void memsys3Unlink(u32 i){
19192 u32 size, hash;
19193 assert( sqlite3_mutex_held(mem3.mutex) );
19194 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
19195 assert( i>=1 );
19196 size = mem3.aPool[i-1].u.hdr.size4x/4;
19197 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
19198 assert( size>=2 );
19199 if( size <= MX_SMALL ){
19200 memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
19201 }else{
19202 hash = size % N_HASH;
19203 memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
19204 }
19205 }
19206
19207 /*
19208 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
19209 ** at *pRoot.
19210 */
19211 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
19212 assert( sqlite3_mutex_held(mem3.mutex) );
19213 mem3.aPool[i].u.list.next = *pRoot;
19214 mem3.aPool[i].u.list.prev = 0;
19215 if( *pRoot ){
19216 mem3.aPool[*pRoot].u.list.prev = i;
19217 }
19218 *pRoot = i;
19219 }
19220
19221 /*
19222 ** Link the chunk at index i into either the appropriate
19223 ** small chunk list, or into the large chunk hash table.
19224 */
19225 static void memsys3Link(u32 i){
19226 u32 size, hash;
19227 assert( sqlite3_mutex_held(mem3.mutex) );
19228 assert( i>=1 );
19229 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
19230 size = mem3.aPool[i-1].u.hdr.size4x/4;
19231 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
19232 assert( size>=2 );
19233 if( size <= MX_SMALL ){
19234 memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
19235 }else{
19236 hash = size % N_HASH;
19237 memsys3LinkIntoList(i, &mem3.aiHash[hash]);
19238 }
19239 }
19240
19241 /*
19242 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
19243 ** will already be held (obtained by code in malloc.c) if
19244 ** sqlite3GlobalConfig.bMemStat is true.
19245 */
19246 static void memsys3Enter(void){
19247 if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
19248 mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
19249 }
19250 sqlite3_mutex_enter(mem3.mutex);
19251 }
19252 static void memsys3Leave(void){
19253 sqlite3_mutex_leave(mem3.mutex);
19254 }
19255
19256 /*
19257 ** Called when we are unable to satisfy an allocation of nBytes.
19258 */
19259 static void memsys3OutOfMemory(int nByte){
19260 if( !mem3.alarmBusy ){
19261 mem3.alarmBusy = 1;
19262 assert( sqlite3_mutex_held(mem3.mutex) );
19263 sqlite3_mutex_leave(mem3.mutex);
19264 sqlite3_release_memory(nByte);
19265 sqlite3_mutex_enter(mem3.mutex);
19266 mem3.alarmBusy = 0;
19267 }
19268 }
19269
19270
19271 /*
19272 ** Chunk i is a free chunk that has been unlinked. Adjust its
19273 ** size parameters for check-out and return a pointer to the
19274 ** user portion of the chunk.
19275 */
19276 static void *memsys3Checkout(u32 i, u32 nBlock){
19277 u32 x;
19278 assert( sqlite3_mutex_held(mem3.mutex) );
19279 assert( i>=1 );
19280 assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
19281 assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
19282 x = mem3.aPool[i-1].u.hdr.size4x;
19283 mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
19284 mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
19285 mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
19286 return &mem3.aPool[i];
19287 }
19288
19289 /*
19290 ** Carve a piece off of the end of the mem3.iMaster free chunk.
19291 ** Return a pointer to the new allocation. Or, if the master chunk
19292 ** is not large enough, return 0.
19293 */
19294 static void *memsys3FromMaster(u32 nBlock){
19295 assert( sqlite3_mutex_held(mem3.mutex) );
19296 assert( mem3.szMaster>=nBlock );
19297 if( nBlock>=mem3.szMaster-1 ){
19298 /* Use the entire master */
19299 void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
19300 mem3.iMaster = 0;
19301 mem3.szMaster = 0;
19302 mem3.mnMaster = 0;
19303 return p;
19304 }else{
19305 /* Split the master block. Return the tail. */
19306 u32 newi, x;
19307 newi = mem3.iMaster + mem3.szMaster - nBlock;
19308 assert( newi > mem3.iMaster+1 );
19309 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
19310 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
19311 mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
19312 mem3.szMaster -= nBlock;
19313 mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
19314 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
19315 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
19316 if( mem3.szMaster < mem3.mnMaster ){
19317 mem3.mnMaster = mem3.szMaster;
19318 }
19319 return (void*)&mem3.aPool[newi];
19320 }
19321 }
19322
19323 /*
19324 ** *pRoot is the head of a list of free chunks of the same size
19325 ** or same size hash. In other words, *pRoot is an entry in either
19326 ** mem3.aiSmall[] or mem3.aiHash[].
19327 **
19328 ** This routine examines all entries on the given list and tries
19329 ** to coalesce each entries with adjacent free chunks.
19330 **
19331 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
19332 ** the current mem3.iMaster with the new larger chunk. In order for
19333 ** this mem3.iMaster replacement to work, the master chunk must be
19334 ** linked into the hash tables. That is not the normal state of
19335 ** affairs, of course. The calling routine must link the master
19336 ** chunk before invoking this routine, then must unlink the (possibly
19337 ** changed) master chunk once this routine has finished.
19338 */
19339 static void memsys3Merge(u32 *pRoot){
19340 u32 iNext, prev, size, i, x;
19341
19342 assert( sqlite3_mutex_held(mem3.mutex) );
19343 for(i=*pRoot; i>0; i=iNext){
19344 iNext = mem3.aPool[i].u.list.next;
19345 size = mem3.aPool[i-1].u.hdr.size4x;
19346 assert( (size&1)==0 );
19347 if( (size&2)==0 ){
19348 memsys3UnlinkFromList(i, pRoot);
19349 assert( i > mem3.aPool[i-1].u.hdr.prevSize );
19350 prev = i - mem3.aPool[i-1].u.hdr.prevSize;
19351 if( prev==iNext ){
19352 iNext = mem3.aPool[prev].u.list.next;
19353 }
19354 memsys3Unlink(prev);
19355 size = i + size/4 - prev;
19356 x = mem3.aPool[prev-1].u.hdr.size4x & 2;
19357 mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
19358 mem3.aPool[prev+size-1].u.hdr.prevSize = size;
19359 memsys3Link(prev);
19360 i = prev;
19361 }else{
19362 size /= 4;
19363 }
19364 if( size>mem3.szMaster ){
19365 mem3.iMaster = i;
19366 mem3.szMaster = size;
19367 }
19368 }
19369 }
19370
19371 /*
19372 ** Return a block of memory of at least nBytes in size.
19373 ** Return NULL if unable.
19374 **
19375 ** This function assumes that the necessary mutexes, if any, are
19376 ** already held by the caller. Hence "Unsafe".
19377 */
19378 static void *memsys3MallocUnsafe(int nByte){
19379 u32 i;
19380 u32 nBlock;
19381 u32 toFree;
19382
19383 assert( sqlite3_mutex_held(mem3.mutex) );
19384 assert( sizeof(Mem3Block)==8 );
19385 if( nByte<=12 ){
19386 nBlock = 2;
19387 }else{
19388 nBlock = (nByte + 11)/8;
19389 }
19390 assert( nBlock>=2 );
19391
19392 /* STEP 1:
19393 ** Look for an entry of the correct size in either the small
19394 ** chunk table or in the large chunk hash table. This is
19395 ** successful most of the time (about 9 times out of 10).
19396 */
19397 if( nBlock <= MX_SMALL ){
19398 i = mem3.aiSmall[nBlock-2];
19399 if( i>0 ){
19400 memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
19401 return memsys3Checkout(i, nBlock);
19402 }
19403 }else{
19404 int hash = nBlock % N_HASH;
19405 for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
19406 if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
19407 memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
19408 return memsys3Checkout(i, nBlock);
19409 }
19410 }
19411 }
19412
19413 /* STEP 2:
19414 ** Try to satisfy the allocation by carving a piece off of the end
19415 ** of the master chunk. This step usually works if step 1 fails.
19416 */
19417 if( mem3.szMaster>=nBlock ){
19418 return memsys3FromMaster(nBlock);
19419 }
19420
19421
19422 /* STEP 3:
19423 ** Loop through the entire memory pool. Coalesce adjacent free
19424 ** chunks. Recompute the master chunk as the largest free chunk.
19425 ** Then try again to satisfy the allocation by carving a piece off
19426 ** of the end of the master chunk. This step happens very
19427 ** rarely (we hope!)
19428 */
19429 for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
19430 memsys3OutOfMemory(toFree);
19431 if( mem3.iMaster ){
19432 memsys3Link(mem3.iMaster);
19433 mem3.iMaster = 0;
19434 mem3.szMaster = 0;
19435 }
19436 for(i=0; i<N_HASH; i++){
19437 memsys3Merge(&mem3.aiHash[i]);
19438 }
19439 for(i=0; i<MX_SMALL-1; i++){
19440 memsys3Merge(&mem3.aiSmall[i]);
19441 }
19442 if( mem3.szMaster ){
19443 memsys3Unlink(mem3.iMaster);
19444 if( mem3.szMaster>=nBlock ){
19445 return memsys3FromMaster(nBlock);
19446 }
19447 }
19448 }
19449
19450 /* If none of the above worked, then we fail. */
19451 return 0;
19452 }
19453
19454 /*
19455 ** Free an outstanding memory allocation.
19456 **
19457 ** This function assumes that the necessary mutexes, if any, are
19458 ** already held by the caller. Hence "Unsafe".
19459 */
19460 static void memsys3FreeUnsafe(void *pOld){
19461 Mem3Block *p = (Mem3Block*)pOld;
19462 int i;
19463 u32 size, x;
19464 assert( sqlite3_mutex_held(mem3.mutex) );
19465 assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
19466 i = p - mem3.aPool;
19467 assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
19468 size = mem3.aPool[i-1].u.hdr.size4x/4;
19469 assert( i+size<=mem3.nPool+1 );
19470 mem3.aPool[i-1].u.hdr.size4x &= ~1;
19471 mem3.aPool[i+size-1].u.hdr.prevSize = size;
19472 mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
19473 memsys3Link(i);
19474
19475 /* Try to expand the master using the newly freed chunk */
19476 if( mem3.iMaster ){
19477 while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
19478 size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
19479 mem3.iMaster -= size;
19480 mem3.szMaster += size;
19481 memsys3Unlink(mem3.iMaster);
19482 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
19483 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
19484 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
19485 }
19486 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
19487 while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
19488 memsys3Unlink(mem3.iMaster+mem3.szMaster);
19489 mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
19490 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
19491 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
19492 }
19493 }
19494 }
19495
19496 /*
19497 ** Return the size of an outstanding allocation, in bytes. The
19498 ** size returned omits the 8-byte header overhead. This only
19499 ** works for chunks that are currently checked out.
19500 */
19501 static int memsys3Size(void *p){
19502 Mem3Block *pBlock;
19503 assert( p!=0 );
19504 pBlock = (Mem3Block*)p;
19505 assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
19506 return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
19507 }
19508
19509 /*
19510 ** Round up a request size to the next valid allocation size.
19511 */
19512 static int memsys3Roundup(int n){
19513 if( n<=12 ){
19514 return 12;
19515 }else{
19516 return ((n+11)&~7) - 4;
19517 }
19518 }
19519
19520 /*
19521 ** Allocate nBytes of memory.
19522 */
19523 static void *memsys3Malloc(int nBytes){
19524 sqlite3_int64 *p;
19525 assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
19526 memsys3Enter();
19527 p = memsys3MallocUnsafe(nBytes);
19528 memsys3Leave();
19529 return (void*)p;
19530 }
19531
19532 /*
19533 ** Free memory.
19534 */
19535 static void memsys3Free(void *pPrior){
19536 assert( pPrior );
19537 memsys3Enter();
19538 memsys3FreeUnsafe(pPrior);
19539 memsys3Leave();
19540 }
19541
19542 /*
19543 ** Change the size of an existing memory allocation
19544 */
19545 static void *memsys3Realloc(void *pPrior, int nBytes){
19546 int nOld;
19547 void *p;
19548 if( pPrior==0 ){
19549 return sqlite3_malloc(nBytes);
19550 }
19551 if( nBytes<=0 ){
19552 sqlite3_free(pPrior);
19553 return 0;
19554 }
19555 nOld = memsys3Size(pPrior);
19556 if( nBytes<=nOld && nBytes>=nOld-128 ){
19557 return pPrior;
19558 }
19559 memsys3Enter();
19560 p = memsys3MallocUnsafe(nBytes);
19561 if( p ){
19562 if( nOld<nBytes ){
19563 memcpy(p, pPrior, nOld);
19564 }else{
19565 memcpy(p, pPrior, nBytes);
19566 }
19567 memsys3FreeUnsafe(pPrior);
19568 }
19569 memsys3Leave();
19570 return p;
19571 }
19572
19573 /*
19574 ** Initialize this module.
19575 */
19576 static int memsys3Init(void *NotUsed){
19577 UNUSED_PARAMETER(NotUsed);
19578 if( !sqlite3GlobalConfig.pHeap ){
19579 return SQLITE_ERROR;
19580 }
19581
19582 /* Store a pointer to the memory block in global structure mem3. */
19583 assert( sizeof(Mem3Block)==8 );
19584 mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
19585 mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
19586
19587 /* Initialize the master block. */
19588 mem3.szMaster = mem3.nPool;
19589 mem3.mnMaster = mem3.szMaster;
19590 mem3.iMaster = 1;
19591 mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
19592 mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
19593 mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
19594
19595 return SQLITE_OK;
19596 }
19597
19598 /*
19599 ** Deinitialize this module.
19600 */
19601 static void memsys3Shutdown(void *NotUsed){
19602 UNUSED_PARAMETER(NotUsed);
19603 mem3.mutex = 0;
19604 return;
19605 }
19606
19607
19608
19609 /*
19610 ** Open the file indicated and write a log of all unfreed memory
19611 ** allocations into that log.
19612 */
19613 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
19614 #ifdef SQLITE_DEBUG
19615 FILE *out;
19616 u32 i, j;
19617 u32 size;
19618 if( zFilename==0 || zFilename[0]==0 ){
19619 out = stdout;
19620 }else{
19621 out = fopen(zFilename, "w");
19622 if( out==0 ){
19623 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
19624 zFilename);
19625 return;
19626 }
19627 }
19628 memsys3Enter();
19629 fprintf(out, "CHUNKS:\n");
19630 for(i=1; i<=mem3.nPool; i+=size/4){
19631 size = mem3.aPool[i-1].u.hdr.size4x;
19632 if( size/4<=1 ){
19633 fprintf(out, "%p size error\n", &mem3.aPool[i]);
19634 assert( 0 );
19635 break;
19636 }
19637 if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
19638 fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
19639 assert( 0 );
19640 break;
19641 }
19642 if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
19643 fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
19644 assert( 0 );
19645 break;
19646 }
19647 if( size&1 ){
19648 fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
19649 }else{
19650 fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
19651 i==mem3.iMaster ? " **master**" : "");
19652 }
19653 }
19654 for(i=0; i<MX_SMALL-1; i++){
19655 if( mem3.aiSmall[i]==0 ) continue;
19656 fprintf(out, "small(%2d):", i);
19657 for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
19658 fprintf(out, " %p(%d)", &mem3.aPool[j],
19659 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
19660 }
19661 fprintf(out, "\n");
19662 }
19663 for(i=0; i<N_HASH; i++){
19664 if( mem3.aiHash[i]==0 ) continue;
19665 fprintf(out, "hash(%2d):", i);
19666 for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
19667 fprintf(out, " %p(%d)", &mem3.aPool[j],
19668 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
19669 }
19670 fprintf(out, "\n");
19671 }
19672 fprintf(out, "master=%d\n", mem3.iMaster);
19673 fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
19674 fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
19675 sqlite3_mutex_leave(mem3.mutex);
19676 if( out==stdout ){
19677 fflush(stdout);
19678 }else{
19679 fclose(out);
19680 }
19681 #else
19682 UNUSED_PARAMETER(zFilename);
19683 #endif
19684 }
19685
19686 /*
19687 ** This routine is the only routine in this file with external
19688 ** linkage.
19689 **
19690 ** Populate the low-level memory allocation function pointers in
19691 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
19692 ** arguments specify the block of memory to manage.
19693 **
19694 ** This routine is only called by sqlite3_config(), and therefore
19695 ** is not required to be threadsafe (it is not).
19696 */
19697 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
19698 static const sqlite3_mem_methods mempoolMethods = {
19699 memsys3Malloc,
19700 memsys3Free,
19701 memsys3Realloc,
19702 memsys3Size,
19703 memsys3Roundup,
19704 memsys3Init,
19705 memsys3Shutdown,
19706 0
19707 };
19708 return &mempoolMethods;
19709 }
19710
19711 #endif /* SQLITE_ENABLE_MEMSYS3 */
19712
19713 /************** End of mem3.c ************************************************/
19714 /************** Begin file mem5.c ********************************************/
19715 /*
19716 ** 2007 October 14
19717 **
19718 ** The author disclaims copyright to this source code. In place of
19719 ** a legal notice, here is a blessing:
19720 **
19721 ** May you do good and not evil.
19722 ** May you find forgiveness for yourself and forgive others.
19723 ** May you share freely, never taking more than you give.
19724 **
19725 *************************************************************************
19726 ** This file contains the C functions that implement a memory
19727 ** allocation subsystem for use by SQLite.
19728 **
19729 ** This version of the memory allocation subsystem omits all
19730 ** use of malloc(). The application gives SQLite a block of memory
19731 ** before calling sqlite3_initialize() from which allocations
19732 ** are made and returned by the xMalloc() and xRealloc()
19733 ** implementations. Once sqlite3_initialize() has been called,
19734 ** the amount of memory available to SQLite is fixed and cannot
19735 ** be changed.
19736 **
19737 ** This version of the memory allocation subsystem is included
19738 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
19739 **
19740 ** This memory allocator uses the following algorithm:
19741 **
19742 ** 1. All memory allocation sizes are rounded up to a power of 2.
19743 **
19744 ** 2. If two adjacent free blocks are the halves of a larger block,
19745 ** then the two blocks are coalesced into the single larger block.
19746 **
19747 ** 3. New memory is allocated from the first available free block.
19748 **
19749 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
19750 ** Concerning Dynamic Storage Allocation". Journal of the Association for
19751 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
19752 **
19753 ** Let n be the size of the largest allocation divided by the minimum
19754 ** allocation size (after rounding all sizes up to a power of 2.) Let M
19755 ** be the maximum amount of memory ever outstanding at one time. Let
19756 ** N be the total amount of memory available for allocation. Robson
19757 ** proved that this memory allocator will never breakdown due to
19758 ** fragmentation as long as the following constraint holds:
19759 **
19760 ** N >= M*(1 + log2(n)/2) - n + 1
19761 **
19762 ** The sqlite3_status() logic tracks the maximum values of n and M so
19763 ** that an application can, at any time, verify this constraint.
19764 */
19765 /* #include "sqliteInt.h" */
19766
19767 /*
19768 ** This version of the memory allocator is used only when
19769 ** SQLITE_ENABLE_MEMSYS5 is defined.
19770 */
19771 #ifdef SQLITE_ENABLE_MEMSYS5
19772
19773 /*
19774 ** A minimum allocation is an instance of the following structure.
19775 ** Larger allocations are an array of these structures where the
19776 ** size of the array is a power of 2.
19777 **
19778 ** The size of this object must be a power of two. That fact is
19779 ** verified in memsys5Init().
19780 */
19781 typedef struct Mem5Link Mem5Link;
19782 struct Mem5Link {
19783 int next; /* Index of next free chunk */
19784 int prev; /* Index of previous free chunk */
19785 };
19786
19787 /*
19788 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
19789 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
19790 ** it is not actually possible to reach this limit.
19791 */
19792 #define LOGMAX 30
19793
19794 /*
19795 ** Masks used for mem5.aCtrl[] elements.
19796 */
19797 #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
19798 #define CTRL_FREE 0x20 /* True if not checked out */
19799
19800 /*
19801 ** All of the static variables used by this module are collected
19802 ** into a single structure named "mem5". This is to keep the
19803 ** static variables organized and to reduce namespace pollution
19804 ** when this module is combined with other in the amalgamation.
19805 */
19806 static SQLITE_WSD struct Mem5Global {
19807 /*
19808 ** Memory available for allocation
19809 */
19810 int szAtom; /* Smallest possible allocation in bytes */
19811 int nBlock; /* Number of szAtom sized blocks in zPool */
19812 u8 *zPool; /* Memory available to be allocated */
19813
19814 /*
19815 ** Mutex to control access to the memory allocation subsystem.
19816 */
19817 sqlite3_mutex *mutex;
19818
19819 /*
19820 ** Performance statistics
19821 */
19822 u64 nAlloc; /* Total number of calls to malloc */
19823 u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
19824 u64 totalExcess; /* Total internal fragmentation */
19825 u32 currentOut; /* Current checkout, including internal fragmentation */
19826 u32 currentCount; /* Current number of distinct checkouts */
19827 u32 maxOut; /* Maximum instantaneous currentOut */
19828 u32 maxCount; /* Maximum instantaneous currentCount */
19829 u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
19830
19831 /*
19832 ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
19833 ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
19834 ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth.
19835 */
19836 int aiFreelist[LOGMAX+1];
19837
19838 /*
19839 ** Space for tracking which blocks are checked out and the size
19840 ** of each block. One byte per block.
19841 */
19842 u8 *aCtrl;
19843
19844 } mem5;
19845
19846 /*
19847 ** Access the static variable through a macro for SQLITE_OMIT_WSD.
19848 */
19849 #define mem5 GLOBAL(struct Mem5Global, mem5)
19850
19851 /*
19852 ** Assuming mem5.zPool is divided up into an array of Mem5Link
19853 ** structures, return a pointer to the idx-th such link.
19854 */
19855 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
19856
19857 /*
19858 ** Unlink the chunk at mem5.aPool[i] from list it is currently
19859 ** on. It should be found on mem5.aiFreelist[iLogsize].
19860 */
19861 static void memsys5Unlink(int i, int iLogsize){
19862 int next, prev;
19863 assert( i>=0 && i<mem5.nBlock );
19864 assert( iLogsize>=0 && iLogsize<=LOGMAX );
19865 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
19866
19867 next = MEM5LINK(i)->next;
19868 prev = MEM5LINK(i)->prev;
19869 if( prev<0 ){
19870 mem5.aiFreelist[iLogsize] = next;
19871 }else{
19872 MEM5LINK(prev)->next = next;
19873 }
19874 if( next>=0 ){
19875 MEM5LINK(next)->prev = prev;
19876 }
19877 }
19878
19879 /*
19880 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
19881 ** free list.
19882 */
19883 static void memsys5Link(int i, int iLogsize){
19884 int x;
19885 assert( sqlite3_mutex_held(mem5.mutex) );
19886 assert( i>=0 && i<mem5.nBlock );
19887 assert( iLogsize>=0 && iLogsize<=LOGMAX );
19888 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
19889
19890 x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
19891 MEM5LINK(i)->prev = -1;
19892 if( x>=0 ){
19893 assert( x<mem5.nBlock );
19894 MEM5LINK(x)->prev = i;
19895 }
19896 mem5.aiFreelist[iLogsize] = i;
19897 }
19898
19899 /*
19900 ** Obtain or release the mutex needed to access global data structures.
19901 */
19902 static void memsys5Enter(void){
19903 sqlite3_mutex_enter(mem5.mutex);
19904 }
19905 static void memsys5Leave(void){
19906 sqlite3_mutex_leave(mem5.mutex);
19907 }
19908
19909 /*
19910 ** Return the size of an outstanding allocation, in bytes.
19911 ** This only works for chunks that are currently checked out.
19912 */
19913 static int memsys5Size(void *p){
19914 int iSize, i;
19915 assert( p!=0 );
19916 i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
19917 assert( i>=0 && i<mem5.nBlock );
19918 iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
19919 return iSize;
19920 }
19921
19922 /*
19923 ** Return a block of memory of at least nBytes in size.
19924 ** Return NULL if unable. Return NULL if nBytes==0.
19925 **
19926 ** The caller guarantees that nByte is positive.
19927 **
19928 ** The caller has obtained a mutex prior to invoking this
19929 ** routine so there is never any chance that two or more
19930 ** threads can be in this routine at the same time.
19931 */
19932 static void *memsys5MallocUnsafe(int nByte){
19933 int i; /* Index of a mem5.aPool[] slot */
19934 int iBin; /* Index into mem5.aiFreelist[] */
19935 int iFullSz; /* Size of allocation rounded up to power of 2 */
19936 int iLogsize; /* Log2 of iFullSz/POW2_MIN */
19937
19938 /* nByte must be a positive */
19939 assert( nByte>0 );
19940
19941 /* Keep track of the maximum allocation request. Even unfulfilled
19942 ** requests are counted */
19943 if( (u32)nByte>mem5.maxRequest ){
19944 /* Abort if the requested allocation size is larger than the largest
19945 ** power of two that we can represent using 32-bit signed integers. */
19946 if( nByte > 0x40000000 ) return 0;
19947 mem5.maxRequest = nByte;
19948 }
19949
19950 /* Round nByte up to the next valid power of two */
19951 for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
19952
19953 /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
19954 ** block. If not, then split a block of the next larger power of
19955 ** two in order to create a new free block of size iLogsize.
19956 */
19957 for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
19958 if( iBin>LOGMAX ){
19959 testcase( sqlite3GlobalConfig.xLog!=0 );
19960 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
19961 return 0;
19962 }
19963 i = mem5.aiFreelist[iBin];
19964 memsys5Unlink(i, iBin);
19965 while( iBin>iLogsize ){
19966 int newSize;
19967
19968 iBin--;
19969 newSize = 1 << iBin;
19970 mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
19971 memsys5Link(i+newSize, iBin);
19972 }
19973 mem5.aCtrl[i] = iLogsize;
19974
19975 /* Update allocator performance statistics. */
19976 mem5.nAlloc++;
19977 mem5.totalAlloc += iFullSz;
19978 mem5.totalExcess += iFullSz - nByte;
19979 mem5.currentCount++;
19980 mem5.currentOut += iFullSz;
19981 if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
19982 if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
19983
19984 #ifdef SQLITE_DEBUG
19985 /* Make sure the allocated memory does not assume that it is set to zero
19986 ** or retains a value from a previous allocation */
19987 memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
19988 #endif
19989
19990 /* Return a pointer to the allocated memory. */
19991 return (void*)&mem5.zPool[i*mem5.szAtom];
19992 }
19993
19994 /*
19995 ** Free an outstanding memory allocation.
19996 */
19997 static void memsys5FreeUnsafe(void *pOld){
19998 u32 size, iLogsize;
19999 int iBlock;
20000
20001 /* Set iBlock to the index of the block pointed to by pOld in
20002 ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
20003 */
20004 iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
20005
20006 /* Check that the pointer pOld points to a valid, non-free block. */
20007 assert( iBlock>=0 && iBlock<mem5.nBlock );
20008 assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
20009 assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
20010
20011 iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
20012 size = 1<<iLogsize;
20013 assert( iBlock+size-1<(u32)mem5.nBlock );
20014
20015 mem5.aCtrl[iBlock] |= CTRL_FREE;
20016 mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
20017 assert( mem5.currentCount>0 );
20018 assert( mem5.currentOut>=(size*mem5.szAtom) );
20019 mem5.currentCount--;
20020 mem5.currentOut -= size*mem5.szAtom;
20021 assert( mem5.currentOut>0 || mem5.currentCount==0 );
20022 assert( mem5.currentCount>0 || mem5.currentOut==0 );
20023
20024 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
20025 while( ALWAYS(iLogsize<LOGMAX) ){
20026 int iBuddy;
20027 if( (iBlock>>iLogsize) & 1 ){
20028 iBuddy = iBlock - size;
20029 }else{
20030 iBuddy = iBlock + size;
20031 }
20032 assert( iBuddy>=0 );
20033 if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
20034 if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
20035 memsys5Unlink(iBuddy, iLogsize);
20036 iLogsize++;
20037 if( iBuddy<iBlock ){
20038 mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
20039 mem5.aCtrl[iBlock] = 0;
20040 iBlock = iBuddy;
20041 }else{
20042 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
20043 mem5.aCtrl[iBuddy] = 0;
20044 }
20045 size *= 2;
20046 }
20047
20048 #ifdef SQLITE_DEBUG
20049 /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
20050 ** not used after being freed */
20051 memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
20052 #endif
20053
20054 memsys5Link(iBlock, iLogsize);
20055 }
20056
20057 /*
20058 ** Allocate nBytes of memory.
20059 */
20060 static void *memsys5Malloc(int nBytes){
20061 sqlite3_int64 *p = 0;
20062 if( nBytes>0 ){
20063 memsys5Enter();
20064 p = memsys5MallocUnsafe(nBytes);
20065 memsys5Leave();
20066 }
20067 return (void*)p;
20068 }
20069
20070 /*
20071 ** Free memory.
20072 **
20073 ** The outer layer memory allocator prevents this routine from
20074 ** being called with pPrior==0.
20075 */
20076 static void memsys5Free(void *pPrior){
20077 assert( pPrior!=0 );
20078 memsys5Enter();
20079 memsys5FreeUnsafe(pPrior);
20080 memsys5Leave();
20081 }
20082
20083 /*
20084 ** Change the size of an existing memory allocation.
20085 **
20086 ** The outer layer memory allocator prevents this routine from
20087 ** being called with pPrior==0.
20088 **
20089 ** nBytes is always a value obtained from a prior call to
20090 ** memsys5Round(). Hence nBytes is always a non-negative power
20091 ** of two. If nBytes==0 that means that an oversize allocation
20092 ** (an allocation larger than 0x40000000) was requested and this
20093 ** routine should return 0 without freeing pPrior.
20094 */
20095 static void *memsys5Realloc(void *pPrior, int nBytes){
20096 int nOld;
20097 void *p;
20098 assert( pPrior!=0 );
20099 assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
20100 assert( nBytes>=0 );
20101 if( nBytes==0 ){
20102 return 0;
20103 }
20104 nOld = memsys5Size(pPrior);
20105 if( nBytes<=nOld ){
20106 return pPrior;
20107 }
20108 p = memsys5Malloc(nBytes);
20109 if( p ){
20110 memcpy(p, pPrior, nOld);
20111 memsys5Free(pPrior);
20112 }
20113 return p;
20114 }
20115
20116 /*
20117 ** Round up a request size to the next valid allocation size. If
20118 ** the allocation is too large to be handled by this allocation system,
20119 ** return 0.
20120 **
20121 ** All allocations must be a power of two and must be expressed by a
20122 ** 32-bit signed integer. Hence the largest allocation is 0x40000000
20123 ** or 1073741824 bytes.
20124 */
20125 static int memsys5Roundup(int n){
20126 int iFullSz;
20127 if( n > 0x40000000 ) return 0;
20128 for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
20129 return iFullSz;
20130 }
20131
20132 /*
20133 ** Return the ceiling of the logarithm base 2 of iValue.
20134 **
20135 ** Examples: memsys5Log(1) -> 0
20136 ** memsys5Log(2) -> 1
20137 ** memsys5Log(4) -> 2
20138 ** memsys5Log(5) -> 3
20139 ** memsys5Log(8) -> 3
20140 ** memsys5Log(9) -> 4
20141 */
20142 static int memsys5Log(int iValue){
20143 int iLog;
20144 for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
20145 return iLog;
20146 }
20147
20148 /*
20149 ** Initialize the memory allocator.
20150 **
20151 ** This routine is not threadsafe. The caller must be holding a mutex
20152 ** to prevent multiple threads from entering at the same time.
20153 */
20154 static int memsys5Init(void *NotUsed){
20155 int ii; /* Loop counter */
20156 int nByte; /* Number of bytes of memory available to this allocator */
20157 u8 *zByte; /* Memory usable by this allocator */
20158 int nMinLog; /* Log base 2 of minimum allocation size in bytes */
20159 int iOffset; /* An offset into mem5.aCtrl[] */
20160
20161 UNUSED_PARAMETER(NotUsed);
20162
20163 /* For the purposes of this routine, disable the mutex */
20164 mem5.mutex = 0;
20165
20166 /* The size of a Mem5Link object must be a power of two. Verify that
20167 ** this is case.
20168 */
20169 assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
20170
20171 nByte = sqlite3GlobalConfig.nHeap;
20172 zByte = (u8*)sqlite3GlobalConfig.pHeap;
20173 assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
20174
20175 /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
20176 nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
20177 mem5.szAtom = (1<<nMinLog);
20178 while( (int)sizeof(Mem5Link)>mem5.szAtom ){
20179 mem5.szAtom = mem5.szAtom << 1;
20180 }
20181
20182 mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
20183 mem5.zPool = zByte;
20184 mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
20185
20186 for(ii=0; ii<=LOGMAX; ii++){
20187 mem5.aiFreelist[ii] = -1;
20188 }
20189
20190 iOffset = 0;
20191 for(ii=LOGMAX; ii>=0; ii--){
20192 int nAlloc = (1<<ii);
20193 if( (iOffset+nAlloc)<=mem5.nBlock ){
20194 mem5.aCtrl[iOffset] = ii | CTRL_FREE;
20195 memsys5Link(iOffset, ii);
20196 iOffset += nAlloc;
20197 }
20198 assert((iOffset+nAlloc)>mem5.nBlock);
20199 }
20200
20201 /* If a mutex is required for normal operation, allocate one */
20202 if( sqlite3GlobalConfig.bMemstat==0 ){
20203 mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
20204 }
20205
20206 return SQLITE_OK;
20207 }
20208
20209 /*
20210 ** Deinitialize this module.
20211 */
20212 static void memsys5Shutdown(void *NotUsed){
20213 UNUSED_PARAMETER(NotUsed);
20214 mem5.mutex = 0;
20215 return;
20216 }
20217
20218 #ifdef SQLITE_TEST
20219 /*
20220 ** Open the file indicated and write a log of all unfreed memory
20221 ** allocations into that log.
20222 */
20223 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
20224 FILE *out;
20225 int i, j, n;
20226 int nMinLog;
20227
20228 if( zFilename==0 || zFilename[0]==0 ){
20229 out = stdout;
20230 }else{
20231 out = fopen(zFilename, "w");
20232 if( out==0 ){
20233 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
20234 zFilename);
20235 return;
20236 }
20237 }
20238 memsys5Enter();
20239 nMinLog = memsys5Log(mem5.szAtom);
20240 for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
20241 for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
20242 fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
20243 }
20244 fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
20245 fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
20246 fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
20247 fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
20248 fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
20249 fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
20250 fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
20251 fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
20252 memsys5Leave();
20253 if( out==stdout ){
20254 fflush(stdout);
20255 }else{
20256 fclose(out);
20257 }
20258 }
20259 #endif
20260
20261 /*
20262 ** This routine is the only routine in this file with external
20263 ** linkage. It returns a pointer to a static sqlite3_mem_methods
20264 ** struct populated with the memsys5 methods.
20265 */
20266 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
20267 static const sqlite3_mem_methods memsys5Methods = {
20268 memsys5Malloc,
20269 memsys5Free,
20270 memsys5Realloc,
20271 memsys5Size,
20272 memsys5Roundup,
20273 memsys5Init,
20274 memsys5Shutdown,
20275 0
20276 };
20277 return &memsys5Methods;
20278 }
20279
20280 #endif /* SQLITE_ENABLE_MEMSYS5 */
20281
20282 /************** End of mem5.c ************************************************/
20283 /************** Begin file mutex.c *******************************************/
20284 /*
20285 ** 2007 August 14
20286 **
20287 ** The author disclaims copyright to this source code. In place of
20288 ** a legal notice, here is a blessing:
20289 **
20290 ** May you do good and not evil.
20291 ** May you find forgiveness for yourself and forgive others.
20292 ** May you share freely, never taking more than you give.
20293 **
20294 *************************************************************************
20295 ** This file contains the C functions that implement mutexes.
20296 **
20297 ** This file contains code that is common across all mutex implementations.
20298 */
20299 /* #include "sqliteInt.h" */
20300
20301 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
20302 /*
20303 ** For debugging purposes, record when the mutex subsystem is initialized
20304 ** and uninitialized so that we can assert() if there is an attempt to
20305 ** allocate a mutex while the system is uninitialized.
20306 */
20307 static SQLITE_WSD int mutexIsInit = 0;
20308 #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
20309
20310
20311 #ifndef SQLITE_MUTEX_OMIT
20312 /*
20313 ** Initialize the mutex system.
20314 */
20315 SQLITE_PRIVATE int sqlite3MutexInit(void){
20316 int rc = SQLITE_OK;
20317 if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
20318 /* If the xMutexAlloc method has not been set, then the user did not
20319 ** install a mutex implementation via sqlite3_config() prior to
20320 ** sqlite3_initialize() being called. This block copies pointers to
20321 ** the default implementation into the sqlite3GlobalConfig structure.
20322 */
20323 sqlite3_mutex_methods const *pFrom;
20324 sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
20325
20326 if( sqlite3GlobalConfig.bCoreMutex ){
20327 pFrom = sqlite3DefaultMutex();
20328 }else{
20329 pFrom = sqlite3NoopMutex();
20330 }
20331 pTo->xMutexInit = pFrom->xMutexInit;
20332 pTo->xMutexEnd = pFrom->xMutexEnd;
20333 pTo->xMutexFree = pFrom->xMutexFree;
20334 pTo->xMutexEnter = pFrom->xMutexEnter;
20335 pTo->xMutexTry = pFrom->xMutexTry;
20336 pTo->xMutexLeave = pFrom->xMutexLeave;
20337 pTo->xMutexHeld = pFrom->xMutexHeld;
20338 pTo->xMutexNotheld = pFrom->xMutexNotheld;
20339 sqlite3MemoryBarrier();
20340 pTo->xMutexAlloc = pFrom->xMutexAlloc;
20341 }
20342 assert( sqlite3GlobalConfig.mutex.xMutexInit );
20343 rc = sqlite3GlobalConfig.mutex.xMutexInit();
20344
20345 #ifdef SQLITE_DEBUG
20346 GLOBAL(int, mutexIsInit) = 1;
20347 #endif
20348
20349 return rc;
20350 }
20351
20352 /*
20353 ** Shutdown the mutex system. This call frees resources allocated by
20354 ** sqlite3MutexInit().
20355 */
20356 SQLITE_PRIVATE int sqlite3MutexEnd(void){
20357 int rc = SQLITE_OK;
20358 if( sqlite3GlobalConfig.mutex.xMutexEnd ){
20359 rc = sqlite3GlobalConfig.mutex.xMutexEnd();
20360 }
20361
20362 #ifdef SQLITE_DEBUG
20363 GLOBAL(int, mutexIsInit) = 0;
20364 #endif
20365
20366 return rc;
20367 }
20368
20369 /*
20370 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
20371 */
20372 SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int id){
20373 #ifndef SQLITE_OMIT_AUTOINIT
20374 if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
20375 if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
20376 #endif
20377 assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
20378 return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
20379 }
20380
20381 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
20382 if( !sqlite3GlobalConfig.bCoreMutex ){
20383 return 0;
20384 }
20385 assert( GLOBAL(int, mutexIsInit) );
20386 assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
20387 return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
20388 }
20389
20390 /*
20391 ** Free a dynamic mutex.
20392 */
20393 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex *p){
20394 if( p ){
20395 assert( sqlite3GlobalConfig.mutex.xMutexFree );
20396 sqlite3GlobalConfig.mutex.xMutexFree(p);
20397 }
20398 }
20399
20400 /*
20401 ** Obtain the mutex p. If some other thread already has the mutex, block
20402 ** until it can be obtained.
20403 */
20404 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex *p){
20405 if( p ){
20406 assert( sqlite3GlobalConfig.mutex.xMutexEnter );
20407 sqlite3GlobalConfig.mutex.xMutexEnter(p);
20408 }
20409 }
20410
20411 /*
20412 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
20413 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
20414 */
20415 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex *p){
20416 int rc = SQLITE_OK;
20417 if( p ){
20418 assert( sqlite3GlobalConfig.mutex.xMutexTry );
20419 return sqlite3GlobalConfig.mutex.xMutexTry(p);
20420 }
20421 return rc;
20422 }
20423
20424 /*
20425 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
20426 ** entered by the same thread. The behavior is undefined if the mutex
20427 ** is not currently entered. If a NULL pointer is passed as an argument
20428 ** this function is a no-op.
20429 */
20430 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex *p){
20431 if( p ){
20432 assert( sqlite3GlobalConfig.mutex.xMutexLeave );
20433 sqlite3GlobalConfig.mutex.xMutexLeave(p);
20434 }
20435 }
20436
20437 #ifndef NDEBUG
20438 /*
20439 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
20440 ** intended for use inside assert() statements.
20441 */
20442 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex *p){
20443 assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
20444 return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
20445 }
20446 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex *p){
20447 assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
20448 return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
20449 }
20450 #endif
20451
20452 #endif /* !defined(SQLITE_MUTEX_OMIT) */
20453
20454 /************** End of mutex.c ***********************************************/
20455 /************** Begin file mutex_noop.c **************************************/
20456 /*
20457 ** 2008 October 07
20458 **
20459 ** The author disclaims copyright to this source code. In place of
20460 ** a legal notice, here is a blessing:
20461 **
20462 ** May you do good and not evil.
20463 ** May you find forgiveness for yourself and forgive others.
20464 ** May you share freely, never taking more than you give.
20465 **
20466 *************************************************************************
20467 ** This file contains the C functions that implement mutexes.
20468 **
20469 ** This implementation in this file does not provide any mutual
20470 ** exclusion and is thus suitable for use only in applications
20471 ** that use SQLite in a single thread. The routines defined
20472 ** here are place-holders. Applications can substitute working
20473 ** mutex routines at start-time using the
20474 **
20475 ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
20476 **
20477 ** interface.
20478 **
20479 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
20480 ** that does error checking on mutexes to make sure they are being
20481 ** called correctly.
20482 */
20483 /* #include "sqliteInt.h" */
20484
20485 #ifndef SQLITE_MUTEX_OMIT
20486
20487 #ifndef SQLITE_DEBUG
20488 /*
20489 ** Stub routines for all mutex methods.
20490 **
20491 ** This routines provide no mutual exclusion or error checking.
20492 */
20493 static int noopMutexInit(void){ return SQLITE_OK; }
20494 static int noopMutexEnd(void){ return SQLITE_OK; }
20495 static sqlite3_mutex *noopMutexAlloc(int id){
20496 UNUSED_PARAMETER(id);
20497 return (sqlite3_mutex*)8;
20498 }
20499 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
20500 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
20501 static int noopMutexTry(sqlite3_mutex *p){
20502 UNUSED_PARAMETER(p);
20503 return SQLITE_OK;
20504 }
20505 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
20506
20507 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
20508 static const sqlite3_mutex_methods sMutex = {
20509 noopMutexInit,
20510 noopMutexEnd,
20511 noopMutexAlloc,
20512 noopMutexFree,
20513 noopMutexEnter,
20514 noopMutexTry,
20515 noopMutexLeave,
20516
20517 0,
20518 0,
20519 };
20520
20521 return &sMutex;
20522 }
20523 #endif /* !SQLITE_DEBUG */
20524
20525 #ifdef SQLITE_DEBUG
20526 /*
20527 ** In this implementation, error checking is provided for testing
20528 ** and debugging purposes. The mutexes still do not provide any
20529 ** mutual exclusion.
20530 */
20531
20532 /*
20533 ** The mutex object
20534 */
20535 typedef struct sqlite3_debug_mutex {
20536 int id; /* The mutex type */
20537 int cnt; /* Number of entries without a matching leave */
20538 } sqlite3_debug_mutex;
20539
20540 /*
20541 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
20542 ** intended for use inside assert() statements.
20543 */
20544 static int debugMutexHeld(sqlite3_mutex *pX){
20545 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
20546 return p==0 || p->cnt>0;
20547 }
20548 static int debugMutexNotheld(sqlite3_mutex *pX){
20549 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
20550 return p==0 || p->cnt==0;
20551 }
20552
20553 /*
20554 ** Initialize and deinitialize the mutex subsystem.
20555 */
20556 static int debugMutexInit(void){ return SQLITE_OK; }
20557 static int debugMutexEnd(void){ return SQLITE_OK; }
20558
20559 /*
20560 ** The sqlite3_mutex_alloc() routine allocates a new
20561 ** mutex and returns a pointer to it. If it returns NULL
20562 ** that means that a mutex could not be allocated.
20563 */
20564 static sqlite3_mutex *debugMutexAlloc(int id){
20565 static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
20566 sqlite3_debug_mutex *pNew = 0;
20567 switch( id ){
20568 case SQLITE_MUTEX_FAST:
20569 case SQLITE_MUTEX_RECURSIVE: {
20570 pNew = sqlite3Malloc(sizeof(*pNew));
20571 if( pNew ){
20572 pNew->id = id;
20573 pNew->cnt = 0;
20574 }
20575 break;
20576 }
20577 default: {
20578 #ifdef SQLITE_ENABLE_API_ARMOR
20579 if( id-2<0 || id-2>=ArraySize(aStatic) ){
20580 (void)SQLITE_MISUSE_BKPT;
20581 return 0;
20582 }
20583 #endif
20584 pNew = &aStatic[id-2];
20585 pNew->id = id;
20586 break;
20587 }
20588 }
20589 return (sqlite3_mutex*)pNew;
20590 }
20591
20592 /*
20593 ** This routine deallocates a previously allocated mutex.
20594 */
20595 static void debugMutexFree(sqlite3_mutex *pX){
20596 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
20597 assert( p->cnt==0 );
20598 if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
20599 sqlite3_free(p);
20600 }else{
20601 #ifdef SQLITE_ENABLE_API_ARMOR
20602 (void)SQLITE_MISUSE_BKPT;
20603 #endif
20604 }
20605 }
20606
20607 /*
20608 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
20609 ** to enter a mutex. If another thread is already within the mutex,
20610 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
20611 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
20612 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
20613 ** be entered multiple times by the same thread. In such cases the,
20614 ** mutex must be exited an equal number of times before another thread
20615 ** can enter. If the same thread tries to enter any other kind of mutex
20616 ** more than once, the behavior is undefined.
20617 */
20618 static void debugMutexEnter(sqlite3_mutex *pX){
20619 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
20620 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
20621 p->cnt++;
20622 }
20623 static int debugMutexTry(sqlite3_mutex *pX){
20624 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
20625 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
20626 p->cnt++;
20627 return SQLITE_OK;
20628 }
20629
20630 /*
20631 ** The sqlite3_mutex_leave() routine exits a mutex that was
20632 ** previously entered by the same thread. The behavior
20633 ** is undefined if the mutex is not currently entered or
20634 ** is not currently allocated. SQLite will never do either.
20635 */
20636 static void debugMutexLeave(sqlite3_mutex *pX){
20637 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
20638 assert( debugMutexHeld(pX) );
20639 p->cnt--;
20640 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
20641 }
20642
20643 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
20644 static const sqlite3_mutex_methods sMutex = {
20645 debugMutexInit,
20646 debugMutexEnd,
20647 debugMutexAlloc,
20648 debugMutexFree,
20649 debugMutexEnter,
20650 debugMutexTry,
20651 debugMutexLeave,
20652
20653 debugMutexHeld,
20654 debugMutexNotheld
20655 };
20656
20657 return &sMutex;
20658 }
20659 #endif /* SQLITE_DEBUG */
20660
20661 /*
20662 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
20663 ** is used regardless of the run-time threadsafety setting.
20664 */
20665 #ifdef SQLITE_MUTEX_NOOP
20666 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
20667 return sqlite3NoopMutex();
20668 }
20669 #endif /* defined(SQLITE_MUTEX_NOOP) */
20670 #endif /* !defined(SQLITE_MUTEX_OMIT) */
20671
20672 /************** End of mutex_noop.c ******************************************/
20673
20674 /* Chain include. */
20675 #include "sqlite3.01.c"
OLDNEW
« no previous file with comments | « third_party/sqlite/BUILD.gn ('k') | third_party/sqlite/amalgamation/sqlite3.01.c » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698